context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
#region License
/*
* WebHeaderCollection.cs
*
* This code is derived from WebHeaderCollection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc. (http://www.ximian.com)
* Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
* - Miguel de Icaza <miguel@novell.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace CustomWebSocketSharp.Net
{
/// <summary>
/// Provides a collection of the HTTP headers associated with a request or response.
/// </summary>
[Serializable]
[ComVisible (true)]
public class WebHeaderCollection : NameValueCollection, ISerializable
{
#region Private Fields
private static readonly Dictionary<string, HttpHeaderInfo> _headers;
private bool _internallyUsed;
private HttpHeaderType _state;
#endregion
#region Static Constructor
static WebHeaderCollection ()
{
_headers =
new Dictionary<string, HttpHeaderInfo> (StringComparer.InvariantCultureIgnoreCase) {
{
"Accept",
new HttpHeaderInfo (
"Accept",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"AcceptCharset",
new HttpHeaderInfo (
"Accept-Charset",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptEncoding",
new HttpHeaderInfo (
"Accept-Encoding",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptLanguage",
new HttpHeaderInfo (
"Accept-Language",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptRanges",
new HttpHeaderInfo (
"Accept-Ranges",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Age",
new HttpHeaderInfo (
"Age",
HttpHeaderType.Response)
},
{
"Allow",
new HttpHeaderInfo (
"Allow",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Authorization",
new HttpHeaderInfo (
"Authorization",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"CacheControl",
new HttpHeaderInfo (
"Cache-Control",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Connection",
new HttpHeaderInfo (
"Connection",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue)
},
{
"ContentEncoding",
new HttpHeaderInfo (
"Content-Encoding",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ContentLanguage",
new HttpHeaderInfo (
"Content-Language",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ContentLength",
new HttpHeaderInfo (
"Content-Length",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"ContentLocation",
new HttpHeaderInfo (
"Content-Location",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentMd5",
new HttpHeaderInfo (
"Content-MD5",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentRange",
new HttpHeaderInfo (
"Content-Range",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentType",
new HttpHeaderInfo (
"Content-Type",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Cookie",
new HttpHeaderInfo (
"Cookie",
HttpHeaderType.Request)
},
{
"Cookie2",
new HttpHeaderInfo (
"Cookie2",
HttpHeaderType.Request)
},
{
"Date",
new HttpHeaderInfo (
"Date",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Expect",
new HttpHeaderInfo (
"Expect",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"Expires",
new HttpHeaderInfo (
"Expires",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ETag",
new HttpHeaderInfo (
"ETag",
HttpHeaderType.Response)
},
{
"From",
new HttpHeaderInfo (
"From",
HttpHeaderType.Request)
},
{
"Host",
new HttpHeaderInfo (
"Host",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"IfMatch",
new HttpHeaderInfo (
"If-Match",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"IfModifiedSince",
new HttpHeaderInfo (
"If-Modified-Since",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"IfNoneMatch",
new HttpHeaderInfo (
"If-None-Match",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"IfRange",
new HttpHeaderInfo (
"If-Range",
HttpHeaderType.Request)
},
{
"IfUnmodifiedSince",
new HttpHeaderInfo (
"If-Unmodified-Since",
HttpHeaderType.Request)
},
{
"KeepAlive",
new HttpHeaderInfo (
"Keep-Alive",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"LastModified",
new HttpHeaderInfo (
"Last-Modified",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"Location",
new HttpHeaderInfo (
"Location",
HttpHeaderType.Response)
},
{
"MaxForwards",
new HttpHeaderInfo (
"Max-Forwards",
HttpHeaderType.Request)
},
{
"Pragma",
new HttpHeaderInfo (
"Pragma",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ProxyAuthenticate",
new HttpHeaderInfo (
"Proxy-Authenticate",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ProxyAuthorization",
new HttpHeaderInfo (
"Proxy-Authorization",
HttpHeaderType.Request)
},
{
"ProxyConnection",
new HttpHeaderInfo (
"Proxy-Connection",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Public",
new HttpHeaderInfo (
"Public",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Range",
new HttpHeaderInfo (
"Range",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"Referer",
new HttpHeaderInfo (
"Referer",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"RetryAfter",
new HttpHeaderInfo (
"Retry-After",
HttpHeaderType.Response)
},
{
"SecWebSocketAccept",
new HttpHeaderInfo (
"Sec-WebSocket-Accept",
HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"SecWebSocketExtensions",
new HttpHeaderInfo (
"Sec-WebSocket-Extensions",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInRequest)
},
{
"SecWebSocketKey",
new HttpHeaderInfo (
"Sec-WebSocket-Key",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"SecWebSocketProtocol",
new HttpHeaderInfo (
"Sec-WebSocket-Protocol",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValueInRequest)
},
{
"SecWebSocketVersion",
new HttpHeaderInfo (
"Sec-WebSocket-Version",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInResponse)
},
{
"Server",
new HttpHeaderInfo (
"Server",
HttpHeaderType.Response)
},
{
"SetCookie",
new HttpHeaderInfo (
"Set-Cookie",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"SetCookie2",
new HttpHeaderInfo (
"Set-Cookie2",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Te",
new HttpHeaderInfo (
"TE",
HttpHeaderType.Request)
},
{
"Trailer",
new HttpHeaderInfo (
"Trailer",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"TransferEncoding",
new HttpHeaderInfo (
"Transfer-Encoding",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue)
},
{
"Translate",
new HttpHeaderInfo (
"Translate",
HttpHeaderType.Request)
},
{
"Upgrade",
new HttpHeaderInfo (
"Upgrade",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"UserAgent",
new HttpHeaderInfo (
"User-Agent",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"Vary",
new HttpHeaderInfo (
"Vary",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Via",
new HttpHeaderInfo (
"Via",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Warning",
new HttpHeaderInfo (
"Warning",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"WwwAuthenticate",
new HttpHeaderInfo (
"WWW-Authenticate",
HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
}
};
}
#endregion
#region Internal Constructors
internal WebHeaderCollection (HttpHeaderType state, bool internallyUsed)
{
_state = state;
_internallyUsed = internallyUsed;
}
#endregion
#region Protected Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class from
/// the specified <see cref="SerializationInfo"/> and <see cref="StreamingContext"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that contains the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the source for the deserialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the specified name isn't found in <paramref name="serializationInfo"/>.
/// </exception>
protected WebHeaderCollection (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
try {
_internallyUsed = serializationInfo.GetBoolean ("InternallyUsed");
_state = (HttpHeaderType) serializationInfo.GetInt32 ("State");
var cnt = serializationInfo.GetInt32 ("Count");
for (var i = 0; i < cnt; i++) {
base.Add (
serializationInfo.GetString (i.ToString ()),
serializationInfo.GetString ((cnt + i).ToString ()));
}
}
catch (SerializationException ex) {
throw new ArgumentException (ex.Message, "serializationInfo", ex);
}
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class.
/// </summary>
public WebHeaderCollection ()
{
}
#endregion
#region Internal Properties
internal HttpHeaderType State {
get {
return _state;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets all header names in the collection.
/// </summary>
/// <value>
/// An array of <see cref="string"/> that contains all header names in the collection.
/// </value>
public override string[] AllKeys {
get {
return base.AllKeys;
}
}
/// <summary>
/// Gets the number of headers in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of headers in the collection.
/// </value>
public override int Count {
get {
return base.Count;
}
}
/// <summary>
/// Gets or sets the specified request <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the request <paramref name="header"/>.
/// </value>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to get or set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public string this[HttpRequestHeader header] {
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets or sets the specified response <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the response <paramref name="header"/>.
/// </value>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to get or set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public string this[HttpResponseHeader header] {
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets a collection of header names in the collection.
/// </summary>
/// <value>
/// A <see cref="NameObjectCollectionBase.KeysCollection"/> that contains
/// all header names in the collection.
/// </value>
public override NameObjectCollectionBase.KeysCollection Keys {
get {
return base.Keys;
}
}
#endregion
#region Private Methods
private void add (string name, string value, bool ignoreRestricted)
{
var act = ignoreRestricted
? (Action <string, string>) addWithoutCheckingNameAndRestricted
: addWithoutCheckingName;
doWithCheckingState (act, checkName (name), value, true);
}
private void addWithoutCheckingName (string name, string value)
{
doWithoutCheckingName (base.Add, name, value);
}
private void addWithoutCheckingNameAndRestricted (string name, string value)
{
base.Add (name, checkValue (value));
}
private static int checkColonSeparated (string header)
{
var idx = header.IndexOf (':');
if (idx == -1)
throw new ArgumentException ("No colon could be found.", "header");
return idx;
}
private static HttpHeaderType checkHeaderType (string name)
{
var info = getHeaderInfo (name);
return info == null
? HttpHeaderType.Unspecified
: info.IsRequest && !info.IsResponse
? HttpHeaderType.Request
: !info.IsRequest && info.IsResponse
? HttpHeaderType.Response
: HttpHeaderType.Unspecified;
}
private static string checkName (string name)
{
if (name == null || name.Length == 0)
throw new ArgumentNullException ("name");
name = name.Trim ();
if (!IsHeaderName (name))
throw new ArgumentException ("Contains invalid characters.", "name");
return name;
}
private void checkRestricted (string name)
{
if (!_internallyUsed && isRestricted (name, true))
throw new ArgumentException ("This header must be modified with the appropiate property.");
}
private void checkState (bool response)
{
if (_state == HttpHeaderType.Unspecified)
return;
if (response && _state == HttpHeaderType.Request)
throw new InvalidOperationException (
"This collection has already been used to store the request headers.");
if (!response && _state == HttpHeaderType.Response)
throw new InvalidOperationException (
"This collection has already been used to store the response headers.");
}
private static string checkValue (string value)
{
if (value == null || value.Length == 0)
return String.Empty;
value = value.Trim ();
if (value.Length > 65535)
throw new ArgumentOutOfRangeException ("value", "Greater than 65,535 characters.");
if (!IsHeaderValue (value))
throw new ArgumentException ("Contains invalid characters.", "value");
return value;
}
private static string convert (string key)
{
HttpHeaderInfo info;
return _headers.TryGetValue (key, out info) ? info.Name : String.Empty;
}
private void doWithCheckingState (
Action <string, string> action, string name, string value, bool setState)
{
var type = checkHeaderType (name);
if (type == HttpHeaderType.Request)
doWithCheckingState (action, name, value, false, setState);
else if (type == HttpHeaderType.Response)
doWithCheckingState (action, name, value, true, setState);
else
action (name, value);
}
private void doWithCheckingState (
Action <string, string> action, string name, string value, bool response, bool setState)
{
checkState (response);
action (name, value);
if (setState && _state == HttpHeaderType.Unspecified)
_state = response ? HttpHeaderType.Response : HttpHeaderType.Request;
}
private void doWithoutCheckingName (Action <string, string> action, string name, string value)
{
checkRestricted (name);
action (name, checkValue (value));
}
private static HttpHeaderInfo getHeaderInfo (string name)
{
foreach (var info in _headers.Values)
if (info.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase))
return info;
return null;
}
private static bool isRestricted (string name, bool response)
{
var info = getHeaderInfo (name);
return info != null && info.IsRestricted (response);
}
private void removeWithoutCheckingName (string name, string unuse)
{
checkRestricted (name);
base.Remove (name);
}
private void setWithoutCheckingName (string name, string value)
{
doWithoutCheckingName (base.Set, name, value);
}
#endregion
#region Internal Methods
internal static string Convert (HttpRequestHeader header)
{
return convert (header.ToString ());
}
internal static string Convert (HttpResponseHeader header)
{
return convert (header.ToString ());
}
internal void InternalRemove (string name)
{
base.Remove (name);
}
internal void InternalSet (string header, bool response)
{
var pos = checkColonSeparated (header);
InternalSet (header.Substring (0, pos), header.Substring (pos + 1), response);
}
internal void InternalSet (string name, string value, bool response)
{
value = checkValue (value);
if (IsMultiValue (name, response))
base.Add (name, value);
else
base.Set (name, value);
}
internal static bool IsHeaderName (string name)
{
return name != null && name.Length > 0 && name.IsToken ();
}
internal static bool IsHeaderValue (string value)
{
return value.IsText ();
}
internal static bool IsMultiValue (string headerName, bool response)
{
if (headerName == null || headerName.Length == 0)
return false;
var info = getHeaderInfo (headerName);
return info != null && info.IsMultiValue (response);
}
internal string ToStringMultiValue (bool response)
{
var buff = new StringBuilder ();
Count.Times (
i => {
var key = GetKey (i);
if (IsMultiValue (key, response))
foreach (var val in GetValues (i))
buff.AppendFormat ("{0}: {1}\r\n", key, val);
else
buff.AppendFormat ("{0}: {1}\r\n", key, Get (i));
});
return buff.Append ("\r\n").ToString ();
}
#endregion
#region Protected Methods
/// <summary>
/// Adds a header to the collection without checking if the header is on
/// the restricted header list.
/// </summary>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="headerValue">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> or <paramref name="headerValue"/> contains invalid characters.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="headerValue"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the <paramref name="headerName"/>.
/// </exception>
protected void AddWithoutValidate (string headerName, string headerValue)
{
add (headerName, headerValue, true);
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified <paramref name="header"/> to the collection.
/// </summary>
/// <param name="header">
/// A <see cref="string"/> that represents the header with the name and value separated by
/// a colon (<c>':'</c>).
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="header"/> is <see langword="null"/>, empty, or the name part of
/// <paramref name="header"/> is empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> doesn't contain a colon.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The name or value part of <paramref name="header"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of the value part of <paramref name="header"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the <paramref name="header"/>.
/// </exception>
public void Add (string header)
{
if (header == null || header.Length == 0)
throw new ArgumentNullException ("header");
var pos = checkColonSeparated (header);
add (header.Substring (0, pos), header.Substring (pos + 1), false);
}
/// <summary>
/// Adds the specified request <paramref name="header"/> with
/// the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Add (HttpRequestHeader header, string value)
{
doWithCheckingState (addWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Adds the specified response <paramref name="header"/> with
/// the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Add (HttpResponseHeader header, string value)
{
doWithCheckingState (addWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Adds a header with the specified <paramref name="name"/> and
/// <paramref name="value"/> to the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Add (string name, string value)
{
add (name, value, false);
}
/// <summary>
/// Removes all headers from the collection.
/// </summary>
public override void Clear ()
{
base.Clear ();
_state = HttpHeaderType.Unspecified;
}
/// <summary>
/// Get the value of the header at the specified <paramref name="index"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string Get (int index)
{
return base.Get (index);
}
/// <summary>
/// Get the value of the header with the specified <paramref name="name"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to find.
/// </param>
public override string Get (string name)
{
return base.Get (name);
}
/// <summary>
/// Gets the enumerator used to iterate through the collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> instance used to iterate through the collection.
/// </returns>
public override IEnumerator GetEnumerator ()
{
return base.GetEnumerator ();
}
/// <summary>
/// Get the name of the header at the specified <paramref name="index"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the header name.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string GetKey (int index)
{
return base.GetKey (index);
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="index"/> position of
/// the collection.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string[] GetValues (int index)
{
var vals = base.GetValues (index);
return vals != null && vals.Length > 0 ? vals : null;
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="header"/>.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="header">
/// A <see cref="string"/> that represents the name of the header to find.
/// </param>
public override string[] GetValues (string header)
{
var vals = base.GetValues (header);
return vals != null && vals.Length > 0 ? vals : null;
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (
SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
serializationInfo.AddValue ("InternallyUsed", _internallyUsed);
serializationInfo.AddValue ("State", (int) _state);
var cnt = Count;
serializationInfo.AddValue ("Count", cnt);
cnt.Times (
i => {
serializationInfo.AddValue (i.ToString (), GetKey (i));
serializationInfo.AddValue ((cnt + i).ToString (), Get (i));
});
}
/// <summary>
/// Determines whether the specified header can be set for the request.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to test.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName)
{
return isRestricted (checkName (headerName), false);
}
/// <summary>
/// Determines whether the specified header can be set for the request or the response.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to test.
/// </param>
/// <param name="response">
/// <c>true</c> if does the test for the response; for the request, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName, bool response)
{
return isRestricted (checkName (headerName), response);
}
/// <summary>
/// Implements the <see cref="ISerializable"/> interface and raises the deserialization event
/// when the deserialization is complete.
/// </summary>
/// <param name="sender">
/// An <see cref="object"/> that represents the source of the deserialization event.
/// </param>
public override void OnDeserialization (object sender)
{
}
/// <summary>
/// Removes the specified request <paramref name="header"/> from the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to remove.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Remove (HttpRequestHeader header)
{
doWithCheckingState (removeWithoutCheckingName, Convert (header), null, false, false);
}
/// <summary>
/// Removes the specified response <paramref name="header"/> from the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to remove.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Remove (HttpResponseHeader header)
{
doWithCheckingState (removeWithoutCheckingName, Convert (header), null, true, false);
}
/// <summary>
/// Removes the specified header from the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Remove (string name)
{
doWithCheckingState (removeWithoutCheckingName, checkName (name), null, false);
}
/// <summary>
/// Sets the specified request <paramref name="header"/> to the specified value.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the request header to set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Set (HttpRequestHeader header, string value)
{
doWithCheckingState (setWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Sets the specified response <paramref name="header"/> to the specified value.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the response header to set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Set (HttpResponseHeader header, string value)
{
doWithCheckingState (setWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Sets the specified header to the specified value.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to set.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Set (string name, string value)
{
doWithCheckingState (setWithoutCheckingName, checkName (name), value, true);
}
/// <summary>
/// Converts the current <see cref="WebHeaderCollection"/> to an array of <see cref="byte"/>.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> that receives the converted current
/// <see cref="WebHeaderCollection"/>.
/// </returns>
public byte[] ToByteArray ()
{
return Encoding.UTF8.GetBytes (ToString ());
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current
/// <see cref="WebHeaderCollection"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current <see cref="WebHeaderCollection"/>.
/// </returns>
public override string ToString ()
{
var buff = new StringBuilder ();
Count.Times (i => buff.AppendFormat ("{0}: {1}\r\n", GetKey (i), Get (i)));
return buff.Append ("\r\n").ToString ();
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the current <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (
SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter,
SerializationFormatter = true)]
void ISerializable.GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData (serializationInfo, streamingContext);
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests In The Money (ITM) index option expiry for short puts.
/// We expect 2 orders from the algorithm, which are:
///
/// * Initial entry, sell SPX Put Option (expiring ITM)
/// * Option assignment
///
/// Additionally, we test delistings for index options and assert that our
/// portfolio holdings reflect the orders the algorithm has submitted.
/// </summary>
public class IndexOptionShortPutITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spx;
private Symbol _spxOption;
private Symbol _expectedContract;
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 31);
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
// Select a index option expiring ITM, and adds it to the algorithm.
_spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time)
.Where(x => x.ID.StrikePrice <= 4200m && x.ID.OptionRight == OptionRight.Put && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
.OrderByDescending(x => x.ID.StrikePrice)
.Take(1)
.Single(), Resolution.Minute).Symbol;
_expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Put, 4200m, new DateTime(2021, 1, 15));
if (_spxOption != _expectedContract)
{
throw new Exception($"Contract {_expectedContract} was not found in the chain");
}
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () =>
{
MarketOrder(_spxOption, -1);
});
}
public override void OnData(Slice data)
{
// Assert delistings, so that we can make sure that we receive the delisting warnings at
// the expected time. These assertions detect bug #4872
foreach (var delisting in data.Delistings.Values)
{
if (delisting.Type == DelistingType.Warning)
{
if (delisting.Time != new DateTime(2021, 1, 15))
{
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
}
}
if (delisting.Type == DelistingType.Delisted)
{
if (delisting.Time != new DateTime(2021, 1, 16))
{
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
}
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status != OrderStatus.Filled)
{
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
return;
}
if (!Securities.ContainsKey(orderEvent.Symbol))
{
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
}
var security = Securities[orderEvent.Symbol];
if (security.Symbol == _spx)
{
AssertIndexOptionOrderExercise(orderEvent, security, Securities[_expectedContract]);
}
else if (security.Symbol == _expectedContract)
{
AssertIndexOptionContractOrder(orderEvent, security);
}
else
{
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
}
Log($"{orderEvent}");
}
private void AssertIndexOptionOrderExercise(OrderEvent orderEvent, Security index, Security optionContract)
{
if (orderEvent.Message.Contains("Assignment"))
{
if (orderEvent.FillPrice != 4200)
{
throw new Exception("Option was not assigned at expected strike price (4200)");
}
if (orderEvent.Direction != OrderDirection.Buy || index.Holdings.Quantity != 0)
{
throw new Exception($"Expected Qty: 0 index holdings for assigned index option {index.Symbol}, found {index.Holdings.Quantity}");
}
}
else if (index.Holdings.Quantity != 0)
{
throw new Exception($"Expected no holdings in index: {index.Symbol}");
}
}
private void AssertIndexOptionContractOrder(OrderEvent orderEvent, Security option)
{
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != -1)
{
throw new Exception($"No holdings were created for option contract {option.Symbol}");
}
if (orderEvent.IsAssignment && option.Holdings.Quantity != 0)
{
throw new Exception($"Holdings were found after option contract was assigned: {option.Symbol}");
}
}
/// <summary>
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
/// </summary>
/// <exception cref="Exception">The algorithm has holdings</exception>
public override void OnEndOfAlgorithm()
{
if (Portfolio.Invested)
{
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "51.07%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "319.986%"},
{"Drawdown", "2.400%"},
{"Expectancy", "0"},
{"Net Profit", "10.624%"},
{"Sharpe Ratio", "5.415"},
{"Probabilistic Sharpe Ratio", "88.697%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.938"},
{"Beta", "-0.235"},
{"Annual Standard Deviation", "0.356"},
{"Annual Variance", "0.127"},
{"Information Ratio", "4.787"},
{"Tracking Error", "0.393"},
{"Treynor Ratio", "-8.187"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX 31KC0UJHC75TA|SPX 31"},
{"Fitness Score", "0.025"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "634.943"},
{"Return Over Maximum Drawdown", "1184.633"},
{"Portfolio Turnover", "0.025"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "77d9040316634cb6b9e8cd2e4e192fd5"}
};
}
}
| |
// 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.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection
{
// This file defines an internal class used to throw exceptions. The main purpose is to reduce code size.
// Also it improves the likelihood that callers will be inlined.
internal static class Throw
{
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCast()
{
throw new InvalidCastException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument(string message, string parameterName)
{
throw new ArgumentException(message, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument_OffsetForVirtualHeapHandle()
{
throw new ArgumentException(SR.CantGetOffsetForVirtualHeapHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind)
{
throw new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_Handle(string parameterName)
{
throw new ArgumentException(SR.Format(SR.InvalidHandle), parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SignatureNotVarArg()
{
throw new InvalidOperationException(SR.SignatureNotVarArg);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ControlFlowBuilderNotAvailable()
{
throw new InvalidOperationException(SR.ControlFlowBuilderNotAvailable);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperationBuilderAlreadyLinked()
{
throw new InvalidOperationException(SR.BuilderAlreadyLinked);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation(string message)
{
throw new InvalidOperationException(message);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_LabelNotMarked(int id)
{
throw new InvalidOperationException(SR.Format(SR.LabelNotMarked, id));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void LabelDoesntBelongToBuilder(string parameterName)
{
throw new ArgumentException(SR.LabelDoesntBelongToBuilder, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapHandleRequired()
{
throw new ArgumentException(SR.NotMetadataHeapHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void EntityOrUserStringHandleRequired()
{
throw new ArgumentException(SR.NotMetadataTableOrUserStringHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidToken()
{
throw new ArgumentException(SR.InvalidToken, "token");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentNull(string parameterName)
{
throw new ArgumentNullException(parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyString(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyString, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyArray(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyArray, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BuilderArgumentNull()
{
throw new ArgumentNullException("builder");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName, string message)
{
throw new ArgumentOutOfRangeException(parameterName, message);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BlobTooLarge(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName, SR.BlobTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void IndexOutOfRange()
{
throw new ArgumentOutOfRangeException("index");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableIndexOutOfRange()
{
throw new ArgumentOutOfRangeException("tableIndex");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void OutOfBounds()
{
throw new BadImageFormatException(SR.OutOfBoundsRead);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void WriteOutOfBounds()
{
throw new InvalidOperationException(SR.OutOfBoundsWrite);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCodedIndex()
{
throw new BadImageFormatException(SR.InvalidCodedIndex);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidHandle()
{
throw new BadImageFormatException(SR.InvalidHandle);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCompressedInteger()
{
throw new BadImageFormatException(SR.InvalidCompressedInteger);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidSerializedString()
{
throw new BadImageFormatException(SR.InvalidSerializedString);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmall()
{
throw new BadImageFormatException(SR.ImageTooSmall);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmallOrContainsInvalidOffsetOrCount()
{
throw new BadImageFormatException(SR.ImageTooSmallOrContainsInvalidOffsetOrCount);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ReferenceOverflow()
{
throw new BadImageFormatException(SR.RowIdOrHeapOffsetTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_TableNotSorted(TableIndex tableIndex)
{
throw new InvalidOperationException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_PEImageNotAvailable()
{
throw new InvalidOperationException(SR.PEImageNotAvailable);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TooManySubnamespaces()
{
throw new BadImageFormatException(SR.TooManySubnamespaces);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueOverflow()
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SequencePointValueOutOfRange()
{
throw new BadImageFormatException(SR.SequencePointValueOutOfRange);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapSizeLimitExceeded(HeapIndex heap)
{
throw new ImageFormatLimitationException(SR.Format(SR.HeapSizeLimitExceeded, heap));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void PEReaderDisposed()
{
throw new ObjectDisposedException(nameof(PortableExecutable.PEReader));
}
}
}
| |
#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;
using System.Collections.Generic;
using System.ComponentModel;
#if !(NET35 || NET20 || PORTABLE40)
using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private Type _rootType;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
{
throw new ArgumentNullException(nameof(jsonWriter));
}
_rootType = objectType;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
if (ShouldWriteReference(value, null, contract, null, null))
{
WriteReference(jsonWriter, value);
}
else
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidently be used for non root values
_rootType = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (InternalSerializer == null)
{
InternalSerializer = new JsonSerializerProxy(this);
}
return InternalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
{
return null;
}
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
{
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
}
else
{
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
}
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
#endif
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
{
isReference = property.IsReference;
}
if (isReference == null && containerProperty != null)
{
isReference = containerProperty.ItemIsReference;
}
if (isReference == null && collectionContract != null)
{
isReference = collectionContract.ItemIsReference;
}
if (isReference == null)
{
isReference = contract.IsReference;
}
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
{
return false;
}
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
{
return false;
}
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
{
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
}
else
{
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
}
if (!isReference.GetValueOrDefault())
{
return false;
}
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
{
return false;
}
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
{
return false;
}
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
{
return true;
}
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
{
referenceLoopHandling = property.ReferenceLoopHandling;
}
if (referenceLoopHandling == null && containerProperty != null)
{
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
}
if (referenceLoopHandling == null && containerContract != null)
{
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
}
bool exists = (Serializer._equalityComparer != null)
? _serializeStack.Contains(value, Serializer._equalityComparer)
: _serializeStack.Contains(value);
if (exists)
{
string message = "Self referencing loop detected";
if (property != null)
{
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
}
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
}
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
}
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
}
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(DOTNET || PORTABLE40 || PORTABLE)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
&& !(converter is ComponentConverter)
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
s = converter.ConvertToInvariantString(value);
return true;
}
}
#endif
#if (DOTNET || PORTABLE)
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
}
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
}
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
{
continue;
}
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
{
continue;
}
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
{
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
}
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
{
return false;
}
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
if (resolvedRequired == Required.DisallowNull)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
// don't make readonly fields the referenced value because they can't be deserialized to
if (isReference && (member == null || member.Writable))
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
}
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
}
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
{
return;
}
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
}
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
{
writer.WriteEndObject();
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
{
writer.WriteEndObject();
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth + 1);
}
else
{
throw;
}
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
// don't make readonly fields the referenced value because they can't be deserialized to
isReference = (isReference && (member == null || member.Writable));
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
{
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
}
return writeMetadataObject;
}
#if !(DOTNET || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35)
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
@"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
WriteReference(writer, serializationEntry.Value);
}
else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
#if !(NET35 || NET20 || PORTABLE40)
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
// only write non-dynamic properties that have an explicit attribute
if (property.HasMemberAttribute)
{
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
{
continue;
}
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (contract.TryGetMember(value, memberName, out memberValue))
{
try
{
JsonContract valueContract = GetContractSafe(memberValue);
if (!ShouldWriteDynamicProperty(memberValue))
{
continue;
}
if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
{
return false;
}
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
{
return false;
}
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
{
return true;
}
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
{
return true;
}
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
{
return true;
}
}
else if (_rootType != null && _serializeStack.Count == _rootLevel)
{
JsonContract rootContract = Serializer._contractResolver.ResolveContract(_rootType);
if (contract.UnderlyingType != rootContract.CreatedType)
{
return true;
}
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
{
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
}
if (contract.KeyContract == null)
{
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
}
int initialDepth = writer.Top;
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = values.GetEnumerator();
try
{
while (e.MoveNext())
{
DictionaryEntry entry = e.Entry;
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.DictionaryKeyResolver != null)
? contract.DictionaryKeyResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
continue;
}
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
finally
{
(e as IDisposable)?.Dispose();
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
DateTime dt = DateTimeUtils.EnsureDateTime((DateTime)name, writer.DateTimeZoneHandling);
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, dt, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#if !NET20
else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#endif
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
{
writer.WriteNull();
}
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
{
return true;
}
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
}
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
{
return true;
}
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
}
return isSpecified;
}
}
}
| |
using System;
using Loon.Java;
using System.IO;
using Loon.Utils;
using Loon.Utils.Collection;
using Loon.Net;
namespace Loon.Core.Resource
{
public sealed class Resources
{
public static Resource ClassRes(string path)
{
return new ClassRes(path);
}
public static Resource FileRes(string path)
{
return new FileRes(path);
}
public static Resource RemoteRes(string path)
{
return new RemoteRes(path);
}
public static Resource SdRes(string path)
{
return new SDRes(path);
}
public static Stream StrRes(string path)
{
if (path == null)
{
return null;
}
Stream ins0 = null;
if (path.IndexOf("->") == -1)
{
if (path.StartsWith("sd:"))
{
ins0 = SdRes(path.Substring(3, (path.Length) - (3))).GetInputStream();
}
else if (path.StartsWith("class:"))
{
ins0 = ClassRes(path.Substring(6, (path.Length) - (6)))
.GetInputStream();
}
else if (path.StartsWith("path:"))
{
ins0 = FileRes(path.Substring(5, (path.Length) - (5))).GetInputStream();
}
else if (path.StartsWith("url:"))
{
ins0 = RemoteRes(path.Substring(4, (path.Length) - (4)))
.GetInputStream();
}
}
else
{
string[] newPath = StringUtils.Split(path, "->");
// ins0 = LPKResource.OpenStream(
// newPath[0].Trim(), newPath[1].Trim());
}
return ins0;
}
private static Type appType;
private static bool supportApplication = true;
public static InputStream OpenSource(string resName)
{
System.IO.Stream stream = OpenStream(resName);
if (stream == null)
{
return null;
}
return stream;
}
public static System.IO.Stream OpenStream(string resName)
{
if (resName.IndexOf("/") == -1 && FileUtils.GetExtension(resName).Length == 0)
{
resName = "Assets/" + resName;
}
Stream resource = StrRes(resName);
if (resource != null)
{
return resource;
}
System.IO.Stream stream = null;
try
{
stream = File.OpenRead(resName);
}
catch
{
try
{
if (stream == null)
{
// stream = XNAConfig.LoadStream(resName);
}
}
catch (Exception)
{
if (stream == null)
{
Uri pathUri = new Uri("/" + JavaRuntime.GetAssemblyName() + ";component/" + resName, UriKind.RelativeOrAbsolute);
// stream = ApplicationResourceStream(pathUri);
}
}
}
if (stream == null)
{
try
{
stream = new System.IO.FileStream(resName, System.IO.FileMode.Open);
}
catch
{
try
{
// System.IO.IsolatedStorage.IsolatedStorageFile store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
// stream = store.OpenFile(resName, System.IO.FileMode.Open);
}
catch (Exception ex)
{
Loon.Utils.Debug.Log.Exception(ex);
Loon.Utils.Debug.Log.DebugWrite("\n" + resName + " file not found !");
}
}
}
return stream;
}
public static ArrayByte GetResource(string resName)
{
if (resName == null)
{
return null;
}
InputStream resource = OpenStream(resName);
if (resource != null)
{
ArrayByte result = new ArrayByte();
try
{
result.Write(resource);
resource.Close();
result.Reset();
}
catch (IOException)
{
result = null;
}
return result;
}
return null;
}
public static InputStream GetResourceAsStream(string fileName)
{
return new ByteArrayInputStream(GetResource(fileName).GetData());
}
public static byte[] GetDataSource(InputStream ins)
{
if (ins == null)
{
return null;
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[8192];
try
{
int read;
while ((read = ins.Read(bytes)) >= 0)
{
byteArrayOutputStream.Write(bytes, 0, read);
}
bytes = byteArrayOutputStream.ToByteArray();
}
catch (IOException)
{
return null;
}
finally
{
try
{
if (byteArrayOutputStream != null)
{
byteArrayOutputStream.Flush();
byteArrayOutputStream = null;
}
if (ins != null)
{
ins.Close();
ins = null;
}
}
catch (IOException)
{
}
}
return bytes;
}
}
}
| |
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Access to the Field Info file that describes document fields and whether or
/// not they are indexed. Each segment has a separate Field Info file. Objects
/// of this class are thread-safe for multiple readers, but only one thread can
/// be adding documents at a time, with no other reader or writer threads
/// accessing this object.
/// </summary>
public sealed class FieldInfo
{
/// <summary>
/// Field's name </summary>
public string Name { get; private set; }
/// <summary>
/// Internal field number </summary>
public int Number { get; private set; }
private bool indexed;
private DocValuesType docValueType;
// True if any document indexed term vectors
private bool storeTermVector;
private DocValuesType normType;
private bool omitNorms; // omit norms associated with indexed fields
private IndexOptions indexOptions;
private bool storePayloads; // whether this field stores payloads together with term positions
private IDictionary<string, string> attributes;
private long dvGen = -1; // the DocValues generation of this field
// LUCENENET specific: De-nested the IndexOptions and DocValuesType enums from this class to prevent naming conflicts
/// <summary>
/// Sole Constructor.
/// <para/>
/// @lucene.experimental
/// </summary>
public FieldInfo(string name, bool indexed, int number, bool storeTermVector, bool omitNorms,
bool storePayloads, IndexOptions indexOptions, DocValuesType docValues, DocValuesType normsType,
IDictionary<string, string> attributes)
{
this.Name = name;
this.indexed = indexed;
this.Number = number;
this.docValueType = docValues;
if (indexed)
{
this.storeTermVector = storeTermVector;
this.storePayloads = storePayloads;
this.omitNorms = omitNorms;
this.indexOptions = indexOptions;
this.normType = !omitNorms ? normsType : DocValuesType.NONE;
} // for non-indexed fields, leave defaults
else
{
this.storeTermVector = false;
this.storePayloads = false;
this.omitNorms = false;
this.indexOptions = IndexOptions.NONE;
this.normType = DocValuesType.NONE;
}
this.attributes = attributes;
if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency());
}
private bool CheckConsistency()
{
if (!indexed)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(!storeTermVector);
Debugging.Assert(!storePayloads);
Debugging.Assert(!omitNorms);
Debugging.Assert(normType == DocValuesType.NONE);
Debugging.Assert(indexOptions == IndexOptions.NONE);
}
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(indexOptions != IndexOptions.NONE);
if (omitNorms)
{
if (Debugging.AssertsEnabled) Debugging.Assert(normType == DocValuesType.NONE);
}
// Cannot store payloads unless positions are indexed:
if (Debugging.AssertsEnabled) Debugging.Assert(indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 || !this.storePayloads);
}
return true;
}
internal void Update(IIndexableFieldType ft)
{
Update(ft.IsIndexed, false, ft.OmitNorms, false, ft.IndexOptions);
}
// should only be called by FieldInfos#addOrUpdate
internal void Update(bool indexed, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions indexOptions)
{
//System.out.println("FI.update field=" + name + " indexed=" + indexed + " omitNorms=" + omitNorms + " this.omitNorms=" + this.omitNorms);
if (this.indexed != indexed)
{
this.indexed = true; // once indexed, always index
}
if (indexed) // if updated field data is not for indexing, leave the updates out
{
if (this.storeTermVector != storeTermVector)
{
this.storeTermVector = true; // once vector, always vector
}
if (this.storePayloads != storePayloads)
{
this.storePayloads = true;
}
if (this.omitNorms != omitNorms)
{
this.omitNorms = true; // if one require omitNorms at least once, it remains off for life
this.normType = DocValuesType.NONE;
}
if (this.indexOptions != indexOptions)
{
if (this.indexOptions == IndexOptions.NONE)
{
this.indexOptions = indexOptions;
}
else
{
// downgrade
this.indexOptions = this.indexOptions.CompareTo(indexOptions) < 0 ? this.indexOptions : indexOptions;
}
if (this.indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0)
{
// cannot store payloads if we don't store positions:
this.storePayloads = false;
}
}
}
if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency());
}
public DocValuesType DocValuesType
{
get => docValueType;
internal set
{
if (docValueType != DocValuesType.NONE && docValueType != value)
{
throw new ArgumentException("cannot change DocValues type from " + docValueType + " to " + value + " for field \"" + Name + "\"");
}
docValueType = value;
if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency());
}
}
/// <summary>
/// Returns <see cref="Index.IndexOptions"/> for the field, or <c>null</c> if the field is not indexed </summary>
public IndexOptions IndexOptions => indexOptions;
/// <summary>
/// Returns <c>true</c> if this field has any docValues.
/// </summary>
public bool HasDocValues => docValueType != DocValuesType.NONE;
/// <summary>
/// Gets or Sets the docValues generation of this field, or -1 if no docValues. </summary>
public long DocValuesGen
{
get => dvGen;
set => this.dvGen = value;
}
/// <summary>
/// Returns <see cref="Index.DocValuesType"/> of the norm. This may be <see cref="DocValuesType.NONE"/> if the field has no norms.
/// </summary>
public DocValuesType NormType
{
get => normType;
internal set
{
if (normType != DocValuesType.NONE && normType != value)
{
throw new ArgumentException("cannot change Norm type from " + normType + " to " + value + " for field \"" + Name + "\"");
}
normType = value;
if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency());
}
}
internal void SetStoreTermVectors()
{
storeTermVector = true;
if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency());
}
internal void SetStorePayloads()
{
if (indexed && indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0)
{
storePayloads = true;
}
if (Debugging.AssertsEnabled) Debugging.Assert(CheckConsistency());
}
/// <summary>
/// Returns <c>true</c> if norms are explicitly omitted for this field
/// </summary>
public bool OmitsNorms => omitNorms;
/// <summary>
/// Returns <c>true</c> if this field actually has any norms.
/// </summary>
public bool HasNorms => normType != DocValuesType.NONE;
/// <summary>
/// Returns <c>true</c> if this field is indexed.
/// </summary>
public bool IsIndexed => indexed;
/// <summary>
/// Returns <c>true</c> if any payloads exist for this field.
/// </summary>
public bool HasPayloads => storePayloads;
/// <summary>
/// Returns <c>true</c> if any term vectors exist for this field.
/// </summary>
public bool HasVectors => storeTermVector;
/// <summary>
/// Get a codec attribute value, or <c>null</c> if it does not exist
/// </summary>
public string GetAttribute(string key)
{
if (attributes == null)
{
return null;
}
else
{
string ret;
attributes.TryGetValue(key, out ret);
return ret;
}
}
/// <summary>
/// Puts a codec attribute value.
/// <para/>
/// this is a key-value mapping for the field that the codec can use
/// to store additional metadata, and will be available to the codec
/// when reading the segment via <see cref="GetAttribute(string)"/>
/// <para/>
/// If a value already exists for the field, it will be replaced with
/// the new value.
/// </summary>
public string PutAttribute(string key, string value)
{
if (attributes == null)
{
attributes = new Dictionary<string, string>();
}
string ret;
// The key was not previously assigned, null will be returned
if (!attributes.TryGetValue(key, out ret))
{
ret = null;
}
attributes[key] = value;
return ret;
}
/// <summary>
/// Returns internal codec attributes map. May be <c>null</c> if no mappings exist.
/// </summary>
public IDictionary<string, string> Attributes => attributes;
}
/// <summary>
/// Controls how much information is stored in the postings lists.
/// <para/>
/// @lucene.experimental
/// </summary>
public enum IndexOptions // LUCENENET specific: de-nested from FieldInfo to prevent naming collisions
{
// NOTE: order is important here; FieldInfo uses this
// order to merge two conflicting IndexOptions (always
// "downgrades" by picking the lowest).
/// <summary>
/// No index options will be used.
/// <para/>
/// NOTE: This is the same as setting to <c>null</c> in Lucene
/// </summary>
// LUCENENET specific
NONE,
/// <summary>
/// Only documents are indexed: term frequencies and positions are omitted.
/// Phrase and other positional queries on the field will throw an exception, and scoring
/// will behave as if any term in the document appears only once.
/// </summary>
// TODO: maybe rename to just DOCS?
DOCS_ONLY,
/// <summary>
/// Only documents and term frequencies are indexed: positions are omitted.
/// this enables normal scoring, except Phrase and other positional queries
/// will throw an exception.
/// </summary>
DOCS_AND_FREQS,
/// <summary>
/// Indexes documents, frequencies and positions.
/// this is a typical default for full-text search: full scoring is enabled
/// and positional queries are supported.
/// </summary>
DOCS_AND_FREQS_AND_POSITIONS,
/// <summary>
/// Indexes documents, frequencies, positions and offsets.
/// Character offsets are encoded alongside the positions.
/// </summary>
DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS
}
/// <summary>
/// DocValues types.
/// Note that DocValues is strongly typed, so a field cannot have different types
/// across different documents.
/// </summary>
public enum DocValuesType // LUCENENET specific: de-nested from FieldInfo to prevent naming collisions
{
/// <summary>
/// No doc values type will be used.
/// <para/>
/// NOTE: This is the same as setting to <c>null</c> in Lucene
/// </summary>
// LUCENENET specific
NONE, // LUCENENET NOTE: The value of this option is 0, which is the default value for any .NET value type
/// <summary>
/// A per-document numeric type
/// </summary>
NUMERIC,
/// <summary>
/// A per-document <see cref="T:byte[]"/>. Values may be larger than
/// 32766 bytes, but different codecs may enforce their own limits.
/// </summary>
BINARY,
/// <summary>
/// A pre-sorted <see cref="T:byte[]"/>. Fields with this type only store distinct byte values
/// and store an additional offset pointer per document to dereference the shared
/// byte[]. The stored byte[] is presorted and allows access via document id,
/// ordinal and by-value. Values must be <= 32766 bytes.
/// </summary>
SORTED,
/// <summary>
/// A pre-sorted ISet<byte[]>. Fields with this type only store distinct byte values
/// and store additional offset pointers per document to dereference the shared
/// <see cref="T:byte[]"/>s. The stored <see cref="T:byte[]"/> is presorted and allows access via document id,
/// ordinal and by-value. Values must be <= 32766 bytes.
/// </summary>
SORTED_SET
}
}
| |
/*
* Copyright (c) 2006, Brendan Grant (grantb@dahat.com)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * All original and modified versions of this source code must include the
* above copyright notice, this list of conditions and the following
* disclaimer.
* * This code may not be used with or within any modules or code that is
* licensed in any way that that compels or requires users or modifiers
* to release their source code or changes as a requirement for
* the use, modification or distribution of binary, object or source code
* based on the licensed source code. (ex: Cannot be used with GPL code.)
* * The name of Brendan Grant may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY BRENDAN GRANT ``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 BRENDAN GRANT 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 Microsoft.Win32;
using System.Xml.Serialization;
namespace BrendanGrant.Helpers.FileAssociation
{
#region Public Enums
/// <summary>
/// Broad categories of system recognized file format types.
/// </summary>
public enum PerceivedTypes
{
/// <summary>
/// No
/// </summary>
None,
/// <summary>
/// Image file
/// </summary>
Image,
/// <summary>
/// Text file
/// </summary>
Text,
/// <summary>
/// Audio file
/// </summary>
Audio,
/// <summary>
/// Video file
/// </summary>
Video,
/// <summary>
/// Compressed file
/// </summary>
Compressed,
/// <summary>
/// System file
/// </summary>
System,
}
#endregion
/// <summary>
/// Provides instance methods for the creation, modification, and deletion of file extension associations in the Windows registry.
/// </summary>
public class FileAssociationInfo
{
private RegistryWrapper registryWrapper = new RegistryWrapper();
/// <summary>
/// Gets array containing known file extensions from HKEY_CLASSES_ROOT.
/// </summary>
/// <returns>String array containing extensions.</returns>
public static string[] GetExtensions()
{
RegistryKey root = RegistryWrapper.ClassesRoot;
List<string> extensionList = new List<string>();
string[] subKeys = root.GetSubKeyNames();
foreach (string subKey in subKeys)
{
//TODO: Consider removing dot?
if (subKey.StartsWith("."))
{
extensionList.Add(subKey);
}
}
return extensionList.ToArray(); ;
}
private string extension;
/// <summary>
/// Gets or sets a value that determines the MIME type of the file.
/// </summary>
public string ContentType
{
get { return GetContentType(this); }
set { SetContentType(this, value); }
}
/// <summary>
/// Gets a value indicating whether the extension exists.
/// </summary>
public bool Exists
{
get
{
RegistryKey root = RegistryWrapper.ClassesRoot;
try
{
RegistryKey key = root.OpenSubKey(extension);
if (key == null)
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
return true;
}
}
/// <summary>
/// Gets the name of the extension.
/// </summary>
public string Extension
{
get { return extension; }
set { extension = value; }
}
/// <summary>
/// Gets or sets array of containing program file names which should be displayed in the Open With List.
/// </summary>
/// <example>notepad.exe, wordpad.exe, othertexteditor.exe</example>
public string[] OpenWithList
{
get { return GetOpenWithList(this); }
set { SetOpenWithList(this, value); }
}
/// <summary>
/// Gets or sets a value that determines the <see cref="PerceivedType"/> of the file.
/// </summary>
public PerceivedTypes PerceivedType
{
get { return GetPerceivedType(this); }
set { SetPerceivedType(this, value); }
}
/// <summary>
/// Gets or sets a value that indicates the filter component that is used to search for text within documents of this type.
/// </summary>
public Guid PersistentHandler
{
get { return GetPersistentHandler(this); }
set { SetPersistentHandler(this, value); }
}
/// <summary>
/// Gets or set a value that indicates the name of the associated application with the behavior to handle this extension.
/// </summary>
[XmlAttribute()]
public string ProgID
{
get { return GetProgID(this); }
set { SetProgID(this, value); }
}
/// <summary>
/// Creates the extension key.
/// </summary>
public void Create()
{
Create(this);
}
/// <summary>
/// Deletes the extension key.
/// </summary>
public void Delete()
{
Delete(this);
}
/// <summary>
/// Verifies that given extension exists and is associated with given program id
/// </summary>
/// <param name="extension">Extension to be checked for.</param>
/// <param name="progId">progId to be checked for.</param>
/// <returns>True if association exists, false if it does not.</returns>
public bool IsValid(string extension, string progId)
{
FileAssociationInfo fai = new FileAssociationInfo(extension);
if (!fai.Exists)
return false;
if (progId != fai.ProgID)
return false;
return true;
}
/// <summary>
/// Initializes a new instance of the <see cref="FileAssociationInfo"/>FileAssociationInfo class, which acts as a wrapper for a file extension within the registry.
/// </summary>
/// <param name="extension">The dot prefixed extension.</param>
/// <example>FileAssociationInfo(".mp3")
/// FileAssociationInfo(".txt")
/// FileAssociationInfo(".doc")</example>
public FileAssociationInfo(string extension)
{
this.extension = extension;
}
#region Public Functions - Creators
/// <summary>
/// Creates actual extension association key in registry for the specified extension and supplied attributes.
/// </summary>
/// <param name="progId">Name of expected handling program.</param>
/// <returns>FileAssociationInfo instance referring to specified extension.</returns>
public FileAssociationInfo Create(string progId)
{
return Create(progId, PerceivedTypes.None, string.Empty, null);
}
/// <summary>
/// Creates actual extension association key in registry for the specified extension and supplied attributes.
/// </summary>
/// <param name="progId">Name of expected handling program.</param>
/// <param name="perceivedType"><see cref="PerceivedTypes"/>PerceivedType of file type.</param>
/// <returns>FileAssociationInfo instance referring to specified extension.</returns>
public FileAssociationInfo Create(string progId, PerceivedTypes perceivedType)
{
return Create(progId, perceivedType, string.Empty, null);
}
/// <summary>
/// Creates actual extension association key in registry for the specified extension and supplied attributes.
/// </summary>
/// <param name="progId">Name of expected handling program.</param>
/// <param name="perceivedType"><see cref="PerceivedTypes"/>PerceivedType of file type.</param>
/// <param name="contentType">MIME type of file type.</param>
/// <returns>FileAssociationInfo instance referring to specified extension.</returns>
public FileAssociationInfo Create(string progId, PerceivedTypes perceivedType, string contentType)
{
return Create(progId, PerceivedTypes.None, contentType, null);
}
/// <summary>
/// Creates actual extension association key in registry for the specified extension and supplied attributes.
/// </summary>
/// <param name="progId">Name of expected handling program.</param>
/// <param name="perceivedType"><see cref="PerceivedTypes"/>PerceivedType of file type.</param>
/// <param name="contentType">MIME type of file type.</param>
/// <param name="openwithList"></param>
/// <returns>FileAssociationInfo instance referring to specified extension.</returns>
public FileAssociationInfo Create(string progId, PerceivedTypes perceivedType, string contentType, string[] openwithList)
{
FileAssociationInfo fai = new FileAssociationInfo(extension);
if (fai.Exists)
{
fai.Delete();
}
fai.Create();
fai.ProgID = progId;
if (perceivedType != PerceivedTypes.None)
fai.PerceivedType = perceivedType;
if (contentType != string.Empty)
fai.ContentType = contentType;
if (openwithList != null)
fai.OpenWithList = openwithList;
return fai;
}
#endregion
#region Private Functions - Property backend
/// <summary>
/// Gets array of containing program file names which should be displayed in the Open With List.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <returns>Program file names</returns>
protected string[] GetOpenWithList(FileAssociationInfo file)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
RegistryKey root = RegistryWrapper.ClassesRoot;
RegistryKey key = root.OpenSubKey(file.extension);
key = key.OpenSubKey("OpenWithList");
if (key == null)
{
return new string[0];
}
return key.GetSubKeyNames();
}
/// <summary>
/// Sets array of containing program file names which should be displayed in the Open With List.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <param name="programList">Program file names</param>
protected void SetOpenWithList(FileAssociationInfo file, string[] programList)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
RegistryKey root = RegistryWrapper.ClassesRoot;
RegistryKey key = root.OpenSubKey(file.extension, true);
RegistryKey tmpkey = key.OpenSubKey("OpenWithList", true);
if (tmpkey != null)
{
key.DeleteSubKeyTree("OpenWithList");
}
key = key.CreateSubKey("OpenWithList");
foreach (string s in programList)
{
key.CreateSubKey(s);
}
ShellNotification.NotifyOfChange();
}
/// <summary>
/// Gets or value that determines the <see cref="PerceivedType"/>PerceivedType of the file.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <returns><see cref="PerceivedTypes"/> that specifies Perceived Type of extension.</returns>
protected PerceivedTypes GetPerceivedType(FileAssociationInfo file)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
object val = registryWrapper.Read(file.extension, "PerceivedType");
PerceivedTypes actualType = PerceivedTypes.None;
if (val == null)
return actualType;
try
{
actualType = (PerceivedTypes)Enum.Parse(typeof(PerceivedTypes), val.ToString(), true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return actualType;
}
/// <summary>
/// Sets a value that determines the <see cref="PerceivedType"/>PerceivedType of the file.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <param name="type"><see cref="PerceivedTypes"/> to be set that specifies Perceived Type of extension.</param>
protected void SetPerceivedType(FileAssociationInfo file, PerceivedTypes type)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
registryWrapper.Write(file.extension, "PerceivedType", type.ToString());
ShellNotification.NotifyOfChange();
}
/// <summary>
/// Gets a value that indicates the filter component that is used to search for text within documents of this type.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <returns>Guid of filter component.</returns>
protected Guid GetPersistentHandler(FileAssociationInfo file)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
object val = registryWrapper.Read(file.extension + "\\PersistentHandler", string.Empty);
if (val == null)
return new Guid();
else
return new Guid(val.ToString());
}
/// <summary>
/// Sets a value that indicates the filter component that is used to search for text within documents of this type.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <param name="persistentHandler">Guid of filter component.</param>
protected void SetPersistentHandler(FileAssociationInfo file, Guid persistentHandler)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
if (persistentHandler == Guid.Empty)
return;
this.registryWrapper.Write(file.extension + "\\" + PersistentHandler, string.Empty, persistentHandler);
ShellNotification.NotifyOfChange();
}
/// <summary>
/// Gets a value that determines the MIME type of the file.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <returns>MIME content type of extension.</returns>
protected string GetContentType(FileAssociationInfo file)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
object val = registryWrapper.Read(file.extension, "Content Type");
if (val == null)
{
return string.Empty;
}
else
{
return val.ToString();
}
}
/// <summary>
/// Sets a value that determines the MIME type of the file.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <param name="type">MIME content type of extension.</param>
protected void SetContentType(FileAssociationInfo file, string type)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
registryWrapper.Write(file.extension, "Content Type", type);
ShellNotification.NotifyOfChange();
}
/// <summary>
/// Gets a value that indicates the name of the associated application with the behavior to handle this extension.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <returns>Associated Program ID of handling program.</returns>
protected string GetProgID(FileAssociationInfo file)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
object val = registryWrapper.Read(file.extension, string.Empty);
if (val == null)
return string.Empty;
return val.ToString();
}
/// <summary>
/// Set a value that indicates the name of the associated application with the behavior to handle this extension.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> that provides specifics of the extension to be changed.</param>
/// <param name="progId">Associated Program ID of handling program.</param>
protected void SetProgID(FileAssociationInfo file, string progId)
{
if (!file.Exists)
throw new Exception("Extension does not exist");
registryWrapper.Write(file.extension, string.Empty, progId);
ShellNotification.NotifyOfChange();
}
#endregion
/// <summary>
/// Creates actual file extension entry in registry.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> instance that contains specifics on extension to be created.</param>
protected void Create(FileAssociationInfo file)
{
if (file.Exists)
{
file.Delete();
}
RegistryKey root = RegistryWrapper.ClassesRoot;
root.CreateSubKey(file.extension);
}
/// <summary>
/// Deletes actual file extension entry in registry.
/// </summary>
/// <param name="file"><see cref="FileAssociationInfo"/> instance that contains specifics on extension to be deleted.</param>
protected void Delete(FileAssociationInfo file)
{
if (!file.Exists)
{
throw new Exception("Key not found.");
}
RegistryKey root = RegistryWrapper.ClassesRoot;
root.DeleteSubKeyTree(file.extension);
}
}
}
| |
using System;
using System.Diagnostics;
namespace YAF.Lucene.Net.Codecs
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BufferedIndexInput = YAF.Lucene.Net.Store.BufferedIndexInput;
using IndexInput = YAF.Lucene.Net.Store.IndexInput;
using MathUtil = YAF.Lucene.Net.Util.MathUtil;
/// <summary>
/// This abstract class reads skip lists with multiple levels.
/// <para/>
/// See <see cref="MultiLevelSkipListWriter"/> for the information about the encoding
/// of the multi level skip lists.
/// <para/>
/// Subclasses must implement the abstract method <see cref="ReadSkipData(int, IndexInput)"/>
/// which defines the actual format of the skip data.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class MultiLevelSkipListReader : IDisposable
{
/// <summary>
/// The maximum number of skip levels possible for this index. </summary>
protected internal int m_maxNumberOfSkipLevels;
// number of levels in this skip list
private int numberOfSkipLevels;
// Expert: defines the number of top skip levels to buffer in memory.
// Reducing this number results in less memory usage, but possibly
// slower performance due to more random I/Os.
// Please notice that the space each level occupies is limited by
// the skipInterval. The top level can not contain more than
// skipLevel entries, the second top level can not contain more
// than skipLevel^2 entries and so forth.
private int numberOfLevelsToBuffer = 1;
private int docCount;
private bool haveSkipped;
/// <summary>
/// SkipStream for each level. </summary>
private IndexInput[] skipStream;
/// <summary>
/// The start pointer of each skip level. </summary>
private long[] skipPointer;
/// <summary>
/// SkipInterval of each level. </summary>
private int[] skipInterval;
/// <summary>
/// Number of docs skipped per level. </summary>
private int[] numSkipped;
/// <summary>
/// Doc id of current skip entry per level. </summary>
protected internal int[] m_skipDoc;
/// <summary>
/// Doc id of last read skip entry with docId <= target. </summary>
private int lastDoc;
/// <summary>
/// Child pointer of current skip entry per level. </summary>
private long[] childPointer;
/// <summary>
/// childPointer of last read skip entry with docId <=
/// target.
/// </summary>
private long lastChildPointer;
private bool inputIsBuffered;
private readonly int skipMultiplier;
/// <summary>
/// Creates a <see cref="MultiLevelSkipListReader"/>. </summary>
protected MultiLevelSkipListReader(IndexInput skipStream, int maxSkipLevels, int skipInterval, int skipMultiplier)
{
this.skipStream = new IndexInput[maxSkipLevels];
this.skipPointer = new long[maxSkipLevels];
this.childPointer = new long[maxSkipLevels];
this.numSkipped = new int[maxSkipLevels];
this.m_maxNumberOfSkipLevels = maxSkipLevels;
this.skipInterval = new int[maxSkipLevels];
this.skipMultiplier = skipMultiplier;
this.skipStream[0] = skipStream;
this.inputIsBuffered = (skipStream is BufferedIndexInput);
this.skipInterval[0] = skipInterval;
for (int i = 1; i < maxSkipLevels; i++)
{
// cache skip intervals
this.skipInterval[i] = this.skipInterval[i - 1] * skipMultiplier;
}
m_skipDoc = new int[maxSkipLevels];
}
/// <summary>
/// Creates a <see cref="MultiLevelSkipListReader"/>, where
/// <see cref="skipInterval"/> and <see cref="skipMultiplier"/> are
/// the same.
/// </summary>
protected internal MultiLevelSkipListReader(IndexInput skipStream, int maxSkipLevels, int skipInterval)
: this(skipStream, maxSkipLevels, skipInterval, skipInterval)
{
}
/// <summary>
/// Returns the id of the doc to which the last call of <see cref="SkipTo(int)"/>
/// has skipped.
/// </summary>
public virtual int Doc
{
get
{
return lastDoc;
}
}
/// <summary>
/// Skips entries to the first beyond the current whose document number is
/// greater than or equal to <paramref name="target"/>. Returns the current doc count.
/// </summary>
public virtual int SkipTo(int target)
{
if (!haveSkipped)
{
// first time, load skip levels
LoadSkipLevels();
haveSkipped = true;
}
// walk up the levels until highest level is found that has a skip
// for this target
int level = 0;
while (level < numberOfSkipLevels - 1 && target > m_skipDoc[level + 1])
{
level++;
}
while (level >= 0)
{
if (target > m_skipDoc[level])
{
if (!LoadNextSkip(level))
{
continue;
}
}
else
{
// no more skips on this level, go down one level
if (level > 0 && lastChildPointer > skipStream[level - 1].GetFilePointer())
{
SeekChild(level - 1);
}
level--;
}
}
return numSkipped[0] - skipInterval[0] - 1;
}
private bool LoadNextSkip(int level)
{
// we have to skip, the target document is greater than the current
// skip list entry
SetLastSkipData(level);
numSkipped[level] += skipInterval[level];
if (numSkipped[level] > docCount)
{
// this skip list is exhausted
m_skipDoc[level] = int.MaxValue;
if (numberOfSkipLevels > level)
{
numberOfSkipLevels = level;
}
return false;
}
// read next skip entry
m_skipDoc[level] += ReadSkipData(level, skipStream[level]);
if (level != 0)
{
// read the child pointer if we are not on the leaf level
childPointer[level] = skipStream[level].ReadVInt64() + skipPointer[level - 1];
}
return true;
}
/// <summary>
/// Seeks the skip entry on the given level. </summary>
protected virtual void SeekChild(int level)
{
skipStream[level].Seek(lastChildPointer);
numSkipped[level] = numSkipped[level + 1] - skipInterval[level + 1];
m_skipDoc[level] = lastDoc;
if (level > 0)
{
childPointer[level] = skipStream[level].ReadVInt64() + skipPointer[level - 1];
}
}
/// <summary>
/// Disposes all resources used by this object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes all resources used by this object. Subclasses may override
/// to dispose their own resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
for (int i = 1; i < skipStream.Length; i++)
{
if (skipStream[i] != null)
{
skipStream[i].Dispose();
}
}
}
}
/// <summary>
/// Initializes the reader, for reuse on a new term. </summary>
public virtual void Init(long skipPointer, int df)
{
this.skipPointer[0] = skipPointer;
this.docCount = df;
Debug.Assert(skipPointer >= 0 && skipPointer <= skipStream[0].Length, "invalid skip pointer: " + skipPointer + ", length=" + skipStream[0].Length);
Array.Clear(m_skipDoc, 0, m_skipDoc.Length);
Array.Clear(numSkipped, 0, numSkipped.Length);
Array.Clear(childPointer, 0, childPointer.Length);
haveSkipped = false;
for (int i = 1; i < numberOfSkipLevels; i++)
{
skipStream[i] = null;
}
}
/// <summary>
/// Loads the skip levels. </summary>
private void LoadSkipLevels()
{
if (docCount <= skipInterval[0])
{
numberOfSkipLevels = 1;
}
else
{
numberOfSkipLevels = 1 + MathUtil.Log(docCount / skipInterval[0], skipMultiplier);
}
if (numberOfSkipLevels > m_maxNumberOfSkipLevels)
{
numberOfSkipLevels = m_maxNumberOfSkipLevels;
}
skipStream[0].Seek(skipPointer[0]);
int toBuffer = numberOfLevelsToBuffer;
for (int i = numberOfSkipLevels - 1; i > 0; i--)
{
// the length of the current level
long length = skipStream[0].ReadVInt64();
// the start pointer of the current level
skipPointer[i] = skipStream[0].GetFilePointer();
if (toBuffer > 0)
{
// buffer this level
skipStream[i] = new SkipBuffer(skipStream[0], (int)length);
toBuffer--;
}
else
{
// clone this stream, it is already at the start of the current level
skipStream[i] = (IndexInput)skipStream[0].Clone();
if (inputIsBuffered && length < BufferedIndexInput.BUFFER_SIZE)
{
((BufferedIndexInput)skipStream[i]).SetBufferSize((int)length);
}
// move base stream beyond the current level
skipStream[0].Seek(skipStream[0].GetFilePointer() + length);
}
}
// use base stream for the lowest level
skipPointer[0] = skipStream[0].GetFilePointer();
}
/// <summary>
/// Subclasses must implement the actual skip data encoding in this method.
/// </summary>
/// <param name="level"> The level skip data shall be read from. </param>
/// <param name="skipStream"> The skip stream to read from. </param>
protected abstract int ReadSkipData(int level, IndexInput skipStream);
/// <summary>
/// Copies the values of the last read skip entry on this <paramref name="level"/>. </summary>
protected virtual void SetLastSkipData(int level)
{
lastDoc = m_skipDoc[level];
lastChildPointer = childPointer[level];
}
/// <summary>
/// Used to buffer the top skip levels. </summary>
private sealed class SkipBuffer : IndexInput
{
private byte[] data;
private long pointer;
private int pos;
internal SkipBuffer(IndexInput input, int length)
: base("SkipBuffer on " + input)
{
data = new byte[length];
pointer = input.GetFilePointer();
input.ReadBytes(data, 0, length);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
data = null;
}
}
public override long GetFilePointer()
{
return pointer + pos;
}
public override long Length
{
get { return data.Length; }
}
public override byte ReadByte()
{
return data[pos++];
}
public override void ReadBytes(byte[] b, int offset, int len)
{
Array.Copy(data, pos, b, offset, len);
pos += len;
}
public override void Seek(long pos)
{
this.pos = (int)(pos - pointer);
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="XmlIndexDataStore.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using DataAccessLayer;
namespace ConcreteDataStore
{
/// <summary>
/// DataSet based store for Index data. IIndexStore is the only interface that non-test callers of this assembly
/// can use. That is what will be returned from XmlIndexStoreFactory.
/// </summary>
internal class XmlIndexDataStore : XmlDataStoreBase, IIndexStore
{
/// <summary>singleton lock object.</summary>
private static readonly object LockObj = new object();
/// <summary>The one and only data store object.</summary>
private static XmlIndexDataStore indexDataStore;
/// <summary>singleton initialization flag.</summary>
private static bool initialized = false;
/// <summary>Initializes a new instance of the <see cref="XmlIndexDataStore"/> class.</summary>
public XmlIndexDataStore() : base(new XmlIndexDataSet())
{
}
/// <summary>Gets IndexDataSet.</summary>
private XmlIndexDataSet IndexDataSet
{
get { return (XmlIndexDataSet)this.DataSet; }
}
/// <summary>Gets or initializes a singleton data store instance.</summary>
/// <param name="backingFile">The backing file.</param>
/// <returns>The data store object.</returns>
public static XmlIndexDataStore GetInstance(string backingFile)
{
if (!initialized)
{
lock (LockObj)
{
if (!initialized)
{
indexDataStore = new XmlIndexDataStore();
indexDataStore.LoadFromFile(backingFile);
// Make sure flag initialization isn't reordered by the compiler.
System.Threading.Thread.MemoryBarrier();
initialized = true;
}
}
}
return indexDataStore;
}
////
// Begin IIndexStore Members
////
/// <summary>Get the key fields from the index given an external entity Id.</summary>
/// <param name="externalEntityId">The external entity id.</param>
/// <param name="storageAccountName">The storage account name.</param>
/// <returns>Storage key for this entity.</returns>
public IStorageKey GetStorageKey(EntityId externalEntityId, string storageAccountName)
{
// The fact that we are an Xml DataSet index doesn't mean the entity store is Xml.
// Get the storage type
var indexRecord = this.IndexDataSet.EntityId.SingleOrDefault(r => r.xId == (Guid)externalEntityId);
// Might be checking if a record exists
if (indexRecord == null)
{
return null;
}
var storageType = indexRecord.StorageType;
// Get the fields based on the storage type
var keyFields = this.GetKeyFieldsByStorageType(externalEntityId, storageType);
return keyFields;
}
/// <summary>
/// Retrieve a list of entities of a given entity category.
/// </summary>
/// <param name="entityCategory">The entity category.</param>
/// <returns>
/// A list of minimally populated raw entities.
/// </returns>
public IList<IEntity> GetEntityInfoByCategory(string entityCategory)
{
throw new NotImplementedException();
}
/// <summary>
/// Get index data for an entity at a specific version.
/// </summary>
/// <param name="externalEntityId">The external entity id.</param><param name="storageAccountName">The storage account name.</param><param name="version">The entity version to get. Null for current.</param>
/// <returns>
/// A partially populated entity with the key.
/// </returns>
public IEntity GetEntity(EntityId externalEntityId, string storageAccountName, int? version)
{
throw new NotImplementedException();
}
/// <summary>Save a reference to an entity in the index store.</summary>
/// <param name="rawEntity">The raw entity.</param>
/// <param name="isUpdate">True if this is an update of an existing entity.</param>
public void SaveEntity(IEntity rawEntity, bool isUpdate = false)
{
if (isUpdate)
{
this.UpdateIndexEntry(rawEntity);
}
// The fact that we are an Xml DataSet index doesn't mean the entity store is Xml.
// Save the key fields for the specific data store type
var storageType = this.IndexDataSet.StorageAccount
.Single(r => r.StorageAccountName == rawEntity.Key.StorageAccountName).StorageType;
this.SaveKeyFieldsByStorageType(rawEntity, storageType);
// TODO: Harden this if the entity already exists in the index
// Create the entity index row object
var xmlEntityIndexRow = this.IndexDataSet.EntityId.NewEntityIdRow();
xmlEntityIndexRow.xId = rawEntity.ExternalEntityId;
xmlEntityIndexRow.HomeStorageAccountName = rawEntity.Key.StorageAccountName;
xmlEntityIndexRow.StorageType = storageType;
xmlEntityIndexRow.CreateDate = rawEntity.CreateDate;
xmlEntityIndexRow.LastModifiedDate = rawEntity.LastModifiedDate;
xmlEntityIndexRow.Version = rawEntity.LocalVersion;
xmlEntityIndexRow.WriteLock = false;
// Add the row objects
this.IndexDataSet.EntityId.AddEntityIdRow(xmlEntityIndexRow);
this.Commit();
}
/// <summary>
/// Set an entity status to active or inactive.
/// </summary>
/// <param name="entityIds">The entity ids.</param><param name="active">True to set active, false for inactive.</param>
public void SetEntityStatus(HashSet<EntityId> entityIds, bool active)
{
throw new NotImplementedException();
}
////
// End IIndexStore Members
////
////
// Begin XmlDataStoreBase Overrides
////
/// <summary>Load data store from xml string.</summary>
/// <param name="xmlData">An xml string conforming to the XmlDataStore schema.</param>
public override void LoadFromXml(string xmlData)
{
this.ReadTableData(xmlData);
}
////
// End XmlDataStoreBase Overrides
////
/// <summary>We just need to update the index metadata (not the keys fields).</summary>
/// <param name="rawEntity">The raw entity.</param>
private void UpdateIndexEntry(IEntity rawEntity)
{
var dataSet = this.IndexDataSet;
var entityIdRow = (from entity in dataSet.EntityId
where entity.xId == (Guid)rawEntity.ExternalEntityId
select entity).Single();
entityIdRow.Version = rawEntity.LocalVersion;
entityIdRow.LastModifiedDate = rawEntity.LastModifiedDate;
this.Commit();
}
/// <summary>Get the keyfields of an entity based on the data store type.</summary>
/// <param name="externalEntityId">The external entity id.</param>
/// <param name="storageType">The storage type.</param>
/// <returns>IStorageKey of the type for the entity store.</returns>
private IStorageKey GetKeyFieldsByStorageType(EntityId externalEntityId, string storageType)
{
// TODO: define an enum for these if they are needed in an AzureSql index
if (storageType == "Xml")
{
return this.GetXmlKeyFields(externalEntityId);
}
if (storageType == "AzureTable")
{
return this.GetAzureKeyFields(externalEntityId);
}
if (storageType == "S3Table")
{
return this.GetS3KeyFields(externalEntityId);
}
return null;
}
/// <summary>Get key fields for an Xml DataSet based data store.</summary>
/// <param name="externalEntityId">The external entity id.</param>
/// <returns>Dictionary of key fields.</returns>
private XmlStorageKey GetXmlKeyFields(Guid externalEntityId)
{
var dataSet = this.IndexDataSet;
var dataTable = dataSet.XmlKeyFields;
var result = (from entity in dataSet.EntityId
join keyFieldsRow in dataTable on
new { Id = entity.xId, Acc = entity.HomeStorageAccountName } equals
new { Id = keyFieldsRow.xId, Acc = keyFieldsRow.StorageAccountName }
where entity.xId == externalEntityId
select keyFieldsRow).Single();
return new XmlStorageKey(result.StorageAccountName, result.TableName, result.Partition, result.RowId);
}
/// <summary>Get key fields for an Azure Table based data store.</summary>
/// <param name="externalEntityId">The external entity id.</param>
/// <returns>Dictionary of key fields.</returns>
private AzureStorageKey GetAzureKeyFields(Guid externalEntityId)
{
var dataSet = this.IndexDataSet;
var dataTable = dataSet.AzureKeyFields;
var result = (from entity in dataSet.EntityId
join keyFieldsRow in dataTable on
new { Id = entity.xId, Acc = entity.HomeStorageAccountName } equals
new { Id = keyFieldsRow.xId, Acc = keyFieldsRow.StorageAccountName }
where entity.xId == externalEntityId
select keyFieldsRow).Single();
return new AzureStorageKey(result.StorageAccountName, result.TableName, result.Partition, result.RowId);
}
/// <summary>Get key fields for an S3 Table based data store.</summary>
/// <param name="externalEntityId">The external entity id.</param>
/// <returns>Dictionary of key fields.</returns>
private S3StorageKey GetS3KeyFields(Guid externalEntityId)
{
var dataSet = this.IndexDataSet;
var dataTable = dataSet.S3KeyFields;
var result = (from entity in dataSet.EntityId
join keyFieldsRow in dataTable on
new { Id = entity.xId, Acc = entity.HomeStorageAccountName } equals
new { Id = keyFieldsRow.xId, Acc = keyFieldsRow.StorageAccountName }
where entity.xId == externalEntityId
select keyFieldsRow).Single();
return new S3StorageKey(result.StorageAccountName, result.TBDS3);
}
/// <summary>Save the key fields for the corresponding type of data store.</summary>
/// <param name="rawEntity">The raw entity.</param>
/// <param name="storageType">The storage type.</param>
private void SaveKeyFieldsByStorageType(IEntity rawEntity, string storageType)
{
// TODO: define an enum for these
if (storageType == "Xml")
{
this.SaveXmlKeyFields(rawEntity);
}
if (storageType == "AzureTable")
{
this.SaveAzureKeyFields(rawEntity);
}
if (storageType == "S3Table")
{
this.SaveS3KeyFields(rawEntity);
}
}
/// <summary>Save key fields for an Xml data store.</summary>
/// <param name="rawEntity">The raw entity.</param>
private void SaveXmlKeyFields(IEntity rawEntity)
{
// Create the keyfields row object
var xmlRawEntity = (XmlRawEntity)rawEntity;
var xmlKey = (XmlStorageKey)xmlRawEntity.Key;
var xmlKeyFieldsRow = this.IndexDataSet.XmlKeyFields.NewXmlKeyFieldsRow();
xmlKeyFieldsRow.xId = rawEntity.ExternalEntityId;
xmlKeyFieldsRow.StorageAccountName = xmlKey.StorageAccountName;
xmlKeyFieldsRow.TableName = xmlKey.TableName;
xmlKeyFieldsRow.Partition = xmlKey.Partition;
xmlKeyFieldsRow.RowId = xmlKey.RowId;
xmlKeyFieldsRow.LocalVersion = rawEntity.LocalVersion;
// Add the row objects
this.IndexDataSet.XmlKeyFields.AddXmlKeyFieldsRow(xmlKeyFieldsRow);
}
/// <summary>Save key fields for an Azure Table data store.</summary>
/// <param name="rawEntity">The raw entity.</param>
private void SaveAzureKeyFields(IEntity rawEntity)
{
// Create the keyfields row object
var storageKey = (AzureStorageKey)rawEntity.Key;
var azureKeyFieldsRow = this.IndexDataSet.AzureKeyFields.NewAzureKeyFieldsRow();
azureKeyFieldsRow.xId = rawEntity.ExternalEntityId;
azureKeyFieldsRow.StorageAccountName = storageKey.StorageAccountName;
azureKeyFieldsRow.TableName = storageKey.TableName;
azureKeyFieldsRow.Partition = storageKey.Partition;
azureKeyFieldsRow.RowId = storageKey.RowId;
azureKeyFieldsRow.LocalVersion = rawEntity.LocalVersion;
// Add the row objects
this.IndexDataSet.AzureKeyFields.AddAzureKeyFieldsRow(azureKeyFieldsRow);
}
/// <summary>Save key fields for an S3 data store.</summary>
/// <param name="rawEntity">The raw entity.</param>
private void SaveS3KeyFields(IEntity rawEntity)
{
// TODO: Implement an S3RawEntity and populate the rest of the fields
var aws3KeyFieldsRow = this.IndexDataSet.S3KeyFields.NewS3KeyFieldsRow();
aws3KeyFieldsRow.StorageAccountName = rawEntity.Key.StorageAccountName;
}
}
}
| |
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using AnalyseVisitorsTool.Models;
using AnalyseVisitorsTool.Models.AccountViewModels;
using AnalyseVisitorsTool.Services;
namespace AnalyseVisitorsTool.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
#if CORECLR
// Use stub for SystemException, SerializationInfo, SerializableAttribute and Serializable
// It is needed for WriteErrorException which ONLY used in Write-Error cmdlet.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace Microsoft.PowerShell.Commands
{
#region WriteDebugCommand
/// <summary>
/// This class implements Write-Debug command
///
/// </summary>
[Cmdlet("Write", "Debug", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113424", RemotingCapability = RemotingCapability.None)]
public sealed class WriteDebugCommand : PSCmdlet
{
/// <summary>
/// Message to be sent and processed if debug mode is on.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// This method implements the ProcessRecord method for Write-Debug command
/// </summary>
protected override void ProcessRecord()
{
//
// The write-debug command must use the script's InvocationInfo rather than its own,
// so we create the DebugRecord here and fill it up with the appropriate InvocationInfo;
// then, we call the command runtime directly and pass this record to WriteDebug().
//
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
if (mshCommandRuntime != null)
{
DebugRecord record = new DebugRecord(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
{
record.SetInvocationInfo(invocationInfo);
}
mshCommandRuntime.WriteDebug(record);
}
else
{
WriteDebug(Message);
}
}//processrecord
}//WriteDebugCommand
#endregion WriteDebugCommand
#region WriteVerboseCommand
/// <summary>
/// This class implements Write-Verbose command
///
/// </summary>
[Cmdlet("Write", "Verbose", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113429", RemotingCapability = RemotingCapability.None)]
public sealed class WriteVerboseCommand : PSCmdlet
{
/// <summary>
/// Message to be sent if verbose messages are being shown.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// This method implements the ProcessRecord method for Write-verbose command
/// </summary>
protected override void ProcessRecord()
{
//
// The write-verbose command must use the script's InvocationInfo rather than its own,
// so we create the VerboseRecord here and fill it up with the appropriate InvocationInfo;
// then, we call the command runtime directly and pass this record to WriteVerbose().
//
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
if (mshCommandRuntime != null)
{
VerboseRecord record = new VerboseRecord(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
{
record.SetInvocationInfo(invocationInfo);
}
mshCommandRuntime.WriteVerbose(record);
}
else
{
WriteVerbose(Message);
}
}//processrecord
}//WriteVerboseCommand
#endregion WriteVerboseCommand
#region WriteWarningCommand
/// <summary>
/// This class implements Write-Warning command
///
/// </summary>
[Cmdlet("Write", "Warning", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113430", RemotingCapability = RemotingCapability.None)]
public sealed class WriteWarningCommand : PSCmdlet
{
/// <summary>
/// Message to be sent if warning messages are being shown.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// This method implements the ProcessRecord method for Write-Warning command
/// </summary>
protected override void ProcessRecord()
{
//
// The write-warning command must use the script's InvocationInfo rather than its own,
// so we create the WarningRecord here and fill it up with the appropriate InvocationInfo;
// then, we call the command runtime directly and pass this record to WriteWarning().
//
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
if (mshCommandRuntime != null)
{
WarningRecord record = new WarningRecord(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
{
record.SetInvocationInfo(invocationInfo);
}
mshCommandRuntime.WriteWarning(record);
}
else
{
WriteWarning(Message);
}
}//processrecord
}//WriteWarningCommand
#endregion WriteWarningCommand
#region WriteInformationCommand
/// <summary>
/// This class implements Write-Information command
///
/// </summary>
[Cmdlet(VerbsCommunications.Write, "Information", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=525909", RemotingCapability = RemotingCapability.None)]
public sealed class WriteInformationCommand : PSCmdlet
{
/// <summary>
/// Object to be sent to the Information stream.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
[Alias("Msg")]
public Object MessageData { get; set; }
/// <summary>
/// Any tags to be associated with this information
/// </summary>
[Parameter(Position = 1)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Tags { get; set; }
/// <summary>
/// This method implements the processing of the Write-Information command
/// </summary>
protected override void BeginProcessing()
{
if (Tags != null)
{
foreach (string tag in Tags)
{
if (tag.StartsWith("PS", StringComparison.OrdinalIgnoreCase))
{
ErrorRecord er = new ErrorRecord(
new InvalidOperationException(StringUtil.Format(UtilityCommonStrings.PSPrefixReservedInInformationTag, tag)),
"PSPrefixReservedInInformationTag", ErrorCategory.InvalidArgument, tag);
ThrowTerminatingError(er);
}
}
}
}
/// <summary>
/// This method implements the ProcessRecord method for Write-Information command
/// </summary>
protected override void ProcessRecord()
{
WriteInformation(MessageData, Tags);
}
}//WriteInformationCommand
#endregion WriteInformationCommand
#region WriteOrThrowErrorCommand
/// <summary>
/// This class implements the Write-Error command
/// </summary>
public class WriteOrThrowErrorCommand : PSCmdlet
{
/// <summary>
/// ErrorRecord.Exception -- if not specified, ErrorRecord.Exception is
/// System.Exception.
/// </summary>
[Parameter(ParameterSetName = "WithException", Mandatory = true)]
public Exception Exception { get; set; } = null;
/// <summary>
/// If Exception is specified, this is ErrorRecord.ErrorDetails.Message.
/// Otherwise, the Exception is System.Exception, and this is
/// Exception.Message.
/// </summary>
[Parameter(Position = 0, ParameterSetName = "NoException", Mandatory = true, ValueFromPipeline = true)]
[Parameter(ParameterSetName = "WithException")]
[AllowNull]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// If Exception is specified, this is ErrorRecord.ErrorDetails.Message.
/// Otherwise, the Exception is System.Exception, and this is
/// Exception.Message.
/// </summary>
[Parameter(ParameterSetName = "ErrorRecord", Mandatory = true)]
public ErrorRecord ErrorRecord { get; set; } = null;
/// <summary>
/// ErrorRecord.CategoryInfo.Category
/// </summary>
[Parameter(ParameterSetName = "NoException")]
[Parameter(ParameterSetName = "WithException")]
public ErrorCategory Category { get; set; } = ErrorCategory.NotSpecified;
/// <summary>
/// ErrorRecord.ErrorId
/// </summary>
[Parameter(ParameterSetName = "NoException")]
[Parameter(ParameterSetName = "WithException")]
public string ErrorId { get; set; } = "";
/// <summary>
/// ErrorRecord.TargetObject
/// </summary>
[Parameter(ParameterSetName = "NoException")]
[Parameter(ParameterSetName = "WithException")]
public object TargetObject { get; set; } = null;
/// <summary>
/// ErrorRecord.ErrorDetails.RecommendedAction
/// </summary>
[Parameter]
public string RecommendedAction { get; set; } = "";
/* 2005/01/25 removing throw-error
/// <summary>
/// If true, this is throw-error. Otherwise, this is write-error.
/// </summary>
internal bool _terminating = false;
*/
/// <summary>
/// ErrorRecord.CategoryInfo.Activity
/// </summary>
[Parameter]
[Alias("Activity")]
public string CategoryActivity { get; set; } = "";
/// <summary>
/// ErrorRecord.CategoryInfo.Reason
/// </summary>
[Parameter]
[Alias("Reason")]
public string CategoryReason { get; set; } = "";
/// <summary>
/// ErrorRecord.CategoryInfo.TargetName
/// </summary>
[Parameter]
[Alias("TargetName")]
public string CategoryTargetName { get; set; } = "";
/// <summary>
/// ErrorRecord.CategoryInfo.TargetType
/// </summary>
[Parameter]
[Alias("TargetType")]
public string CategoryTargetType { get; set; } = "";
/// <summary>
/// Write an error to the output pipe, or throw a terminating error.
/// </summary>
protected override void ProcessRecord()
{
ErrorRecord errorRecord = this.ErrorRecord;
if (null != errorRecord)
{
// copy constructor
errorRecord = new ErrorRecord(errorRecord, null);
}
else
{
Exception e = this.Exception;
string msg = Message;
if (null == e)
{
e = new WriteErrorException(msg);
}
string errid = ErrorId;
if (String.IsNullOrEmpty(errid))
{
errid = e.GetType().FullName;
}
errorRecord = new ErrorRecord(
e,
errid,
Category,
TargetObject
);
if ((null != this.Exception && !String.IsNullOrEmpty(msg)))
{
errorRecord.ErrorDetails = new ErrorDetails(msg);
}
}
string recact = RecommendedAction;
if (!String.IsNullOrEmpty(recact))
{
if (null == errorRecord.ErrorDetails)
{
errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString());
}
errorRecord.ErrorDetails.RecommendedAction = recact;
}
if (!String.IsNullOrEmpty(CategoryActivity))
errorRecord.CategoryInfo.Activity = CategoryActivity;
if (!String.IsNullOrEmpty(CategoryReason))
errorRecord.CategoryInfo.Reason = CategoryReason;
if (!String.IsNullOrEmpty(CategoryTargetName))
errorRecord.CategoryInfo.TargetName = CategoryTargetName;
if (!String.IsNullOrEmpty(CategoryTargetType))
errorRecord.CategoryInfo.TargetType = CategoryTargetType;
/* 2005/01/25 removing throw-error
if (_terminating)
{
ThrowTerminatingError(errorRecord);
}
else
{
*/
// 2005/07/14-913791 "write-error output is confusing and misleading"
// set InvocationInfo to the script not the command
InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (null != myInvocation)
{
errorRecord.SetInvocationInfo(myInvocation);
errorRecord.PreserveInvocationInfoOnce = true;
if (!String.IsNullOrEmpty(CategoryActivity))
errorRecord.CategoryInfo.Activity = CategoryActivity;
else
errorRecord.CategoryInfo.Activity = "Write-Error";
}
WriteError(errorRecord);
/*
}
*/
}//processrecord
}//WriteOrThrowErrorCommand
/// <summary>
/// This class implements Write-Error command
/// </summary>
[Cmdlet("Write", "Error", DefaultParameterSetName = "NoException",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113425", RemotingCapability = RemotingCapability.None)]
public sealed class WriteErrorCommand : WriteOrThrowErrorCommand
{
/// <summary>
/// constructor
/// </summary>
public WriteErrorCommand()
{
}
}
/* 2005/01/25 removing throw-error
/// <summary>
/// This class implements Write-Error command
/// </summary>
[Cmdlet("Throw", "Error", DefaultParameterSetName = "NoException")]
public sealed class ThrowErrorCommand : WriteOrThrowErrorCommand
{
/// <summary>
/// constructor
/// </summary>
public ThrowErrorCommand()
{
using (tracer.TraceConstructor(this))
{
_terminating = true;
}
}
}
*/
#endregion WriteOrThrowErrorCommand
#region WriteErrorException
/// <summary>
/// The write-error cmdlet uses WriteErrorException
/// when the user only specifies a string and not
/// an Exception or ErrorRecord.
/// </summary>
[Serializable]
public class WriteErrorException : SystemException
{
#region ctor
/// <summary>
/// Constructor for class WriteErrorException
/// </summary>
/// <returns> constructed object </returns>
public WriteErrorException()
: base(StringUtil.Format(WriteErrorStrings.WriteErrorException))
{
}
/// <summary>
/// Constructor for class WriteErrorException
/// </summary>
/// <param name="message"> </param>
/// <returns> constructed object </returns>
public WriteErrorException(string message)
: base(message)
{
}
/// <summary>
/// Constructor for class WriteErrorException
/// </summary>
/// <param name="message"> </param>
/// <param name="innerException"> </param>
/// <returns> constructed object </returns>
public WriteErrorException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Serialization constructor for class WriteErrorException
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
/// <returns> constructed object </returns>
protected WriteErrorException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
} // WriteErrorException
#endregion WriteErrorException
} //namespace
| |
using System;
using System.Data;
namespace Epi.Epi2000
{
/// <summary>
/// A page in an Epi2000 project
/// </summary>
public class Page
{
#region Fields
private int position = 0;
private string name = string.Empty;
private string checkCodeBefore = string.Empty;
private string checkCodeAfter = string.Empty;
#endregion Fields
#region Constructors
/// <summary>
/// Constructs a page linked to a view
/// </summary>
/// <param name="view">A view object</param>
public Page(View view)
{
}
/// <summary>
/// Constructs a page from database table row
/// </summary>
/// <param name="row"></param>
/// <param name="view"></param>
public Page(DataRow row, View view)
{
if (row[ColumnNames.NAME] != DBNull.Value)
this.Name = row[ColumnNames.NAME].ToString();
// zero based Position in Epi 7
this.Position = Math.Abs(short.Parse(row[ColumnNames.PAGE_NUMBER].ToString())) - 1;
string checkCodeBlock = row[ColumnNames.CHECK_CODE].ToString();
RebuildCheckCode(checkCodeBlock, view);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Returns or sets the Id
/// </summary>
public int Id
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
/// Returns the name of the page
/// </summary>
public string Name
{
get
{
return (name);
}
set
{
name = value;
}
}
/// <summary>
/// Position of the page in it's views
/// </summary>
public int Position
{
get
{
return (position);
}
set
{
position = value;
}
}
/// <summary>
/// Check code that executes after all the data is entered on the page
/// </summary>
public string CheckCodeAfter
{
get
{
return (checkCodeAfter);
}
set
{
checkCodeAfter = value;
}
}
/// <summary>
/// Check code that executes before the page is loaded for data entry
/// </summary>
public string CheckCodeBefore
{
get
{
return (checkCodeBefore);
}
set
{
checkCodeBefore = value;
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Copies a page object into this one.
/// </summary>
/// <param name="other">The page</param>
public void CopyTo(Epi.Page other)
{
other.Name = this.Name;
other.Position = this.Position;
other.CheckCodeBefore = this.CheckCodeBefore;
other.CheckCodeAfter = this.CheckCodeAfter;
}
/// <summary>
/// Rebuilds the check code for the page
/// </summary>
/// <param name="checkCodeBlock">The check code block</param>
/// <param name="view">The view</param>
public void RebuildCheckCode(string checkCodeBlock, View view)
{
if (checkCodeBlock == null)
{
return;
}
System.Text.StringBuilder CheckCode = new System.Text.StringBuilder();
bool PageHasBeforeCheckCode = false;
bool PageHasAfterCheckCode = false;
string ckBefore = string.Empty;
string ckAfter = string.Empty;
Epi2000.MetadataDbProvider.SplitCheckCode(checkCodeBlock, ref ckBefore, ref ckAfter);
if (!string.IsNullOrEmpty(ckAfter))
{
PageHasAfterCheckCode = true;
}
if (!string.IsNullOrEmpty(ckBefore))
{
PageHasBeforeCheckCode = true;
}
if (PageHasBeforeCheckCode || PageHasAfterCheckCode)
{
CheckCode.Append("\nPage ");
if (this.name.Trim().IndexOf(' ') > -1 || this.name.ToLowerInvariant().Equals("page"))
{
CheckCode.Append("[");
CheckCode.Append(this.name.Trim().Replace("&", string.Empty)); // Imported page names can't have & symbol
CheckCode.Append("]");
}
else
{
CheckCode.Append(this.name.Trim().Replace("&", string.Empty)); // Imported page names can't have & symbol
}
if (PageHasBeforeCheckCode)
{
CheckCode.Append("\n\tBefore\n\t\t");
CheckCode.Append(ckBefore.Replace("\n", "\n\t\t"));
CheckCode.Append("\n\tEnd-Before\n");
}
if (PageHasAfterCheckCode)
{
CheckCode.Append("\n\tAfter\n\t\t");
CheckCode.Append(ckAfter.Replace("\n", "\n\t\t"));
CheckCode.Append("\n\tEnd-After\n");
}
CheckCode.Append("End-Page\n");
}
this.CheckCodeBefore = CheckCode.ToString();
}
#endregion Public Methods
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.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
/// reserved IPs for your subscription.
/// </summary>
internal partial class ReservedIPOperations : IServiceOperations<NetworkManagementClient>, Microsoft.WindowsAzure.Management.Network.IReservedIPOperations
{
/// <summary>
/// Initializes a new instance of the ReservedIPOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ReservedIPOperations(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 Begin Creating Reserved IP operation creates a reserved IP from
/// your the subscription.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Creating Reserved IP
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<OperationStatusResponse> BeginCreatingAsync(NetworkReservedIPCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// 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("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/reservedips";
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 = null;
XDocument requestDoc = new XDocument();
XElement reservedIPElement = new XElement(XName.Get("ReservedIP", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(reservedIPElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
reservedIPElement.Add(nameElement);
}
if (parameters.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = parameters.Label;
reservedIPElement.Add(labelElement);
}
if (parameters.Location != null)
{
XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
locationElement.Value = parameters.Location;
reservedIPElement.Add(locationElement);
}
if (parameters.ServiceName != null)
{
XElement serviceNameElement = new XElement(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure"));
serviceNameElement.Value = parameters.ServiceName;
reservedIPElement.Add(serviceNameElement);
}
if (parameters.DeploymentName != null)
{
XElement deploymentNameElement = new XElement(XName.Get("DeploymentName", "http://schemas.microsoft.com/windowsazure"));
deploymentNameElement.Value = parameters.DeploymentName;
reservedIPElement.Add(deploymentNameElement);
}
requestContent = requestDoc.ToString();
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
OperationStatusResponse result = null;
result = new OperationStatusResponse();
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 Begin Deleting Reserved IP operation removes a reserved IP from
/// your the subscription.
/// </summary>
/// <param name='ipName'>
/// Required. The name of the reserved IP.
/// </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<OperationResponse> BeginDeletingAsync(string ipName, CancellationToken cancellationToken)
{
// Validate
if (ipName == null)
{
throw new ArgumentNullException("ipName");
}
// 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("ipName", ipName);
Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/reservedips/" + ipName.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.Accepted)
{
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
OperationResponse result = null;
result = new OperationResponse();
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 Create Reserved IP operation creates a reserved IP from your
/// the subscription.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Reserved IP operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<OperationStatusResponse> CreateAsync(NetworkReservedIPCreateParameters parameters, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
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("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.ReservedIPs.BeginCreatingAsync(parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// The Delete Reserved IP operation removes a reserved IP from your
/// the subscription.
/// </summary>
/// <param name='ipName'>
/// Required. The name of the reserved IP.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<OperationStatusResponse> DeleteAsync(string ipName, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
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("ipName", ipName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
OperationResponse response = await client.ReservedIPs.BeginDeletingAsync(ipName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// The Get Reserved IP operation retrieves the details for the virtual
/// IP reserved for the subscription.
/// </summary>
/// <param name='ipName'>
/// Required. The name of the reserved IP to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A reserved IP associated with your subscription.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.NetworkReservedIPGetResponse> GetAsync(string ipName, CancellationToken cancellationToken)
{
// Validate
if (ipName == null)
{
throw new ArgumentNullException("ipName");
}
// 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("ipName", ipName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/reservedips/" + ipName.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
NetworkReservedIPGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkReservedIPGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement reservedIPElement = responseDoc.Element(XName.Get("ReservedIP", "http://schemas.microsoft.com/windowsazure"));
if (reservedIPElement != null)
{
XElement nameElement = reservedIPElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
result.Name = nameInstance;
}
XElement addressElement = reservedIPElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
if (addressElement != null)
{
string addressInstance = addressElement.Value;
result.Address = addressInstance;
}
XElement idElement = reservedIPElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement labelElement = reservedIPElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = labelElement.Value;
result.Label = labelInstance;
}
XElement stateElement = reservedIPElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
result.State = stateInstance;
}
XElement inUseElement = reservedIPElement.Element(XName.Get("InUse", "http://schemas.microsoft.com/windowsazure"));
if (inUseElement != null)
{
bool inUseInstance = bool.Parse(inUseElement.Value);
result.InUse = inUseInstance;
}
XElement serviceNameElement = reservedIPElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure"));
if (serviceNameElement != null)
{
string serviceNameInstance = serviceNameElement.Value;
result.ServiceName = serviceNameInstance;
}
XElement deploymentNameElement = reservedIPElement.Element(XName.Get("DeploymentName", "http://schemas.microsoft.com/windowsazure"));
if (deploymentNameElement != null)
{
string deploymentNameInstance = deploymentNameElement.Value;
result.DeploymentName = deploymentNameInstance;
}
XElement locationElement = reservedIPElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
result.Location = locationInstance;
}
}
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 Reserved IP operation retrieves all of the virtual IPs
/// reserved for the subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response structure for the Server List operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.NetworkReservedIPListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/reservedips";
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
NetworkReservedIPListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new NetworkReservedIPListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement reservedIPsSequenceElement = responseDoc.Element(XName.Get("ReservedIPs", "http://schemas.microsoft.com/windowsazure"));
if (reservedIPsSequenceElement != null)
{
foreach (XElement reservedIPsElement in reservedIPsSequenceElement.Elements(XName.Get("ReservedIP", "http://schemas.microsoft.com/windowsazure")))
{
NetworkReservedIPListResponse.ReservedIP reservedIPInstance = new NetworkReservedIPListResponse.ReservedIP();
result.ReservedIPs.Add(reservedIPInstance);
XElement nameElement = reservedIPsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
reservedIPInstance.Name = nameInstance;
}
XElement addressElement = reservedIPsElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
if (addressElement != null)
{
string addressInstance = addressElement.Value;
reservedIPInstance.Address = addressInstance;
}
XElement idElement = reservedIPsElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
reservedIPInstance.Id = idInstance;
}
XElement labelElement = reservedIPsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = labelElement.Value;
reservedIPInstance.Label = labelInstance;
}
XElement stateElement = reservedIPsElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
reservedIPInstance.State = stateInstance;
}
XElement inUseElement = reservedIPsElement.Element(XName.Get("InUse", "http://schemas.microsoft.com/windowsazure"));
if (inUseElement != null)
{
bool inUseInstance = bool.Parse(inUseElement.Value);
reservedIPInstance.InUse = inUseInstance;
}
XElement serviceNameElement = reservedIPsElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure"));
if (serviceNameElement != null)
{
string serviceNameInstance = serviceNameElement.Value;
reservedIPInstance.ServiceName = serviceNameInstance;
}
XElement deploymentNameElement = reservedIPsElement.Element(XName.Get("DeploymentName", "http://schemas.microsoft.com/windowsazure"));
if (deploymentNameElement != null)
{
string deploymentNameInstance = deploymentNameElement.Value;
reservedIPInstance.DeploymentName = deploymentNameInstance;
}
XElement locationElement = reservedIPsElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
reservedIPInstance.Location = locationInstance;
}
}
}
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();
}
}
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
// Based on the work by https://github.com/keijiro/NoiseShader
using System;
using UnityEditor;
using UnityEngine;
namespace AmplifyShaderEditor
{
public enum NoiseGeneratorType
{
Simplex2D,
Simplex3D
};
[Serializable]
[NodeAttributes( "Noise Generator", "Image Effects", "Collection of procedural noise generators" )]
public sealed class NoiseGeneratorNode : ParentNode
{
private const string TypeLabelStr = "Type";
// Simplex 2D
private const string Simplex2DFloat3Mod289Func = "float3 mod289( float3 x ) { return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0; }";
private const string Simplex2DFloat2Mod289Func = "float2 mod289( float2 x ) { return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0; }";
private const string Simplex2DPermuteFunc = "float3 permute( float3 x ) { return mod289( ( ( x * 34.0 ) + 1.0 ) * x ); }";
private const string SimplexNoise2DHeader = "float snoise( float2 v )";
private const string SimplexNoise2DFunc = "snoise( {0} )";
private readonly string[] SimplexNoise2DBody = { "const float4 C = float4( 0.211324865405187, 0.366025403784439, -0.577350269189626, 0.024390243902439 );",
"float2 i = floor( v + dot( v, C.yy ) );",
"float2 x0 = v - i + dot( i, C.xx );",
"float2 i1;",
"i1 = ( x0.x > x0.y ) ? float2( 1.0, 0.0 ) : float2( 0.0, 1.0 );",
"float4 x12 = x0.xyxy + C.xxzz;",
"x12.xy -= i1;",
"i = mod289( i );",
"float3 p = permute( permute( i.y + float3( 0.0, i1.y, 1.0 ) ) + i.x + float3( 0.0, i1.x, 1.0 ) );",
"float3 m = max( 0.5 - float3( dot( x0, x0 ), dot( x12.xy, x12.xy ), dot( x12.zw, x12.zw ) ), 0.0 );",
"m = m * m;",
"m = m * m;",
"float3 x = 2.0 * frac( p * C.www ) - 1.0;",
"float3 h = abs( x ) - 0.5;",
"float3 ox = floor( x + 0.5 );",
"float3 a0 = x - ox;",
"m *= 1.79284291400159 - 0.85373472095314 * ( a0 * a0 + h * h );",
"float3 g;",
"g.x = a0.x * x0.x + h.x * x0.y;",
"g.yz = a0.yz * x12.xz + h.yz * x12.yw;",
"return 130.0 * dot( m, g );" };
// Simplex 3D
private const string Simplex3DFloat3Mod289 = "float3 mod289( float3 x ) { return x - floor( x / 289.0 ) * 289.0; }";
private const string Simplex3DFloat4Mod289 = "float4 mod289( float4 x ) { return x - floor( x / 289.0 ) * 289.0; }";
private const string Simplex3DFloat4Permute = "float4 permute( float4 x ) { return mod289( ( x * 34.0 + 1.0 ) * x ); }";
private const string TaylorInvSqrtFunc = "float4 taylorInvSqrt( float4 r ) { return 1.79284291400159 - r * 0.85373472095314; }";
private const string SimplexNoise3DHeader = "float snoise( float3 v )";
private const string SimplexNoise3DFunc = "snoise( {0} )";
private readonly string[] SimplexNoise3DBody = {"const float2 C = float2( 1.0 / 6.0, 1.0 / 3.0 );",
"float3 i = floor( v + dot( v, C.yyy ) );",
"float3 x0 = v - i + dot( i, C.xxx );",
"float3 g = step( x0.yzx, x0.xyz );",
"float3 l = 1.0 - g;",
"float3 i1 = min( g.xyz, l.zxy );",
"float3 i2 = max( g.xyz, l.zxy );",
"float3 x1 = x0 - i1 + C.xxx;",
"float3 x2 = x0 - i2 + C.yyy;",
"float3 x3 = x0 - 0.5;",
"i = mod289( i);",
"float4 p = permute( permute( permute( i.z + float4( 0.0, i1.z, i2.z, 1.0 ) ) + i.y + float4( 0.0, i1.y, i2.y, 1.0 ) ) + i.x + float4( 0.0, i1.x, i2.x, 1.0 ) );",
"float4 j = p - 49.0 * floor( p / 49.0 ); // mod(p,7*7)",
"float4 x_ = floor( j / 7.0 );",
"float4 y_ = floor( j - 7.0 * x_ ); // mod(j,N)",
"float4 x = ( x_ * 2.0 + 0.5 ) / 7.0 - 1.0;",
"float4 y = ( y_ * 2.0 + 0.5 ) / 7.0 - 1.0;",
"float4 h = 1.0 - abs( x ) - abs( y );",
"float4 b0 = float4( x.xy, y.xy );",
"float4 b1 = float4( x.zw, y.zw );",
"float4 s0 = floor( b0 ) * 2.0 + 1.0;",
"float4 s1 = floor( b1 ) * 2.0 + 1.0;",
"float4 sh = -step( h, 0.0 );",
"float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;",
"float4 a1 = b1.xzyw + s1.xzyw * sh.zzww;",
"float3 g0 = float3( a0.xy, h.x );",
"float3 g1 = float3( a0.zw, h.y );",
"float3 g2 = float3( a1.xy, h.z );",
"float3 g3 = float3( a1.zw, h.w );",
"float4 norm = taylorInvSqrt( float4( dot( g0, g0 ), dot( g1, g1 ), dot( g2, g2 ), dot( g3, g3 ) ) );",
"g0 *= norm.x;",
"g1 *= norm.y;",
"g2 *= norm.z;",
"g3 *= norm.w;",
"float4 m = max( 0.6 - float4( dot( x0, x0 ), dot( x1, x1 ), dot( x2, x2 ), dot( x3, x3 ) ), 0.0 );",
"m = m* m;",
"m = m* m;",
"float4 px = float4( dot( x0, g0 ), dot( x1, g1 ), dot( x2, g2 ), dot( x3, g3 ) );",
"return 42.0 * dot( m, px);"};
[SerializeField]
private NoiseGeneratorType m_type = NoiseGeneratorType.Simplex2D;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddInputPort( WirePortDataType.FLOAT2, false, "Size" );
AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue );
m_useInternalPortData = true;
m_autoWrapProperties = true;
}
public override void DrawProperties()
{
base.DrawProperties();
EditorGUI.BeginChangeCheck();
m_type = (NoiseGeneratorType)EditorGUILayoutEnumPopup( TypeLabelStr, m_type );
if ( EditorGUI.EndChangeCheck() )
{
ConfigurePorts();
}
EditorGUILayout.HelpBox( "Node still under construction. Use with caution" , MessageType.Info );
}
void ConfigurePorts()
{
switch ( m_type )
{
case NoiseGeneratorType.Simplex2D:
{
m_inputPorts[ 0 ].ChangeType( WirePortDataType.FLOAT2 , false );
}break;
case NoiseGeneratorType.Simplex3D:
{
m_inputPorts[ 0 ].ChangeType( WirePortDataType.FLOAT3, false );
}break;
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if ( m_outputPorts[ 0 ].IsLocalValue )
{
return m_outputPorts[ 0 ].LocalValue;
}
switch ( m_type )
{
case NoiseGeneratorType.Simplex2D:
{
string float3Mod289Func = string.Empty;
IOUtils.AddSingleLineFunction( ref float3Mod289Func, Simplex2DFloat3Mod289Func );
dataCollector.AddFunction( Simplex2DFloat3Mod289Func, float3Mod289Func );
string float2Mod289Func = string.Empty;
IOUtils.AddSingleLineFunction( ref float2Mod289Func, Simplex2DFloat2Mod289Func );
dataCollector.AddFunction( Simplex2DFloat2Mod289Func, float2Mod289Func );
string permuteFunc = string.Empty;
IOUtils.AddSingleLineFunction( ref permuteFunc, Simplex2DPermuteFunc );
dataCollector.AddFunction( Simplex2DPermuteFunc, permuteFunc );
string snoiseFunc = string.Empty;
IOUtils.AddFunctionHeader( ref snoiseFunc, SimplexNoise2DHeader );
for ( int i = 0; i < SimplexNoise2DBody.Length; i++ )
{
IOUtils.AddFunctionLine( ref snoiseFunc, SimplexNoise2DBody[ i ] );
}
IOUtils.CloseFunctionBody( ref snoiseFunc );
dataCollector.AddFunction( SimplexNoise2DHeader, snoiseFunc );
string size = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
RegisterLocalVariable( 0, string.Format( SimplexNoise2DFunc, size ), ref dataCollector, ( "simplePerlin2D" + OutputId ) );
}break;
case NoiseGeneratorType.Simplex3D:
{
string float3Mod289Func = string.Empty;
IOUtils.AddSingleLineFunction( ref float3Mod289Func, Simplex3DFloat3Mod289 );
dataCollector.AddFunction( Simplex3DFloat3Mod289, float3Mod289Func );
string float4Mod289Func = string.Empty;
IOUtils.AddSingleLineFunction( ref float4Mod289Func, Simplex3DFloat4Mod289 );
dataCollector.AddFunction( Simplex3DFloat4Mod289, float4Mod289Func );
string permuteFunc = string.Empty;
IOUtils.AddSingleLineFunction( ref permuteFunc, Simplex3DFloat4Permute );
dataCollector.AddFunction( Simplex3DFloat4Permute, permuteFunc );
string taylorInvSqrtFunc = string.Empty;
IOUtils.AddSingleLineFunction( ref taylorInvSqrtFunc, TaylorInvSqrtFunc );
dataCollector.AddFunction( TaylorInvSqrtFunc, taylorInvSqrtFunc );
string snoiseFunc = string.Empty;
IOUtils.AddFunctionHeader( ref snoiseFunc, SimplexNoise3DHeader );
for ( int i = 0; i < SimplexNoise3DBody.Length; i++ )
{
IOUtils.AddFunctionLine( ref snoiseFunc, SimplexNoise3DBody[ i ] );
}
IOUtils.CloseFunctionBody( ref snoiseFunc );
dataCollector.AddFunction( SimplexNoise3DHeader, snoiseFunc );
string size = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
RegisterLocalVariable( 0, string.Format( SimplexNoise3DFunc, size ), ref dataCollector, ( "simplePerlin3D" + OutputId ) );
}
break;
}
return m_outputPorts[ 0 ].LocalValue;
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_type = ( NoiseGeneratorType ) Enum.Parse( typeof( NoiseGeneratorType ), GetCurrentParam( ref nodeParams ) );
ConfigurePorts();
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_type );
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
namespace Complete {
public class GameManager: MonoBehaviour {
private PlyrsCtrl plyrsCtrl;
public int m_NumRoundsToWin = 5; // The number of rounds a single player has to win to win the game.
public float m_StartDelay = 3f; // The delay between the start of RoundStarting and RoundPlaying phases.
public float m_EndDelay = 3f; // The delay between the end of RoundPlaying and RoundEnding phases.
public CameraControl m_CameraControl; // Reference to the CameraControl script for control during different phases.
public Text m_MessageText; // Reference to the overlay Text to display winning text, etc.
public GameObject m_TankPrefab; // Reference to the prefab the players will control.
public TankManager[] m_Tanks; // A collection of managers for enabling and disabling different aspects of the tanks.
public float maxSpawnRadius = 10f;
private int m_RoundNumber; // Which round the game is currently on.
private WaitForSeconds m_StartWait; // Used to have a delay whilst the round starts.
private WaitForSeconds m_EndWait; // Used to have a delay whilst the round or game ends.
private TankManager m_RoundWinner; // Reference to the winner of the current round. Used to make an announcement of who won.
private TankManager m_GameWinner; // Reference to the winner of the game. Used to make an announcement of who won.
public static List<string> paths = new List<string>() { null, null };
private void Start() {
// Create the delays so they only have to be made once.
m_StartWait = new WaitForSeconds(m_StartDelay);
m_EndWait = new WaitForSeconds(m_EndDelay);
SpawnAllTanks();
SetCameraTargets();
plyrsCtrl = GetComponent<PlyrsCtrl>();
var validPaths = new List<string>();
foreach (var path in paths)
if (!string.IsNullOrEmpty(path))
validPaths.Add(path);
plyrsCtrl.Init(m_Tanks, validPaths.ToArray());
// Once the tanks have been created and the camera is using them as targets, start the game.
StartCoroutine(GameLoop());
}
private void SpawnAllTanks() {
// For all the tanks...
for (int i = 0; i < m_Tanks.Length; i++) {
float radius = Random.Range(0, this.maxSpawnRadius),
angle = Random.Range(0, 2 * Mathf.PI);
float xOffset = radius * Mathf.Cos(angle),
zOffset = radius * Mathf.Sin(angle);
var offset = new Vector3(xOffset, 0, zOffset);
m_Tanks[i].m_SpawnPoint.transform.position += offset;
// ... create them, set their player number and references needed for control.
m_Tanks[i].m_Instance = Instantiate(m_TankPrefab, m_Tanks[i].m_SpawnPoint.transform.position,
m_Tanks[i].m_SpawnPoint.rotation) as GameObject;
m_Tanks[i].m_PlayerNumber = i + 1;
m_Tanks[i].Setup();
}
}
private void SetCameraTargets() {
// Create a collection of transforms the same size as the number of tanks.
Transform[] targets = new Transform[m_Tanks.Length];
// For each of these transforms...
for (int i = 0; i < targets.Length; i++)
// ... set it to the appropriate tank transform.
targets[i] = m_Tanks[i].m_Instance.transform;
// These are the targets the camera should follow.
m_CameraControl.m_Targets = targets;
}
// This is called from start and will run each phase of the game one after another.
private IEnumerator GameLoop() {
// Start off by running the 'RoundStarting' coroutine but don't return until it's finished.
yield return StartCoroutine(RoundStarting());
// Once the 'RoundStarting' coroutine is finished, run the 'RoundPlaying' coroutine but don't return until it's finished.
yield return StartCoroutine(RoundPlaying());
// Once execution has returned here, run the 'RoundEnding' coroutine, again don't return until it's finished.
yield return StartCoroutine(RoundEnding());
// This code is not run until 'RoundEnding' has finished. At which point, check if a game winner has been found.
if (m_GameWinner != null)
// If there is a game winner, restart the level.
SceneManager.LoadScene(1);
else
// If there isn't a winner yet, restart this coroutine so the loop continues.
// Note that this coroutine doesn't yield. This means that the current version of the GameLoop will end.
StartCoroutine(GameLoop());
}
private IEnumerator RoundStarting() {
// As soon as the round starts reset the tanks and make sure they can't move.
ResetAllTanks();
DisableTankControl();
// Snap the camera's zoom and position to something appropriate for the reset tanks.
m_CameraControl.SetStartPositionAndSize();
// Increment the round number and display text showing the players what round it is.
m_RoundNumber++;
m_MessageText.text = "ROUND " + m_RoundNumber;
// Wait for the specified length of time until yielding control back to the game loop.
yield return m_StartWait;
}
private IEnumerator RoundPlaying() {
// As soon as the round begins playing let the players control the tanks.
EnableTankControl();
// Clear the text from the screen.
m_MessageText.text = string.Empty;
// While there is not one tank left...
while (!OneTankLeft()) {
this.plyrsCtrl.DoTurn();
// ... return on the next frame.
yield return null;
}
}
private IEnumerator RoundEnding() {
// Stop tanks from moving.
DisableTankControl();
// Clear the winner from the previous round.
m_RoundWinner = null;
// See if there is a winner now the round is over.
m_RoundWinner = GetRoundWinner();
// If there is a winner, increment their score.
if (m_RoundWinner != null)
m_RoundWinner.m_Wins++;
// Now the winner's score has been incremented, see if someone has one the game.
m_GameWinner = GetGameWinner();
// Get a message based on the scores and whether or not there is a game winner and display it.
string message = EndMessage();
m_MessageText.text = message;
// Wait for the specified length of time until yielding control back to the game loop.
yield return m_EndWait;
}
// This is used to check if there is one or fewer tanks remaining and thus the round should end.
private bool OneTankLeft() {
// Start the count of tanks left at zero.
int numTanksLeft = 0;
// Go through all the tanks...
for (int i = 0; i < m_Tanks.Length; i++)
// ... and if they are active, increment the counter.
if (m_Tanks[i].m_Instance.activeSelf)
numTanksLeft++;
// If there are one or fewer tanks remaining return true, otherwise return false.
return numTanksLeft <= 1;
}
// This function is to find out if there is a winner of the round.
// This function is called with the assumption that 1 or fewer tanks are currently active.
private TankManager GetRoundWinner() {
// Go through all the tanks...
for (int i = 0; i < m_Tanks.Length; i++)
// ... and if one of them is active, it is the winner so return it.
if (m_Tanks[i].m_Instance.activeSelf)
return m_Tanks[i];
// If none of the tanks are active it is a draw so return null.
return null;
}
// This function is to find out if there is a winner of the game.
private TankManager GetGameWinner() {
// Go through all the tanks...
for (int i = 0; i < m_Tanks.Length; i++)
// ... and if one of them has enough rounds to win the game, return it.
if (m_Tanks[i].m_Wins == m_NumRoundsToWin)
return m_Tanks[i];
// If no tanks have enough rounds to win, return null.
return null;
}
// Returns a string message to display at the end of each round.
private string EndMessage() {
// By default when a round ends there are no winners so the default end message is a draw.
string message = "DRAW!";
// If there is a winner then change the message to reflect that.
if (m_RoundWinner != null)
message = m_RoundWinner.m_ColoredPlayerText + " WINS THE ROUND!";
// Add some line breaks after the initial message.
message += "\n\n\n\n";
// Go through all the tanks and add each of their scores to the message.
for (int i = 0; i < m_Tanks.Length; i++)
message += m_Tanks[i].m_ColoredPlayerText + ": " + m_Tanks[i].m_Wins + " WINS\n";
// If there is a game winner, change the entire message to reflect that.
if (m_GameWinner != null)
message = m_GameWinner.m_ColoredPlayerText + " WINS THE GAME!";
return message;
}
// This function is used to turn all the tanks back on and reset their positions and properties.
private void ResetAllTanks() {
for (int i = 0; i < m_Tanks.Length; i++)
m_Tanks[i].Reset();
}
private void EnableTankControl() {
for (int i = 0; i < m_Tanks.Length; i++)
m_Tanks[i].EnableControl();
}
private void DisableTankControl() {
for (int i = 0; i < m_Tanks.Length; i++)
m_Tanks[i].DisableControl();
}
}
}
| |
namespace CarService.Data.Migrations
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Faker;
using Faker.Extensions;
using CarService.Models;
using CarService.Common;
public sealed class Configuration : DbMigrationsConfiguration<CarServiceDbContext>
{
private readonly List<DateTime> _startDates;
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
_startDates = GetStartDates();
}
protected override void Seed(CarServiceDbContext context)
{
SeedUsersAndRoles(context);
SeedCars(context);
SeedCategories(context);
SeedReplacementParts(context);
SeedRepairDocuments(context);
SeedDocumentsParts(context);
}
private void SeedDocumentsParts(CarServiceDbContext context)
{
if (context.DocumentsParts.Any())
{
return;
}
var documents = context.RepairDocuments.ToList();
var parts = context.ReplacementParts.ToList();
foreach (var doc in documents)
{
var partsCount = RandomGenerator.GetRandomInteger(0, 11);
var partsPrice = 0m;
for (int i = 0; i < partsCount; i++)
{
var part = parts[RandomGenerator.GetRandomInteger(0, parts.Count - 1)];
var docPart = doc.DocumentsParts.FirstOrDefault(dp => dp.PartId == part.Id);
if (docPart == null)
{
docPart = new DocumentsParts { DocumentId = doc.Id, PartId = part.Id };
if (doc.FinishedOn.HasValue)
{
docPart.UnitPrice = part.Price;
}
context.DocumentsParts.Add(docPart);
}
else
{
docPart.Quantity++;
}
partsPrice += part.Price;
}
doc.TotalPrice = Math.Round(partsPrice + partsPrice / 5m, 2);
if (partsPrice == 0m)
{
doc.TotalPrice = RandomGenerator.GetRandomInteger(20, 100) + 0.01m * RandomGenerator.GetRandomInteger(0, 99);
}
if (doc.FinishedOn == null && RandomGenerator.GetRandomInteger() % 2 == 0)
{
doc.TotalPrice = null;
}
}
context.SaveChanges();
}
private void SeedRepairDocuments(CarServiceDbContext context)
{
if (context.RepairDocuments.Any())
{
return;
}
var employeeIds = context.Users.Select(e => e.Id).ToList();
var testUserId = context.Users.FirstOrDefault(u => u.UserName == "testuser").Id;
var testAdminId = context.Users.FirstOrDefault(u => u.UserName == "testadmin").Id;
var carIds = context.Cars.Select(c=>c.Id).ToList();
for (int i = 0; i < GlobalConstants.TestReapairDocumentsCount; i++)
{
var partsCount = RandomGenerator.GetRandomInteger(0, 11);
var repairDoc = new RepairDocument
{
CarId = carIds[RandomGenerator.GetRandomInteger(0, carIds.Count - 1)],
CreatedById = employeeIds[RandomGenerator.GetRandomInteger(0, employeeIds.Count - 1)],
MechanicId = employeeIds[RandomGenerator.GetRandomInteger(0, employeeIds.Count - 1)],
RepairDescription = String.Join(Environment.NewLine, Lorem.Paragraphs(RandomGenerator.GetRandomInteger(1, 2))),
};
repairDoc.CreatedOn = _startDates[i];
repairDoc.FinishedOn = GetFinishedDate(repairDoc.CreatedOn);
if (!repairDoc.FinishedOn.HasValue && RandomGenerator.GetRandomInteger() > 50)
{
repairDoc.CreatedById = RandomGenerator.GetRandomInteger() > 33 ? testAdminId : testUserId;
}
context.RepairDocuments.Add(repairDoc);
}
context.SaveChanges();
var cars = context.Cars.Where(c => !c.RepairDocuments.Any()).ToList();
foreach (var car in cars)
{
context.Cars.Remove(car);
}
context.SaveChanges();
}
private void SeedReplacementParts(CarServiceDbContext context)
{
if (context.ReplacementParts.Any())
{
return;
}
var categories = context.Categories.ToList();
for (int i = 0; i < GlobalConstants.TestReplacementPartsCount; i++)
{
Category category = categories[RandomGenerator.GetRandomInteger(0, categories.Count - 1)];
string categoryIdentifier = category.Name.Substring(0, 4).Replace(' ', 'X');
string index = i.ToString().PadLeft(3, '0');
ReplacementPart part = new ReplacementPart
{
Name = String.Join(" ", Lorem.Words(RandomGenerator.GetRandomInteger(2, 4))).ToUpper(),
CategoryId = category.Id,
CatalogNumber = categoryIdentifier + index + RandomGenerator.GetRandomInteger(0, 999).ToString().PadLeft(3, '0'),
Price = (decimal)RandomGenerator.GetRandomInteger(5, 400) + 0.01m * (decimal)RandomGenerator.GetRandomInteger(0, 99),
IsActive = RandomGenerator.GetRandomInteger() < 75
};
context.ReplacementParts.Add(part);
}
context.SaveChanges();
}
private void SeedCategories(CarServiceDbContext context)
{
if (context.Categories.Any())
{
return;
}
for (int i = 0; i < GlobalConstants.TestCategoriesCount; i++)
{
Category category = new Category
{
Name = String.Join(" ", Lorem.Words(RandomGenerator.GetRandomInteger(2, 4))).ToUpper()
};
context.Categories.Add(category);
}
context.SaveChanges();
}
private void SeedCars(CarServiceDbContext context)
{
if (context.Cars.Any())
{
return;
}
string[] vendors = new string[] { "Peugeot", "Renault", "Ford", "Opel", "BMW", "Dacia", "Toyota", "Mazda", "Seat", "Saab", "Mercedes", "Alfa Romeo", "Volkswagen"};
string[] regNumbers = new string[] { "C", "CA", "CB", "PK", "KH", "CO", "E", "C", "CA", "CB" };
string[] lastLetters = new string[] { "A", "B", "C", "E", "H", "K", "M", "O", "P", "T", "X" };
string[] colors = new string[] { "red", "black", "blue", "white", "silver", "green", "yellow" };
int[] engines = new int[] { 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800 };
string[] phoneCodes = new string[] { "0888", "0878", "0898" };
for (int i = 0; i < GlobalConstants.TestCarsCount; i++)
{
Car car = new Car
{
RegNumber = regNumbers[RandomGenerator.GetRandomInteger(0, regNumbers.Length - 1)] + RandomGenerator.GetRandomInteger(1, 9999).ToString().PadLeft(4, '0') + lastLetters[RandomGenerator.GetRandomInteger(0, lastLetters.Length - 1)] + lastLetters[RandomGenerator.GetRandomInteger(0, lastLetters.Length - 1)],
OwnerName = RandomGenerator.GetRandomInteger() % 2 == 0 ? Name.FullName(NameFormats.Standard) : null,
OwnerPhone = RandomGenerator.GetRandomInteger() % 2 == 0 ? phoneCodes[RandomGenerator.GetRandomInteger(0, phoneCodes.Length - 1)] + RandomGenerator.GetRandomInteger(200000, 999999) : null,
Year = RandomGenerator.GetRandomInteger() % 2 == 0 ? RandomGenerator.GetRandomInteger(DateTime.Now.Year - 25, DateTime.Now.Year - 1) : default(int?),
Color = RandomGenerator.GetRandomInteger() % 2 == 0 ? colors[RandomGenerator.GetRandomInteger(0, colors.Length - 1)] : null,
ChassisNumber = RandomGenerator.GetRandomString(6, 6).ToUpper() + RandomGenerator.GetRandomInteger(1000, 9999) + RandomGenerator.GetRandomString(3, 3).ToUpper() + RandomGenerator.GetRandomInteger(0, 9) + RandomGenerator.GetRandomString(3, 3).ToUpper(),
EngineNumber = RandomGenerator.GetRandomString(4, 4).ToUpper() + RandomGenerator.GetRandomInteger(10000, 99999) + RandomGenerator.GetRandomString(4, 4).ToUpper() + RandomGenerator.GetRandomInteger(10, 99) + RandomGenerator.GetRandomString(1, 1).ToUpper(),
EngineCapacity = RandomGenerator.GetRandomInteger() % 2 == 0 ? engines[RandomGenerator.GetRandomInteger(0, engines.Length - 1)] : default(int?),
Description = RandomGenerator.GetRandomInteger() % 2 == 0 ? Faker.Lorem.Paragraph(2) : null,
};
if (RandomGenerator.GetRandomInteger() % 2 == 0)
{
car.Vendor = vendors[RandomGenerator.GetRandomInteger(0, vendors.Length - 1)].ToUpper();
car.Model = RandomGenerator.GetRandomString(3, 6).ToUpper();
}
context.Cars.Add(car);
}
context.SaveChanges();
}
private static void SeedUsersAndRoles(CarServiceDbContext context)
{
if (context.Roles.Any())
{
return;
}
context.Roles.Add(new IdentityRole(GlobalConstants.AdminRole));
context.Roles.Add(new IdentityRole(GlobalConstants.EmployeeRole));
context.Roles.Add(new IdentityRole(GlobalConstants.InactivRole));
context.SaveChanges();
var userManager = new UserManager<User>(new UserStore<User>(context));
string[] phoneCodes = new string[] { "0888", "0878", "0898" };
for (int i = 0; i < GlobalConstants.TestUsersCount - 2; i++)
{
User user = new User
{
FirstName = Name.First().ToUpper(),
LastName = Name.Last().ToUpper(),
PhoneNumber = phoneCodes[RandomGenerator.GetRandomInteger(0, phoneCodes.Length - 1)] + RandomGenerator.GetRandomInteger(200000, 999999)
};
user.UserName = (user.FirstName + user.LastName).ToLower();
userManager.Create(user, GlobalConstants.TestPassword);
userManager.AddToRole(user.Id, GlobalConstants.EmployeeRole);
context.SaveChanges();
}
User testadmin = new User
{
FirstName = "TEST",
LastName = "ADMIN",
UserName = "testadmin",
PhoneNumber = phoneCodes[RandomGenerator.GetRandomInteger(0, phoneCodes.Length - 1)] + RandomGenerator.GetRandomInteger(200000, 999999)
};
userManager.Create(testadmin, GlobalConstants.TestPassword);
userManager.AddToRole(testadmin.Id, GlobalConstants.AdminRole);
context.SaveChanges();
User testuser = new User
{
FirstName = "TEST",
LastName = "USER",
UserName = "testuser",
PhoneNumber = phoneCodes[RandomGenerator.GetRandomInteger(0, phoneCodes.Length - 1)] + RandomGenerator.GetRandomInteger(200000, 999999)
};
userManager.Create(testuser, GlobalConstants.TestPassword);
userManager.AddToRole(testuser.Id, GlobalConstants.EmployeeRole);
context.SaveChanges();
}
private List<DateTime> GetStartDates()
{
List<DateTime> datesOnCreation = new List<DateTime>();
DateTime startDate = DateTime.Now.AddMonths(-3);
for (int i = 0; i < GlobalConstants.TestReapairDocumentsCount; i++)
{
DateTime dateOnCreation;
do
{
dateOnCreation = RandomGenerator.GetRandomDateTime(startDate, 3 * 30 * 24 + 24);
} while (!(dateOnCreation.Hour >= 9 && dateOnCreation.Hour <= 18 && dateOnCreation.DayOfWeek != DayOfWeek.Sunday));
datesOnCreation.Add(dateOnCreation);
}
datesOnCreation.Sort();
return datesOnCreation;
}
private DateTime? GetFinishedDate(DateTime startDate)
{
DateTime finishedDate;
do
{
finishedDate = RandomGenerator.GetRandomDateTime(startDate, 6 * 24);
if (finishedDate >= DateTime.Now)
{
return null;
}
} while (!(finishedDate.Hour >= 9 && finishedDate.Hour <= 18 && finishedDate.DayOfWeek != DayOfWeek.Sunday));
return finishedDate;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Statistics;
namespace osu.Framework.Graphics.Performance
{
/// <summary>
/// Provides time-optimised updates for lifetime change notifications.
/// This is used in specialised <see cref="CompositeDrawable"/>s to optimise lifetime changes (see: <see cref="LifetimeManagementContainer"/>).
/// </summary>
/// <remarks>
/// The time complexity of updating lifetimes is O(number of alive items).
/// </remarks>
public class LifetimeEntryManager
{
/// <summary>
/// Invoked immediately when a <see cref="LifetimeEntry"/> becomes alive.
/// </summary>
public event Action<LifetimeEntry> EntryBecameAlive;
/// <summary>
/// Invoked immediately when a <see cref="LifetimeEntry"/> becomes dead.
/// </summary>
public event Action<LifetimeEntry> EntryBecameDead;
/// <summary>
/// Invoked when a <see cref="LifetimeEntry"/> crosses a lifetime boundary.
/// </summary>
public event Action<LifetimeEntry, LifetimeBoundaryKind, LifetimeBoundaryCrossingDirection> EntryCrossedBoundary;
/// <summary>
/// Contains all the newly-added (but not yet processed) entries.
/// </summary>
private readonly List<LifetimeEntry> newEntries = new List<LifetimeEntry>();
/// <summary>
/// Contains all the currently-alive entries.
/// </summary>
private readonly List<LifetimeEntry> activeEntries = new List<LifetimeEntry>();
/// <summary>
/// Contains all entries that should come alive in the future.
/// </summary>
private readonly SortedSet<LifetimeEntry> futureEntries = new SortedSet<LifetimeEntry>(new LifetimeStartComparator());
/// <summary>
/// Contains all entries that were alive in the past.
/// </summary>
private readonly SortedSet<LifetimeEntry> pastEntries = new SortedSet<LifetimeEntry>(new LifetimeEndComparator());
private readonly Queue<(LifetimeEntry, LifetimeBoundaryKind, LifetimeBoundaryCrossingDirection)> eventQueue =
new Queue<(LifetimeEntry, LifetimeBoundaryKind, LifetimeBoundaryCrossingDirection)>();
/// <summary>
/// Used to ensure a stable sort if multiple entries with the same lifetime are added.
/// </summary>
private ulong currentChildId;
/// <summary>
/// Adds an entry.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/> to add.</param>
public void AddEntry(LifetimeEntry entry)
{
entry.RequestLifetimeUpdate += requestLifetimeUpdate;
entry.ChildId = ++currentChildId;
entry.State = LifetimeEntryState.New;
newEntries.Add(entry);
}
/// <summary>
/// Removes an entry.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/> to remove.</param>
/// <returns>Whether <paramref name="entry"/> was contained by this <see cref="LifetimeEntryManager"/>.</returns>
public bool RemoveEntry(LifetimeEntry entry)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
bool removed = false;
switch (entry.State)
{
case LifetimeEntryState.New:
removed = newEntries.Remove(entry);
break;
case LifetimeEntryState.Current:
removed = activeEntries.Remove(entry);
if (removed)
EntryBecameDead?.Invoke(entry);
break;
case LifetimeEntryState.Past:
// Past entries may be found in the newEntries set after a lifetime change (see requestLifetimeUpdate).
removed = pastEntries.Remove(entry) || newEntries.Remove(entry);
break;
case LifetimeEntryState.Future:
// Future entries may be found in the newEntries set after a lifetime change (see requestLifetimeUpdate).
removed = futureEntries.Remove(entry) || newEntries.Remove(entry);
break;
}
if (!removed)
return false;
entry.ChildId = 0;
return true;
}
/// <summary>
/// Removes all entries.
/// </summary>
public void ClearEntries()
{
foreach (var entry in newEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
entry.ChildId = 0;
}
foreach (var entry in pastEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
entry.ChildId = 0;
}
foreach (var entry in activeEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
EntryBecameDead?.Invoke(entry);
entry.ChildId = 0;
}
foreach (var entry in futureEntries)
{
entry.RequestLifetimeUpdate -= requestLifetimeUpdate;
entry.ChildId = 0;
}
newEntries.Clear();
pastEntries.Clear();
activeEntries.Clear();
futureEntries.Clear();
}
/// <summary>
/// Invoked when the lifetime of an entry is going to changed.
/// </summary>
private void requestLifetimeUpdate(LifetimeEntry entry)
{
// Entries in the past/future sets need to be re-sorted to prevent the comparer from becoming unstable.
// To prevent, e.g. CompositeDrawable alive children changing during enumeration, the entry's state must not be updated immediately.
//
// In order to achieve the above, the entry is first removed from the past/future set (resolving the comparer stability issues)
// and then re-queued back onto the new entries list to be re-processed in the next Update().
//
// Note that this does not apply to entries that are in the current set, as they don't utilise a lifetime comparer.
var futureOrPastSet = futureOrPastEntries(entry.State);
if (futureOrPastSet?.Remove(entry) == true)
{
// Enqueue the entry to be processed in the next Update().
newEntries.Add(entry);
}
}
/// <summary>
/// Retrieves the sorted set for a <see cref="LifetimeEntryState"/>.
/// </summary>
/// <param name="state">The <see cref="LifetimeEntryState"/>.</param>
/// <returns>Either <see cref="futureEntries"/>, <see cref="pastEntries"/>, or null.</returns>
[CanBeNull]
private SortedSet<LifetimeEntry> futureOrPastEntries(LifetimeEntryState state)
{
switch (state)
{
case LifetimeEntryState.Future:
return futureEntries;
case LifetimeEntryState.Past:
return pastEntries;
default:
return null;
}
}
/// <summary>
/// Updates the lifetime of entries at a single time value.
/// </summary>
/// <param name="time">The time to update at.</param>
/// <returns>Whether the state of any entries changed.</returns>
public bool Update(double time) => Update(time, time);
/// <summary>
/// Updates the lifetime of entries within a given time range.
/// </summary>
/// <param name="startTime">The start of the time range.</param>
/// <param name="endTime">The end of the time range.</param>
/// <returns>Whether the state of any entries changed.</returns>
public bool Update(double startTime, double endTime)
{
endTime = Math.Max(endTime, startTime);
bool aliveChildrenChanged = false;
// Check for newly-added entries.
foreach (var entry in newEntries)
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, true, true);
newEntries.Clear();
// Check for newly alive entries when time is increased.
while (futureEntries.Count > 0)
{
FrameStatistics.Increment(StatisticsCounterType.CCL);
var entry = futureEntries.Min.AsNonNull(); // guaranteed by the .Count > 0 guard.
Debug.Assert(entry.State == LifetimeEntryState.Future);
if (getState(entry, startTime, endTime) == LifetimeEntryState.Future)
break;
futureEntries.Remove(entry);
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, false, true);
}
// Check for newly alive entries when time is decreased.
while (pastEntries.Count > 0)
{
FrameStatistics.Increment(StatisticsCounterType.CCL);
var entry = pastEntries.Max.AsNonNull(); // guaranteed by the .Count > 0 guard.
Debug.Assert(entry.State == LifetimeEntryState.Past);
if (getState(entry, startTime, endTime) == LifetimeEntryState.Past)
break;
pastEntries.Remove(entry);
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, false, true);
}
// Checks for newly dead entries when time is increased/decreased.
foreach (var entry in activeEntries)
{
FrameStatistics.Increment(StatisticsCounterType.CCL);
aliveChildrenChanged |= updateChildEntry(entry, startTime, endTime, false, false);
}
// Remove all newly-dead entries.
activeEntries.RemoveAll(e => e.State != LifetimeEntryState.Current);
while (eventQueue.Count != 0)
{
var (entry, kind, direction) = eventQueue.Dequeue();
EntryCrossedBoundary?.Invoke(entry, kind, direction);
}
return aliveChildrenChanged;
}
/// <summary>
/// Updates the state of a single <see cref="LifetimeEntry"/>.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/> to update.</param>
/// <param name="startTime">The start of the time range.</param>
/// <param name="endTime">The end of the time range.</param>
/// <param name="isNewEntry">Whether <paramref name="entry"/> is part of the new entries set.
/// The state may be "new" or "past"/"future", in which case it will undergo further processing to return it to the correct set.</param>
/// <param name="mutateActiveEntries">Whether <see cref="activeEntries"/> should be mutated by this invocation.
/// If <c>false</c>, the caller is expected to handle mutation of <see cref="activeEntries"/> based on any changes to the entry's state.</param>
/// <returns>Whether the state of <paramref name="entry"/> has changed.</returns>
private bool updateChildEntry(LifetimeEntry entry, double startTime, double endTime, bool isNewEntry, bool mutateActiveEntries)
{
LifetimeEntryState oldState = entry.State;
// Past/future sets don't call this function unless a state change is guaranteed.
Debug.Assert(!futureEntries.Contains(entry) && !pastEntries.Contains(entry));
// The entry can be in one of three states:
// 1. The entry was previously in the past/future sets but a lifetime change was requested. Its state is currently "past"/"future".
// 2. The entry is a completely new entry. Its state is currently "new".
// 3. The entry is currently-active. Its state is "current" but it's also in the active set.
Debug.Assert(oldState != LifetimeEntryState.Current || activeEntries.Contains(entry));
LifetimeEntryState newState = getState(entry, startTime, endTime);
Debug.Assert(newState != LifetimeEntryState.New);
if (newState == oldState)
{
// If the state hasn't changed, then there's two possibilities:
// 1. The entry was in the past/future sets and a lifetime change was requested. The entry needs to be added back to the past/future sets.
// 2. The entry is and continues to remain active.
if (isNewEntry)
futureOrPastEntries(newState)?.Add(entry);
else
Debug.Assert(newState == LifetimeEntryState.Current);
// In both cases, the entry doesn't need to be processed further as it's already in the correct state.
return false;
}
bool aliveEntriesChanged = false;
if (newState == LifetimeEntryState.Current)
{
if (mutateActiveEntries)
activeEntries.Add(entry);
EntryBecameAlive?.Invoke(entry);
aliveEntriesChanged = true;
}
else if (oldState == LifetimeEntryState.Current)
{
if (mutateActiveEntries)
activeEntries.Remove(entry);
EntryBecameDead?.Invoke(entry);
aliveEntriesChanged = true;
}
entry.State = newState;
futureOrPastEntries(newState)?.Add(entry);
enqueueEvents(entry, oldState, newState);
return aliveEntriesChanged;
}
/// <summary>
/// Retrieves the new state for an entry.
/// </summary>
/// <param name="entry">The <see cref="LifetimeEntry"/>.</param>
/// <param name="startTime">The start of the time range.</param>
/// <param name="endTime">The end of the time range.</param>
/// <returns>The state of <paramref name="entry"/>. Can be either <see cref="LifetimeEntryState.Past"/>, <see cref="LifetimeEntryState.Current"/>, or <see cref="LifetimeEntryState.Future"/>.</returns>
private LifetimeEntryState getState(LifetimeEntry entry, double startTime, double endTime)
{
// Consider a static entry and a moving time range:
// [-----------Entry-----------]
// [----Range----] | | (not alive)
// [----Range----] | (alive)
// | [----Range----] (alive)
// | [----Range----] (not alive)
// | | [----Range----] (not alive)
// | |
if (endTime < entry.LifetimeStart)
return LifetimeEntryState.Future;
if (startTime >= entry.LifetimeEnd)
return LifetimeEntryState.Past;
return LifetimeEntryState.Current;
}
private void enqueueEvents(LifetimeEntry entry, LifetimeEntryState oldState, LifetimeEntryState newState)
{
Debug.Assert(oldState != newState);
switch (oldState)
{
case LifetimeEntryState.Future:
eventQueue.Enqueue((entry, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Forward));
if (newState == LifetimeEntryState.Past)
eventQueue.Enqueue((entry, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward));
break;
case LifetimeEntryState.Current:
eventQueue.Enqueue(newState == LifetimeEntryState.Past
? (entry, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward)
: (entry, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward));
break;
case LifetimeEntryState.Past:
eventQueue.Enqueue((entry, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward));
if (newState == LifetimeEntryState.Future)
eventQueue.Enqueue((entry, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward));
break;
}
}
/// <summary>
/// Compares by <see cref="LifetimeEntry.LifetimeStart"/>.
/// </summary>
private sealed class LifetimeStartComparator : IComparer<LifetimeEntry>
{
public int Compare(LifetimeEntry x, LifetimeEntry y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
int c = x.LifetimeStart.CompareTo(y.LifetimeStart);
return c != 0 ? c : x.ChildId.CompareTo(y.ChildId);
}
}
/// <summary>
/// Compares by <see cref="LifetimeEntry.LifetimeEnd"/>.
/// </summary>
private sealed class LifetimeEndComparator : IComparer<LifetimeEntry>
{
public int Compare(LifetimeEntry x, LifetimeEntry y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
int c = x.LifetimeEnd.CompareTo(y.LifetimeEnd);
return c != 0 ? c : x.ChildId.CompareTo(y.ChildId);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using gt = Google.Type;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Channel.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCloudChannelServiceClientTest
{
[xunit::FactAttribute]
public void GetCustomerRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCustomerRequest request = new GetCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.GetCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer response = client.GetCustomer(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCustomerRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCustomerRequest request = new GetCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.GetCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer responseCallSettings = await client.GetCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Customer responseCancellationToken = await client.GetCustomerAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCustomer()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCustomerRequest request = new GetCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.GetCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer response = client.GetCustomer(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCustomerAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCustomerRequest request = new GetCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.GetCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer responseCallSettings = await client.GetCustomerAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Customer responseCancellationToken = await client.GetCustomerAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCustomerResourceNames()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCustomerRequest request = new GetCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.GetCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer response = client.GetCustomer(request.CustomerName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCustomerResourceNamesAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCustomerRequest request = new GetCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.GetCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer responseCallSettings = await client.GetCustomerAsync(request.CustomerName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Customer responseCancellationToken = await client.GetCustomerAsync(request.CustomerName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CheckCloudIdentityAccountsExistRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CheckCloudIdentityAccountsExistRequest request = new CheckCloudIdentityAccountsExistRequest
{
Parent = "parent7858e4d0",
Domain = "domaine8825fad",
};
CheckCloudIdentityAccountsExistResponse expectedResponse = new CheckCloudIdentityAccountsExistResponse
{
CloudIdentityAccounts =
{
new CloudIdentityCustomerAccount(),
},
};
mockGrpcClient.Setup(x => x.CheckCloudIdentityAccountsExist(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
CheckCloudIdentityAccountsExistResponse response = client.CheckCloudIdentityAccountsExist(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CheckCloudIdentityAccountsExistRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CheckCloudIdentityAccountsExistRequest request = new CheckCloudIdentityAccountsExistRequest
{
Parent = "parent7858e4d0",
Domain = "domaine8825fad",
};
CheckCloudIdentityAccountsExistResponse expectedResponse = new CheckCloudIdentityAccountsExistResponse
{
CloudIdentityAccounts =
{
new CloudIdentityCustomerAccount(),
},
};
mockGrpcClient.Setup(x => x.CheckCloudIdentityAccountsExistAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CheckCloudIdentityAccountsExistResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
CheckCloudIdentityAccountsExistResponse responseCallSettings = await client.CheckCloudIdentityAccountsExistAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CheckCloudIdentityAccountsExistResponse responseCancellationToken = await client.CheckCloudIdentityAccountsExistAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateCustomerRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCustomerRequest request = new CreateCustomerRequest
{
Parent = "parent7858e4d0",
Customer = new Customer(),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.CreateCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer response = client.CreateCustomer(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateCustomerRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateCustomerRequest request = new CreateCustomerRequest
{
Parent = "parent7858e4d0",
Customer = new Customer(),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.CreateCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer responseCallSettings = await client.CreateCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Customer responseCancellationToken = await client.CreateCustomerAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateCustomerRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateCustomerRequest request = new UpdateCustomerRequest
{
Customer = new Customer(),
UpdateMask = new wkt::FieldMask(),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.UpdateCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer response = client.UpdateCustomer(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateCustomerRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateCustomerRequest request = new UpdateCustomerRequest
{
Customer = new Customer(),
UpdateMask = new wkt::FieldMask(),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.UpdateCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer responseCallSettings = await client.UpdateCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Customer responseCancellationToken = await client.UpdateCustomerAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteCustomerRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteCustomerRequest request = new DeleteCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteCustomer(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteCustomerRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteCustomerRequest request = new DeleteCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteCustomerAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteCustomer()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteCustomerRequest request = new DeleteCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteCustomer(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteCustomerAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteCustomerRequest request = new DeleteCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteCustomerAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteCustomerAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteCustomerResourceNames()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteCustomerRequest request = new DeleteCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteCustomer(request.CustomerName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteCustomerResourceNamesAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteCustomerRequest request = new DeleteCustomerRequest
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteCustomerAsync(request.CustomerName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteCustomerAsync(request.CustomerName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportCustomerRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ImportCustomerRequest request = new ImportCustomerRequest
{
Parent = "parent7858e4d0",
Domain = "domaine8825fad",
CloudIdentityId = "cloud_identity_idcb2e1526",
AuthToken = "auth_token85f233bb",
OverwriteIfExists = false,
ChannelPartnerId = "channel_partner_ida548fd43",
CustomerAsCustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.ImportCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer response = client.ImportCustomer(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportCustomerRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
ImportCustomerRequest request = new ImportCustomerRequest
{
Parent = "parent7858e4d0",
Domain = "domaine8825fad",
CloudIdentityId = "cloud_identity_idcb2e1526",
AuthToken = "auth_token85f233bb",
OverwriteIfExists = false,
ChannelPartnerId = "channel_partner_ida548fd43",
CustomerAsCustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
};
Customer expectedResponse = new Customer
{
CustomerName = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]"),
OrgDisplayName = "org_display_nameb29ddfcb",
OrgPostalAddress = new gt::PostalAddress(),
PrimaryContactInfo = new ContactInfo(),
AlternateEmail = "alternate_email3cdfc6ce",
Domain = "domaine8825fad",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
CloudIdentityId = "cloud_identity_idcb2e1526",
LanguageCode = "language_code2f6c7160",
CloudIdentityInfo = new CloudIdentityInfo(),
ChannelPartnerId = "channel_partner_ida548fd43",
};
mockGrpcClient.Setup(x => x.ImportCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Customer responseCallSettings = await client.ImportCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Customer responseCancellationToken = await client.ImportCustomerAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEntitlementRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntitlementRequest request = new GetEntitlementRequest
{
EntitlementName = EntitlementName.FromAccountCustomerEntitlement("[ACCOUNT]", "[CUSTOMER]", "[ENTITLEMENT]"),
};
Entitlement expectedResponse = new Entitlement
{
EntitlementName = EntitlementName.FromAccountCustomerEntitlement("[ACCOUNT]", "[CUSTOMER]", "[ENTITLEMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
OfferAsOfferName = OfferName.FromAccountOffer("[ACCOUNT]", "[OFFER]"),
CommitmentSettings = new CommitmentSettings(),
ProvisioningState = Entitlement.Types.ProvisioningState.Unspecified,
ProvisionedService = new ProvisionedService(),
SuspensionReasons =
{
Entitlement.Types.SuspensionReason.TrialEnded,
},
PurchaseOrderId = "purchase_order_id4111e034",
TrialSettings = new TrialSettings(),
AssociationInfo = new AssociationInfo(),
Parameters = { new Parameter(), },
};
mockGrpcClient.Setup(x => x.GetEntitlement(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Entitlement response = client.GetEntitlement(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEntitlementRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntitlementRequest request = new GetEntitlementRequest
{
EntitlementName = EntitlementName.FromAccountCustomerEntitlement("[ACCOUNT]", "[CUSTOMER]", "[ENTITLEMENT]"),
};
Entitlement expectedResponse = new Entitlement
{
EntitlementName = EntitlementName.FromAccountCustomerEntitlement("[ACCOUNT]", "[CUSTOMER]", "[ENTITLEMENT]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
OfferAsOfferName = OfferName.FromAccountOffer("[ACCOUNT]", "[OFFER]"),
CommitmentSettings = new CommitmentSettings(),
ProvisioningState = Entitlement.Types.ProvisioningState.Unspecified,
ProvisionedService = new ProvisionedService(),
SuspensionReasons =
{
Entitlement.Types.SuspensionReason.TrialEnded,
},
PurchaseOrderId = "purchase_order_id4111e034",
TrialSettings = new TrialSettings(),
AssociationInfo = new AssociationInfo(),
Parameters = { new Parameter(), },
};
mockGrpcClient.Setup(x => x.GetEntitlementAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Entitlement>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Entitlement responseCallSettings = await client.GetEntitlementAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Entitlement responseCancellationToken = await client.GetEntitlementAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetChannelPartnerLinkRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetChannelPartnerLinkRequest request = new GetChannelPartnerLinkRequest
{
Name = "name1c9368b0",
View = ChannelPartnerLinkView.Basic,
};
ChannelPartnerLink expectedResponse = new ChannelPartnerLink
{
ChannelPartnerLinkName = ChannelPartnerLinkName.FromAccountChannelPartnerLink("[ACCOUNT]", "[CHANNEL_PARTNER_LINK]"),
ResellerCloudIdentityId = "reseller_cloud_identity_id1b90ae2b",
LinkState = ChannelPartnerLinkState.Revoked,
InviteLinkUri = "invite_link_urie81ac099",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PublicId = "public_id4d74e21e",
ChannelPartnerCloudIdentityInfo = new CloudIdentityInfo(),
};
mockGrpcClient.Setup(x => x.GetChannelPartnerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
ChannelPartnerLink response = client.GetChannelPartnerLink(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetChannelPartnerLinkRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetChannelPartnerLinkRequest request = new GetChannelPartnerLinkRequest
{
Name = "name1c9368b0",
View = ChannelPartnerLinkView.Basic,
};
ChannelPartnerLink expectedResponse = new ChannelPartnerLink
{
ChannelPartnerLinkName = ChannelPartnerLinkName.FromAccountChannelPartnerLink("[ACCOUNT]", "[CHANNEL_PARTNER_LINK]"),
ResellerCloudIdentityId = "reseller_cloud_identity_id1b90ae2b",
LinkState = ChannelPartnerLinkState.Revoked,
InviteLinkUri = "invite_link_urie81ac099",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PublicId = "public_id4d74e21e",
ChannelPartnerCloudIdentityInfo = new CloudIdentityInfo(),
};
mockGrpcClient.Setup(x => x.GetChannelPartnerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ChannelPartnerLink>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
ChannelPartnerLink responseCallSettings = await client.GetChannelPartnerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ChannelPartnerLink responseCancellationToken = await client.GetChannelPartnerLinkAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateChannelPartnerLinkRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateChannelPartnerLinkRequest request = new CreateChannelPartnerLinkRequest
{
Parent = "parent7858e4d0",
ChannelPartnerLink = new ChannelPartnerLink(),
};
ChannelPartnerLink expectedResponse = new ChannelPartnerLink
{
ChannelPartnerLinkName = ChannelPartnerLinkName.FromAccountChannelPartnerLink("[ACCOUNT]", "[CHANNEL_PARTNER_LINK]"),
ResellerCloudIdentityId = "reseller_cloud_identity_id1b90ae2b",
LinkState = ChannelPartnerLinkState.Revoked,
InviteLinkUri = "invite_link_urie81ac099",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PublicId = "public_id4d74e21e",
ChannelPartnerCloudIdentityInfo = new CloudIdentityInfo(),
};
mockGrpcClient.Setup(x => x.CreateChannelPartnerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
ChannelPartnerLink response = client.CreateChannelPartnerLink(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateChannelPartnerLinkRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateChannelPartnerLinkRequest request = new CreateChannelPartnerLinkRequest
{
Parent = "parent7858e4d0",
ChannelPartnerLink = new ChannelPartnerLink(),
};
ChannelPartnerLink expectedResponse = new ChannelPartnerLink
{
ChannelPartnerLinkName = ChannelPartnerLinkName.FromAccountChannelPartnerLink("[ACCOUNT]", "[CHANNEL_PARTNER_LINK]"),
ResellerCloudIdentityId = "reseller_cloud_identity_id1b90ae2b",
LinkState = ChannelPartnerLinkState.Revoked,
InviteLinkUri = "invite_link_urie81ac099",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PublicId = "public_id4d74e21e",
ChannelPartnerCloudIdentityInfo = new CloudIdentityInfo(),
};
mockGrpcClient.Setup(x => x.CreateChannelPartnerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ChannelPartnerLink>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
ChannelPartnerLink responseCallSettings = await client.CreateChannelPartnerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ChannelPartnerLink responseCancellationToken = await client.CreateChannelPartnerLinkAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateChannelPartnerLinkRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateChannelPartnerLinkRequest request = new UpdateChannelPartnerLinkRequest
{
Name = "name1c9368b0",
ChannelPartnerLink = new ChannelPartnerLink(),
UpdateMask = new wkt::FieldMask(),
};
ChannelPartnerLink expectedResponse = new ChannelPartnerLink
{
ChannelPartnerLinkName = ChannelPartnerLinkName.FromAccountChannelPartnerLink("[ACCOUNT]", "[CHANNEL_PARTNER_LINK]"),
ResellerCloudIdentityId = "reseller_cloud_identity_id1b90ae2b",
LinkState = ChannelPartnerLinkState.Revoked,
InviteLinkUri = "invite_link_urie81ac099",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PublicId = "public_id4d74e21e",
ChannelPartnerCloudIdentityInfo = new CloudIdentityInfo(),
};
mockGrpcClient.Setup(x => x.UpdateChannelPartnerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
ChannelPartnerLink response = client.UpdateChannelPartnerLink(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateChannelPartnerLinkRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateChannelPartnerLinkRequest request = new UpdateChannelPartnerLinkRequest
{
Name = "name1c9368b0",
ChannelPartnerLink = new ChannelPartnerLink(),
UpdateMask = new wkt::FieldMask(),
};
ChannelPartnerLink expectedResponse = new ChannelPartnerLink
{
ChannelPartnerLinkName = ChannelPartnerLinkName.FromAccountChannelPartnerLink("[ACCOUNT]", "[CHANNEL_PARTNER_LINK]"),
ResellerCloudIdentityId = "reseller_cloud_identity_id1b90ae2b",
LinkState = ChannelPartnerLinkState.Revoked,
InviteLinkUri = "invite_link_urie81ac099",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
PublicId = "public_id4d74e21e",
ChannelPartnerCloudIdentityInfo = new CloudIdentityInfo(),
};
mockGrpcClient.Setup(x => x.UpdateChannelPartnerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ChannelPartnerLink>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
ChannelPartnerLink responseCallSettings = await client.UpdateChannelPartnerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ChannelPartnerLink responseCancellationToken = await client.UpdateChannelPartnerLinkAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void LookupOfferRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
LookupOfferRequest request = new LookupOfferRequest
{
EntitlementAsEntitlementName = EntitlementName.FromAccountCustomerEntitlement("[ACCOUNT]", "[CUSTOMER]", "[ENTITLEMENT]"),
};
Offer expectedResponse = new Offer
{
OfferName = OfferName.FromAccountOffer("[ACCOUNT]", "[OFFER]"),
MarketingInfo = new MarketingInfo(),
Sku = new Sku(),
Plan = new Plan(),
Constraints = new Constraints(),
PriceByResources =
{
new PriceByResource(),
},
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
ParameterDefinitions =
{
new ParameterDefinition(),
},
};
mockGrpcClient.Setup(x => x.LookupOffer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Offer response = client.LookupOffer(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task LookupOfferRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
LookupOfferRequest request = new LookupOfferRequest
{
EntitlementAsEntitlementName = EntitlementName.FromAccountCustomerEntitlement("[ACCOUNT]", "[CUSTOMER]", "[ENTITLEMENT]"),
};
Offer expectedResponse = new Offer
{
OfferName = OfferName.FromAccountOffer("[ACCOUNT]", "[OFFER]"),
MarketingInfo = new MarketingInfo(),
Sku = new Sku(),
Plan = new Plan(),
Constraints = new Constraints(),
PriceByResources =
{
new PriceByResource(),
},
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
ParameterDefinitions =
{
new ParameterDefinition(),
},
};
mockGrpcClient.Setup(x => x.LookupOfferAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Offer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
Offer responseCallSettings = await client.LookupOfferAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Offer responseCancellationToken = await client.LookupOfferAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void RegisterSubscriberRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RegisterSubscriberRequest request = new RegisterSubscriberRequest
{
Account = "account3e4468e2",
ServiceAccount = "service_accounta3c1b923",
};
RegisterSubscriberResponse expectedResponse = new RegisterSubscriberResponse
{
Topic = "topicac689b9d",
};
mockGrpcClient.Setup(x => x.RegisterSubscriber(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
RegisterSubscriberResponse response = client.RegisterSubscriber(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task RegisterSubscriberRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
RegisterSubscriberRequest request = new RegisterSubscriberRequest
{
Account = "account3e4468e2",
ServiceAccount = "service_accounta3c1b923",
};
RegisterSubscriberResponse expectedResponse = new RegisterSubscriberResponse
{
Topic = "topicac689b9d",
};
mockGrpcClient.Setup(x => x.RegisterSubscriberAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RegisterSubscriberResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
RegisterSubscriberResponse responseCallSettings = await client.RegisterSubscriberAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
RegisterSubscriberResponse responseCancellationToken = await client.RegisterSubscriberAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UnregisterSubscriberRequestObject()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UnregisterSubscriberRequest request = new UnregisterSubscriberRequest
{
Account = "account3e4468e2",
ServiceAccount = "service_accounta3c1b923",
};
UnregisterSubscriberResponse expectedResponse = new UnregisterSubscriberResponse
{
Topic = "topicac689b9d",
};
mockGrpcClient.Setup(x => x.UnregisterSubscriber(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
UnregisterSubscriberResponse response = client.UnregisterSubscriber(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UnregisterSubscriberRequestObjectAsync()
{
moq::Mock<CloudChannelService.CloudChannelServiceClient> mockGrpcClient = new moq::Mock<CloudChannelService.CloudChannelServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UnregisterSubscriberRequest request = new UnregisterSubscriberRequest
{
Account = "account3e4468e2",
ServiceAccount = "service_accounta3c1b923",
};
UnregisterSubscriberResponse expectedResponse = new UnregisterSubscriberResponse
{
Topic = "topicac689b9d",
};
mockGrpcClient.Setup(x => x.UnregisterSubscriberAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UnregisterSubscriberResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CloudChannelServiceClient client = new CloudChannelServiceClientImpl(mockGrpcClient.Object, null);
UnregisterSubscriberResponse responseCallSettings = await client.UnregisterSubscriberAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
UnregisterSubscriberResponse responseCancellationToken = await client.UnregisterSubscriberAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// CodeContracts
//
// 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.
// File System.Web.HttpApplication.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0067
// Disable the "this event is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web
{
public partial class HttpApplication : IHttpAsyncHandler, IHttpHandler, System.ComponentModel.IComponent, IDisposable
{
#region Methods and constructors
public void AddOnAcquireRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnAcquireRequestStateAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnAuthenticateRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnAuthenticateRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnAuthorizeRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnAuthorizeRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnBeginRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnBeginRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnEndRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnEndRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnLogRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnLogRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnMapRequestHandlerAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnMapRequestHandlerAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostAcquireRequestStateAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostAcquireRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostAuthenticateRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostAuthenticateRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostAuthorizeRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostAuthorizeRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostLogRequestAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostLogRequestAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostMapRequestHandlerAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostMapRequestHandlerAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostReleaseRequestStateAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostReleaseRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostRequestHandlerExecuteAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostRequestHandlerExecuteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostResolveRequestCacheAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPostResolveRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostUpdateRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPostUpdateRequestCacheAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnPreRequestHandlerExecuteAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnPreRequestHandlerExecuteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnReleaseRequestStateAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnReleaseRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnResolveRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnResolveRequestCacheAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void AddOnUpdateRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
{
}
public void AddOnUpdateRequestCacheAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
{
}
public void CompleteRequest ()
{
}
public virtual new void Dispose ()
{
}
#if NETFRAMEWORK_4_0
public virtual new string GetOutputCacheProviderName (HttpContext context)
{
return default(string);
}
#endif
public virtual new string GetVaryByCustomString (HttpContext context, string custom)
{
Contract.Requires (context != null);
return default(string);
}
public HttpApplication ()
{
}
public virtual new void Init ()
{
}
IAsyncResult System.Web.IHttpAsyncHandler.BeginProcessRequest (HttpContext context, AsyncCallback cb, Object extraData)
{
return default(IAsyncResult);
}
void System.Web.IHttpAsyncHandler.EndProcessRequest (IAsyncResult result)
{
}
void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
{
}
#endregion
#region Properties and indexers
public HttpApplicationState Application
{
get
{
return default(HttpApplicationState);
}
}
public HttpContext Context
{
get
{
Contract.Ensures(Contract.Result<HttpContext>() != null);
return default(HttpContext);
}
}
protected System.ComponentModel.EventHandlerList Events
{
get
{
Contract.Ensures (Contract.Result<System.ComponentModel.EventHandlerList>() != null);
return default(System.ComponentModel.EventHandlerList);
}
}
public HttpModuleCollection Modules
{
get
{
Contract.Ensures (Contract.Result<System.Web.HttpModuleCollection>() != null);
return default(HttpModuleCollection);
}
}
public HttpRequest Request
{
get
{
Contract.Ensures (Contract.Result<System.Web.HttpRequest>() != null);
return default(HttpRequest);
}
}
public HttpResponse Response
{
get
{
Contract.Ensures (Contract.Result<System.Web.HttpResponse>() != null);
return default(HttpResponse);
}
}
public HttpServerUtility Server
{
get
{
Contract.Ensures(Contract.Result<HttpServerUtility>() != null);
return default(HttpServerUtility);
}
}
public System.Web.SessionState.HttpSessionState Session
{
get
{
Contract.Ensures (Contract.Result<System.Web.SessionState.HttpSessionState>() != null);
return default(System.Web.SessionState.HttpSessionState);
}
}
public System.ComponentModel.ISite Site
{
get
{
return default(System.ComponentModel.ISite);
}
set
{
}
}
bool System.Web.IHttpHandler.IsReusable
{
get
{
return default(bool);
}
}
public System.Security.Principal.IPrincipal User
{
get
{
return default(System.Security.Principal.IPrincipal);
}
}
#endregion
#region IComponent Members
//extern event EventHandler Disposed;
#endregion
#region IComponent Members
extern public event EventHandler Disposed;
#endregion
}
}
| |
namespace EIDSS.RAM.Layout
{
partial class PivotReportForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PivotReportForm));
this.printControlReport = new DevExpress.XtraPrinting.Control.PrintControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.printBarManager = new DevExpress.XtraPrinting.Preview.PrintBarManager();
this.previewBar1 = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.biFilter = new DevExpress.XtraBars.BarButtonItem();
this.biCancelChanges = new DevExpress.XtraBars.BarButtonItem();
this.biSave = new DevExpress.XtraBars.BarButtonItem();
this.biFind = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPrint = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPrintDirect = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPageSetup = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biScale = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biHandTool = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biMagnifier = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biZoomOut = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biZoom = new DevExpress.XtraPrinting.Preview.ZoomBarEditItem();
this.printPreviewRepositoryItemComboBox1 = new DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox();
this.ZoomIn = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowFirstPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowPrevPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowNextPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowLastPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biMultiplePages = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biFillBackground = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biExportFile = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.previewBar2 = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.printPreviewStaticItem1 = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem();
this.barStaticItem1 = new DevExpress.XtraBars.BarStaticItem();
this.progressBarEditItem1 = new DevExpress.XtraPrinting.Preview.ProgressBarEditItem();
this.repositoryItemProgressBar1 = new DevExpress.XtraEditors.Repository.RepositoryItemProgressBar();
this.printPreviewBarItem1 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem();
this.printPreviewStaticItem2 = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem();
this.previewBar3 = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.printPreviewSubItem1 = new DevExpress.XtraPrinting.Preview.PrintPreviewSubItem();
this.printPreviewSubItem2 = new DevExpress.XtraPrinting.Preview.PrintPreviewSubItem();
this.printPreviewSubItem4 = new DevExpress.XtraPrinting.Preview.PrintPreviewSubItem();
this.printPreviewBarItem27 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.printPreviewBarItem28 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barToolbarsListItem1 = new DevExpress.XtraBars.BarToolbarsListItem();
this.printPreviewSubItem3 = new DevExpress.XtraPrinting.Preview.PrintPreviewSubItem();
this.biExportPdf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportHtm = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportMht = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportRtf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportXls = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportCsv = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportTxt = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportGraphic = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.printPreviewBarItem2 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.grcMap = new DevExpress.XtraEditors.GroupControl();
this.grcReportMain = new DevExpress.XtraEditors.GroupControl();
this.nbControlReport = new DevExpress.XtraNavBar.NavBarControl();
this.nbGroupSettings = new DevExpress.XtraNavBar.NavBarGroup();
this.nbContainerSettings = new DevExpress.XtraNavBar.NavBarGroupControlContainer();
this.grcMapSettings = new DevExpress.XtraEditors.GroupControl();
this.lblPivotName = new System.Windows.Forms.Label();
this.memFilter = new DevExpress.XtraEditors.MemoEdit();
this.tbPivotName = new DevExpress.XtraEditors.TextEdit();
this.lblFilter = new System.Windows.Forms.Label();
this.printControlReport.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.printBarManager)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grcMap)).BeginInit();
this.grcMap.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grcReportMain)).BeginInit();
this.grcReportMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nbControlReport)).BeginInit();
this.nbControlReport.SuspendLayout();
this.nbContainerSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grcMapSettings)).BeginInit();
this.grcMapSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.memFilter.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tbPivotName.Properties)).BeginInit();
this.SuspendLayout();
//
// printControlReport
//
resources.ApplyResources(this.printControlReport, "printControlReport");
this.printControlReport.Controls.Add(this.barDockControlLeft);
this.printControlReport.Controls.Add(this.barDockControlRight);
this.printControlReport.Controls.Add(this.barDockControlBottom);
this.printControlReport.Controls.Add(this.barDockControlTop);
this.printControlReport.Name = "printControlReport";
//
// barDockControlLeft
//
this.barDockControlLeft.CausesValidation = false;
resources.ApplyResources(this.barDockControlLeft, "barDockControlLeft");
//
// barDockControlRight
//
this.barDockControlRight.CausesValidation = false;
resources.ApplyResources(this.barDockControlRight, "barDockControlRight");
//
// barDockControlBottom
//
this.barDockControlBottom.CausesValidation = false;
resources.ApplyResources(this.barDockControlBottom, "barDockControlBottom");
//
// barDockControlTop
//
this.barDockControlTop.CausesValidation = false;
resources.ApplyResources(this.barDockControlTop, "barDockControlTop");
//
// printBarManager
//
this.printBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.previewBar1,
this.previewBar2,
this.previewBar3});
this.printBarManager.DockControls.Add(this.barDockControlTop);
this.printBarManager.DockControls.Add(this.barDockControlBottom);
this.printBarManager.DockControls.Add(this.barDockControlLeft);
this.printBarManager.DockControls.Add(this.barDockControlRight);
this.printBarManager.Form = this.printControlReport;
this.printBarManager.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("printBarManager.ImageStream")));
this.printBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.printPreviewStaticItem1,
this.barStaticItem1,
this.progressBarEditItem1,
this.printPreviewBarItem1,
this.barButtonItem1,
this.printPreviewStaticItem2,
this.biFind,
this.biPrint,
this.biPrintDirect,
this.biPageSetup,
this.biScale,
this.biHandTool,
this.biMagnifier,
this.biZoomOut,
this.biZoom,
this.ZoomIn,
this.biShowFirstPage,
this.biShowPrevPage,
this.biShowNextPage,
this.biShowLastPage,
this.biMultiplePages,
this.biFillBackground,
this.biExportFile,
this.printPreviewSubItem1,
this.printPreviewSubItem2,
this.printPreviewSubItem3,
this.printPreviewSubItem4,
this.printPreviewBarItem27,
this.printPreviewBarItem28,
this.barToolbarsListItem1,
this.biExportPdf,
this.biExportHtm,
this.biExportMht,
this.biExportRtf,
this.biExportXls,
this.biExportCsv,
this.biExportTxt,
this.biExportGraphic,
this.biFilter,
this.biSave,
this.biCancelChanges});
this.printBarManager.MainMenu = this.previewBar3;
this.printBarManager.MaxItemId = 58;
this.printBarManager.PreviewBar = this.previewBar1;
this.printBarManager.PrintControl = this.printControlReport;
this.printBarManager.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.repositoryItemProgressBar1,
this.printPreviewRepositoryItemComboBox1});
this.printBarManager.StatusBar = this.previewBar2;
//
// previewBar1
//
this.previewBar1.BarName = "Toolbar";
this.previewBar1.DockCol = 0;
this.previewBar1.DockRow = 1;
this.previewBar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.previewBar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biFilter),
new DevExpress.XtraBars.LinkPersistInfo(this.biCancelChanges),
new DevExpress.XtraBars.LinkPersistInfo(this.biSave),
new DevExpress.XtraBars.LinkPersistInfo(this.biFind, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrint),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrintDirect),
new DevExpress.XtraBars.LinkPersistInfo(this.biPageSetup),
new DevExpress.XtraBars.LinkPersistInfo(this.biScale),
new DevExpress.XtraBars.LinkPersistInfo(this.biHandTool, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biMagnifier),
new DevExpress.XtraBars.LinkPersistInfo(this.biZoomOut, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biZoom),
new DevExpress.XtraBars.LinkPersistInfo(this.ZoomIn),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowFirstPage, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowPrevPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowNextPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowLastPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biMultiplePages, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biFillBackground),
new DevExpress.XtraBars.LinkPersistInfo(this.biExportFile, true)});
this.previewBar1.OptionsBar.AllowQuickCustomization = false;
this.previewBar1.OptionsBar.DisableClose = true;
this.previewBar1.OptionsBar.DisableCustomization = true;
this.previewBar1.OptionsBar.DrawDragBorder = false;
resources.ApplyResources(this.previewBar1, "previewBar1");
//
// biFilter
//
resources.ApplyResources(this.biFilter, "biFilter");
this.biFilter.Glyph = global::EIDSS.RAM.Properties.Resources.layoutFilter;
this.biFilter.Id = 55;
this.biFilter.ImageIndex = 14;
this.biFilter.Name = "biFilter";
this.biFilter.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biFilter_ItemClick);
//
// biCancelChanges
//
resources.ApplyResources(this.biCancelChanges, "biCancelChanges");
this.biCancelChanges.Glyph = global::EIDSS.RAM.Properties.Resources.layout_undo3;
this.biCancelChanges.Id = 57;
this.biCancelChanges.Name = "biCancelChanges";
this.biCancelChanges.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biCancelChanges_ItemClick);
//
// biSave
//
resources.ApplyResources(this.biSave, "biSave");
this.biSave.Glyph = global::EIDSS.RAM.Properties.Resources.layout_save_1;
this.biSave.Id = 56;
this.biSave.Name = "biSave";
this.biSave.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biSave_ItemClick);
//
// biFind
//
resources.ApplyResources(this.biFind, "biFind");
this.biFind.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Find;
this.biFind.Enabled = false;
this.biFind.Id = 8;
this.biFind.ImageIndex = 20;
this.biFind.Name = "biFind";
//
// biPrint
//
this.biPrint.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biPrint, "biPrint");
this.biPrint.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Print;
this.biPrint.Enabled = false;
this.biPrint.Id = 12;
this.biPrint.ImageIndex = 0;
this.biPrint.Name = "biPrint";
//
// biPrintDirect
//
resources.ApplyResources(this.biPrintDirect, "biPrintDirect");
this.biPrintDirect.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PrintDirect;
this.biPrintDirect.Enabled = false;
this.biPrintDirect.Id = 13;
this.biPrintDirect.ImageIndex = 1;
this.biPrintDirect.Name = "biPrintDirect";
//
// biPageSetup
//
this.biPageSetup.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biPageSetup, "biPageSetup");
this.biPageSetup.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup;
this.biPageSetup.Enabled = false;
this.biPageSetup.Id = 14;
this.biPageSetup.ImageIndex = 2;
this.biPageSetup.Name = "biPageSetup";
//
// biScale
//
this.biScale.ActAsDropDown = true;
this.biScale.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biScale, "biScale");
this.biScale.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Scale;
this.biScale.Enabled = false;
this.biScale.Id = 16;
this.biScale.ImageIndex = 25;
this.biScale.Name = "biScale";
//
// biHandTool
//
this.biHandTool.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biHandTool, "biHandTool");
this.biHandTool.Command = DevExpress.XtraPrinting.PrintingSystemCommand.HandTool;
this.biHandTool.Enabled = false;
this.biHandTool.Id = 17;
this.biHandTool.ImageIndex = 16;
this.biHandTool.Name = "biHandTool";
//
// biMagnifier
//
this.biMagnifier.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biMagnifier, "biMagnifier");
this.biMagnifier.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Magnifier;
this.biMagnifier.Enabled = false;
this.biMagnifier.Id = 18;
this.biMagnifier.ImageIndex = 3;
this.biMagnifier.Name = "biMagnifier";
//
// biZoomOut
//
resources.ApplyResources(this.biZoomOut, "biZoomOut");
this.biZoomOut.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomOut;
this.biZoomOut.Enabled = false;
this.biZoomOut.Id = 19;
this.biZoomOut.ImageIndex = 5;
this.biZoomOut.Name = "biZoomOut";
//
// biZoom
//
resources.ApplyResources(this.biZoom, "biZoom");
this.biZoom.Edit = this.printPreviewRepositoryItemComboBox1;
this.biZoom.EditValue = "100%";
this.biZoom.Enabled = false;
this.biZoom.Id = 20;
this.biZoom.Name = "biZoom";
//
// printPreviewRepositoryItemComboBox1
//
this.printPreviewRepositoryItemComboBox1.AutoComplete = false;
this.printPreviewRepositoryItemComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("printPreviewRepositoryItemComboBox1.Buttons"))))});
this.printPreviewRepositoryItemComboBox1.DropDownRows = 11;
this.printPreviewRepositoryItemComboBox1.Name = "printPreviewRepositoryItemComboBox1";
//
// ZoomIn
//
resources.ApplyResources(this.ZoomIn, "ZoomIn");
this.ZoomIn.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomIn;
this.ZoomIn.Enabled = false;
this.ZoomIn.Id = 21;
this.ZoomIn.ImageIndex = 4;
this.ZoomIn.Name = "ZoomIn";
//
// biShowFirstPage
//
resources.ApplyResources(this.biShowFirstPage, "biShowFirstPage");
this.biShowFirstPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowFirstPage;
this.biShowFirstPage.Enabled = false;
this.biShowFirstPage.Id = 22;
this.biShowFirstPage.ImageIndex = 7;
this.biShowFirstPage.Name = "biShowFirstPage";
//
// biShowPrevPage
//
resources.ApplyResources(this.biShowPrevPage, "biShowPrevPage");
this.biShowPrevPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowPrevPage;
this.biShowPrevPage.Enabled = false;
this.biShowPrevPage.Id = 23;
this.biShowPrevPage.ImageIndex = 8;
this.biShowPrevPage.Name = "biShowPrevPage";
//
// biShowNextPage
//
resources.ApplyResources(this.biShowNextPage, "biShowNextPage");
this.biShowNextPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowNextPage;
this.biShowNextPage.Enabled = false;
this.biShowNextPage.Id = 24;
this.biShowNextPage.ImageIndex = 9;
this.biShowNextPage.Name = "biShowNextPage";
//
// biShowLastPage
//
resources.ApplyResources(this.biShowLastPage, "biShowLastPage");
this.biShowLastPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowLastPage;
this.biShowLastPage.Enabled = false;
this.biShowLastPage.Id = 25;
this.biShowLastPage.ImageIndex = 10;
this.biShowLastPage.Name = "biShowLastPage";
//
// biMultiplePages
//
this.biMultiplePages.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biMultiplePages, "biMultiplePages");
this.biMultiplePages.Command = DevExpress.XtraPrinting.PrintingSystemCommand.MultiplePages;
this.biMultiplePages.Enabled = false;
this.biMultiplePages.Id = 26;
this.biMultiplePages.ImageIndex = 11;
this.biMultiplePages.Name = "biMultiplePages";
//
// biFillBackground
//
this.biFillBackground.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biFillBackground, "biFillBackground");
this.biFillBackground.Command = DevExpress.XtraPrinting.PrintingSystemCommand.FillBackground;
this.biFillBackground.Enabled = false;
this.biFillBackground.Id = 27;
this.biFillBackground.ImageIndex = 12;
this.biFillBackground.Name = "biFillBackground";
//
// biExportFile
//
this.biExportFile.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biExportFile, "biExportFile");
this.biExportFile.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportFile;
this.biExportFile.Enabled = false;
this.biExportFile.Id = 29;
this.biExportFile.ImageIndex = 18;
this.biExportFile.Name = "biExportFile";
//
// previewBar2
//
this.previewBar2.BarName = "Status Bar";
this.previewBar2.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.previewBar2.DockCol = 0;
this.previewBar2.DockRow = 0;
this.previewBar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.previewBar2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewStaticItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.barStaticItem1, true),
new DevExpress.XtraBars.LinkPersistInfo(this.progressBarEditItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewStaticItem2, true)});
this.previewBar2.OptionsBar.AllowQuickCustomization = false;
this.previewBar2.OptionsBar.DrawDragBorder = false;
this.previewBar2.OptionsBar.UseWholeRow = true;
resources.ApplyResources(this.previewBar2, "previewBar2");
//
// printPreviewStaticItem1
//
this.printPreviewStaticItem1.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.printPreviewStaticItem1, "printPreviewStaticItem1");
this.printPreviewStaticItem1.Id = 0;
this.printPreviewStaticItem1.LeftIndent = 1;
this.printPreviewStaticItem1.Name = "printPreviewStaticItem1";
this.printPreviewStaticItem1.RightIndent = 1;
this.printPreviewStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near;
this.printPreviewStaticItem1.Type = "PageOfPages";
//
// barStaticItem1
//
this.barStaticItem1.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.barStaticItem1.Id = 1;
this.barStaticItem1.Name = "barStaticItem1";
this.barStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near;
//
// progressBarEditItem1
//
this.progressBarEditItem1.Edit = this.repositoryItemProgressBar1;
this.progressBarEditItem1.EditHeight = 12;
this.progressBarEditItem1.Id = 2;
this.progressBarEditItem1.Name = "progressBarEditItem1";
this.progressBarEditItem1.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
resources.ApplyResources(this.progressBarEditItem1, "progressBarEditItem1");
//
// repositoryItemProgressBar1
//
this.repositoryItemProgressBar1.Name = "repositoryItemProgressBar1";
//
// printPreviewBarItem1
//
resources.ApplyResources(this.printPreviewBarItem1, "printPreviewBarItem1");
this.printPreviewBarItem1.Command = DevExpress.XtraPrinting.PrintingSystemCommand.StopPageBuilding;
this.printPreviewBarItem1.Enabled = false;
this.printPreviewBarItem1.Id = 3;
this.printPreviewBarItem1.Name = "printPreviewBarItem1";
this.printPreviewBarItem1.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
//
// barButtonItem1
//
this.barButtonItem1.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Left;
this.barButtonItem1.Enabled = false;
this.barButtonItem1.Id = 4;
this.barButtonItem1.Name = "barButtonItem1";
//
// printPreviewStaticItem2
//
this.printPreviewStaticItem2.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right;
this.printPreviewStaticItem2.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.printPreviewStaticItem2, "printPreviewStaticItem2");
this.printPreviewStaticItem2.Id = 5;
this.printPreviewStaticItem2.Name = "printPreviewStaticItem2";
this.printPreviewStaticItem2.TextAlignment = System.Drawing.StringAlignment.Near;
this.printPreviewStaticItem2.Type = "ZoomFactor";
//
// previewBar3
//
this.previewBar3.BarName = "Main Menu";
this.previewBar3.DockCol = 0;
this.previewBar3.DockRow = 0;
this.previewBar3.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.previewBar3.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewSubItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewSubItem2),
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewSubItem3)});
this.previewBar3.OptionsBar.MultiLine = true;
this.previewBar3.OptionsBar.UseWholeRow = true;
resources.ApplyResources(this.previewBar3, "previewBar3");
this.previewBar3.Visible = false;
//
// printPreviewSubItem1
//
resources.ApplyResources(this.printPreviewSubItem1, "printPreviewSubItem1");
this.printPreviewSubItem1.Command = DevExpress.XtraPrinting.PrintingSystemCommand.File;
this.printPreviewSubItem1.Id = 32;
this.printPreviewSubItem1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biPageSetup),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrint),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrintDirect),
new DevExpress.XtraBars.LinkPersistInfo(this.biExportFile, true)});
this.printPreviewSubItem1.Name = "printPreviewSubItem1";
//
// printPreviewSubItem2
//
resources.ApplyResources(this.printPreviewSubItem2, "printPreviewSubItem2");
this.printPreviewSubItem2.Command = DevExpress.XtraPrinting.PrintingSystemCommand.View;
this.printPreviewSubItem2.Id = 33;
this.printPreviewSubItem2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewSubItem4, true),
new DevExpress.XtraBars.LinkPersistInfo(this.barToolbarsListItem1, true)});
this.printPreviewSubItem2.Name = "printPreviewSubItem2";
//
// printPreviewSubItem4
//
resources.ApplyResources(this.printPreviewSubItem4, "printPreviewSubItem4");
this.printPreviewSubItem4.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayout;
this.printPreviewSubItem4.Id = 35;
this.printPreviewSubItem4.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem27),
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem28)});
this.printPreviewSubItem4.Name = "printPreviewSubItem4";
//
// printPreviewBarItem27
//
this.printPreviewBarItem27.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem27, "printPreviewBarItem27");
this.printPreviewBarItem27.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutFacing;
this.printPreviewBarItem27.Enabled = false;
this.printPreviewBarItem27.GroupIndex = 100;
this.printPreviewBarItem27.Id = 36;
this.printPreviewBarItem27.Name = "printPreviewBarItem27";
//
// printPreviewBarItem28
//
this.printPreviewBarItem28.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem28, "printPreviewBarItem28");
this.printPreviewBarItem28.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutContinuous;
this.printPreviewBarItem28.Enabled = false;
this.printPreviewBarItem28.GroupIndex = 100;
this.printPreviewBarItem28.Id = 37;
this.printPreviewBarItem28.Name = "printPreviewBarItem28";
//
// barToolbarsListItem1
//
resources.ApplyResources(this.barToolbarsListItem1, "barToolbarsListItem1");
this.barToolbarsListItem1.Id = 38;
this.barToolbarsListItem1.Name = "barToolbarsListItem1";
//
// printPreviewSubItem3
//
resources.ApplyResources(this.printPreviewSubItem3, "printPreviewSubItem3");
this.printPreviewSubItem3.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Background;
this.printPreviewSubItem3.Id = 34;
this.printPreviewSubItem3.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biFillBackground)});
this.printPreviewSubItem3.Name = "printPreviewSubItem3";
//
// biExportPdf
//
resources.ApplyResources(this.biExportPdf, "biExportPdf");
this.biExportPdf.Checked = true;
this.biExportPdf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportPdf;
this.biExportPdf.Enabled = false;
this.biExportPdf.GroupIndex = 1;
this.biExportPdf.Id = 39;
this.biExportPdf.Name = "biExportPdf";
//
// biExportHtm
//
resources.ApplyResources(this.biExportHtm, "biExportHtm");
this.biExportHtm.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportHtm;
this.biExportHtm.Enabled = false;
this.biExportHtm.GroupIndex = 1;
this.biExportHtm.Id = 40;
this.biExportHtm.Name = "biExportHtm";
//
// biExportMht
//
resources.ApplyResources(this.biExportMht, "biExportMht");
this.biExportMht.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportMht;
this.biExportMht.Enabled = false;
this.biExportMht.GroupIndex = 1;
this.biExportMht.Id = 41;
this.biExportMht.Name = "biExportMht";
//
// biExportRtf
//
resources.ApplyResources(this.biExportRtf, "biExportRtf");
this.biExportRtf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportRtf;
this.biExportRtf.Enabled = false;
this.biExportRtf.GroupIndex = 1;
this.biExportRtf.Id = 42;
this.biExportRtf.Name = "biExportRtf";
//
// biExportXls
//
resources.ApplyResources(this.biExportXls, "biExportXls");
this.biExportXls.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportXls;
this.biExportXls.Enabled = false;
this.biExportXls.GroupIndex = 1;
this.biExportXls.Id = 43;
this.biExportXls.Name = "biExportXls";
//
// biExportCsv
//
resources.ApplyResources(this.biExportCsv, "biExportCsv");
this.biExportCsv.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportCsv;
this.biExportCsv.Enabled = false;
this.biExportCsv.GroupIndex = 1;
this.biExportCsv.Id = 44;
this.biExportCsv.Name = "biExportCsv";
//
// biExportTxt
//
resources.ApplyResources(this.biExportTxt, "biExportTxt");
this.biExportTxt.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportTxt;
this.biExportTxt.Enabled = false;
this.biExportTxt.GroupIndex = 1;
this.biExportTxt.Id = 45;
this.biExportTxt.Name = "biExportTxt";
//
// biExportGraphic
//
resources.ApplyResources(this.biExportGraphic, "biExportGraphic");
this.biExportGraphic.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportGraphic;
this.biExportGraphic.Enabled = false;
this.biExportGraphic.GroupIndex = 1;
this.biExportGraphic.Id = 46;
this.biExportGraphic.Name = "biExportGraphic";
//
// printPreviewBarItem2
//
this.printPreviewBarItem2.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem2, "printPreviewBarItem2");
this.printPreviewBarItem2.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup;
this.printPreviewBarItem2.Enabled = false;
this.printPreviewBarItem2.Id = 14;
this.printPreviewBarItem2.ImageIndex = 2;
this.printPreviewBarItem2.Name = "printPreviewBarItem2";
//
// grcMap
//
this.grcMap.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.grcMap.Controls.Add(this.grcReportMain);
this.grcMap.Controls.Add(this.nbControlReport);
resources.ApplyResources(this.grcMap, "grcMap");
this.grcMap.MinimumSize = new System.Drawing.Size(400, 300);
this.grcMap.Name = "grcMap";
this.grcMap.ShowCaption = false;
//
// grcReportMain
//
this.grcReportMain.Controls.Add(this.printControlReport);
resources.ApplyResources(this.grcReportMain, "grcReportMain");
this.grcReportMain.Name = "grcReportMain";
//
// nbControlReport
//
this.nbControlReport.ActiveGroup = this.nbGroupSettings;
this.nbControlReport.ContentButtonHint = null;
this.nbControlReport.Controls.Add(this.nbContainerSettings);
resources.ApplyResources(this.nbControlReport, "nbControlReport");
this.nbControlReport.ExplorerBarGroupInterval = 1;
this.nbControlReport.ExplorerBarGroupOuterIndent = 0;
this.nbControlReport.Groups.AddRange(new DevExpress.XtraNavBar.NavBarGroup[] {
this.nbGroupSettings});
this.nbControlReport.LookAndFeel.SkinName = "Black";
this.nbControlReport.LookAndFeel.UseDefaultLookAndFeel = false;
this.nbControlReport.Name = "nbControlReport";
this.nbControlReport.OptionsNavPane.ExpandedWidth = ((int)(resources.GetObject("resource.ExpandedWidth")));
this.nbControlReport.View = new DevExpress.XtraNavBar.ViewInfo.StandardSkinExplorerBarViewInfoRegistrator("Blue");
this.nbControlReport.GroupExpanded += new DevExpress.XtraNavBar.NavBarGroupEventHandler(this.nbControlReport_GroupExpanded);
this.nbControlReport.GroupCollapsed += new DevExpress.XtraNavBar.NavBarGroupEventHandler(this.nbControlReport_GroupCollapsed);
//
// nbGroupSettings
//
resources.ApplyResources(this.nbGroupSettings, "nbGroupSettings");
this.nbGroupSettings.ControlContainer = this.nbContainerSettings;
this.nbGroupSettings.Expanded = true;
this.nbGroupSettings.GroupClientHeight = 66;
this.nbGroupSettings.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer;
this.nbGroupSettings.Name = "nbGroupSettings";
//
// nbContainerSettings
//
this.nbContainerSettings.Controls.Add(this.grcMapSettings);
this.nbContainerSettings.Name = "nbContainerSettings";
resources.ApplyResources(this.nbContainerSettings, "nbContainerSettings");
//
// grcMapSettings
//
this.grcMapSettings.Controls.Add(this.lblPivotName);
this.grcMapSettings.Controls.Add(this.memFilter);
this.grcMapSettings.Controls.Add(this.tbPivotName);
this.grcMapSettings.Controls.Add(this.lblFilter);
resources.ApplyResources(this.grcMapSettings, "grcMapSettings");
this.grcMapSettings.Name = "grcMapSettings";
this.grcMapSettings.ShowCaption = false;
//
// lblPivotName
//
resources.ApplyResources(this.lblPivotName, "lblPivotName");
this.lblPivotName.Name = "lblPivotName";
//
// memFilter
//
resources.ApplyResources(this.memFilter, "memFilter");
this.memFilter.Name = "memFilter";
this.memFilter.Properties.Appearance.Options.UseFont = true;
this.memFilter.Properties.AppearanceDisabled.Options.UseFont = true;
this.memFilter.Properties.AppearanceFocused.Options.UseFont = true;
this.memFilter.Properties.AppearanceReadOnly.Options.UseFont = true;
this.memFilter.Tag = "{alwayseditable}";
this.memFilter.Leave += new System.EventHandler(this.memFilter_Leave);
//
// tbPivotName
//
resources.ApplyResources(this.tbPivotName, "tbPivotName");
this.tbPivotName.Name = "tbPivotName";
this.tbPivotName.Properties.Appearance.Options.UseFont = true;
this.tbPivotName.Properties.AppearanceDisabled.Options.UseFont = true;
this.tbPivotName.Properties.AppearanceFocused.Options.UseFont = true;
this.tbPivotName.Properties.AppearanceReadOnly.Options.UseFont = true;
this.tbPivotName.Tag = "{alwayseditable}";
this.tbPivotName.Leave += new System.EventHandler(this.tbPivotName_Leave);
//
// lblFilter
//
resources.ApplyResources(this.lblFilter, "lblFilter");
this.lblFilter.Name = "lblFilter";
//
// PivotReportForm
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.grcMap);
this.HelpTopicID = "AVR_Reports_Management";
this.Name = "PivotReportForm";
this.printControlReport.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.printBarManager)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grcMap)).EndInit();
this.grcMap.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.grcReportMain)).EndInit();
this.grcReportMain.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.nbControlReport)).EndInit();
this.nbControlReport.ResumeLayout(false);
this.nbContainerSettings.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.grcMapSettings)).EndInit();
this.grcMapSettings.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.memFilter.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tbPivotName.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraPrinting.Control.PrintControl printControlReport;
private DevExpress.XtraPrinting.Preview.PrintBarManager printBarManager;
private DevExpress.XtraPrinting.Preview.PreviewBar previewBar1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFind;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrint;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrintDirect;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPageSetup;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biScale;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biHandTool;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMagnifier;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biZoomOut;
private DevExpress.XtraPrinting.Preview.ZoomBarEditItem biZoom;
private DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox printPreviewRepositoryItemComboBox1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem ZoomIn;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowFirstPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowPrevPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowNextPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowLastPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMultiplePages;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFillBackground;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biExportFile;
private DevExpress.XtraPrinting.Preview.PreviewBar previewBar2;
private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem printPreviewStaticItem1;
private DevExpress.XtraBars.BarStaticItem barStaticItem1;
private DevExpress.XtraPrinting.Preview.ProgressBarEditItem progressBarEditItem1;
private DevExpress.XtraEditors.Repository.RepositoryItemProgressBar repositoryItemProgressBar1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem1;
private DevExpress.XtraBars.BarButtonItem barButtonItem1;
private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem printPreviewStaticItem2;
private DevExpress.XtraPrinting.Preview.PreviewBar previewBar3;
private DevExpress.XtraPrinting.Preview.PrintPreviewSubItem printPreviewSubItem1;
private DevExpress.XtraPrinting.Preview.PrintPreviewSubItem printPreviewSubItem2;
private DevExpress.XtraPrinting.Preview.PrintPreviewSubItem printPreviewSubItem4;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem27;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem28;
private DevExpress.XtraBars.BarToolbarsListItem barToolbarsListItem1;
private DevExpress.XtraPrinting.Preview.PrintPreviewSubItem printPreviewSubItem3;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportPdf;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportHtm;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportMht;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportRtf;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportXls;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportCsv;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportTxt;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportGraphic;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem2;
private DevExpress.XtraBars.BarButtonItem biFilter;
private DevExpress.XtraBars.BarButtonItem biSave;
private DevExpress.XtraBars.BarButtonItem biCancelChanges;
private DevExpress.XtraEditors.GroupControl grcMap;
private DevExpress.XtraEditors.GroupControl grcReportMain;
private DevExpress.XtraNavBar.NavBarControl nbControlReport;
private DevExpress.XtraNavBar.NavBarGroup nbGroupSettings;
private DevExpress.XtraNavBar.NavBarGroupControlContainer nbContainerSettings;
private DevExpress.XtraEditors.GroupControl grcMapSettings;
private System.Windows.Forms.Label lblFilter;
private System.Windows.Forms.Label lblPivotName;
private DevExpress.XtraEditors.MemoEdit memFilter;
private DevExpress.XtraEditors.TextEdit tbPivotName;
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
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.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SpatialAnalysis.Data;
namespace SpatialAnalysis.Agents.MandatoryScenario.Visualization
{
/// <summary>
/// Interaction logic for RealTimeMandatoryNavigationControler.xaml
/// </summary>
///
public partial class RealTimeMandatoryNavigationControler : Window
{
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
this.Owner.WindowState = this.WindowState;
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
this._velocityMin.TextChanged -= _velocityMin_TextChanged;
this._velocity.ValueChanged -= _velocity_ValueChanged;
this._velocityMax.TextChanged -= _velocityMax_TextChanged;
this._angularVelocityMin.TextChanged -= _angularVelocityMin_TextChanged;
this._angularVelocity.ValueChanged -= _angularVelocity_ValueChanged;
this._angularVelocityMax.TextChanged -= _angularVelocityMax_TextChanged;
this._bodySizeMin.TextChanged -= _bodySizeMin_TextChanged;
this._bodySize.ValueChanged -= _bodySize_ValueChanged;
this._bodySizeMax.TextChanged -= _bodySizeMax_TextChanged;
this._viewAngleMin.TextChanged -= _viewAngleMin_TextChanged;
this._viewAngle.ValueChanged -= _viewAngle_ValueChanged;
this._viewAngleMax.TextChanged -= _viewAngleMax_TextChanged;
this._minBarrierRepulsionRange.TextChanged -= _minBarrierRepulsionRange_TextChanged;
this._barrierRepulsionRange.ValueChanged -= _barrierRepulsionRange_ValueChanged;
this._maxBarrierRepulsionRange.TextChanged -= _maxBarrierRepulsionRange_TextChanged;
this._minRepulsionChangeRate.TextChanged -= _minRepulsionChangeRate_TextChanged;
this._repulsionChangeRate.ValueChanged -= _repulsionChangeRate_ValueChanged;
this._maxRepulsionChangeRate.TextChanged -= _maxRepulsionChangeRate_TextChanged;
this._accelerationMagnitudeMin.TextChanged -= _accelerationMagnitudeMin_TextChanged;
this._accelerationMagnitude.ValueChanged -= _accelerationMagnitude_ValueChanged;
this._accelerationMagnitudeMax.TextChanged -= _accelerationMagnitudeMax_TextChanged;
this._barrierFrictionMin.TextChanged -= _barrierFrictionMin_TextChanged;
this._barrierFriction.ValueChanged -= _barrierFriction_ValueChanged;
this._barrierFrictionMax.TextChanged -= _barrierFrictionMax_TextChanged;
this._bodyElasticityMin.TextChanged -= _bodyElasticityMin_TextChanged;
this._bodyElasticity.ValueChanged -= _bodyElasticity_ValueChanged;
this._bodyElasticityMax.TextChanged -= _bodyElasticityMax_TextChanged;
}
public RealTimeMandatoryNavigationControler()
{
InitializeComponent();
this._velocityMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Minimum.ToString();
this._velocityMin.TextChanged += _velocityMin_TextChanged;
this._velocity.Value = Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Value;
this._velocity.ValueChanged += _velocity_ValueChanged;
this._velocityMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Maximum.ToString();
this._velocityMax.TextChanged += _velocityMax_TextChanged;
this._angularVelocityMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Minimum.ToString();
this._angularVelocityMin.TextChanged += _angularVelocityMin_TextChanged;
this._angularVelocity.Value = Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Value;
this._angularVelocity.ValueChanged += _angularVelocity_ValueChanged;
this._angularVelocityMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Maximum.ToString();
this._angularVelocityMax.TextChanged += _angularVelocityMax_TextChanged;
this._bodySizeMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Minimum.ToString();
this._bodySizeMin.TextChanged += _bodySizeMin_TextChanged;
this._bodySize.Value = Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Value;
this._bodySize.ValueChanged += _bodySize_ValueChanged;
this._bodySizeMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Maximum.ToString();
this._bodySizeMax.TextChanged += _bodySizeMax_TextChanged;
this._viewAngleMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Minimum.ToString();
this._viewAngleMin.TextChanged += _viewAngleMin_TextChanged;
this._viewAngle.Value = Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Value;
this._viewAngle.ValueChanged += _viewAngle_ValueChanged;
this._viewAngleMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Maximum.ToString();
this._viewAngleMax.TextChanged += _viewAngleMax_TextChanged;
this._minBarrierRepulsionRange.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Minimum.ToString();
this._minBarrierRepulsionRange.TextChanged += _minBarrierRepulsionRange_TextChanged;
this._barrierRepulsionRange.Value = Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Value;
this._barrierRepulsionRange.ValueChanged += _barrierRepulsionRange_ValueChanged;
this._maxBarrierRepulsionRange.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Maximum.ToString();
this._maxBarrierRepulsionRange.TextChanged += _maxBarrierRepulsionRange_TextChanged;
this._minRepulsionChangeRate.Text = Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Minimum.ToString();
this._minRepulsionChangeRate.TextChanged += _minRepulsionChangeRate_TextChanged;
this._repulsionChangeRate.Value = Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Value;
this._repulsionChangeRate.ValueChanged += _repulsionChangeRate_ValueChanged;
this._maxRepulsionChangeRate.Text = Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Maximum.ToString();
this._maxRepulsionChangeRate.TextChanged += _maxRepulsionChangeRate_TextChanged;
this._accelerationMagnitudeMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Minimum.ToString();
this._accelerationMagnitudeMin.TextChanged += _accelerationMagnitudeMin_TextChanged;
this._accelerationMagnitude.Value = Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Value;
this._accelerationMagnitude.ValueChanged += _accelerationMagnitude_ValueChanged;
this._accelerationMagnitudeMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Maximum.ToString();
this._accelerationMagnitudeMax.TextChanged += _accelerationMagnitudeMax_TextChanged;
this._barrierFrictionMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Minimum.ToString();
this._barrierFrictionMin.TextChanged += _barrierFrictionMin_TextChanged;
this._barrierFriction.Value = Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Value;
this._barrierFriction.ValueChanged += _barrierFriction_ValueChanged;
this._barrierFrictionMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Maximum.ToString();
this._barrierFrictionMax.TextChanged += _barrierFrictionMax_TextChanged;
this._bodyElasticityMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Minimum.ToString();
this._bodyElasticityMin.TextChanged += _bodyElasticityMin_TextChanged;
this._bodyElasticity.Value = Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Value;
this._bodyElasticity.ValueChanged += _bodyElasticity_ValueChanged;
this._bodyElasticityMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Maximum.ToString();
this._bodyElasticityMax.TextChanged += _bodyElasticityMax_TextChanged;
}
void _bodyElasticityMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _bodyElasticity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Value = e.NewValue;
}
void _bodyElasticityMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _barrierFrictionMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _barrierFriction_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Value = e.NewValue;
}
void _barrierFrictionMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _accelerationMagnitudeMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _accelerationMagnitude_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Value = e.NewValue;
}
void _accelerationMagnitudeMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _maxRepulsionChangeRate_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _repulsionChangeRate_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Value = e.NewValue;
}
void _minRepulsionChangeRate_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _maxBarrierRepulsionRange_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _barrierRepulsionRange_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Value = e.NewValue;
}
void _minBarrierRepulsionRange_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _viewAngleMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _viewAngle_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Value = e.NewValue;
}
void _viewAngleMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _bodySizeMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _bodySize_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Value = e.NewValue;
}
void _bodySizeMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _angularVelocityMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _angularVelocity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Value = e.NewValue;
}
catch (Exception ) { }
}
void _angularVelocityMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _velocityMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _velocity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Value = e.NewValue;
}
void _velocityMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Prism.Regions;
using Prism.Regions.Behaviors;
using Prism.Wpf.Tests.Mocks;
namespace Prism.Wpf.Tests.Regions.Behaviors
{
[TestClass]
public class RegionMemberLifetimeBehaviorFixture
{
protected Region Region { get; set; }
protected RegionMemberLifetimeBehavior Behavior { get; set; }
[TestInitialize]
public void TestInitialize()
{
Arrange();
}
protected virtual void Arrange()
{
this.Region = new Region();
this.Behavior = new RegionMemberLifetimeBehavior();
this.Behavior.Region = this.Region;
this.Behavior.Attach();
}
[TestMethod]
public void WhenBehaviorAttachedThenReportsIsAttached()
{
Assert.IsTrue(Behavior.IsAttached);
}
[TestMethod]
public void WhenIRegionMemberLifetimeItemReturnsKeepAliveFalseRemovesWhenInactive()
{
// Arrange
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(false);
Region.Add(regionItemMock.Object);
Region.Activate(regionItemMock.Object);
// Act
Region.Deactivate(regionItemMock.Object);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItemMock.Object));
}
[TestMethod]
public void WhenIRegionMemberLifetimeItemReturnsKeepAliveTrueDoesNotRemoveOnDeactivation()
{
// Arrange
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(true);
Region.Add(regionItemMock.Object);
Region.Activate(regionItemMock.Object);
// Act
Region.Deactivate(regionItemMock.Object);
// Assert
Assert.IsTrue(Region.Views.Contains(regionItemMock.Object));
}
[TestMethod]
public void WhenRegionContainsMultipleMembers_OnlyRemovesThoseDeactivated()
{
// Arrange
var firstMockItem = new Mock<IRegionMemberLifetime>();
firstMockItem.Setup(i => i.KeepAlive).Returns(true);
var secondMockItem = new Mock<IRegionMemberLifetime>();
secondMockItem.Setup(i => i.KeepAlive).Returns(false);
Region.Add(firstMockItem.Object);
Region.Activate(firstMockItem.Object);
Region.Add(secondMockItem.Object);
Region.Activate(secondMockItem.Object);
// Act
Region.Deactivate(secondMockItem.Object);
// Assert
Assert.IsTrue(Region.Views.Contains(firstMockItem.Object));
Assert.IsFalse(Region.Views.Contains(secondMockItem.Object));
}
[TestMethod]
public void WhenMemberNeverActivatedThenIsNotRemovedOnAnothersDeactivation()
{
// Arrange
var firstMockItem = new Mock<IRegionMemberLifetime>();
firstMockItem.Setup(i => i.KeepAlive).Returns(false);
var secondMockItem = new Mock<IRegionMemberLifetime>();
secondMockItem.Setup(i => i.KeepAlive).Returns(false);
Region.Add(firstMockItem.Object); // Never activated
Region.Add(secondMockItem.Object);
Region.Activate(secondMockItem.Object);
// Act
Region.Deactivate(secondMockItem.Object);
// Assert
Assert.IsTrue(Region.Views.Contains(firstMockItem.Object));
Assert.IsFalse(Region.Views.Contains(secondMockItem.Object));
}
[TestMethod]
public virtual void RemovesRegionItemIfDataContextReturnsKeepAliveFalse()
{
// Arrange
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(false);
var regionItem = new MockFrameworkElement();
regionItem.DataContext = regionItemMock.Object;
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItem));
}
[TestMethod]
public virtual void RemovesOnlyDeactivatedItemsInRegionBasedOnDataContextKeepAlive()
{
// Arrange
var retionItemDataContextToKeepAlive = new Mock<IRegionMemberLifetime>();
retionItemDataContextToKeepAlive.Setup(i => i.KeepAlive).Returns(true);
var regionItemToKeepAlive = new MockFrameworkElement();
regionItemToKeepAlive.DataContext = retionItemDataContextToKeepAlive.Object;
Region.Add(regionItemToKeepAlive);
Region.Activate(regionItemToKeepAlive);
var regionItemMock = new Mock<IRegionMemberLifetime>();
regionItemMock.Setup(i => i.KeepAlive).Returns(false);
var regionItem = new MockFrameworkElement();
regionItem.DataContext = regionItemMock.Object;
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItem));
Assert.IsTrue(Region.Views.Contains(regionItemToKeepAlive));
}
[TestMethod]
public virtual void WillRemoveDeactivatedItemIfKeepAliveAttributeFalse()
{
// Arrange
var regionItem = new RegionMemberNotKeptAlive();
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains((object)regionItem));
}
[TestMethod]
public virtual void WillNotRemoveDeactivatedItemIfKeepAliveAttributeTrue()
{
// Arrange
var regionItem = new RegionMemberKeptAlive();
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsTrue(Region.Views.Contains((object)regionItem));
}
[TestMethod]
public virtual void WillRemoveDeactivatedItemIfDataContextKeepAliveAttributeFalse()
{
// Arrange
var regionItemDataContext = new RegionMemberNotKeptAlive();
var regionItem = new MockFrameworkElement() { DataContext = regionItemDataContext };
Region.Add(regionItem);
Region.Activate(regionItem);
// Act
Region.Deactivate(regionItem);
// Assert
Assert.IsFalse(Region.Views.Contains(regionItem));
}
[RegionMemberLifetime(KeepAlive = false)]
public class RegionMemberNotKeptAlive
{
}
[RegionMemberLifetime(KeepAlive = true)]
public class RegionMemberKeptAlive
{
}
}
[TestClass]
public class RegionMemberLifetimeBehaviorAgainstSingleActiveRegionFixture
: RegionMemberLifetimeBehaviorFixture
{
protected override void Arrange()
{
this.Region = new SingleActiveRegion();
this.Behavior = new RegionMemberLifetimeBehavior();
this.Behavior.Region = this.Region;
this.Behavior.Attach();
}
}
}
| |
#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.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
/// </summary>
public abstract partial class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// A <see cref="JsonReader"/> read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The <see cref="JsonReader.Close()"/> method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader is in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object _value;
internal char _quoteChar;
internal State _currentState;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private string _dateFormatString;
private List<JsonPosition> _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState => _currentState;
/// <summary>
/// Gets or sets a value indicating whether the source should be closed when this reader is closed.
/// </summary>
/// <value>
/// <c>true</c> to close the source when this reader is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether multiple pieces of JSON content can
/// be read from a continuous stream without erroring.
/// </summary>
/// <value>
/// <c>true</c> to support reading multiple pieces of JSON content; otherwise <c>false</c>.
/// The default is <c>false</c>.
/// </value>
public bool SupportMultipleContent { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get => _quoteChar;
protected internal set => _quoteChar = value;
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> time zones are handled when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get => _dateTimeZoneHandling;
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Gets or sets how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get => _dateParseHandling;
set
{
if (value < DateParseHandling.None ||
#if HAVE_DATE_TIME_OFFSET
value > DateParseHandling.DateTimeOffset
#else
value > DateParseHandling.DateTime
#endif
)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateParseHandling = value;
}
}
/// <summary>
/// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get => _floatParseHandling;
set
{
if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatParseHandling = value;
}
}
/// <summary>
/// Gets or sets how custom date formatted strings are parsed when reading JSON.
/// </summary>
public string DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = value;
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get => _maxDepth;
set
{
if (value <= 0)
{
throw new ArgumentException("Value must be positive.", nameof(value));
}
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType => _tokenType;
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value => _value;
/// <summary>
/// Gets the .NET type for the current JSON token.
/// </summary>
public virtual Type ValueType => _value?.GetType();
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _stack?.Count ?? 0;
if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
{
return depth;
}
else
{
return depth + 1;
}
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get => _culture ?? CultureInfo.InvariantCulture;
set => _culture = value;
}
internal JsonPosition GetPosition(int depth)
{
if (_stack != null && depth < _stack.Count)
{
return _stack[depth];
}
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack != null && _stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
{
_hasExceededMaxDepth = false;
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the source.
/// </summary>
/// <returns><c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Int32"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Int32"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual int? ReadAsInt32()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
if (v is int i)
{
return i;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
i = (int)value;
}
else
#endif
{
try
{
i = Convert.ToInt32(v, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
// handle error for large integer overflow exceptions
throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex);
}
}
SetToken(JsonToken.Integer, i, false);
return i;
case JsonToken.String:
string s = (string)Value;
return ReadInt32String(s);
}
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadInt32String(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out int i))
{
SetToken(JsonToken.Integer, i, false);
return i;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual string ReadAsString()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.String:
return (string)Value;
}
if (JsonTokenUtils.IsPrimitiveToken(t))
{
object v = Value;
if (v != null)
{
string s;
if (v is IFormattable formattable)
{
s = formattable.ToString(null, Culture);
}
else
{
Uri uri = v as Uri;
s = uri != null ? uri.OriginalString : v.ToString();
}
SetToken(JsonToken.String, s, false);
return s;
}
}
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Byte"/>[].
/// </summary>
/// <returns>A <see cref="Byte"/>[] or <c>null</c> if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public virtual byte[] ReadAsBytes()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.StartObject:
{
ReadIntoWrappedTypeObject();
byte[] data = ReadAsBytes();
ReaderReadAndAssert();
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
case JsonToken.String:
{
// attempt to convert possible base 64 or GUID string to bytes
// GUID has to have format 00000000-0000-0000-0000-000000000000
string s = (string)Value;
byte[] data;
if (s.Length == 0)
{
data = CollectionUtils.ArrayEmpty<byte>();
}
else if (ConvertUtils.TryConvertGuid(s, out Guid g1))
{
data = g1.ToByteArray();
}
else
{
data = Convert.FromBase64String(s);
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Bytes:
if (Value is Guid g2)
{
byte[] data = g2.ToByteArray();
SetToken(JsonToken.Bytes, data, false);
return data;
}
return (byte[])Value;
case JsonToken.StartArray:
return ReadArrayIntoByteArray();
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal byte[] ReadArrayIntoByteArray()
{
List<byte> buffer = new List<byte>();
while (true)
{
if (!Read())
{
SetToken(JsonToken.None);
}
if (ReadArrayElementIntoByteArrayReportDone(buffer))
{
byte[] d = buffer.ToArray();
SetToken(JsonToken.Bytes, d, false);
return d;
}
}
}
private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
{
switch (TokenType)
{
case JsonToken.None:
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
case JsonToken.Integer:
buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
return false;
case JsonToken.EndArray:
return true;
case JsonToken.Comment:
return false;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Double"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Double"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual double? ReadAsDouble()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
if (v is double d)
{
return d;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
d = (double)value;
}
else
#endif
{
d = Convert.ToDouble(v, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Float, d, false);
return (double)d;
case JsonToken.String:
return ReadDoubleString((string)Value);
}
throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal double? ReadDoubleString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out double d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Boolean"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Boolean"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual bool? ReadAsBoolean()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger integer)
{
b = integer != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case JsonToken.String:
return ReadBooleanString((string)Value);
case JsonToken.Boolean:
return (bool)Value;
}
throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal bool? ReadBooleanString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (bool.TryParse(s, out bool b))
{
SetToken(JsonToken.Boolean, b, false);
return b;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Decimal"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Decimal"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual decimal? ReadAsDecimal()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
if (v is decimal d)
{
return d;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
d = (decimal)value;
}
else
#endif
{
try
{
d = Convert.ToDecimal(v, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
// handle error for large integer overflow exceptions
throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex);
}
}
SetToken(JsonToken.Float, d, false);
return d;
case JsonToken.String:
return ReadDecimalString((string)Value);
}
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadDecimalString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
decimal d;
if (decimal.TryParse(s, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out d) == ParseResult.Success)
{
// This is to handle strings like "96.014e-05" that are not supported by traditional decimal.TryParse
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual DateTime? ReadAsDateTime()
{
switch (GetContentToken())
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Date:
#if HAVE_DATE_TIME_OFFSET
if (Value is DateTimeOffset offset)
{
SetToken(JsonToken.Date, offset.DateTime, false);
}
#endif
return (DateTime)Value;
case JsonToken.String:
string s = (string)Value;
return ReadDateTimeString(s);
}
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal DateTime? ReadDateTimeString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out DateTime dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual DateTimeOffset? ReadAsDateTimeOffset()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Date:
if (Value is DateTime time)
{
SetToken(JsonToken.Date, new DateTimeOffset(time), false);
}
return (DateTimeOffset)Value;
case JsonToken.String:
string s = (string)Value;
return ReadDateTimeOffsetString(s);
default:
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
internal DateTimeOffset? ReadDateTimeOffsetString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out DateTimeOffset dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
#endif
internal void ReaderReadAndAssert()
{
if (!Read())
{
throw CreateUnexpectedEndException();
}
}
internal JsonReaderException CreateUnexpectedEndException()
{
return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
}
internal void ReadIntoWrappedTypeObject()
{
ReaderReadAndAssert();
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
ReaderReadAndAssert();
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
ReaderReadAndAssert();
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
{
Read();
}
if (JsonTokenUtils.IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
{
SetToken(newToken, value, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
/// <param name="updateIndex">A flag indicating whether the position index inside an array should be updated.</param>
protected void SetToken(JsonToken newToken, object value, bool updateIndex)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string)value;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
SetPostValueState(updateIndex);
break;
}
}
internal void SetPostValueState(bool updateIndex)
{
if (Peek() != JsonContainerType.None || SupportMultipleContent)
{
_currentState = State.PostValue;
}
else
{
SetFinished();
}
if (updateIndex)
{
UpdateScopeWithFinishedValue();
}
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
{
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
}
if (Peek() != JsonContainerType.None || SupportMultipleContent)
{
_currentState = State.PostValue;
}
else
{
SetFinished();
}
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
SetFinished();
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
private void SetFinished()
{
_currentState = SupportMultipleContent ? State.Start : State.Finished;
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
{
Close();
}
}
/// <summary>
/// Changes the reader's state to <see cref="JsonReader.State.Closed"/>.
/// If <see cref="JsonReader.CloseInput"/> is set to <c>true</c>, the source is also closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
internal void ReadAndAssert()
{
if (!Read())
{
throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
}
}
internal void ReadForTypeAndAssert(JsonContract contract, bool hasConverter)
{
if (!ReadForType(contract, hasConverter))
{
throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
}
}
internal bool ReadForType(JsonContract contract, bool hasConverter)
{
// don't read properties with converters as a specific value
// the value might be a string which will then get converted which will error if read as date for example
if (hasConverter)
{
return Read();
}
ReadType t = contract?.InternalReadType ?? ReadType.Read;
switch (t)
{
case ReadType.Read:
return ReadAndMoveToContent();
case ReadType.ReadAsInt32:
ReadAsInt32();
break;
case ReadType.ReadAsInt64:
bool result = ReadAndMoveToContent();
if (TokenType == JsonToken.Undefined)
{
throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
}
return result;
case ReadType.ReadAsDecimal:
ReadAsDecimal();
break;
case ReadType.ReadAsDouble:
ReadAsDouble();
break;
case ReadType.ReadAsBytes:
ReadAsBytes();
break;
case ReadType.ReadAsBoolean:
ReadAsBoolean();
break;
case ReadType.ReadAsString:
ReadAsString();
break;
case ReadType.ReadAsDateTime:
ReadAsDateTime();
break;
#if HAVE_DATE_TIME_OFFSET
case ReadType.ReadAsDateTimeOffset:
ReadAsDateTimeOffset();
break;
#endif
default:
throw new ArgumentOutOfRangeException();
}
return (TokenType != JsonToken.None);
}
internal bool ReadAndMoveToContent()
{
return Read() && MoveToContent();
}
internal bool MoveToContent()
{
JsonToken t = TokenType;
while (t == JsonToken.None || t == JsonToken.Comment)
{
if (!Read())
{
return false;
}
t = TokenType;
}
return true;
}
private JsonToken GetContentToken()
{
JsonToken t;
do
{
if (!Read())
{
SetToken(JsonToken.None);
return JsonToken.None;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
return t;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using Microsoft.Research.Tools;
namespace Microsoft.Research.DryadAnalysis
{
partial class ClusterBrowser
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ClusterBrowser));
this.contextMenuStrip_job = new System.Windows.Forms.ContextMenuStrip(this.components);
this.openInJobBrowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.diagnoseToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.terminateToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.cancelToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.statuslabel = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar = new System.Windows.Forms.ToolStripProgressBar();
this.flowLayoutPanel_header = new System.Windows.Forms.FlowLayoutPanel();
this.label_vc = new System.Windows.Forms.Label();
this.comboBox_virtualCluster = new System.Windows.Forms.ComboBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.jobToolStripMenuItem_file = new System.Windows.Forms.ToolStripMenuItem();
this.newWindowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.refreshToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem_job = new System.Windows.Forms.ToolStripMenuItem();
this.jobBrowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.diagnoseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.terminateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFromURLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.logFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.autoRefreshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clusterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.filteredDataGridView = new FilteredDataGridView();
this.contextMenuStrip_job.SuspendLayout();
this.statusStrip.SuspendLayout();
this.flowLayoutPanel_header.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// contextMenuStrip_job
//
this.contextMenuStrip_job.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openInJobBrowserToolStripMenuItem,
this.diagnoseToolStripMenuItem1,
this.terminateToolStripMenuItem1});
this.contextMenuStrip_job.Name = "contextMenuStrip_job";
this.contextMenuStrip_job.Size = new System.Drawing.Size(182, 70);
//
// openInJobBrowserToolStripMenuItem
//
this.openInJobBrowserToolStripMenuItem.Name = "openInJobBrowserToolStripMenuItem";
this.openInJobBrowserToolStripMenuItem.Size = new System.Drawing.Size(181, 22);
this.openInJobBrowserToolStripMenuItem.Text = "Open in job browser";
this.openInJobBrowserToolStripMenuItem.Click += new System.EventHandler(this.jobBrowserToolStripMenuItem_Click);
//
// diagnoseToolStripMenuItem1
//
this.diagnoseToolStripMenuItem1.Name = "diagnoseToolStripMenuItem1";
this.diagnoseToolStripMenuItem1.Size = new System.Drawing.Size(181, 22);
this.diagnoseToolStripMenuItem1.Text = "Diagnose";
this.diagnoseToolStripMenuItem1.Visible = false;
this.diagnoseToolStripMenuItem1.Click += new System.EventHandler(this.diagnoseToolStripMenuItem_Click);
//
// terminateToolStripMenuItem1
//
this.terminateToolStripMenuItem1.Name = "terminateToolStripMenuItem1";
this.terminateToolStripMenuItem1.Size = new System.Drawing.Size(181, 22);
this.terminateToolStripMenuItem1.Text = "Terminate";
this.terminateToolStripMenuItem1.Click += new System.EventHandler(this.terminateToolStripMenuItem_Click);
//
// cancelToolStripMenuItem1
//
this.cancelToolStripMenuItem1.Name = "cancelToolStripMenuItem1";
this.cancelToolStripMenuItem1.Size = new System.Drawing.Size(186, 22);
this.cancelToolStripMenuItem1.Text = "Cancel current work";
this.cancelToolStripMenuItem1.Click += new System.EventHandler(this.cancelToolStripMenuItem_Click);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statuslabel,
this.toolStripProgressBar});
this.statusStrip.Location = new System.Drawing.Point(0, 431);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(1143, 22);
this.statusStrip.TabIndex = 3;
this.statusStrip.Text = "statusStrip";
//
// statuslabel
//
this.statuslabel.Name = "statuslabel";
this.statuslabel.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.statuslabel.Size = new System.Drawing.Size(1026, 17);
this.statuslabel.Spring = true;
this.statuslabel.Text = "Status displayed here";
this.statuslabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// toolStripProgressBar
//
this.toolStripProgressBar.Name = "toolStripProgressBar";
this.toolStripProgressBar.Size = new System.Drawing.Size(100, 16);
//
// flowLayoutPanel_header
//
this.flowLayoutPanel_header.AutoSize = true;
this.flowLayoutPanel_header.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel_header.Controls.Add(this.label_vc);
this.flowLayoutPanel_header.Controls.Add(this.comboBox_virtualCluster);
this.flowLayoutPanel_header.Dock = System.Windows.Forms.DockStyle.Top;
this.flowLayoutPanel_header.Location = new System.Drawing.Point(0, 24);
this.flowLayoutPanel_header.MinimumSize = new System.Drawing.Size(400, 32);
this.flowLayoutPanel_header.Name = "flowLayoutPanel_header";
this.flowLayoutPanel_header.Size = new System.Drawing.Size(1143, 32);
this.flowLayoutPanel_header.TabIndex = 12;
this.flowLayoutPanel_header.Visible = false;
//
// label_vc
//
this.label_vc.AutoSize = true;
this.label_vc.Dock = System.Windows.Forms.DockStyle.Left;
this.label_vc.Enabled = false;
this.label_vc.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label_vc.Location = new System.Drawing.Point(3, 3);
this.label_vc.Margin = new System.Windows.Forms.Padding(3);
this.label_vc.Name = "label_vc";
this.label_vc.Padding = new System.Windows.Forms.Padding(3);
this.label_vc.Size = new System.Drawing.Size(95, 22);
this.label_vc.TabIndex = 12;
this.label_vc.Text = "Virtual Cluster";
this.label_vc.Visible = false;
//
// comboBox_virtualCluster
//
this.comboBox_virtualCluster.Dock = System.Windows.Forms.DockStyle.Left;
this.comboBox_virtualCluster.Enabled = false;
this.comboBox_virtualCluster.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.comboBox_virtualCluster.FormattingEnabled = true;
this.comboBox_virtualCluster.Location = new System.Drawing.Point(104, 3);
this.comboBox_virtualCluster.Name = "comboBox_virtualCluster";
this.comboBox_virtualCluster.Size = new System.Drawing.Size(218, 24);
this.comboBox_virtualCluster.TabIndex = 13;
this.comboBox_virtualCluster.Visible = false;
this.comboBox_virtualCluster.SelectedIndexChanged += new System.EventHandler(this.comboBox_virtualCluster_SelectedIndexChanged);
this.comboBox_virtualCluster.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.comboBox_virtualCluster_KeyPress);
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.jobToolStripMenuItem_file,
this.toolStripMenuItem_job,
this.settingsToolStripMenuItem,
this.clusterToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1143, 24);
this.menuStrip.TabIndex = 13;
this.menuStrip.Text = "menuStrip1";
//
// jobToolStripMenuItem_file
//
this.jobToolStripMenuItem_file.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cancelToolStripMenuItem1,
this.newWindowToolStripMenuItem,
this.refreshToolStripMenuItem1,
this.exitToolStripMenuItem1});
this.jobToolStripMenuItem_file.Name = "jobToolStripMenuItem_file";
this.jobToolStripMenuItem_file.Size = new System.Drawing.Size(44, 20);
this.jobToolStripMenuItem_file.Text = "&View";
//
// newWindowToolStripMenuItem
//
this.newWindowToolStripMenuItem.Name = "newWindowToolStripMenuItem";
this.newWindowToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newWindowToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.newWindowToolStripMenuItem.Text = "&New window";
this.newWindowToolStripMenuItem.ToolTipText = "Open a new cluster browser window.";
this.newWindowToolStripMenuItem.Click += new System.EventHandler(this.newWindowToolStripMenuItem_Click);
//
// refreshToolStripMenuItem1
//
this.refreshToolStripMenuItem1.Name = "refreshToolStripMenuItem1";
this.refreshToolStripMenuItem1.ShortcutKeys = System.Windows.Forms.Keys.F5;
this.refreshToolStripMenuItem1.Size = new System.Drawing.Size(186, 22);
this.refreshToolStripMenuItem1.Text = "&Refresh";
this.refreshToolStripMenuItem1.ToolTipText = "Refresh the list of jobs on the cluster.";
this.refreshToolStripMenuItem1.Click += new System.EventHandler(this.refreshToolStripMenuItem1_Click);
//
// exitToolStripMenuItem1
//
this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1";
this.exitToolStripMenuItem1.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Q)));
this.exitToolStripMenuItem1.Size = new System.Drawing.Size(186, 22);
this.exitToolStripMenuItem1.Text = "Close";
this.exitToolStripMenuItem1.ToolTipText = "Save settings and close the window.";
this.exitToolStripMenuItem1.Click += new System.EventHandler(this.exitToolStripMenuItem2_Click);
//
// toolStripMenuItem_job
//
this.toolStripMenuItem_job.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.jobBrowserToolStripMenuItem,
this.diagnoseToolStripMenuItem,
this.terminateToolStripMenuItem,
this.openFromURLToolStripMenuItem});
this.toolStripMenuItem_job.Name = "toolStripMenuItem_job";
this.toolStripMenuItem_job.Size = new System.Drawing.Size(37, 20);
this.toolStripMenuItem_job.Text = "&Job";
this.toolStripMenuItem_job.ToolTipText = "View job informaotion in detail.";
//
// jobBrowserToolStripMenuItem
//
this.jobBrowserToolStripMenuItem.Name = "jobBrowserToolStripMenuItem";
this.jobBrowserToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.jobBrowserToolStripMenuItem.Text = "Start job browser";
this.jobBrowserToolStripMenuItem.Click += new System.EventHandler(this.jobBrowserToolStripMenuItem_Click);
//
// diagnoseToolStripMenuItem
//
this.diagnoseToolStripMenuItem.Name = "diagnoseToolStripMenuItem";
this.diagnoseToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.diagnoseToolStripMenuItem.Text = "Diagnose";
this.diagnoseToolStripMenuItem.ToolTipText = "Attempt to diagnose job failures.";
this.diagnoseToolStripMenuItem.Visible = false;
this.diagnoseToolStripMenuItem.Click += new System.EventHandler(this.diagnoseToolStripMenuItem_Click);
//
// terminateToolStripMenuItem
//
this.terminateToolStripMenuItem.Name = "terminateToolStripMenuItem";
this.terminateToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.terminateToolStripMenuItem.Text = "Terminate job";
this.terminateToolStripMenuItem.ToolTipText = "Ask cluster to terminate job execution.";
this.terminateToolStripMenuItem.Click += new System.EventHandler(this.terminateToolStripMenuItem_Click);
//
// openFromURLToolStripMenuItem
//
this.openFromURLToolStripMenuItem.Name = "openFromURLToolStripMenuItem";
this.openFromURLToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.openFromURLToolStripMenuItem.Text = "Open job URL...";
this.openFromURLToolStripMenuItem.ToolTipText = "Open the job given a URL.";
this.openFromURLToolStripMenuItem.Visible = false;
this.openFromURLToolStripMenuItem.Click += new System.EventHandler(this.openFromURLToolStripMenuItem_Click);
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.logFileToolStripMenuItem,
this.autoRefreshToolStripMenuItem});
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(61, 20);
this.settingsToolStripMenuItem.Text = "Settings";
//
// logFileToolStripMenuItem
//
this.logFileToolStripMenuItem.Name = "logFileToolStripMenuItem";
this.logFileToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.logFileToolStripMenuItem.Text = "Log file";
this.logFileToolStripMenuItem.ToolTipText = "When enabled logs errors in the selected file.";
this.logFileToolStripMenuItem.Click += new System.EventHandler(this.logFileToolStripMenuItem_Click);
//
// autoRefreshToolStripMenuItem
//
this.autoRefreshToolStripMenuItem.Name = "autoRefreshToolStripMenuItem";
this.autoRefreshToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.autoRefreshToolStripMenuItem.Text = "Auto refresh";
this.autoRefreshToolStripMenuItem.Click += new System.EventHandler(this.autoRefreshToolStripMenuItem_Click);
//
// clusterToolStripMenuItem
//
this.clusterToolStripMenuItem.Name = "clusterToolStripMenuItem";
this.clusterToolStripMenuItem.Size = new System.Drawing.Size(56, 20);
this.clusterToolStripMenuItem.Text = "Cluster";
//
// filteredDataGridView
//
this.filteredDataGridView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.filteredDataGridView.ContextMenuStrip = this.contextMenuStrip_job;
this.filteredDataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.filteredDataGridView.Location = new System.Drawing.Point(0, 24);
this.filteredDataGridView.Name = "filteredDataGridView";
this.filteredDataGridView.Size = new System.Drawing.Size(1143, 429);
this.filteredDataGridView.TabIndex = 15;
this.filteredDataGridView.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.filteredDataGridView_CellFormatting);
this.filteredDataGridView.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.filteredDataGridView_CellMouseDoubleClick);
//
// ClusterBrowser
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1143, 453);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.flowLayoutPanel_header);
this.Controls.Add(this.filteredDataGridView);
this.Controls.Add(this.menuStrip);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ClusterBrowser";
this.Text = "Cluster Browser";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ClusterBrowser_FormClosing);
this.Load += new System.EventHandler(this.ClusterBrowser_Load);
this.contextMenuStrip_job.ResumeLayout(false);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.flowLayoutPanel_header.ResumeLayout(false);
this.flowLayoutPanel_header.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
private void cancelToolStripMenuItem_Click(object sender, System.EventArgs e)
{
this.queue.CancelCurrentWork();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel statuslabel;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel_header;
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_job;
private System.Windows.Forms.ToolStripMenuItem jobToolStripMenuItem_file;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem jobBrowserToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem refreshToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem openFromURLToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem terminateToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem diagnoseToolStripMenuItem;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip_job;
private System.Windows.Forms.ToolStripMenuItem openInJobBrowserToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem diagnoseToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem terminateToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem cancelToolStripMenuItem1;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar;
private FilteredDataGridView filteredDataGridView;
private System.Windows.Forms.ToolStripMenuItem newWindowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem logFileToolStripMenuItem;
private System.Windows.Forms.Label label_vc;
private System.Windows.Forms.ComboBox comboBox_virtualCluster;
private System.Windows.Forms.ToolStripMenuItem autoRefreshToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clusterToolStripMenuItem;
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// AnimationPlayer.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
#endregion
namespace SkinnedModel
{
/// <summary>
/// The animation player is in charge of decoding bone position
/// matrices from an animation clip.
/// </summary>
public class AnimationPlayer
{
#region Fields
// Information about the currently playing animation clip.
AnimationClip currentClipValue;
TimeSpan currentTimeValue;
int currentKeyframe;
// Current animation transform matrices.
Matrix[] boneTransforms;
Matrix[] worldTransforms;
Matrix[] skinTransforms;
// Backlink to the bind pose and skeleton hierarchy data.
SkinningData skinningDataValue;
#endregion
/// <summary>
/// Constructs a new animation player.
/// </summary>
public AnimationPlayer(SkinningData skinningData)
{
if (skinningData == null)
throw new ArgumentNullException("skinningData");
skinningDataValue = skinningData;
boneTransforms = new Matrix[skinningData.BindPose.Count];
worldTransforms = new Matrix[skinningData.BindPose.Count];
skinTransforms = new Matrix[skinningData.BindPose.Count];
}
/// <summary>
/// Starts decoding the specified animation clip.
/// </summary>
public void StartClip(AnimationClip clip)
{
if (clip == null)
throw new ArgumentNullException("clip");
currentClipValue = clip;
currentTimeValue = TimeSpan.Zero;
currentKeyframe = 0;
// Initialize bone transforms to the bind pose.
skinningDataValue.BindPose.CopyTo(boneTransforms, 0);
}
/// <summary>
/// Advances the current animation position.
/// </summary>
public void Update(TimeSpan time, bool relativeToCurrentTime,
Matrix rootTransform)
{
UpdateBoneTransforms(time, relativeToCurrentTime);
UpdateWorldTransforms(rootTransform);
UpdateSkinTransforms();
}
/// <summary>
/// Helper used by the Update method to refresh the BoneTransforms data.
/// </summary>
public void UpdateBoneTransforms(TimeSpan time, bool relativeToCurrentTime)
{
if (currentClipValue == null)
throw new InvalidOperationException(
"AnimationPlayer.Update was called before StartClip");
// Update the animation position.
if (relativeToCurrentTime)
{
time += currentTimeValue;
// If we reached the end, loop back to the start.
while (time >= currentClipValue.Duration)
time -= currentClipValue.Duration;
}
if ((time < TimeSpan.Zero) || (time >= currentClipValue.Duration))
throw new ArgumentOutOfRangeException("time");
// If the position moved backwards, reset the keyframe index.
if (time < currentTimeValue)
{
currentKeyframe = 0;
skinningDataValue.BindPose.CopyTo(boneTransforms, 0);
}
currentTimeValue = time;
// Read keyframe matrices.
IList<Keyframe> keyframes = currentClipValue.Keyframes;
while (currentKeyframe < keyframes.Count)
{
Keyframe keyframe = keyframes[currentKeyframe];
// Stop when we've read up to the current time position.
if (keyframe.Time > currentTimeValue)
break;
// Use this keyframe.
boneTransforms[keyframe.Bone] = keyframe.Transform;
currentKeyframe++;
}
}
/// <summary>
/// Helper used by the Update method to refresh the WorldTransforms data.
/// </summary>
public void UpdateWorldTransforms(Matrix rootTransform)
{
// Root bone.
worldTransforms[0] = boneTransforms[0] * rootTransform;
// Child bones.
for (int bone = 1; bone < worldTransforms.Length; bone++)
{
int parentBone = skinningDataValue.SkeletonHierarchy[bone];
worldTransforms[bone] = boneTransforms[bone] *
worldTransforms[parentBone];
}
}
/// <summary>
/// Helper used by the Update method to refresh the SkinTransforms data.
/// </summary>
public void UpdateSkinTransforms()
{
for (int bone = 0; bone < skinTransforms.Length; bone++)
{
skinTransforms[bone] = skinningDataValue.InverseBindPose[bone] *
worldTransforms[bone];
}
}
/// <summary>
/// Gets the current bone transform matrices, relative to their parent bones.
/// </summary>
public Matrix[] GetBoneTransforms()
{
return boneTransforms;
}
/// <summary>
/// Gets the current bone transform matrices, in absolute format.
/// </summary>
public Matrix[] GetWorldTransforms()
{
return worldTransforms;
}
/// <summary>
/// Gets the current bone transform matrices,
/// relative to the skinning bind pose.
/// </summary>
public Matrix[] GetSkinTransforms()
{
return skinTransforms;
}
/// <summary>
/// Gets the clip currently being decoded.
/// </summary>
public AnimationClip CurrentClip
{
get { return currentClipValue; }
}
/// <summary>
/// Gets the current play position.
/// </summary>
public TimeSpan CurrentTime
{
get { return currentTimeValue; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using hw.DebugFormatter;
using hw.Helper;
using JetBrains.Annotations;
// ReSharper disable CheckNamespace
namespace hw.Forms
{
[PublicAPI]
public static class Extension
{
public const int ShiftKey = 4;
public const int AltKey = 32;
public const int ControlKey = 8;
public const int LeftMouseButton = 1;
public const int RightMouseButton = 2;
public const int MiddleMouseButton = 16;
static BindingFlags DefaultBindingFlags => BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy;
/// <summary>
/// Creates a tree-node.with a given title from an object
/// </summary>
/// <param name="nodeData"> </param>
/// <param name="title"> </param>
/// <param name="iconKey"> </param>
/// <param name="isDefaultIcon"> </param>
/// <param name="name"></param>
/// <returns> </returns>
public static TreeNode CreateNode
(
this object nodeData,
string title = "",
string iconKey = null,
bool isDefaultIcon = false,
string name = null
)
{
var text = title + nodeData.GetAdditionalInfo();
var effectiveName = nodeData.GetName(name) ?? text;
var result = new TreeNode(text) {Tag = nodeData, Name = effectiveName};
if(iconKey == null)
iconKey = nodeData.GetIconKey();
if(isDefaultIcon)
{
var defaultIcon = nodeData.GetIconKey();
if(defaultIcon != null)
iconKey = defaultIcon;
}
if(iconKey != null)
{
result.ImageKey = iconKey;
result.SelectedImageKey = iconKey;
}
return result;
}
/// <summary>
/// Creates a tree-node.with a given title from an object (format: <title> = <nodeData.ToString()>)
/// </summary>
/// <param name="title"> The title. </param>
/// <param name="iconKey"> The icon key. </param>
/// <param name="isDefaultIcon"> if set to <c>true</c> [is default icon]. </param>
/// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param>
/// <param name="name"></param>
/// <returns> </returns>
/// created 06.02.2007 23:26
public static TreeNode CreateNamedNode
(
this object nodeData,
string title,
string iconKey = null,
bool isDefaultIcon = false,
string name = null
)
=> nodeData
.CreateNode(title + " = ", iconKey, isDefaultIcon, name);
/// <summary>
/// Creates a tree-node.with a given title from an object (format: <title>: <nodeData.ToString()>)
/// </summary>
/// <param name="title"> The title. </param>
/// <param name="iconKey"> The icon key. </param>
/// <param name="isDefaultIcon"> if set to <c>true</c> [is default icon]. </param>
/// <param name="nodeData"> The node data. Can be <see cref="IIconKeyProvider" /> </param>
/// <param name="name"></param>
/// <returns> </returns>
/// created 06.02.2007 23:26
public static TreeNode CreateTaggedNode
(
this object nodeData,
string title,
string iconKey = null,
bool isDefaultIcon = false,
string name = null
)
=> nodeData
.CreateNode(title + ": ", iconKey, isDefaultIcon, name);
/// <summary>
/// Gets the name of the icon.
/// </summary>
/// <param name="nodeData"> The node data. </param>
/// <returns> </returns>
public static string GetIconKey(this object nodeData)
{
if(nodeData == null)
return null;
if(nodeData is IIconKeyProvider ip)
return ip.IconKey;
if(nodeData is string)
return "String";
if(nodeData is bool)
return "Bool";
if(nodeData.GetType().IsPrimitive)
return "Number";
if(nodeData is IDictionary)
return "Dictionary";
if(nodeData is IList)
return "List";
return null;
}
public static TreeNode[] CreateNodes(this object target)
{
if(target == null)
return new TreeNode[0];
if(target is ITreeNodeSupport xn)
return xn.CreateNodes().ToArray();
return CreateAutomaticNodes(target);
}
public static TreeNode[] CreateAutomaticNodes(this object target)
{
if(target is IList xl)
return InternalCreateNodes(xl);
if(target is IDictionary xd)
return InternalCreateNodes(xd);
if(target is DictionaryEntry entry)
return InternalCreateNodes(entry);
return InternalCreateNodes(target);
}
public static void Connect(this TreeView treeView, object target) => Connect(target, treeView);
public static void Connect(this object target, TreeView treeView)
{
CreateNodeList(treeView.Nodes, target);
AddSubNodes(treeView.Nodes);
treeView.BeforeExpand += (sender, e) => BeforeExpand(e.Node.Nodes);
}
public static void BeforeExpand(this TreeNodeCollection nodes)
{
LazyNodes(nodes);
AddSubNodes(nodes);
}
/// <summary>
/// Installs a <see cref="PositionConfig" /> for target
/// </summary>
/// <param name="target">the form that will be watched</param>
/// <param name="getFileName">
/// function to obtain filename of configuration file.
/// <para>It will be called each time the name is required. </para>
/// <para>Default: Target.Name</para>
/// </param>
public static PositionConfig InstallPositionConfig
(this Form target, Func<string> getFileName = null) => new PositionConfig(getFileName) {Target = target};
/// <summary>
/// Turns collection into IEnumerable
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static IEnumerable<TreeNode> _(this TreeNodeCollection value) => value.Cast<TreeNode>();
/// <summary>
/// Turns collection into IEnumerable
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static IEnumerable<Control> _(this Control.ControlCollection value) => value.Cast<Control>();
/// <summary>
/// Flatten node hierarchy
/// </summary>
/// <param name="tree"></param>
/// <returns></returns>
// ReSharper disable once IdentifierTypo
public static IEnumerable<TreeNode> SelectHierachical(this TreeView tree) => tree
.Nodes
._()
.SelectMany(n => n.SelectHierarchical(nn => nn.Nodes._()));
/// <summary>
/// Call a function or invoke it if required
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="control"></param>
/// <param name="function"></param>
/// <returns></returns>
public static T ThreadCallGuard<T>(this Control control, Func<T> function)
{
if(control.InvokeRequired)
return (T)control.Invoke(function);
return function();
}
/// <summary>
/// Call an action or invoke it if required
/// </summary>
/// <param name="control"></param>
/// <param name="function"></param>
/// <returns></returns>
public static void ThreadCallGuard(this Control control, Action function)
{
if(control.InvokeRequired)
control.Invoke(function);
else
function();
}
public static bool SetEffect<T>(this DragEventArgs e, Func<T, bool> getIsValid, DragDropEffects defaultEffect)
{
e.Effect = ObtainEffect(e, getIsValid, defaultEffect);
return e.Effect != DragDropEffects.None;
}
public static DragDropEffects ObtainEffect<T>
(DragEventArgs e, Func<T, bool> getIsValid, DragDropEffects defaultEffect)
{
if(e.IsValid(getIsValid))
{
if(e.KeyState.HasBitSet(AltKey) && e.AllowedEffect.HasFlag(DragDropEffects.Link))
return DragDropEffects.Link;
if(e.KeyState.HasBitSet(ShiftKey) && e.AllowedEffect.HasFlag(DragDropEffects.Move))
return DragDropEffects.Move;
if(e.KeyState.HasBitSet(ControlKey) && e.AllowedEffect.HasFlag(DragDropEffects.Copy))
return DragDropEffects.Copy;
if(e.AllowedEffect.HasFlag(defaultEffect))
return defaultEffect;
}
return DragDropEffects.None;
}
public static bool IsValid<T>
(this DragEventArgs e, Func<T, bool> getIsValid) => e.Data.GetDataPresent(typeof(T))
&& getIsValid((T)e.Data.GetData(typeof(T)));
public static bool SetEffectCopy(this DragEventArgs e, bool isValid)
{
(e.AllowedEffect == DragDropEffects.Copy).Assert();
e.Effect = isValid && e.KeyState.HasBitSet(ControlKey)? DragDropEffects.Copy : DragDropEffects.None;
return e.Effect != DragDropEffects.None;
}
public static Bitmap AsBitmap(this Control c)
{
var result = new Bitmap(c.Width, c.Height);
c.DrawToBitmap(result, new Rectangle(0, 0, c.Width, c.Height));
return result;
}
public static Cursor ToCursor(this Control control, Point? hotSpot = null)
{
var iconInfo = new CursorUtil.IconInfo(control.AsBitmap());
if(hotSpot != null)
iconInfo.HotSpot = hotSpot.Value;
return iconInfo.Cursor;
}
internal static string GetName([CanBeNull] this object nodeData, string name)
{
if(nodeData == null)
return name;
if(nodeData is INodeNameProvider additionalNodeInfoProvider)
return additionalNodeInfoProvider.Value(name);
var attr = nodeData.GetType().GetAttribute<NodeNameAttribute>(true);
if(attr != null)
return nodeData.GetType()
.InvokeMember(attr.Property, BindingFlags.Default, null, nodeData, new object[] {name}).ToString();
return name;
}
[NotNull]
internal static string GetAdditionalInfo([CanBeNull] this object nodeData)
{
if(nodeData == null)
return "<null>";
if(nodeData is IAdditionalNodeInfoProvider additionalNodeInfoProvider)
return additionalNodeInfoProvider.AdditionalNodeInfo;
var attr = nodeData.GetType().GetAttribute<AdditionalNodeInfoAttribute>(true);
if(attr != null)
return nodeData.GetType().GetProperty(attr.Property)?.GetValue(nodeData, null).ToString() ?? "";
if(nodeData is IList il)
return il.GetType().PrettyName() + "[" + il.Count + "]";
var nameSpace = nodeData.GetType().Namespace;
if(nameSpace != null && nameSpace.StartsWith("System"))
return nodeData.ToString();
return "";
}
internal static void CreateNodeList(this TreeNode node) => CreateNodeList(node.Nodes, node.Tag);
internal static void CreateLazyNodeList(this TreeNode node)
{
var probe = node.Tag as ITreeNodeProbeSupport;
if(probe == null || probe.IsEmpty)
{
CreateNodeList(node);
return;
}
node.Nodes.Clear();
// ReSharper disable once StringLiteralTypo
node.Nodes.Add(new TreeNode {Tag = new LazyNode {Target = node.Tag}, Text = "<lazynode>"});
}
static TreeNode[] InternalCreateNodes(IDictionary dictionary)
{
var result = new List<TreeNode>();
foreach(var element in dictionary)
result.Add(CreateNumberedNode(element, result.Count, "ListItem"));
return result.ToArray();
}
static TreeNode CreateNumberedNode
(
object nodeData,
int i,
string iconKey,
bool isDefaultIcon = false,
string name = null
)
=> nodeData
.CreateNode("[" + i + "] ", iconKey, isDefaultIcon, name ?? i.ToString());
static TreeNode[] InternalCreateNodes(IList list)
{
var result = new List<TreeNode>();
foreach(var o in list)
result.Add(CreateNumberedNode(o, result.Count, "ListItem", true));
return result.ToArray();
}
static TreeNode[] InternalCreateNodes(DictionaryEntry dictionaryEntry) => new[]
{
dictionaryEntry.Key.CreateTaggedNode("key", "Key", true), dictionaryEntry.Value.CreateTaggedNode("value")
};
static TreeNode[] InternalCreateNodes(object target)
{
var result = new List<TreeNode>();
result.AddRange(CreateFieldNodes(target));
result.AddRange(CreatePropertyNodes(target));
return result.ToArray();
}
static TreeNode[] CreatePropertyNodes(object nodeData) => nodeData
.GetType()
.GetProperties(DefaultBindingFlags)
.Select(propertyInfo => CreateTreeNode(nodeData, propertyInfo))
.Where(treeNode => treeNode != null)
.ToArray();
static TreeNode[] CreateFieldNodes(object nodeData) => nodeData
.GetType()
.GetFieldInfos()
.Select(fieldInfo => CreateTreeNode(nodeData, fieldInfo))
.Where(treeNode => treeNode != null)
.ToArray();
static TreeNode CreateTreeNode(object nodeData, FieldInfo fieldInfo) => CreateTreeNode(
fieldInfo,
() => Value(fieldInfo, nodeData));
static TreeNode CreateTreeNode(object nodeData, PropertyInfo propertyInfo) => CreateTreeNode(
propertyInfo,
() => Value(propertyInfo, nodeData));
static object Value(FieldInfo fieldInfo, object nodeData) => fieldInfo.GetValue(nodeData);
static object Value(PropertyInfo propertyInfo, object nodeData) => propertyInfo.GetValue(nodeData, null);
static TreeNode CreateTreeNode(MemberInfo memberInfo, Func<object> getValue)
{
var attribute = memberInfo.GetAttribute<NodeAttribute>(true);
if(attribute == null)
return null;
var value = CatchedEval(getValue);
if(value == null)
return null;
var result = CreateNamedNode(value, memberInfo.Name, attribute.IconKey, name: attribute.Name);
return memberInfo.GetAttribute<SmartNodeAttribute>(true) == null? result : SmartNodeAttribute.Process(result);
}
static object CatchedEval(Func<object> value)
{
try
{
return value();
}
catch(Exception e)
{
return e;
}
}
static void CreateNodeList(TreeNodeCollection nodes, object target)
{
var treeNodes = CreateNodes(target);
//Tracer.FlaggedLine(treeNodes.Dump());
//Tracer.ConditionalBreak(treeNodes.Length == 20,"");
nodes.Clear();
nodes.AddRange(treeNodes);
}
static void AddSubNodesAsync(TreeNodeCollection nodes)
{
lock(nodes)
{
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (sender, e) => AddSubNodes(nodes);
backgroundWorker.RunWorkerAsync();
}
}
static void AddSubNodes(TreeNodeCollection nodes)
{
foreach(TreeNode node in nodes)
CreateLazyNodeList(node);
}
static void LazyNodes(TreeNodeCollection nodes)
{
if(nodes.Count != 1)
return;
var lazyNode = nodes[0].Tag as LazyNode;
if(lazyNode == null)
return;
CreateNodeList(nodes, lazyNode.Target);
}
}
}
| |
//
// MenuItem.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.ComponentModel;
using Xwt.Drawing;
namespace Xwt
{
[BackendType (typeof(IMenuItemBackend))]
public class MenuItem: XwtComponent, ICellContainer
{
CellViewCollection cells;
Menu subMenu;
EventHandler clicked;
Image image;
protected class MenuItemBackendHost: BackendHost<MenuItem,IMenuItemBackend>, IMenuItemEventSink
{
protected override void OnBackendCreated ()
{
base.OnBackendCreated ();
Backend.Initialize (this);
}
public void OnClicked ()
{
Parent.DoClick ();
}
}
protected override Xwt.Backends.BackendHost CreateBackendHost ()
{
return new MenuItemBackendHost ();
}
static MenuItem ()
{
MapEvent (MenuItemEvent.Clicked, typeof(MenuItem), "OnClicked");
}
public MenuItem ()
{
if (!IsSeparator)
UseMnemonic = true;
}
public MenuItem (Command command)
{
VerifyConstructorCall (this);
LoadCommandProperties (command);
}
public MenuItem (string label)
{
VerifyConstructorCall (this);
Label = label;
}
public MenuItem (string label, Image image, EventHandler clicked):this(label) {
Clicked += clicked;
Image = image;
}
public MenuItem (string label, Image image, EventHandler clicked, params MenuItem[] subItems)
: this(label, image, clicked) {
SubMenu = new Menu();
for (int i = 0; i < subItems.Length; i++)
SubMenu.InsertItem(i, subItems[i]);
}
protected void LoadCommandProperties (Command command)
{
Label = command.Label;
Image = command.Icon;
}
IMenuItemBackend Backend {
get { return (IMenuItemBackend) base.BackendHost.Backend; }
}
bool IsSeparator {
get { return this is SeparatorMenuItem; }
}
[DefaultValue ("")]
public string Label {
get { return Backend.Label; }
set {
if (IsSeparator)
throw new NotSupportedException ();
Backend.Label = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Xwt.Button"/> uses a mnemonic.
/// </summary>
/// <value><c>true</c> if it uses a mnemonic; otherwise, <c>false</c>.</value>
/// <remarks>
/// When set to true, the character after the first underscore character in the Label property value is
/// interpreted as the mnemonic for that Label.
/// </remarks>
[DefaultValue(true)]
public bool UseMnemonic {
get { return Backend.UseMnemonic; }
set {
if (IsSeparator)
throw new NotSupportedException ();
Backend.UseMnemonic = value;
}
}
[DefaultValue (true)]
public bool Sensitive {
get { return Backend.Sensitive; }
set { Backend.Sensitive = value; }
}
[DefaultValue (true)]
public bool Visible {
get { return Backend.Visible; }
set { Backend.Visible = value; }
}
public Image Image {
get { return image; }
set {
if (IsSeparator)
throw new NotSupportedException ();
image = value;
if (!IsSeparator)
Backend.SetImage (image != null ? image.ImageDescription : ImageDescription.Null);
}
}
public void Show ()
{
Visible = true;
}
public void Hide ()
{
Visible = false;
}
public CellViewCollection Cells {
get {
if (cells == null)
cells = new CellViewCollection (this);
return cells;
}
}
public Menu SubMenu {
get { return subMenu; }
set {
if (IsSeparator)
throw new NotSupportedException ();
Backend.SetSubmenu ((IMenuBackend)BackendHost.ToolkitEngine.GetSafeBackend (value));
subMenu = value;
}
}
public void NotifyCellChanged ()
{
throw new NotImplementedException ();
}
internal virtual void DoClick ()
{
OnClicked (EventArgs.Empty);
}
protected virtual void OnClicked (EventArgs e)
{
if (clicked != null)
clicked (this, e);
}
public event EventHandler Clicked {
add {
base.BackendHost.OnBeforeEventAdd (MenuItemEvent.Clicked, clicked);
clicked += value;
}
remove {
clicked -= value;
base.BackendHost.OnAfterEventRemove (MenuItemEvent.Clicked, clicked);
}
}
}
public enum MenuItemType
{
Normal,
CheckBox,
RadioButton
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Test.Helpers;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Components.Authorization
{
public class AuthorizeRouteViewTest
{
private static readonly IReadOnlyDictionary<string, object> EmptyParametersDictionary = new Dictionary<string, object>();
private readonly TestAuthenticationStateProvider _authenticationStateProvider;
private readonly TestRenderer _renderer;
private readonly RouteView _authorizeRouteViewComponent;
private readonly int _authorizeRouteViewComponentId;
private readonly TestAuthorizationService _testAuthorizationService;
public AuthorizeRouteViewTest()
{
_authenticationStateProvider = new TestAuthenticationStateProvider();
_authenticationStateProvider.CurrentAuthStateTask = Task.FromResult(
new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
_testAuthorizationService = new TestAuthorizationService();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<AuthenticationStateProvider>(_authenticationStateProvider);
serviceCollection.AddSingleton<IAuthorizationPolicyProvider, TestAuthorizationPolicyProvider>();
serviceCollection.AddSingleton<IAuthorizationService>(_testAuthorizationService);
serviceCollection.AddSingleton<NavigationManager, TestNavigationManager>();
_renderer = new TestRenderer(serviceCollection.BuildServiceProvider());
_authorizeRouteViewComponent = new AuthorizeRouteView();
_authorizeRouteViewComponentId = _renderer.AssignRootComponentId(_authorizeRouteViewComponent);
}
[Fact]
public void WhenAuthorized_RendersPageInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), new Dictionary<string, object>
{
{ nameof(TestPageRequiringAuthorization.Message), "Hello, world!" }
});
_testAuthorizationService.NextResult = AuthorizationResult.Success();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Assert: renders layout
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<TestPageRequiringAuthorization>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
},
edit => AssertPrependText(batch, edit, "Layout ends here"));
// Assert: renders page
var pageDiff = batch.GetComponentDiffs<TestPageRequiringAuthorization>().Single();
Assert.Collection(pageDiff.Edits,
edit => AssertPrependText(batch, edit, "Hello from the page with message: Hello, world!"));
}
[Fact]
public void AuthorizesWhenResourceIsSet()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), new Dictionary<string, object>
{
{ nameof(TestPageRequiringAuthorization.Message), "Hello, world!" }
});
var resource = "foo";
_testAuthorizationService.NextResult = AuthorizationResult.Success();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.Resource), resource }
}));
// Assert: renders layout
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<TestPageRequiringAuthorization>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
},
edit => AssertPrependText(batch, edit, "Layout ends here"));
// Assert: renders page
var pageDiff = batch.GetComponentDiffs<TestPageRequiringAuthorization>().Single();
Assert.Collection(pageDiff.Edits,
edit => AssertPrependText(batch, edit, "Hello from the page with message: Hello, world!"));
// Assert: Asserts that the Resource is present and set to "foo"
Assert.Collection(_testAuthorizationService.AuthorizeCalls, call=>
{
Assert.Equal(resource, call.resource.ToString());
});
}
[Fact]
public void NotAuthorizedWhenResourceMissing()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
_testAuthorizationService.NextResult = AuthorizationResult.Failed();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Assert: renders layout containing "not authorized" message
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Not authorized"),
edit => AssertPrependText(batch, edit, "Layout ends here"));
// Assert: Asserts that the Resource is Null
Assert.Collection(_testAuthorizationService.AuthorizeCalls, call=>
{
Assert.Null(call.resource);
});
}
[Fact]
public void WhenNotAuthorized_RendersDefaultNotAuthorizedContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
_testAuthorizationService.NextResult = AuthorizationResult.Failed();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Assert: renders layout containing "not authorized" message
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Not authorized"),
edit => AssertPrependText(batch, edit, "Layout ends here"));
}
[Fact]
public void WhenNotAuthorized_RendersCustomNotAuthorizedContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
_testAuthorizationService.NextResult = AuthorizationResult.Failed();
_authenticationStateProvider.CurrentAuthStateTask = Task.FromResult(new AuthenticationState(
new ClaimsPrincipal(new TestIdentity { Name = "Bert" })));
// Act
RenderFragment<AuthenticationState> customNotAuthorized =
state => builder => builder.AddContent(0, $"Go away, {state.User.Identity.Name}");
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.NotAuthorized), customNotAuthorized },
}));
// Assert: renders layout containing "not authorized" message
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Go away, Bert"),
edit => AssertPrependText(batch, edit, "Layout ends here"));
}
[Fact]
public async Task WhenAuthorizing_RendersDefaultAuthorizingContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
var authStateTcs = new TaskCompletionSource<AuthenticationState>();
_authenticationStateProvider.CurrentAuthStateTask = authStateTcs.Task;
RenderFragment<AuthenticationState> customNotAuthorized =
state => builder => builder.AddContent(0, $"Go away, {state.User.Identity.Name}");
// Act
var firstRenderTask = _renderer.RenderRootComponentAsync(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.NotAuthorized), customNotAuthorized },
}));
// Assert: renders layout containing "authorizing" message
Assert.False(firstRenderTask.IsCompleted);
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Authorizing..."),
edit => AssertPrependText(batch, edit, "Layout ends here"));
// Act 2: updates when authorization completes
authStateTcs.SetResult(new AuthenticationState(
new ClaimsPrincipal(new TestIdentity { Name = "Bert" })));
await firstRenderTask;
// Assert 2: Only the layout is updated
batch = _renderer.Batches.Skip(1).Single();
var nonEmptyDiff = batch.DiffsInOrder.Where(d => d.Edits.Any()).Single();
Assert.Equal(layoutDiff.ComponentId, nonEmptyDiff.ComponentId);
Assert.Collection(nonEmptyDiff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
AssertFrame.Text(batch.ReferenceFrames[edit.ReferenceFrameIndex], "Go away, Bert");
});
}
[Fact]
public void WhenAuthorizing_RendersCustomAuthorizingContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
var authStateTcs = new TaskCompletionSource<AuthenticationState>();
_authenticationStateProvider.CurrentAuthStateTask = authStateTcs.Task;
RenderFragment customAuthorizing =
builder => builder.AddContent(0, "Hold on, we're checking your papers.");
// Act
var firstRenderTask = _renderer.RenderRootComponentAsync(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.Authorizing), customAuthorizing },
}));
// Assert: renders layout containing "authorizing" message
Assert.False(firstRenderTask.IsCompleted);
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Hold on, we're checking your papers."),
edit => AssertPrependText(batch, edit, "Layout ends here"));
}
[Fact]
public void WithoutCascadedAuthenticationState_WrapsOutputInCascadingAuthenticationState()
{
// Arrange/Act
var routeData = new RouteData(typeof(TestPageWithNoAuthorization), EmptyParametersDictionary);
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData }
}));
// Assert
var batch = _renderer.Batches.Single();
var componentInstances = batch.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Component)
.Select(f => f.Component);
Assert.Collection(componentInstances,
// This is the hierarchy inside the AuthorizeRouteView, which contains its
// own CascadingAuthenticationState
component => Assert.IsType<CascadingAuthenticationState>(component),
component => Assert.IsType<CascadingValue<Task<AuthenticationState>>>(component),
component => Assert.IsAssignableFrom<AuthorizeViewCore>(component),
component => Assert.IsType<LayoutView>(component),
component => Assert.IsType<TestPageWithNoAuthorization>(component));
}
[Fact]
public void WithCascadedAuthenticationState_DoesNotWrapOutputInCascadingAuthenticationState()
{
// Arrange
var routeData = new RouteData(typeof(TestPageWithNoAuthorization), EmptyParametersDictionary);
var rootComponent = new AuthorizeRouteViewWithExistingCascadedAuthenticationState(
_authenticationStateProvider.CurrentAuthStateTask,
routeData);
var rootComponentId = _renderer.AssignRootComponentId(rootComponent);
// Act
_renderer.RenderRootComponent(rootComponentId);
// Assert
var batch = _renderer.Batches.Single();
var componentInstances = batch.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Component)
.Select(f => f.Component);
Assert.Collection(componentInstances,
// This is the externally-supplied cascading value
component => Assert.IsType<CascadingValue<Task<AuthenticationState>>>(component),
component => Assert.IsType<AuthorizeRouteView>(component),
// This is the hierarchy inside the AuthorizeRouteView. It doesn't contain a
// further CascadingAuthenticationState
component => Assert.IsAssignableFrom<AuthorizeViewCore>(component),
component => Assert.IsType<LayoutView>(component),
component => Assert.IsType<TestPageWithNoAuthorization>(component));
}
[Fact]
public void UpdatesOutputWhenRouteDataChanges()
{
// Arrange/Act 1: Start on some route
// Not asserting about the initial output, as that is covered by other tests
var routeData = new RouteData(typeof(TestPageWithNoAuthorization), EmptyParametersDictionary);
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Act 2: Move to another route
var routeData2 = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
var render2Task = _renderer.Dispatcher.InvokeAsync(() => _authorizeRouteViewComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData2 },
})));
// Assert: we retain the layout instance, and mutate its contents
Assert.True(render2Task.IsCompletedSuccessfully);
Assert.Equal(2, _renderer.Batches.Count);
var batch2 = _renderer.Batches[1];
var diff = batch2.DiffsInOrder.Where(d => d.Edits.Any()).Single();
Assert.Collection(diff.Edits,
edit =>
{
// Inside the layout, we add the new content
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
AssertFrame.Text(batch2.ReferenceFrames[edit.ReferenceFrameIndex], "Not authorized");
},
edit =>
{
// ... and remove the old content
Assert.Equal(RenderTreeEditType.RemoveFrame, edit.Type);
Assert.Equal(2, edit.SiblingIndex);
});
}
private static void AssertPrependText(CapturedBatch batch, RenderTreeEdit edit, string text)
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
ref var referenceFrame = ref batch.ReferenceFrames[edit.ReferenceFrameIndex];
AssertFrame.Text(referenceFrame, text);
}
class TestPageWithNoAuthorization : ComponentBase { }
[Authorize]
class TestPageRequiringAuthorization : ComponentBase
{
[Parameter] public string Message { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, $"Hello from the page with message: {Message}");
}
}
class TestLayout : LayoutComponentBase
{
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, "Layout starts here");
builder.AddContent(1, Body);
builder.AddContent(2, "Layout ends here");
}
}
class AuthorizeRouteViewWithExistingCascadedAuthenticationState : AutoRenderComponent
{
private readonly Task<AuthenticationState> _authenticationState;
private readonly RouteData _routeData;
public AuthorizeRouteViewWithExistingCascadedAuthenticationState(
Task<AuthenticationState> authenticationState,
RouteData routeData)
{
_authenticationState = authenticationState;
_routeData = routeData;
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenComponent<CascadingValue<Task<AuthenticationState>>>(0);
builder.AddAttribute(1, nameof(CascadingValue<object>.Value), _authenticationState);
builder.AddAttribute(2, nameof(CascadingValue<object>.ChildContent), (RenderFragment)(builder =>
{
builder.OpenComponent<AuthorizeRouteView>(0);
builder.AddAttribute(1, nameof(AuthorizeRouteView.RouteData), _routeData);
builder.CloseComponent();
}));
builder.CloseComponent();
}
}
class TestNavigationManager : NavigationManager
{
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Util;
using Encog.Util.Simple;
namespace Encog.Neural.PNN
{
/// <summary>
/// This class implements either a:
/// Probabilistic Neural Network (PNN)
/// General Regression Neural Network (GRNN)
/// To use a PNN specify an output mode of classification, to make use of a GRNN
/// specify either an output mode of regression or un-supervised autoassociation.
/// The PNN/GRNN networks are potentially very useful. They share some
/// similarities with RBF-neural networks and also the Support Vector Machine
/// (SVM). These network types directly support the use of classification.
/// The following book was very helpful in implementing PNN/GRNN's in Encog.
/// Advanced Algorithms for Neural Networks: A C++ Sourcebook
/// by Timothy Masters, PhD (http://www.timothymasters.info/) John Wiley Sons
/// Inc (Computers); April 3, 1995, ISBN: 0471105880
/// </summary>
[Serializable]
public class BasicPNN : AbstractPNN, IMLRegression, IMLClassification, IMLError
{
/// <summary>
/// The sigma's specify the widths of each kernel used.
/// </summary>
///
private readonly double[] _sigma;
/// <summary>
/// Used for classification, the number of cases in each class.
/// </summary>
///
private int[] _countPer;
/// <summary>
/// The prior probability weights.
/// </summary>
///
private double[] _priors;
/// <summary>
/// The training samples that form the memory of this network.
/// </summary>
///
private BasicMLDataSet _samples;
/// <summary>
/// Construct a BasicPNN network.
/// </summary>
///
/// <param name="kernel">The kernel to use.</param>
/// <param name="outmodel">The output model for this network.</param>
/// <param name="inputCount">The number of inputs in this network.</param>
/// <param name="outputCount">The number of outputs in this network.</param>
public BasicPNN(PNNKernelType kernel, PNNOutputMode outmodel,
int inputCount, int outputCount) : base(kernel, outmodel, inputCount, outputCount)
{
SeparateClass = false;
_sigma = new double[inputCount];
}
/// <value>the countPer</value>
public int[] CountPer
{
get { return _countPer; }
}
/// <value>the priors</value>
public double[] Priors
{
get { return _priors; }
}
/// <value>the samples to set</value>
public BasicMLDataSet Samples
{
get { return _samples; }
set
{
_samples = value;
// update counts per
if (OutputMode == PNNOutputMode.Classification)
{
_countPer = new int[OutputCount];
_priors = new double[OutputCount];
foreach (IMLDataPair pair in value)
{
var i = (int) pair.Ideal[0];
if (i >= _countPer.Length)
{
throw new NeuralNetworkError(
"Training data contains more classes than neural network has output neurons to hold.");
}
_countPer[i]++;
}
for (int i = 0; i < _priors.Length; i++)
{
_priors[i] = -1;
}
}
}
}
/// <value>the sigma</value>
public double[] Sigma
{
get { return _sigma; }
}
/// <summary>
/// Compute the output from this network.
/// </summary>
///
/// <param name="input">The input to the network.</param>
/// <returns>The output from the network.</returns>
public override sealed IMLData Compute(IMLData input)
{
var xout = new double[OutputCount];
double psum = 0.0d;
int r = -1;
foreach (IMLDataPair pair in _samples)
{
r++;
if (r == Exclude)
{
continue;
}
double dist = 0.0d;
for (int i = 0; i < InputCount; i++)
{
double diff = input[i] - pair.Input[i];
diff /= _sigma[i];
dist += diff*diff;
}
if (Kernel == PNNKernelType.Gaussian)
{
dist = Math.Exp(-dist);
}
else if (Kernel == PNNKernelType.Reciprocal)
{
dist = 1.0d/(1.0d + dist);
}
if (dist < 1.0e-40d)
{
dist = 1.0e-40d;
}
if (OutputMode == PNNOutputMode.Classification)
{
var pop = (int) pair.Ideal[0];
xout[pop] += dist;
}
else if (OutputMode == PNNOutputMode.Unsupervised)
{
for (int i = 0; i < InputCount; i++)
{
xout[i] += dist*pair.Input[i];
}
psum += dist;
}
else if (OutputMode == PNNOutputMode.Regression)
{
for (int i = 0; i < OutputCount; i++)
{
xout[i] += dist*pair.Ideal[i];
}
psum += dist;
}
}
if (OutputMode == PNNOutputMode.Classification)
{
psum = 0.0d;
for (int i = 0; i < OutputCount; i++)
{
if (_priors[i] >= 0.0d)
{
xout[i] *= _priors[i]/_countPer[i];
}
psum += xout[i];
}
if (psum < 1.0e-40d)
{
psum = 1.0e-40d;
}
for (int i = 0; i < OutputCount; i++)
{
xout[i] /= psum;
}
}
else if (OutputMode == PNNOutputMode.Unsupervised)
{
for (int i = 0; i < InputCount; i++)
{
xout[i] /= psum;
}
}
else if (OutputMode == PNNOutputMode.Regression)
{
for (int i = 0; i < OutputCount; i++)
{
xout[i] /= psum;
}
}
return new BasicMLData(xout, false);
}
/// <inheritdoc/>
public override void UpdateProperties()
{
// unneeded
}
/// <inheritdoc/>
public double CalculateError(IMLDataSet data)
{
if (OutputMode == PNNOutputMode.Classification)
{
return EncogUtility.CalculateClassificationError(this, data);
}
else
{
return EncogUtility.CalculateRegressionError(this, data);
}
}
/// <inheritdoc/>
public int Classify(IMLData input)
{
IMLData output = Compute(input);
return EngineArray.MaxIndex(output);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using JetBrains.Annotations;
using log4net;
using log4net.Core;
using NUnit.Framework;
namespace GeoToolkit.Logging
{
public static class LogHelper
{
private static readonly Dictionary<Type, GeoLogger> _loggers = new Dictionary<Type, GeoLogger>();
private static readonly object _syncRoot = new object();
public static event EventHandler<LogEventArgs> Logging;
private static void Log(object obj, Level level, object message, Exception exception)
{
if (obj == null)
throw new ArgumentNullException("obj");
var logger = GetLogger(obj.GetType(),
s =>
{
var stackFrames = new StackTrace().GetFrames();
if (stackFrames == null)
return s;
if (stackFrames.Length < 6)
return s;
var stackFrame = stackFrames[5];
var method = (MethodInfo)stackFrame.GetMethod();
return string.Format("[{0}.{1}] {2}",
obj.GetType().Name,
method.Name, s);
});
if (level == Level.Info)
logger.Info(message, exception);
else if (level == Level.Debug)
logger.Debug(message, exception);
else if (level == Level.Warn)
logger.Warn(message, exception);
else if (level == Level.Error)
logger.Error(message, exception);
else if (level == Level.Fatal)
logger.Fatal(message, exception);
}
public static void LogInfo(this object obj, object message, Exception exception)
{
Log(obj, Level.Info, message, exception);
}
[StringFormatMethod("format")]
public static void LogInfoFormat(this object obj, string format, params object[] objs)
{
Log(obj, Level.Info, string.Format(format, objs), null);
}
public static void LogInfo(this object obj, object message)
{
Log(obj, Level.Info, message, null);
}
public static void LogDebug(this object obj, object message, Exception exception)
{
Log(obj, Level.Debug, message, exception);
}
[StringFormatMethod("format")]
public static void LogDebugFormat(this object obj, string format, params object[] objs)
{
Log(obj, Level.Debug, string.Format(format, objs), null);
}
public static void LogDebug(this object obj, object message)
{
Log(obj, Level.Debug, message, null);
}
public static void LogWarn(this object obj, object message, Exception exception)
{
Log(obj, Level.Warn, message, exception);
}
[StringFormatMethod("format")]
public static void LogWarnFormat(this object obj, string format, params object[] objs)
{
Log(obj, Level.Warn, string.Format(format, objs), null);
}
public static void LogWarn(this object obj, object message)
{
Log(obj, Level.Warn, message, null);
}
public static void LogError(this object obj, object message, Exception exception)
{
Log(obj, Level.Error, message, exception);
}
[StringFormatMethod("format")]
public static void LogErrorFormat(this object obj, string format, params object[] objs)
{
Log(obj, Level.Error, string.Format(format, objs), null);
}
public static void LogError(this object obj, object message)
{
Log(obj, Level.Error, message, null);
}
public static void LogFatal(this object obj, object message, Exception exception)
{
Log(obj, Level.Fatal, message, exception);
}
[StringFormatMethod("format")]
public static void LogFatalFormat(this object obj, string format, params object[] objs)
{
Log(obj, Level.Fatal, string.Format(format, objs), null);
}
public static void LogFatal(this object obj, object message)
{
Log(obj, Level.Fatal, message, null);
}
public static ILog GetLogger(Type type, Func<string, string> strConverter = null)
{
lock (_syncRoot)
{
GeoLogger result;
if (_loggers.TryGetValue(type, out result))
return result;
var logger = new GeoLogger(type, strConverter);
logger.LogEventRaised += LoggerLogEventRaised;
_loggers.Add(type, logger);
return logger;
}
}
private static void LoggerLogEventRaised(object sender, LogEventArgs e)
{
var handler = Logging;
if (handler == null)
return;
e.Message = string.Format("{0}, {1}: {2}{3}",
DateTime.Now.ToString("dd.MM hh:mm:ss"), e.Level, e.Message,
e.Exception != null ? Environment.NewLine + e.Exception : string.Empty);
handler(null, e);
}
private class GeoLogger : ILog
{
private readonly ILog _logger;
private readonly Func<string, string> _strConverter;
public Type Type { get; private set; }
public event EventHandler<LogEventArgs> LogEventRaised;
private void OnLogEventRaised(LogEventArgs eventArgs)
{
var handler = LogEventRaised;
if (handler != null)
handler(this, eventArgs);
}
public GeoLogger(Type type, Func<string, string> strConverter = null)
{
_logger = LogManager.GetLogger(type);
_strConverter = strConverter;
Type = type;
}
private string Convert(string str)
{
if (_strConverter == null)
return str;
return _strConverter(str);
}
public void Debug(object message)
{
var msg = Convert(message.ToString());
_logger.Debug(msg);
OnLogEventRaised(new LogEventArgs(Level.Debug, msg));
}
public void Debug(object message, Exception exception)
{
var str = Convert(message.ToString());
_logger.Debug(str, exception);
OnLogEventRaised(new LogEventArgs(Level.Debug, str, exception));
}
[StringFormatMethod("format")]
public void DebugFormat(string format, params object[] args)
{
var str = Convert(string.Format(format, args));
_logger.DebugFormat(str);
OnLogEventRaised(new LogEventArgs(Level.Debug, str));
}
public void DebugFormat(string format, object arg0)
{
DebugFormat(format, new[] { arg0 });
}
public void DebugFormat(string format, object arg0, object arg1)
{
DebugFormat(format, new[] { arg0, arg1 });
}
public void DebugFormat(string format, object arg0, object arg1, object arg2)
{
DebugFormat(format, new[] { arg0, arg1, arg2 });
}
public void DebugFormat(IFormatProvider provider, string format, params object[] args)
{
throw new NotImplementedException();
}
public void Info(object message)
{
var str = Convert(message.ToString());
_logger.Info(str);
OnLogEventRaised(new LogEventArgs(Level.Info, str));
}
public void Info(object message, Exception exception)
{
var str = Convert(message.ToString());
_logger.Info(str, exception);
OnLogEventRaised(new LogEventArgs(Level.Info, str, exception));
}
[StringFormatMethod("format")]
public void InfoFormat(string format, params object[] args)
{
var str = Convert(string.Format(format, args));
_logger.InfoFormat(str);
OnLogEventRaised(new LogEventArgs(Level.Info, str));
}
public void InfoFormat(string format, object arg0)
{
InfoFormat(format, new[] { arg0 });
}
public void InfoFormat(string format, object arg0, object arg1)
{
InfoFormat(format, new[] { arg0, arg1 });
}
public void InfoFormat(string format, object arg0, object arg1, object arg2)
{
InfoFormat(format, new[] { arg0, arg1, arg2 });
}
public void InfoFormat(IFormatProvider provider, string format, params object[] args)
{
throw new NotImplementedException();
}
public void Warn(object message)
{
var str = Convert(message.ToString());
_logger.Warn(str);
OnLogEventRaised(new LogEventArgs(Level.Warn, str));
}
public void Warn(object message, Exception exception)
{
var str = Convert(message.ToString());
_logger.Warn(str, exception);
OnLogEventRaised(new LogEventArgs(Level.Warn, str, exception));
}
[StringFormatMethod("format")]
public void WarnFormat(string format, params object[] args)
{
var str = Convert(string.Format(format, args));
_logger.WarnFormat(str);
OnLogEventRaised(new LogEventArgs(Level.Warn, str));
}
public void WarnFormat(string format, object arg0)
{
WarnFormat(format, new[] { arg0 });
}
public void WarnFormat(string format, object arg0, object arg1)
{
WarnFormat(format, new[] { arg0, arg1 });
}
public void WarnFormat(string format, object arg0, object arg1, object arg2)
{
WarnFormat(format, new[] { arg0, arg1, arg2 });
}
public void WarnFormat(IFormatProvider provider, string format, params object[] args)
{
throw new NotImplementedException();
}
public void Error(object message)
{
var str = Convert(message.ToString());
_logger.Error(str);
OnLogEventRaised(new LogEventArgs(Level.Error, str));
}
public void Error(object message, Exception exception)
{
var str = Convert(message.ToString());
_logger.Error(str, exception);
OnLogEventRaised(new LogEventArgs(Level.Error, str, exception));
}
[StringFormatMethod("format")]
public void ErrorFormat(string format, params object[] args)
{
var str = Convert(string.Format(format, args));
_logger.ErrorFormat(str);
OnLogEventRaised(new LogEventArgs(Level.Error, str));
}
public void ErrorFormat(string format, object arg0)
{
ErrorFormat(format, new[] { arg0 });
}
public void ErrorFormat(string format, object arg0, object arg1)
{
ErrorFormat(format, new[] { arg0, arg1 });
}
public void ErrorFormat(string format, object arg0, object arg1, object arg2)
{
ErrorFormat(format, new[] { arg0, arg1, arg2 });
}
public void ErrorFormat(IFormatProvider provider, string format, params object[] args)
{
throw new NotImplementedException();
}
public void Fatal(object message)
{
var str = Convert(message.ToString());
_logger.Fatal(str);
OnLogEventRaised(new LogEventArgs(Level.Fatal, str));
}
public void Fatal(object message, Exception exception)
{
var str = Convert(message.ToString());
_logger.Fatal(str, exception);
OnLogEventRaised(new LogEventArgs(Level.Fatal, str, exception));
}
[StringFormatMethod("format")]
public void FatalFormat(string format, params object[] args)
{
var str = Convert(string.Format(format, args));
_logger.FatalFormat(str);
OnLogEventRaised(new LogEventArgs(Level.Fatal, str));
}
public void FatalFormat(string format, object arg0)
{
FatalFormat(format, new[] { arg0 });
}
public void FatalFormat(string format, object arg0, object arg1)
{
FatalFormat(format, new[] { arg0, arg1 });
}
public void FatalFormat(string format, object arg0, object arg1, object arg2)
{
FatalFormat(format, new[] { arg0, arg1, arg2 });
}
public void FatalFormat(IFormatProvider provider, string format, params object[] args)
{
throw new NotImplementedException();
}
public bool IsDebugEnabled
{
get { return _logger.IsDebugEnabled; }
}
public bool IsInfoEnabled
{
get { return _logger.IsInfoEnabled; }
}
public bool IsWarnEnabled
{
get { return _logger.IsWarnEnabled; }
}
public bool IsErrorEnabled
{
get { return _logger.IsErrorEnabled; }
}
public bool IsFatalEnabled
{
get { return _logger.IsFatalEnabled; }
}
public ILogger Logger
{
get { return _logger.Logger; }
}
}
public class LogEventArgs : EventArgs
{
public string Message { get; set; }
public Exception Exception { get; private set; }
public Level Level { get; private set; }
public LogEventArgs(Level level, string message, Exception exception)
{
Message = message;
Exception = exception;
Level = level;
}
public LogEventArgs(Level level, object message, Exception exception)
: this(level, message.ToString(), exception)
{
}
public LogEventArgs(Level level, string message) : this(level, message, null)
{
}
public LogEventArgs(Level level, object message) : this(level, message.ToString())
{
}
}
}
#if DEBUG
[TestFixture]
public class LogHelperTest
{
[Test]
public void LogTest()
{
this.LogInfo("test");
}
[Test]
public void LoadTest()
{
var stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 100000; i++)
this.LogDebug("test string");
stopWatch.Stop();
Console.WriteLine("time for 100000 log items: {0}ms", stopWatch.ElapsedMilliseconds);
}
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.Text;
using System.Xml;
namespace System.ServiceModel.Channels
{
internal class BinaryMessageEncoderFactory : MessageEncoderFactory
{
private const int maxPooledXmlReaderPerMessage = 2;
private BinaryMessageEncoder _messageEncoder;
private MessageVersion _messageVersion;
private int _maxWritePoolSize;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile SynchronizedPool<BinaryBufferedMessageData> _bufferedDataPool;
private volatile SynchronizedPool<BinaryBufferedMessageWriter> _bufferedWriterPool;
private volatile SynchronizedPool<RecycledMessageState> _recycledStatePool;
private XmlDictionaryReaderQuotas _bufferedReadReaderQuotas;
private BinaryVersion _binaryVersion;
public BinaryMessageEncoderFactory(MessageVersion messageVersion, int maxReadPoolSize, int maxWritePoolSize, int maxSessionSize,
XmlDictionaryReaderQuotas readerQuotas, long maxReceivedMessageSize, BinaryVersion version, CompressionFormat compressionFormat)
{
_messageVersion = messageVersion;
MaxReadPoolSize = maxReadPoolSize;
_maxWritePoolSize = maxWritePoolSize;
MaxSessionSize = maxSessionSize;
ThisLock = new object();
ReaderQuotas = new XmlDictionaryReaderQuotas();
if (readerQuotas != null)
{
readerQuotas.CopyTo(ReaderQuotas);
}
_bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(ReaderQuotas);
MaxReceivedMessageSize = maxReceivedMessageSize;
_binaryVersion = version;
CompressionFormat = compressionFormat;
_messageEncoder = new BinaryMessageEncoder(this, false, 0);
}
public static IXmlDictionary XmlDictionary
{
get { return XD.Dictionary; }
}
public override MessageEncoder Encoder
{
get
{
return _messageEncoder;
}
}
public override MessageVersion MessageVersion
{
get { return _messageVersion; }
}
public int MaxWritePoolSize
{
get { return _maxWritePoolSize; }
}
public XmlDictionaryReaderQuotas ReaderQuotas { get; }
public int MaxReadPoolSize { get; }
public int MaxSessionSize { get; }
public CompressionFormat CompressionFormat { get; }
private long MaxReceivedMessageSize
{
get;
set;
}
private object ThisLock { get; }
private SynchronizedPool<RecycledMessageState> RecycledStatePool
{
get
{
if (_recycledStatePool == null)
{
lock (ThisLock)
{
if (_recycledStatePool == null)
{
//running = true;
_recycledStatePool = new SynchronizedPool<RecycledMessageState>(MaxReadPoolSize);
}
}
}
return _recycledStatePool;
}
}
public override MessageEncoder CreateSessionEncoder()
{
return new BinaryMessageEncoder(this, true, MaxSessionSize);
}
private XmlDictionaryWriter TakeStreamedWriter(Stream stream)
{
return XmlDictionaryWriter.CreateBinaryWriter(stream, _binaryVersion.Dictionary, null, false);
}
private void ReturnStreamedWriter(XmlDictionaryWriter xmlWriter)
{
xmlWriter.Dispose();
}
private BinaryBufferedMessageWriter TakeBufferedWriter()
{
if (_bufferedWriterPool == null)
{
lock (ThisLock)
{
if (_bufferedWriterPool == null)
{
//running = true;
_bufferedWriterPool = new SynchronizedPool<BinaryBufferedMessageWriter>(_maxWritePoolSize);
}
}
}
BinaryBufferedMessageWriter messageWriter = _bufferedWriterPool.Take();
if (messageWriter == null)
{
messageWriter = new BinaryBufferedMessageWriter(_binaryVersion.Dictionary);
if (WcfEventSource.Instance.WritePoolMissIsEnabled())
{
WcfEventSource.Instance.WritePoolMiss(messageWriter.GetType().Name);
}
}
return messageWriter;
}
private void ReturnMessageWriter(BinaryBufferedMessageWriter messageWriter)
{
_bufferedWriterPool.Return(messageWriter);
}
private XmlDictionaryReader TakeStreamedReader(Stream stream)
{
return XmlDictionaryReader.CreateBinaryReader(stream,
_binaryVersion.Dictionary,
ReaderQuotas,
null);
}
private BinaryBufferedMessageData TakeBufferedData(BinaryMessageEncoder messageEncoder)
{
if (_bufferedDataPool == null)
{
lock (ThisLock)
{
if (_bufferedDataPool == null)
{
//running = true;
_bufferedDataPool = new SynchronizedPool<BinaryBufferedMessageData>(MaxReadPoolSize);
}
}
}
BinaryBufferedMessageData messageData = _bufferedDataPool.Take();
if (messageData == null)
{
messageData = new BinaryBufferedMessageData(this, maxPooledXmlReaderPerMessage);
if (WcfEventSource.Instance.ReadPoolMissIsEnabled())
{
WcfEventSource.Instance.ReadPoolMiss(messageData.GetType().Name);
}
}
messageData.SetMessageEncoder(messageEncoder);
return messageData;
}
private void ReturnBufferedData(BinaryBufferedMessageData messageData)
{
messageData.SetMessageEncoder(null);
_bufferedDataPool.Return(messageData);
}
internal class BinaryBufferedMessageData : BufferedMessageData
{
private BinaryMessageEncoderFactory _factory;
private BinaryMessageEncoder _messageEncoder;
private Pool<XmlDictionaryReader> _readerPool;
private OnXmlDictionaryReaderClose _onClose;
public BinaryBufferedMessageData(BinaryMessageEncoderFactory factory, int maxPoolSize)
: base(factory.RecycledStatePool)
{
_factory = factory;
_readerPool = new Pool<XmlDictionaryReader>(maxPoolSize);
_onClose = new OnXmlDictionaryReaderClose(OnXmlReaderClosed);
}
public override MessageEncoder MessageEncoder
{
get { return _messageEncoder; }
}
public override XmlDictionaryReaderQuotas Quotas
{
get { return _factory.ReaderQuotas; }
}
public void SetMessageEncoder(BinaryMessageEncoder messageEncoder)
{
_messageEncoder = messageEncoder;
}
protected override XmlDictionaryReader TakeXmlReader()
{
ArraySegment<byte> buffer = Buffer;
return XmlDictionaryReader.CreateBinaryReader(buffer.Array, buffer.Offset, buffer.Count,
_factory._binaryVersion.Dictionary,
_factory._bufferedReadReaderQuotas,
_messageEncoder.ReaderSession);
}
protected override void ReturnXmlReader(XmlDictionaryReader reader)
{
_readerPool.Return(reader);
}
protected override void OnClosed()
{
_factory.ReturnBufferedData(this);
}
}
internal class BinaryBufferedMessageWriter : BufferedMessageWriter
{
private IXmlDictionary _dictionary;
private XmlBinaryWriterSession _session;
public BinaryBufferedMessageWriter(IXmlDictionary dictionary)
{
_dictionary = dictionary;
}
public BinaryBufferedMessageWriter(IXmlDictionary dictionary, XmlBinaryWriterSession session)
{
_dictionary = dictionary;
_session = session;
}
protected override XmlDictionaryWriter TakeXmlWriter(Stream stream)
{
return XmlDictionaryWriter.CreateBinaryWriter(stream, _dictionary, _session, false);
}
protected override void ReturnXmlWriter(XmlDictionaryWriter writer)
{
writer.Dispose();
}
}
internal class BinaryMessageEncoder : MessageEncoder, ICompressedMessageEncoder
{
private const string SupportedCompressionTypesMessageProperty = "BinaryMessageEncoder.SupportedCompressionTypes";
private BinaryMessageEncoderFactory _factory;
private bool _isSession;
private XmlBinaryWriterSessionWithQuota _writerSession;
private BinaryBufferedMessageWriter _sessionMessageWriter;
private XmlBinaryReaderSession _readerSessionForLogging;
private bool _readerSessionForLoggingIsInvalid = false;
private int _writeIdCounter;
private int _idCounter;
private int _maxSessionSize;
private int _remainingReaderSessionSize;
private bool _isReaderSessionInvalid;
private MessagePatterns _messagePatterns;
private string _contentType;
private string _normalContentType;
private string _gzipCompressedContentType;
private string _deflateCompressedContentType;
private CompressionFormat _sessionCompressionFormat;
private readonly long _maxReceivedMessageSize;
public BinaryMessageEncoder(BinaryMessageEncoderFactory factory, bool isSession, int maxSessionSize)
{
_factory = factory;
_isSession = isSession;
_maxSessionSize = maxSessionSize;
_remainingReaderSessionSize = maxSessionSize;
_normalContentType = isSession ? factory._binaryVersion.SessionContentType : factory._binaryVersion.ContentType;
_gzipCompressedContentType = isSession ? BinaryVersion.GZipVersion1.SessionContentType : BinaryVersion.GZipVersion1.ContentType;
_deflateCompressedContentType = isSession ? BinaryVersion.DeflateVersion1.SessionContentType : BinaryVersion.DeflateVersion1.ContentType;
_sessionCompressionFormat = _factory.CompressionFormat;
_maxReceivedMessageSize = _factory.MaxReceivedMessageSize;
switch (_factory.CompressionFormat)
{
case CompressionFormat.Deflate:
_contentType = _deflateCompressedContentType;
break;
case CompressionFormat.GZip:
_contentType = _gzipCompressedContentType;
break;
default:
_contentType = _normalContentType;
break;
}
}
public override string ContentType
{
get
{
return _contentType;
}
}
public override MessageVersion MessageVersion
{
get { return _factory._messageVersion; }
}
public override string MediaType
{
get { return _contentType; }
}
public XmlBinaryReaderSession ReaderSession { get; private set; }
public bool CompressionEnabled
{
get { return _factory.CompressionFormat != CompressionFormat.None; }
}
private ArraySegment<byte> AddSessionInformationToMessage(ArraySegment<byte> messageData, BufferManager bufferManager, int maxMessageSize)
{
int dictionarySize = 0;
byte[] buffer = messageData.Array;
if (_writerSession.HasNewStrings)
{
IList<XmlDictionaryString> newStrings = _writerSession.GetNewStrings();
for (int i = 0; i < newStrings.Count; i++)
{
int utf8ValueSize = Encoding.UTF8.GetByteCount(newStrings[i].Value);
dictionarySize += IntEncoder.GetEncodedSize(utf8ValueSize) + utf8ValueSize;
}
int messageSize = messageData.Offset + messageData.Count;
int remainingMessageSize = maxMessageSize - messageSize;
if (remainingMessageSize - dictionarySize < 0)
{
string excMsg = SR.Format(SR.MaxSentMessageSizeExceeded, maxMessageSize);
if (WcfEventSource.Instance.MaxSentMessageSizeExceededIsEnabled())
{
WcfEventSource.Instance.MaxSentMessageSizeExceeded(excMsg);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(excMsg));
}
int requiredBufferSize = messageData.Offset + messageData.Count + dictionarySize;
if (buffer.Length < requiredBufferSize)
{
byte[] newBuffer = bufferManager.TakeBuffer(requiredBufferSize);
Buffer.BlockCopy(buffer, messageData.Offset, newBuffer, messageData.Offset, messageData.Count);
bufferManager.ReturnBuffer(buffer);
buffer = newBuffer;
}
Buffer.BlockCopy(buffer, messageData.Offset, buffer, messageData.Offset + dictionarySize, messageData.Count);
int offset = messageData.Offset;
for (int i = 0; i < newStrings.Count; i++)
{
string newString = newStrings[i].Value;
int utf8ValueSize = Encoding.UTF8.GetByteCount(newString);
offset += IntEncoder.Encode(utf8ValueSize, buffer, offset);
offset += Encoding.UTF8.GetBytes(newString, 0, newString.Length, buffer, offset);
}
_writerSession.ClearNewStrings();
}
int headerSize = IntEncoder.GetEncodedSize(dictionarySize);
int newOffset = messageData.Offset - headerSize;
int newSize = headerSize + messageData.Count + dictionarySize;
IntEncoder.Encode(dictionarySize, buffer, newOffset);
return new ArraySegment<byte>(buffer, newOffset, newSize);
}
private ArraySegment<byte> ExtractSessionInformationFromMessage(ArraySegment<byte> messageData)
{
if (_isReaderSessionInvalid)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.BinaryEncoderSessionInvalid));
}
byte[] buffer = messageData.Array;
int dictionarySize;
int headerSize;
int newOffset;
int newSize;
bool throwing = true;
try
{
IntDecoder decoder = new IntDecoder();
headerSize = decoder.Decode(buffer, messageData.Offset, messageData.Count);
dictionarySize = decoder.Value;
if (dictionarySize > messageData.Count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.BinaryEncoderSessionMalformed));
}
newOffset = messageData.Offset + headerSize + dictionarySize;
newSize = messageData.Count - headerSize - dictionarySize;
if (newSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.BinaryEncoderSessionMalformed));
}
if (dictionarySize > 0)
{
if (dictionarySize > _remainingReaderSessionSize)
{
string message = SR.Format(SR.BinaryEncoderSessionTooLarge, _maxSessionSize);
if (WcfEventSource.Instance.MaxSessionSizeReachedIsEnabled())
{
WcfEventSource.Instance.MaxSessionSizeReached(message);
}
Exception inner = new QuotaExceededException(message);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner));
}
else
{
_remainingReaderSessionSize -= dictionarySize;
}
int size = dictionarySize;
int offset = messageData.Offset + headerSize;
while (size > 0)
{
decoder.Reset();
int bytesDecoded = decoder.Decode(buffer, offset, size);
int utf8ValueSize = decoder.Value;
offset += bytesDecoded;
size -= bytesDecoded;
if (utf8ValueSize > size)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.BinaryEncoderSessionMalformed));
}
string value = Encoding.UTF8.GetString(buffer, offset, utf8ValueSize);
offset += utf8ValueSize;
size -= utf8ValueSize;
ReaderSession.Add(_idCounter, value);
_idCounter++;
}
}
throwing = false;
}
finally
{
if (throwing)
{
_isReaderSessionInvalid = true;
}
}
return new ArraySegment<byte>(buffer, newOffset, newSize);
}
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
if (bufferManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(bufferManager));
}
CompressionFormat compressionFormat = CheckContentType(contentType);
if (WcfEventSource.Instance.BinaryMessageDecodingStartIsEnabled())
{
WcfEventSource.Instance.BinaryMessageDecodingStart();
}
if (compressionFormat != CompressionFormat.None)
{
MessageEncoderCompressionHandler.DecompressBuffer(ref buffer, bufferManager, compressionFormat, _maxReceivedMessageSize);
}
if (_isSession)
{
if (ReaderSession == null)
{
ReaderSession = new XmlBinaryReaderSession();
_messagePatterns = new MessagePatterns(_factory._binaryVersion.Dictionary, ReaderSession, MessageVersion);
}
try
{
buffer = ExtractSessionInformationFromMessage(buffer);
}
catch (InvalidDataException)
{
MessageLogger.LogMessage(buffer, MessageLoggingSource.Malformed);
throw;
}
}
BinaryBufferedMessageData messageData = _factory.TakeBufferedData(this);
Message message;
if (_messagePatterns != null)
{
message = _messagePatterns.TryCreateMessage(buffer.Array, buffer.Offset, buffer.Count, bufferManager, messageData);
}
else
{
message = null;
}
if (message == null)
{
messageData.Open(buffer, bufferManager);
RecycledMessageState messageState = messageData.TakeMessageState();
if (messageState == null)
{
messageState = new RecycledMessageState();
}
message = new BufferedMessage(messageData, messageState);
}
message.Properties.Encoder = this;
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
{
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
}
CompressionFormat compressionFormat = CheckContentType(contentType);
if (WcfEventSource.Instance.BinaryMessageDecodingStartIsEnabled())
{
WcfEventSource.Instance.BinaryMessageDecodingStart();
}
if (compressionFormat != CompressionFormat.None)
{
stream = new MaxMessageSizeStream(
MessageEncoderCompressionHandler.GetDecompressStream(stream, compressionFormat), _maxReceivedMessageSize);
}
XmlDictionaryReader reader = _factory.TakeStreamedReader(stream);
Message message = Message.CreateMessage(reader, maxSizeOfHeaders, _factory._messageVersion);
message.Properties.Encoder = this;
if (WcfEventSource.Instance.StreamedMessageReadByEncoderIsEnabled())
{
WcfEventSource.Instance.StreamedMessageReadByEncoder(
EventTraceActivityHelper.TryExtractActivity(message, true));
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message));
}
if (bufferManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(bufferManager));
}
if (maxMessageSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxMessageSize), maxMessageSize,
SR.ValueMustBeNonNegative));
}
EventTraceActivity eventTraceActivity = null;
if (WcfEventSource.Instance.BinaryMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
WcfEventSource.Instance.BinaryMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
if (_isSession)
{
if (_writerSession == null)
{
_writerSession = new XmlBinaryWriterSessionWithQuota(_maxSessionSize);
_sessionMessageWriter = new BinaryBufferedMessageWriter(_factory._binaryVersion.Dictionary, _writerSession);
}
messageOffset += IntEncoder.MaxEncodedSize;
}
if (messageOffset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(messageOffset), messageOffset,
SR.ValueMustBeNonNegative));
}
if (messageOffset > maxMessageSize)
{
string excMsg = SR.Format(SR.MaxSentMessageSizeExceeded, maxMessageSize);
if (WcfEventSource.Instance.MaxSentMessageSizeExceededIsEnabled())
{
WcfEventSource.Instance.MaxSentMessageSizeExceeded(excMsg);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(excMsg));
}
ThrowIfMismatchedMessageVersion(message);
BinaryBufferedMessageWriter messageWriter;
if (_isSession)
{
messageWriter = _sessionMessageWriter;
}
else
{
messageWriter = _factory.TakeBufferedWriter();
}
ArraySegment<byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize);
if (MessageLogger.LogMessagesAtTransportLevel && !_readerSessionForLoggingIsInvalid)
{
if (_isSession)
{
if (_readerSessionForLogging == null)
{
_readerSessionForLogging = new XmlBinaryReaderSession();
}
if (_writerSession.HasNewStrings)
{
foreach (XmlDictionaryString xmlDictionaryString in _writerSession.GetNewStrings())
{
_readerSessionForLogging.Add(_writeIdCounter++, xmlDictionaryString.Value);
}
}
}
XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateBinaryReader(messageData.Array, messageData.Offset, messageData.Count, XD.Dictionary, XmlDictionaryReaderQuotas.Max, _readerSessionForLogging);
MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend);
}
else
{
_readerSessionForLoggingIsInvalid = true;
}
if (_isSession)
{
messageData = AddSessionInformationToMessage(messageData, bufferManager, maxMessageSize);
}
else
{
_factory.ReturnMessageWriter(messageWriter);
}
CompressionFormat compressionFormat = CheckCompressedWrite(message);
if (compressionFormat != CompressionFormat.None)
{
MessageEncoderCompressionHandler.CompressBuffer(ref messageData, bufferManager, compressionFormat);
}
return messageData;
}
public override void WriteMessage(Message message, Stream stream)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(message)));
}
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(stream)));
}
EventTraceActivity eventTraceActivity = null;
if (WcfEventSource.Instance.BinaryMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
WcfEventSource.Instance.BinaryMessageEncodingStart(eventTraceActivity);
}
CompressionFormat compressionFormat = CheckCompressedWrite(message);
if (compressionFormat != CompressionFormat.None)
{
stream = MessageEncoderCompressionHandler.GetCompressStream(stream, compressionFormat);
}
ThrowIfMismatchedMessageVersion(message);
message.Properties.Encoder = this;
XmlDictionaryWriter xmlWriter = _factory.TakeStreamedWriter(stream);
message.WriteMessage(xmlWriter);
xmlWriter.Flush();
if (WcfEventSource.Instance.StreamedMessageWrittenByEncoderIsEnabled())
{
WcfEventSource.Instance.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message));
}
_factory.ReturnStreamedWriter(xmlWriter);
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend);
}
if (compressionFormat != CompressionFormat.None)
{
// Stream.Close() has been replaced with Dispose()
stream.Dispose();
}
}
public override bool IsContentTypeSupported(string contentType)
{
bool supported = true;
if (!base.IsContentTypeSupported(contentType))
{
if (CompressionEnabled)
{
supported = (_factory.CompressionFormat == CompressionFormat.GZip &&
base.IsContentTypeSupported(contentType, _gzipCompressedContentType, _gzipCompressedContentType)) ||
(_factory.CompressionFormat == CompressionFormat.Deflate &&
base.IsContentTypeSupported(contentType, _deflateCompressedContentType, _deflateCompressedContentType)) ||
base.IsContentTypeSupported(contentType, _normalContentType, _normalContentType);
}
else
{
supported = false;
}
}
return supported;
}
public void SetSessionContentType(string contentType)
{
if (base.IsContentTypeSupported(contentType, _gzipCompressedContentType, _gzipCompressedContentType))
{
_sessionCompressionFormat = CompressionFormat.GZip;
}
else if (base.IsContentTypeSupported(contentType, _deflateCompressedContentType, _deflateCompressedContentType))
{
_sessionCompressionFormat = CompressionFormat.Deflate;
}
else
{
_sessionCompressionFormat = CompressionFormat.None;
}
}
public void AddCompressedMessageProperties(Message message, string supportedCompressionTypes)
{
message.Properties.Add(SupportedCompressionTypesMessageProperty, supportedCompressionTypes);
}
private static bool ContentTypeEqualsOrStartsWith(string contentType, string supportedContentType)
{
return contentType == supportedContentType || contentType.StartsWith(supportedContentType, StringComparison.OrdinalIgnoreCase);
}
private CompressionFormat CheckContentType(string contentType)
{
CompressionFormat compressionFormat = CompressionFormat.None;
if (contentType == null)
{
compressionFormat = _sessionCompressionFormat;
}
else
{
if (!CompressionEnabled)
{
if (!ContentTypeEqualsOrStartsWith(contentType, ContentType))
{
throw FxTrace.Exception.AsError(new ProtocolException(SR.Format(SR.EncoderUnrecognizedContentType, contentType, ContentType)));
}
}
else
{
if (_factory.CompressionFormat == CompressionFormat.GZip && ContentTypeEqualsOrStartsWith(contentType, _gzipCompressedContentType))
{
compressionFormat = CompressionFormat.GZip;
}
else if (_factory.CompressionFormat == CompressionFormat.Deflate && ContentTypeEqualsOrStartsWith(contentType, _deflateCompressedContentType))
{
compressionFormat = CompressionFormat.Deflate;
}
else if (ContentTypeEqualsOrStartsWith(contentType, _normalContentType))
{
compressionFormat = CompressionFormat.None;
}
else
{
throw FxTrace.Exception.AsError(new ProtocolException(SR.Format(SR.EncoderUnrecognizedContentType, contentType, ContentType)));
}
}
}
return compressionFormat;
}
private CompressionFormat CheckCompressedWrite(Message message)
{
CompressionFormat compressionFormat = _sessionCompressionFormat;
if (compressionFormat != CompressionFormat.None && !_isSession)
{
string acceptEncoding;
if (message.Properties.TryGetValue(SupportedCompressionTypesMessageProperty, out acceptEncoding) &&
acceptEncoding != null)
{
acceptEncoding = acceptEncoding.ToLowerInvariant();
if ((compressionFormat == CompressionFormat.GZip &&
!acceptEncoding.Contains(MessageEncoderCompressionHandler.GZipContentEncoding)) ||
(compressionFormat == CompressionFormat.Deflate &&
!acceptEncoding.Contains(MessageEncoderCompressionHandler.DeflateContentEncoding)))
{
compressionFormat = CompressionFormat.None;
}
}
}
return compressionFormat;
}
}
internal class XmlBinaryWriterSessionWithQuota : XmlBinaryWriterSession
{
private int _bytesRemaining;
private List<XmlDictionaryString> _newStrings;
public XmlBinaryWriterSessionWithQuota(int maxSessionSize)
{
_bytesRemaining = maxSessionSize;
}
public bool HasNewStrings
{
get { return _newStrings != null; }
}
public override bool TryAdd(XmlDictionaryString s, out int key)
{
if (_bytesRemaining == 0)
{
key = -1;
return false;
}
int bytesRequired = Encoding.UTF8.GetByteCount(s.Value);
bytesRequired += IntEncoder.GetEncodedSize(bytesRequired);
if (bytesRequired > _bytesRemaining)
{
key = -1;
_bytesRemaining = 0;
return false;
}
if (base.TryAdd(s, out key))
{
if (_newStrings == null)
{
_newStrings = new List<XmlDictionaryString>();
}
_newStrings.Add(s);
_bytesRemaining -= bytesRequired;
return true;
}
else
{
return false;
}
}
public IList<XmlDictionaryString> GetNewStrings()
{
return _newStrings;
}
public void ClearNewStrings()
{
_newStrings = null;
}
}
}
internal class BinaryFormatBuilder
{
private List<byte> _bytes;
public BinaryFormatBuilder()
{
_bytes = new List<byte>();
}
public int Count
{
get { return _bytes.Count; }
}
public void AppendPrefixDictionaryElement(char prefix, int key)
{
AppendNode(XmlBinaryNodeType.PrefixDictionaryElementA + GetPrefixOffset(prefix));
AppendKey(key);
}
public void AppendDictionaryXmlnsAttribute(char prefix, int key)
{
AppendNode(XmlBinaryNodeType.DictionaryXmlnsAttribute);
AppendUtf8(prefix);
AppendKey(key);
}
public void AppendPrefixDictionaryAttribute(char prefix, int key, char value)
{
AppendNode(XmlBinaryNodeType.PrefixDictionaryAttributeA + GetPrefixOffset(prefix));
AppendKey(key);
if (value == '1')
{
AppendNode(XmlBinaryNodeType.OneText);
}
else
{
AppendNode(XmlBinaryNodeType.Chars8Text);
AppendUtf8(value);
}
}
public void AppendDictionaryAttribute(char prefix, int key, char value)
{
AppendNode(XmlBinaryNodeType.DictionaryAttribute);
AppendUtf8(prefix);
AppendKey(key);
AppendNode(XmlBinaryNodeType.Chars8Text);
AppendUtf8(value);
}
public void AppendDictionaryTextWithEndElement(int key)
{
AppendNode(XmlBinaryNodeType.DictionaryTextWithEndElement);
AppendKey(key);
}
public void AppendDictionaryTextWithEndElement()
{
AppendNode(XmlBinaryNodeType.DictionaryTextWithEndElement);
}
public void AppendUniqueIDWithEndElement()
{
AppendNode(XmlBinaryNodeType.UniqueIdTextWithEndElement);
}
public void AppendEndElement()
{
AppendNode(XmlBinaryNodeType.EndElement);
}
private void AppendKey(int key)
{
if (key < 0 || key >= 0x4000)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(key), key,
SR.Format(SR.ValueMustBeInRange, 0, 0x4000)));
}
if (key >= 0x80)
{
AppendByte((key & 0x7f) | 0x80);
AppendByte(key >> 7);
}
else
{
AppendByte(key);
}
}
private void AppendNode(XmlBinaryNodeType value)
{
AppendByte((int)value);
}
private void AppendByte(int value)
{
if (value < 0 || value > 0xFF)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value,
SR.Format(SR.ValueMustBeInRange, 0, 0xFF)));
}
_bytes.Add((byte)value);
}
private void AppendUtf8(char value)
{
AppendByte(1);
AppendByte((int)value);
}
public int GetStaticKey(int value)
{
return value * 2;
}
public int GetSessionKey(int value)
{
return value * 2 + 1;
}
private int GetPrefixOffset(char prefix)
{
if (prefix < 'a' && prefix > 'z')
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefix), prefix,
SR.Format(SR.ValueMustBeInRange, 'a', 'z')));
}
return prefix - 'a';
}
public byte[] ToByteArray()
{
byte[] array = _bytes.ToArray();
_bytes.Clear();
return array;
}
}
internal static class BinaryFormatParser
{
public static bool IsSessionKey(int value)
{
return (value & 1) != 0;
}
public static int GetSessionKey(int value)
{
return value / 2;
}
public static int GetStaticKey(int value)
{
return value / 2;
}
public static int ParseInt32(byte[] buffer, int offset, int size)
{
switch (size)
{
case 1:
return buffer[offset];
case 2:
return (buffer[offset] & 0x7f) + (buffer[offset + 1] << 7);
case 3:
return (buffer[offset] & 0x7f) + ((buffer[offset + 1] & 0x7f) << 7) + (buffer[offset + 2] << 14);
case 4:
return (buffer[offset] & 0x7f) + ((buffer[offset + 1] & 0x7f) << 7) + ((buffer[offset + 2] & 0x7f) << 14) + (buffer[offset + 3] << 21);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(size), size,
SR.Format(SR.ValueMustBeInRange, 1, 4)));
}
}
public static int ParseKey(byte[] buffer, int offset, int size)
{
return ParseInt32(buffer, offset, size);
}
public unsafe static UniqueId ParseUniqueID(byte[] buffer, int offset, int size)
{
return new UniqueId(buffer, offset);
}
public static int MatchBytes(byte[] buffer, int offset, int size, byte[] buffer2)
{
if (size < buffer2.Length)
{
return 0;
}
int j = offset;
for (int i = 0; i < buffer2.Length; i++, j++)
{
if (buffer2[i] != buffer[j])
{
return 0;
}
}
return buffer2.Length;
}
public static bool MatchAttributeNode(byte[] buffer, int offset, int size)
{
const XmlBinaryNodeType minAttribute = XmlBinaryNodeType.ShortAttribute;
const XmlBinaryNodeType maxAttribute = XmlBinaryNodeType.DictionaryAttribute;
if (size < 1)
{
return false;
}
XmlBinaryNodeType nodeType = (XmlBinaryNodeType)buffer[offset];
return nodeType >= minAttribute && nodeType <= maxAttribute;
}
public static int MatchKey(byte[] buffer, int offset, int size)
{
return MatchInt32(buffer, offset, size);
}
public static int MatchInt32(byte[] buffer, int offset, int size)
{
if (size > 0)
{
if ((buffer[offset] & 0x80) == 0)
{
return 1;
}
}
if (size > 1)
{
if ((buffer[offset + 1] & 0x80) == 0)
{
return 2;
}
}
if (size > 2)
{
if ((buffer[offset + 2] & 0x80) == 0)
{
return 3;
}
}
if (size > 3)
{
if ((buffer[offset + 3] & 0x80) == 0)
{
return 4;
}
}
return 0;
}
public static int MatchUniqueID(byte[] buffer, int offset, int size)
{
if (size < 16)
{
return 0;
}
return 16;
}
}
internal class MessagePatterns
{
private static readonly byte[] s_commonFragment; // <Envelope><Headers><Action>
private static readonly byte[] s_requestFragment1; // </Action><MessageID>
private static readonly byte[] s_requestFragment2; // </MessageID><ReplyTo>...</ReplyTo><To>session-to-key</To></Headers><Body>
private static readonly byte[] s_responseFragment1; // </Action><RelatesTo>
private static readonly byte[] s_responseFragment2; // </RelatesTo><To>static-anonymous-key</To></Headers><Body>
private static readonly byte[] s_bodyFragment; // <Envelope><Body>
private const int ToValueSessionKey = 1;
private IXmlDictionary _dictionary;
private XmlBinaryReaderSession _readerSession;
private ToHeader _toHeader;
private MessageVersion _messageVersion;
static MessagePatterns()
{
BinaryFormatBuilder builder = new BinaryFormatBuilder();
MessageDictionary messageDictionary = XD.MessageDictionary;
Message12Dictionary message12Dictionary = XD.Message12Dictionary;
AddressingDictionary addressingDictionary = XD.AddressingDictionary;
Addressing10Dictionary addressing10Dictionary = XD.Addressing10Dictionary;
char messagePrefix = MessageStrings.Prefix[0];
char addressingPrefix = AddressingStrings.Prefix[0];
// <s:Envelope xmlns:s="soap-ns" xmlns="addressing-ns">
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Envelope.Key));
builder.AppendDictionaryXmlnsAttribute(messagePrefix, builder.GetStaticKey(message12Dictionary.Namespace.Key));
builder.AppendDictionaryXmlnsAttribute(addressingPrefix, builder.GetStaticKey(addressing10Dictionary.Namespace.Key));
// <s:Header>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Header.Key));
// <a:Action>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.Action.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement();
s_commonFragment = builder.ToByteArray();
// <a:MessageID>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.MessageId.Key));
builder.AppendUniqueIDWithEndElement();
s_requestFragment1 = builder.ToByteArray();
// <a:ReplyTo><a:Address>static-anonymous-key</a:Address></a:ReplyTo>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.ReplyTo.Key));
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.Address.Key));
builder.AppendDictionaryTextWithEndElement(builder.GetStaticKey(addressing10Dictionary.Anonymous.Key));
builder.AppendEndElement();
// <a:To>session-to-key</a:To>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.To.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement(builder.GetSessionKey(ToValueSessionKey));
// </s:Header>
builder.AppendEndElement();
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
s_requestFragment2 = builder.ToByteArray();
// <a:RelatesTo>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.RelatesTo.Key));
builder.AppendUniqueIDWithEndElement();
s_responseFragment1 = builder.ToByteArray();
// <a:To>static-anonymous-key</a:To>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.To.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement(builder.GetStaticKey(addressing10Dictionary.Anonymous.Key));
// </s:Header>
builder.AppendEndElement();
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
s_responseFragment2 = builder.ToByteArray();
// <s:Envelope xmlns:s="soap-ns" xmlns="addressing-ns">
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Envelope.Key));
builder.AppendDictionaryXmlnsAttribute(messagePrefix, builder.GetStaticKey(message12Dictionary.Namespace.Key));
builder.AppendDictionaryXmlnsAttribute(addressingPrefix, builder.GetStaticKey(addressing10Dictionary.Namespace.Key));
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
s_bodyFragment = builder.ToByteArray();
}
public MessagePatterns(IXmlDictionary dictionary, XmlBinaryReaderSession readerSession, MessageVersion messageVersion)
{
_dictionary = dictionary;
_readerSession = readerSession;
_messageVersion = messageVersion;
}
public Message TryCreateMessage(byte[] buffer, int offset, int size, BufferManager bufferManager, BufferedMessageData messageData)
{
RelatesToHeader relatesToHeader;
MessageIDHeader messageIDHeader;
XmlDictionaryString toString;
int currentOffset = offset;
int remainingSize = size;
int bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_commonFragment);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchKey(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int actionOffset = currentOffset;
int actionSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
int totalBytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_requestFragment1);
if (bytesMatched != 0)
{
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchUniqueID(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int messageIDOffset = currentOffset;
int messageIDSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_requestFragment2);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
if (BinaryFormatParser.MatchAttributeNode(buffer, currentOffset, remainingSize))
{
return null;
}
UniqueId messageId = BinaryFormatParser.ParseUniqueID(buffer, messageIDOffset, messageIDSize);
messageIDHeader = MessageIDHeader.Create(messageId, _messageVersion.Addressing);
relatesToHeader = null;
if (!_readerSession.TryLookup(ToValueSessionKey, out toString))
{
return null;
}
totalBytesMatched = s_requestFragment1.Length + messageIDSize + s_requestFragment2.Length;
}
else
{
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_responseFragment1);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchUniqueID(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int messageIDOffset = currentOffset;
int messageIDSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, s_responseFragment2);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
if (BinaryFormatParser.MatchAttributeNode(buffer, currentOffset, remainingSize))
{
return null;
}
UniqueId messageId = BinaryFormatParser.ParseUniqueID(buffer, messageIDOffset, messageIDSize);
relatesToHeader = RelatesToHeader.Create(messageId, _messageVersion.Addressing);
messageIDHeader = null;
toString = XD.Addressing10Dictionary.Anonymous;
totalBytesMatched = s_responseFragment1.Length + messageIDSize + s_responseFragment2.Length;
}
totalBytesMatched += s_commonFragment.Length + actionSize;
int actionKey = BinaryFormatParser.ParseKey(buffer, actionOffset, actionSize);
XmlDictionaryString actionString;
if (!TryLookupKey(actionKey, out actionString))
{
return null;
}
ActionHeader actionHeader = ActionHeader.Create(actionString, _messageVersion.Addressing);
if (_toHeader == null)
{
_toHeader = ToHeader.Create(new Uri(toString.Value), _messageVersion.Addressing);
}
int abandonedSize = totalBytesMatched - s_bodyFragment.Length;
offset += abandonedSize;
size -= abandonedSize;
Buffer.BlockCopy(s_bodyFragment, 0, buffer, offset, s_bodyFragment.Length);
messageData.Open(new ArraySegment<byte>(buffer, offset, size), bufferManager);
PatternMessage patternMessage = new PatternMessage(messageData, _messageVersion);
MessageHeaders headers = patternMessage.Headers;
headers.AddActionHeader(actionHeader);
if (messageIDHeader != null)
{
headers.AddMessageIDHeader(messageIDHeader);
headers.AddReplyToHeader(ReplyToHeader.AnonymousReplyTo10);
}
else
{
headers.AddRelatesToHeader(relatesToHeader);
}
headers.AddToHeader(_toHeader);
return patternMessage;
}
private bool TryLookupKey(int key, out XmlDictionaryString result)
{
if (BinaryFormatParser.IsSessionKey(key))
{
return _readerSession.TryLookup(BinaryFormatParser.GetSessionKey(key), out result);
}
else
{
return _dictionary.TryLookup(BinaryFormatParser.GetStaticKey(key), out result);
}
}
internal sealed class PatternMessage : ReceivedMessage
{
private IBufferedMessageData _messageData;
private MessageHeaders _headers;
private RecycledMessageState _recycledMessageState;
private MessageProperties _properties;
private XmlDictionaryReader _reader;
public PatternMessage(IBufferedMessageData messageData, MessageVersion messageVersion)
{
_messageData = messageData;
_recycledMessageState = messageData.TakeMessageState();
if (_recycledMessageState == null)
{
_recycledMessageState = new RecycledMessageState();
}
_properties = _recycledMessageState.TakeProperties();
if (_properties == null)
{
_properties = new MessageProperties();
}
_headers = _recycledMessageState.TakeHeaders();
if (_headers == null)
{
_headers = new MessageHeaders(messageVersion);
}
else
{
_headers.Init(messageVersion);
}
XmlDictionaryReader reader = messageData.GetMessageReader();
reader.ReadStartElement();
VerifyStartBody(reader, messageVersion.Envelope);
ReadStartBody(reader);
_reader = reader;
}
public PatternMessage(IBufferedMessageData messageData, MessageVersion messageVersion,
KeyValuePair<string, object>[] properties, MessageHeaders headers)
{
_messageData = messageData;
_messageData.Open();
_recycledMessageState = _messageData.TakeMessageState();
if (_recycledMessageState == null)
{
_recycledMessageState = new RecycledMessageState();
}
_properties = _recycledMessageState.TakeProperties();
if (_properties == null)
{
_properties = new MessageProperties();
}
if (properties != null)
{
_properties.CopyProperties(properties);
}
_headers = _recycledMessageState.TakeHeaders();
if (_headers == null)
{
_headers = new MessageHeaders(messageVersion);
}
if (headers != null)
{
_headers.CopyHeadersFrom(headers);
}
XmlDictionaryReader reader = messageData.GetMessageReader();
reader.ReadStartElement();
VerifyStartBody(reader, messageVersion.Envelope);
ReadStartBody(reader);
_reader = reader;
}
public override MessageHeaders Headers
{
get
{
if (IsDisposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return _headers;
}
}
public override MessageProperties Properties
{
get
{
if (IsDisposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return _properties;
}
}
public override MessageVersion Version
{
get
{
if (IsDisposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return _headers.MessageVersion;
}
}
internal override RecycledMessageState RecycledMessageState
{
get { return _recycledMessageState; }
}
private XmlDictionaryReader GetBufferedReaderAtBody()
{
XmlDictionaryReader reader = _messageData.GetMessageReader();
reader.ReadStartElement();
reader.ReadStartElement();
return reader;
}
protected override void OnBodyToString(XmlDictionaryWriter writer)
{
using (XmlDictionaryReader reader = GetBufferedReaderAtBody())
{
while (reader.NodeType != XmlNodeType.EndElement)
{
writer.WriteNode(reader, false);
}
}
}
protected override void OnClose()
{
Exception ex = null;
try
{
base.OnClose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ex = e;
}
try
{
_properties.Dispose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
try
{
if (_reader != null)
{
_reader.Dispose();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
try
{
_recycledMessageState.ReturnHeaders(_headers);
_recycledMessageState.ReturnProperties(_properties);
_messageData.ReturnMessageState(_recycledMessageState);
_recycledMessageState = null;
_messageData.Close();
_messageData = null;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
if (ex != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
}
}
protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count];
((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0);
_messageData.EnableMultipleUsers();
return new PatternMessageBuffer(_messageData, Version, properties, _headers);
}
protected override XmlDictionaryReader OnGetReaderAtBodyContents()
{
XmlDictionaryReader reader = _reader;
_reader = null;
return reader;
}
protected override string OnGetBodyAttribute(string localName, string ns)
{
return null;
}
}
internal class PatternMessageBuffer : MessageBuffer
{
private bool _closed;
private MessageHeaders _headers;
private IBufferedMessageData _messageDataAtBody;
private MessageVersion _messageVersion;
private KeyValuePair<string, object>[] _properties;
private RecycledMessageState _recycledMessageState;
public PatternMessageBuffer(IBufferedMessageData messageDataAtBody, MessageVersion messageVersion,
KeyValuePair<string, object>[] properties, MessageHeaders headers)
{
_messageDataAtBody = messageDataAtBody;
_messageDataAtBody.Open();
_recycledMessageState = _messageDataAtBody.TakeMessageState();
if (_recycledMessageState == null)
{
_recycledMessageState = new RecycledMessageState();
}
_headers = _recycledMessageState.TakeHeaders();
if (_headers == null)
{
_headers = new MessageHeaders(messageVersion);
}
_headers.CopyHeadersFrom(headers);
_properties = properties;
_messageVersion = messageVersion;
}
public override int BufferSize
{
get
{
lock (ThisLock)
{
if (_closed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException());
}
return _messageDataAtBody.Buffer.Count;
}
}
}
private object ThisLock { get; } = new object();
public override void Close()
{
lock (ThisLock)
{
if (!_closed)
{
_closed = true;
_recycledMessageState.ReturnHeaders(_headers);
_messageDataAtBody.ReturnMessageState(_recycledMessageState);
_messageDataAtBody.Close();
_recycledMessageState = null;
_messageDataAtBody = null;
_properties = null;
_messageVersion = null;
_headers = null;
}
}
}
public override Message CreateMessage()
{
lock (ThisLock)
{
if (_closed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException());
}
return new PatternMessage(_messageDataAtBody, _messageVersion, _properties,
_headers);
}
}
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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.IO;
using System.Threading;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Net;
using Android.OS;
using Android.Provider;
using Android.Speech;
using Android.Support.V4.Content;
using Android.Widget;
using Newtonsoft.Json;
using Sensus;
using Xamarin;
using Sensus.Probes.Location;
using Sensus.Probes;
using Sensus.Probes.Movement;
using System.Linq;
using Android.Graphics;
using Android.Media;
using Android.Bluetooth;
using Android.Hardware;
using Sensus.Android.Probes.Context;
using Sensus.Android;
using System.Threading.Tasks;
namespace Sensus.Android
{
public class AndroidSensusServiceHelper : SensusServiceHelper, IAndroidSensusServiceHelper
{
private AndroidSensusService _service;
private string _deviceId;
private AndroidMainActivity _focusedMainActivity;
private readonly object _focusedMainActivityLocker = new object();
private PowerManager.WakeLock _wakeLock;
private int _wakeLockAcquisitionCount;
private List<Action<AndroidMainActivity>> _actionsToRunUsingMainActivity;
private bool _userDeniedBluetoothEnable;
public override string DeviceId
{
get { return _deviceId; }
}
public override bool WiFiConnected
{
get
{
ConnectivityManager connectivityManager = _service.GetSystemService(global::Android.Content.Context.ConnectivityService) as ConnectivityManager;
if (connectivityManager == null)
{
Logger.Log("No connectivity manager available for WiFi check.", LoggingLevel.Normal, GetType());
return false;
}
// https://github.com/predictive-technology-laboratory/sensus/wiki/Backwards-Compatibility
#if __ANDROID_21__
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
return connectivityManager.GetAllNetworks().Select(network => connectivityManager.GetNetworkInfo(network)).Any(networkInfo => networkInfo != null && networkInfo.Type == ConnectivityType.Wifi && networkInfo.IsConnected); // API level 21
else
#endif
{
// ignore deprecation warning
#pragma warning disable 618
return connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).IsConnected;
#pragma warning restore 618
}
}
}
public override bool IsCharging
{
get
{
IntentFilter filter = new IntentFilter(Intent.ActionBatteryChanged);
BatteryStatus status = (BatteryStatus)_service.RegisterReceiver(null, filter).GetIntExtra(BatteryManager.ExtraStatus, -1);
return status == BatteryStatus.Charging || status == BatteryStatus.Full;
}
}
public override string OperatingSystem
{
get
{
return "Android " + Build.VERSION.SdkInt;
}
}
protected override bool IsOnMainThread
{
get
{
// we should always have a service. if we do not, assume the worst -- that we're on the main thread. this will hopefully
// produce an error report back at xamarin insights.
if (_service == null)
return true;
// if we have a service, compare the current thread's looper to the main thread's looper
else
return Looper.MyLooper() == _service.MainLooper;
}
}
public override string Version
{
get
{
return _service?.PackageManager.GetPackageInfo(_service.PackageName, PackageInfoFlags.Activities).VersionName ?? null;
}
}
[JsonIgnore]
public int WakeLockAcquisitionCount
{
get { return _wakeLockAcquisitionCount; }
}
public bool UserDeniedBluetoothEnable
{
get
{
return _userDeniedBluetoothEnable;
}
set
{
_userDeniedBluetoothEnable = value;
}
}
public AndroidSensusServiceHelper()
{
_actionsToRunUsingMainActivity = new List<Action<AndroidMainActivity>>();
_userDeniedBluetoothEnable = false;
}
public void SetService(AndroidSensusService service)
{
_service = service;
if (_service == null)
{
if (_wakeLock != null)
{
_wakeLock.Dispose();
_wakeLock = null;
}
}
else
{
_wakeLock = (_service.GetSystemService(global::Android.Content.Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
_wakeLockAcquisitionCount = 0;
_deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);
}
}
#region main activity
/// <summary>
/// Runs an action using main activity, optionally bringing the main activity into focus if it is not already focused.
/// </summary>
/// <param name="action">Action to run.</param>
/// <param name="startMainActivityIfNotFocused">Whether or not to start the main activity if it is not currently focused.</param>
/// <param name="holdActionIfNoActivity">If the main activity is not focused and we're not starting a new one to refocus it, whether
/// or not to hold the action for later when the activity is refocused.</param>
public void RunActionUsingMainActivityAsync(Action<AndroidMainActivity> action, bool startMainActivityIfNotFocused, bool holdActionIfNoActivity)
{
// this must be done asynchronously because it blocks waiting for the activity to start. calling this method from the UI would create deadlocks.
new Thread(() =>
{
lock (_focusedMainActivityLocker)
{
// run actions now only if the main activity is focused. this is a stronger requirement than merely started/resumed since it
// implies that the user interface is up. this is important because if certain actions (e.g., speech recognition) are run
// after the activity is resumed but before the window is up, the appearance of the activity's window can hide/cancel the
// action's window.
if (_focusedMainActivity == null)
{
if (startMainActivityIfNotFocused)
{
// we'll run the action when the activity is focused
lock (_actionsToRunUsingMainActivity)
_actionsToRunUsingMainActivity.Add(action);
Logger.Log("Starting main activity to run action.", LoggingLevel.Normal, GetType());
// start the activity. when it starts, it will call back to SetFocusedMainActivity indicating readiness. once
// this happens, we'll be ready to run the action that was just passed in as well as any others that need to be run.
Intent intent = new Intent(_service, typeof(AndroidMainActivity));
intent.AddFlags(ActivityFlags.FromBackground | ActivityFlags.NewTask);
_service.StartActivity(intent);
}
else if (holdActionIfNoActivity)
{
// we'll run the action the next time the activity is focused
lock (_actionsToRunUsingMainActivity)
_actionsToRunUsingMainActivity.Add(action);
}
}
else
{
// we'll run the action now
lock (_actionsToRunUsingMainActivity)
_actionsToRunUsingMainActivity.Add(action);
RunActionsUsingMainActivity();
}
}
}).Start();
}
public void SetFocusedMainActivity(AndroidMainActivity focusedMainActivity)
{
lock (_focusedMainActivityLocker)
{
_focusedMainActivity = focusedMainActivity;
if (_focusedMainActivity == null)
Logger.Log("Main activity not focused.", LoggingLevel.Normal, GetType());
else
{
Logger.Log("Main activity focused.", LoggingLevel.Normal, GetType());
RunActionsUsingMainActivity();
}
}
}
private void RunActionsUsingMainActivity()
{
lock (_focusedMainActivityLocker)
{
lock (_actionsToRunUsingMainActivity)
{
Logger.Log("Running " + _actionsToRunUsingMainActivity.Count + " actions using main activity.", LoggingLevel.Debug, GetType());
foreach (Action<AndroidMainActivity> action in _actionsToRunUsingMainActivity)
action(_focusedMainActivity);
_actionsToRunUsingMainActivity.Clear();
}
}
}
#endregion
#region miscellaneous platform-specific functions
public override void PromptForAndReadTextFileAsync(string promptTitle, Action<string> callback)
{
new Thread(() =>
{
try
{
Intent intent = new Intent(Intent.ActionGetContent);
intent.SetType("*/*");
intent.AddCategory(Intent.CategoryOpenable);
RunActionUsingMainActivityAsync(mainActivity =>
{
mainActivity.GetActivityResultAsync(intent, AndroidActivityResultRequestCode.PromptForFile, result =>
{
if (result != null && result.Item1 == Result.Ok)
{
try
{
using (StreamReader file = new StreamReader(_service.ContentResolver.OpenInputStream(result.Item2.Data)))
{
callback(file.ReadToEnd());
}
}
catch (Exception ex)
{
FlashNotificationAsync("Error reading text file: " + ex.Message);
}
}
});
}, true, false);
}
catch (ActivityNotFoundException)
{
FlashNotificationAsync("Please install a file manager from the Apps store.");
}
catch (Exception ex)
{
FlashNotificationAsync("Something went wrong while prompting you for a file to read: " + ex.Message);
}
}).Start();
}
public override void ShareFileAsync(string path, string subject, string mimeType)
{
new Thread(() =>
{
try
{
Intent intent = new Intent(Intent.ActionSend);
intent.SetType(mimeType);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
if (!string.IsNullOrWhiteSpace(subject))
intent.PutExtra(Intent.ExtraSubject, subject);
Java.IO.File file = new Java.IO.File(path);
global::Android.Net.Uri uri = FileProvider.GetUriForFile(_service, "edu.virginia.sie.ptl.sensus.fileprovider", file);
intent.PutExtra(Intent.ExtraStream, uri);
// run from main activity to get a smoother transition back to sensus
RunActionUsingMainActivityAsync(mainActivity =>
{
mainActivity.StartActivity(intent);
}, true, false);
}
catch (Exception ex)
{
Logger.Log("Failed to start intent to share file \"" + path + "\": " + ex.Message, LoggingLevel.Normal, GetType());
}
}).Start();
}
public override void SendEmailAsync(string toAddress, string subject, string message)
{
RunActionUsingMainActivityAsync(mainActivity =>
{
Intent emailIntent = new Intent(Intent.ActionSend);
emailIntent.PutExtra(Intent.ExtraEmail, new string[] { toAddress });
emailIntent.PutExtra(Intent.ExtraSubject, subject);
emailIntent.PutExtra(Intent.ExtraText, message);
emailIntent.SetType("text/plain");
mainActivity.StartActivity(emailIntent);
}, true, false);
}
public override Task TextToSpeechAsync(string text)
{
return Task.Run(async () =>
{
AndroidTextToSpeech textToSpeech = new AndroidTextToSpeech(_service);
await textToSpeech.SpeakAsync(text);
textToSpeech.Dispose();
});
}
public override Task<string> RunVoicePromptAsync(string prompt, Action postDisplayCallback)
{
return Task.Run(() =>
{
string input = null;
ManualResetEvent dialogDismissWait = new ManualResetEvent(false);
RunActionUsingMainActivityAsync(mainActivity =>
{
mainActivity.RunOnUiThread(() =>
{
#region set up dialog
TextView promptView = new TextView(mainActivity) { Text = prompt, TextSize = 20 };
EditText inputEdit = new EditText(mainActivity) { TextSize = 20 };
LinearLayout scrollLayout = new LinearLayout(mainActivity) { Orientation = global::Android.Widget.Orientation.Vertical };
scrollLayout.AddView(promptView);
scrollLayout.AddView(inputEdit);
ScrollView scrollView = new ScrollView(mainActivity);
scrollView.AddView(scrollLayout);
AlertDialog dialog = new AlertDialog.Builder(mainActivity)
.SetTitle("Sensus is requesting input...")
.SetView(scrollView)
.SetPositiveButton("OK", (o, e) =>
{
input = inputEdit.Text;
})
.SetNegativeButton("Cancel", (o, e) =>
{
})
.Create();
dialog.DismissEvent += (o, e) =>
{
dialogDismissWait.Set();
};
ManualResetEvent dialogShowWait = new ManualResetEvent(false);
dialog.ShowEvent += (o, e) =>
{
dialogShowWait.Set();
if (postDisplayCallback != null)
postDisplayCallback();
};
// dismiss the keyguard when dialog appears
dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.DismissKeyguard);
dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.ShowWhenLocked);
dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.TurnScreenOn);
dialog.Window.SetSoftInputMode(global::Android.Views.SoftInput.AdjustResize | global::Android.Views.SoftInput.StateAlwaysHidden);
// dim whatever is behind the dialog
dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.DimBehind);
dialog.Window.Attributes.DimAmount = 0.75f;
dialog.Show();
#endregion
#region voice recognizer
Task.Run(() =>
{
// wait for the dialog to be shown so it doesn't hide our speech recognizer activity
dialogShowWait.WaitOne();
// there's a slight race condition between the dialog showing and speech recognition showing. pause here to prevent the dialog from hiding the speech recognizer.
Thread.Sleep(1000);
Intent intent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
intent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
intent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500);
intent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500);
intent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000);
intent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
intent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);
intent.PutExtra(RecognizerIntent.ExtraPrompt, prompt);
mainActivity.GetActivityResultAsync(intent, AndroidActivityResultRequestCode.RecognizeSpeech, result =>
{
if (result != null && result.Item1 == Result.Ok)
{
IList<string> matches = result.Item2.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
if (matches != null && matches.Count > 0)
mainActivity.RunOnUiThread(() =>
{
inputEdit.Text = matches[0];
});
}
});
});
#endregion
});
}, true, false);
dialogDismissWait.WaitOne();
return input;
});
}
#endregion
protected override void ProtectedFlashNotificationAsync(string message, bool flashLaterIfNotVisible, TimeSpan duration, Action callback)
{
Task.Run(() =>
{
RunActionUsingMainActivityAsync(mainActivity =>
{
mainActivity.RunOnUiThread(() =>
{
int shortToasts = (int)Math.Ceiling(duration.TotalSeconds / 2); // each short toast is 2 seconds.
for (int i = 0; i < shortToasts; ++i)
Toast.MakeText(mainActivity, message, ToastLength.Short).Show();
callback?.Invoke();
});
}, false, flashLaterIfNotVisible);
});
}
public override bool EnableProbeWhenEnablingAll(Probe probe)
{
// listening for locations doesn't work very well in android, since it conflicts with polling and uses more power. don't enable probes that need location listening by default.
return !(probe is ListeningLocationProbe) &&
!(probe is ListeningSpeedProbe) &&
!(probe is ListeningPointsOfInterestProximityProbe);
}
public override Xamarin.Forms.ImageSource GetQrCodeImageSource(string contents)
{
return null;
}
/// <summary>
/// Enables the Bluetooth adapter, or prompts the user to do so if we cannot do this programmatically. Must not be called from the UI thread.
/// </summary>
/// <returns><c>true</c>, if Bluetooth was enabled, <c>false</c> otherwise.</returns>
/// <param name="lowEnergy">If set to <c>true</c> low energy.</param>
/// <param name="rationale">Rationale.</param>
public override bool EnableBluetooth(bool lowEnergy, string rationale)
{
base.EnableBluetooth(lowEnergy, rationale);
bool enabled = false;
// ensure that the device has the required feature
if (!_service.PackageManager.HasSystemFeature(lowEnergy ? PackageManager.FeatureBluetoothLe : PackageManager.FeatureBluetooth))
{
FlashNotificationAsync("This device does not have Bluetooth " + (lowEnergy ? "Low Energy" : "") + ".", false);
return enabled;
}
ManualResetEvent enableWait = new ManualResetEvent(false);
// check whether bluetooth is enabled
BluetoothManager bluetoothManager = _service.GetSystemService(global::Android.Content.Context.BluetoothService) as BluetoothManager;
BluetoothAdapter bluetoothAdapter = bluetoothManager.Adapter;
if (bluetoothAdapter == null || !bluetoothAdapter.IsEnabled)
{
// if it's not and if the user has previously denied bluetooth, quit now.
if (_userDeniedBluetoothEnable)
enableWait.Set();
else
{
// bring up sensus so we can request bluetooth enable
RunActionUsingMainActivityAsync(mainActivity =>
{
mainActivity.RunOnUiThread(async () =>
{
try
{
// explain why we need bluetooth
await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Bluetooth", "Sensus will now prompt you to enable Bluetooth. " + rationale, "OK");
// prompt for permission
Intent enableIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
mainActivity.GetActivityResultAsync(enableIntent, AndroidActivityResultRequestCode.EnableBluetooth, resultIntent =>
{
if (resultIntent.Item1 == Result.Canceled)
_userDeniedBluetoothEnable = true;
else if (resultIntent.Item1 == Result.Ok)
enabled = true;
enableWait.Set();
});
}
catch (Exception ex)
{
Logger.Log("Failed to start Bluetooth: " + ex.Message, LoggingLevel.Normal, GetType());
enableWait.Set();
}
});
}, true, false);
}
}
else
{
enabled = true;
enableWait.Set();
}
enableWait.WaitOne();
if (enabled)
_userDeniedBluetoothEnable = false;
return enabled;
}
public override bool DisableBluetooth(bool reenable, bool lowEnergy = true, string rationale = null)
{
base.DisableBluetooth(reenable, lowEnergy, rationale);
// check whether bluetooth is enabled
BluetoothManager bluetoothManager = _service.GetSystemService(global::Android.Content.Context.BluetoothService) as BluetoothManager;
BluetoothAdapter bluetoothAdapter = bluetoothManager.Adapter;
if (bluetoothAdapter != null && bluetoothAdapter.IsEnabled)
{
ManualResetEvent disableWait = new ManualResetEvent(false);
ManualResetEvent enableWait = new ManualResetEvent(false);
EventHandler<global::Android.Bluetooth.State> StateChangedHandler = (sender, newState) =>
{
if (newState == global::Android.Bluetooth.State.Off)
disableWait.Set();
else if (newState == global::Android.Bluetooth.State.On)
enableWait.Set();
};
AndroidBluetoothBroadcastReceiver.STATE_CHANGED += StateChangedHandler;
try
{
if (!bluetoothAdapter.Disable())
disableWait.Set();
}
catch (Exception)
{
disableWait.Set();
}
disableWait.WaitOne(5000);
if (reenable)
{
try
{
if (!bluetoothAdapter.Enable())
enableWait.Set();
}
catch (Exception)
{
enableWait.Set();
}
enableWait.WaitOne(5000);
}
AndroidBluetoothBroadcastReceiver.STATE_CHANGED -= StateChangedHandler;
}
bool isEnabled = bluetoothAdapter?.IsEnabled ?? false;
// dispatch an intent to reenable bluetooth, which will require user interaction
if (reenable && !isEnabled)
return EnableBluetooth(lowEnergy, rationale);
else
return isEnabled;
}
#region device awake / sleep
public override void KeepDeviceAwake()
{
if (_wakeLock != null)
{
lock (_wakeLock)
{
_wakeLock.Acquire();
Logger.Log("Wake lock acquisition count: " + ++_wakeLockAcquisitionCount, LoggingLevel.Verbose, GetType());
}
}
}
public override void LetDeviceSleep()
{
if (_wakeLock != null)
{
lock (_wakeLock)
{
_wakeLock.Release();
Logger.Log("Wake lock acquisition count: " + --_wakeLockAcquisitionCount, LoggingLevel.Verbose, GetType());
}
}
}
public override void BringToForeground()
{
ManualResetEvent foregroundWait = new ManualResetEvent(false);
RunActionUsingMainActivityAsync(mainActivity =>
{
foregroundWait.Set();
}, true, false);
foregroundWait.WaitOne();
}
#endregion
public void StopAndroidSensusService()
{
_service.Stop();
}
public SensorManager GetSensorManager()
{
return _service.GetSystemService(global::Android.Content.Context.SensorService) as SensorManager;
}
}
}
| |
using System;
using System.Security;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using TestLibrary;
namespace PInvokeTests
{
#region structure def
[SecuritySafeCritical]
[StructLayout(LayoutKind.Sequential)]
public struct Sstr
{
public int a;
public bool b;
public string str;
public Sstr(int _a, bool _b, string _str)
{
a = _a;
b = _b;
str = String.Concat(_str, "");
}
}
//Using this structure for pass by value scenario
//because we don't support returning a structure
//containing a non-blittable type like string.
[SecuritySafeCritical]
[StructLayout(LayoutKind.Sequential)]
public struct Sstr_simple
{
public int a;
public bool b;
public double c;
public Sstr_simple(int _a, bool _b, double _c)
{
a = _a;
b = _b;
c = _c;
}
}
[SecuritySafeCritical]
[StructLayout(LayoutKind.Explicit)]
public struct ExplStruct
{
[FieldOffset(0)]
public DialogResult type;
[FieldOffset(8)]
public int i;
[FieldOffset(8)]
public bool b;
[FieldOffset(8)]
public double c;
public ExplStruct(DialogResult t, int num)
{
type = t;
b = false;
c = num;
i = num;
}
public ExplStruct(DialogResult t, double dnum)
{
type = t;
b = false;
i = 0;
c = dnum;
}
public ExplStruct(DialogResult t, bool bnum)
{
type = t;
i = 0;
c = 0;
b = bnum;
}
}
public enum DialogResult
{
None = 0,
OK = 1,
Cancel = 2
}
#endregion
class StructureTests
{
#region direct Pinvoke declarartions
#region cdecl
//Simple struct - sequential layout by ref
[DllImport("SimpleStructNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CdeclSimpleStructByRef(ref Sstr p);
[DllImport("SimpleStructNative", EntryPoint = "GetFptr")]
[return: MarshalAs(UnmanagedType.FunctionPtr)]
public static extern CdeclSimpleStructByRefDelegate GetFptrCdeclSimpleStructByRef(int i);
//Simple struct - sequential layout by value
[DllImport("SimpleStructNative", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr CdeclSimpleStruct(Sstr_simple p, ref bool retval);
[DllImport("SimpleStructNative", EntryPoint = "GetFptr")]
[return: MarshalAs(UnmanagedType.FunctionPtr)]
public static extern CdeclSimpleStructDelegate GetFptrCdeclSimpleStruct(int i);
//Simple struct - explicit layout by value
[DllImport("SimpleStructNative", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr CdeclSimpleExplStruct(ExplStruct p, ref bool retval);
[DllImport("SimpleStructNative", EntryPoint = "GetFptr")]
[return: MarshalAs(UnmanagedType.FunctionPtr)]
public static extern CdeclSimpleExplStructDelegate GetFptrCdeclSimpleExplStruct(int i);
//Simple struct - explicit layout by ref
[DllImport("SimpleStructNative", EntryPoint = "GetFptr")]
[return: MarshalAs(UnmanagedType.FunctionPtr)]
public static extern CdeclSimpleExplStructByRefDelegate GetFptrCdeclSimpleExplStructByRef(int i);
[DllImport("SimpleStructNative", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CdeclSimpleExplStructByRef(ref ExplStruct p);
#endregion
#endregion
#region delegate pinvoke
//Simple struct - sequential layout by value
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr CdeclSimpleStructDelegate(Sstr_simple p, ref bool retval);
//Simple struct - explicit layout by value
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr CdeclSimpleExplStructDelegate(ExplStruct p, ref bool retval);
//Simple struct - sequential layout by ref
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool CdeclSimpleStructByRefDelegate(ref Sstr p);
//Simple struct - explicit layout by ref
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool CdeclSimpleExplStructByRefDelegate(ref ExplStruct p);
#endregion
#region reverse pinvoke
#endregion
#region public methods related to pinvoke declrarations
//Simple struct - sequential layout by ref
[System.Security.SecuritySafeCritical]
public static bool DoCdeclSimpleStructByRef(ref Sstr p)
{
return CdeclSimpleStructByRef(ref p);
}
//Simple struct - explicit by ref
[System.Security.SecuritySafeCritical]
public static bool DoCdeclSimpleExplStructByRef(ref ExplStruct p)
{
return CdeclSimpleExplStructByRef(ref p);
}
//Simple struct - sequential layout by value
[System.Security.SecuritySafeCritical]
public static Sstr_simple DoCdeclSimpleStruct(Sstr_simple p, ref bool retval)
{
IntPtr st = CdeclSimpleStruct(p, ref retval);
Sstr_simple simple = Marshal.PtrToStructure<Sstr_simple>(st);
return simple;
}
//Simple Struct - Explicit layout by value
[System.Security.SecuritySafeCritical]
public static ExplStruct DoCdeclSimpleExplStruct(ExplStruct p, ref bool retval)
{
IntPtr st = CdeclSimpleExplStruct(p, ref retval);
ExplStruct simple = Marshal.PtrToStructure<ExplStruct>(st);
return simple;
}
#endregion
#region test methods
//Simple sequential struct by reference testcase
[System.Security.SecuritySafeCritical]
public static bool PosTest1()
{
string s = "before";
string changedValue = "after";
bool retval = true;
Sstr p = new Sstr(0, false, s);
TestFramework.BeginScenario("Test #1 (Roundtrip of a simple structre by reference. Verify that values updated on unmanaged side reflect on managed side)");
//Direct pinvoke
//cdecl calling convention.
try
{
TestFramework.LogInformation(" Case 2: Direct p/invoke cdecl calling convention");
retval = DoCdeclSimpleStructByRef(ref p);
if ((p.a != 100) || (!p.b) || (!p.str.Equals(changedValue)))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->a=" + 100 + "\nSimpleStruct->b=TRUE\n" + "SimpleStruct->str=after\n");
Console.WriteLine("\nActual values:\n SimpleStruct->a=" + p.a + "\nSimpleStruct->b=" + p.b + "\nSimpleStruct->str=" + p.str + "\n");
TestFramework.LogError("03", "PInvokeTests->PosTest1 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("04", "Unexpected exception: " + e.ToString());
retval = false;
}
//Delegate pinvoke
//cdecl
try
{
TestFramework.LogInformation(" Case 4: Delegate p/invoke - cdecl calling convention");
CdeclSimpleStructByRefDelegate std = GetFptrCdeclSimpleStructByRef(14);
retval = std(ref p);
if ((p.a != 100) || (!p.b) || (!p.str.Equals(changedValue)))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->a=" + 100 + "\nSimpleStruct->b=TRUE\n" + "SimpleStruct->str=after\n");
Console.WriteLine("\nActual values:\n SimpleStruct->a=" + p.a + "\nSimpleStruct->b=" + p.b + "\nSimpleStruct->str=" + p.str + "\n");
TestFramework.LogError("01", "PInvokeTests->PosTest1 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("02", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
//Simple Sequential struct by value
[System.Security.SecuritySafeCritical]
public static bool PosTest2()
{
string s = "Before";
bool retval = true;
double d = 3.142;
Sstr p = new Sstr(100, false, s);
TestFramework.BeginScenario("\n\nTest #2 (Roundtrip of a simple structre by value. Verify that values updated on unmanaged side reflect on managed side)");
//direct pinvoke
// //cdecl calling convention
try
{
TestFramework.LogInformation(" Case 2: Direct p/invoke cdecl calling convention");
Sstr_simple simple = new Sstr_simple(100, false, d);
simple = DoCdeclSimpleStruct(simple, ref retval);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
return false;
}
if ((simple.a != 101) || (!simple.b) || (simple.c != 10.11))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->a=101\nSimpleStruct->b=TRUE\nSimpleStruct->c=10.11\n");
Console.WriteLine("\nActual values:\n SimpleStruct->a=" + simple.a + "\nSimpleStruct->b=" + simple.b + "\nSimpleStruct->c=" + simple.c + "\n");
TestFramework.LogError("02", "PInvokeTests->PosTest2 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
retval = false;
}
// //delegate pinvoke
// //cdecl calling convention
try
{
TestFramework.LogInformation(" Case 4: Delegate p/invoke cdecl calling convention");
Sstr_simple simple = new Sstr_simple(100, false, d);
CdeclSimpleStructDelegate std = GetFptrCdeclSimpleStruct(16);
IntPtr st = std(simple, ref retval);
simple = Marshal.PtrToStructure<Sstr_simple>(st);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
return false;
}
if ((simple.a != 101) || (!simple.b) || (simple.c != 10.11))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->a=101\nSimpleStruct->b=TRUE\nSimpleStruct->c=10.11\n");
Console.WriteLine("\nActual values:\n SimpleStruct->a=" + simple.a + "\nSimpleStruct->b=" + simple.b + "\nSimpleStruct->c=" + simple.c + "\n");
TestFramework.LogError("02", "PInvokeTests->PosTest2 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
//Simple struct explicit layout by reference.
[System.Security.SecuritySafeCritical]
public static bool PosTest3()
{
ExplStruct p;
bool retval = false;
TestFramework.BeginScenario("\n\nTest #3 (Roundtrip of a simple structre (explicit layout) by reference. Verify that values updated on unmanaged side reflect on managed side)");
//direct pinvoke
//cdecl
try
{
p = new ExplStruct(DialogResult.None, 10);
TestFramework.LogInformation(" Case 2: Direct p/invoke cdecl calling convention");
retval = DoCdeclSimpleExplStructByRef(ref p);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->PosTest3 : Unexpected error occured on unmanaged side");
return false;
}
if ((p.type != DialogResult.OK) || (!p.b))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->type=1\nSimpleStruct->b=TRUE\n");
Console.WriteLine("\nActual values:\n SimpleStruct->type=" + p.type + "\nSimpleStruct->b=" + p.b);
TestFramework.LogError("02", "PInvokeTests->PosTest3 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
retval = false;
}
//Delegate pinvoke --- cdecl
try
{
p = new ExplStruct(DialogResult.None, 10);
TestFramework.LogInformation(" Case 4: Delegate p/invoke cdecl calling convention");
CdeclSimpleExplStructByRefDelegate std = GetFptrCdeclSimpleExplStructByRef(18);
retval = std(ref p);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->PosTest3 : Unexpected error occured on unmanaged side");
return false;
}
if ((p.type != DialogResult.OK) || (!p.b))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->type=1\nSimpleStruct->b=TRUE\n");
Console.WriteLine("\nActual values:\n SimpleStruct->type=" + p.type + "\nSimpleStruct->b=" + p.b);
TestFramework.LogError("02", "PInvokeTests->PosTest3 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
//Simple struct explicit layout by value.
[System.Security.SecuritySafeCritical]
public static bool PosTest4()
{
ExplStruct p;
bool retval = false;
TestFramework.BeginScenario("\n\nTest #4 (Roundtrip of a simple structre (Explicit layout) by value. Verify that values updated on unmanaged side reflect on managed side)");
//direct pinvoke
//cdecl
try
{
p = new ExplStruct(DialogResult.OK, false);
TestFramework.LogInformation(" Case 2: Direct p/invoke cdecl calling convention");
p = DoCdeclSimpleExplStruct(p, ref retval);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
return false;
}
if ((p.type != DialogResult.Cancel) || (p.c != 3.142))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->a=2\nSimpleStruct->c=3.142\n");
Console.WriteLine("\nActual values:\n SimpleStruct->a=" + p.type + "\nSimpleStruct->c=" + p.c + "\n");
TestFramework.LogError("02", "PInvokeTests->PosTest4 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
retval = false;
}
//delegate pinvoke
//cdecl
try
{
p = new ExplStruct(DialogResult.OK, false);
TestFramework.LogInformation(" Case 4: Direct p/invoke cdecl calling convention");
CdeclSimpleExplStructDelegate std = GetFptrCdeclSimpleExplStruct(20);
IntPtr st = std(p, ref retval);
p = Marshal.PtrToStructure<ExplStruct>(st);
if (retval == false)
{
TestFramework.LogError("01", "PInvokeTests->PosTest2 : values of passed in structure not matched with expected once on unmanaged side.");
return false;
}
if ((p.type != DialogResult.Cancel) || (p.c != 3.142))
{
Console.WriteLine("\nExpected values:\n SimpleStruct->a=2\nSimpleStruct->c=3.142\n");
Console.WriteLine("\nActual values:\n SimpleStruct->a=" + p.type + "\nSimpleStruct->c=" + p.c + "\n");
TestFramework.LogError("02", "PInvokeTests->PosTest4 : Returned values are different from expected values");
retval = false;
}
}
catch (Exception e)
{
TestFramework.LogError("03", "Unexpected exception: " + e.ToString());
retval = false;
}
return retval;
}
#endregion
public static int Main(string[] argv)
{
bool retVal = true;
retVal = retVal && PosTest1();
retVal = retVal && PosTest2();
retVal = retVal && PosTest3();
// https://github.com/dotnet/coreclr/issues/4193
// retVal = retVal && PosTest4();
if (!retVal)
Console.WriteLine("FAIL");
else
Console.WriteLine("PASS");
return (retVal ? 100 : 101);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Logger.cs" company="">
//
// </copyright>
// <summary>
// The logger.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace UX.Testing.Core.Logging
{
using System;
using System.Diagnostics;
using NLog;
/// <summary>The logger.</summary>
public class Logger : ILogger
{
#region Fields
/// <summary>The nlogger.</summary>
private NLog.Logger nlogger;
/// <summary>The instance.</summary>
private static Logger instance;
#endregion
#region Constructors and Destructors
/// <summary>Initializes a new instance of the <see cref="Logger"/> class.</summary>
public Logger()
{
this.nlogger = LogManager.GetCurrentClassLogger();
}
#endregion
/// <summary>Gets the instance.</summary>
public static Logger Instance
{
get
{
if (instance == null)
{
instance = new Logger();
}
return instance;
}
}
#region Public Properties
/// <summary>Gets or sets Logger.</summary>
public NLog.Logger Nlogger
{
get
{
return this.nlogger;
}
set
{
this.nlogger = value;
}
}
#endregion
#region Public Methods and Operators
/// <summary>The GetMethodInfo method that gathers DeclaringType.Name and Method.Name.</summary>
private static string GetMethodInfo()
{
var method = new StackFrame(2, true).GetMethod();
var callingProgram = string.Format(
"{0}.{1}", method.DeclaringType.Name, method.Name);
return callingProgram;
}
/// <summary>The debug.</summary>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public void Debug(string message, params object[] parameters)
{
var callingProgram = GetMethodInfo();
var msg = string.Format("DEBUG {0}: {1}", callingProgram, message);
this.nlogger.Debug(msg, parameters);
if (TestSettings.Instance.DisableDiagnosticLogging)
{
return;
}
try
{
System.Diagnostics.Trace.TraceInformation(msg, parameters);
}
catch
{
}
}
/// <summary>The error.</summary>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public void Error(string message, params object[] parameters)
{
var callingProgram = GetMethodInfo();
var msg = string.Format("ERROR {0}: {1}", callingProgram, message);
this.nlogger.Error(msg, parameters);
if (TestSettings.Instance.DisableDiagnosticLogging)
{
return;
}
try
{
System.Diagnostics.Trace.TraceError(msg, parameters);
}
catch
{
}
}
/// <summary>The fatal.</summary>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public void Fatal(string message, params object[] parameters)
{
var callingProgram = GetMethodInfo();
var msg = string.Format("FATAL {0}: {1}", callingProgram, message);
this.nlogger.Fatal(msg, parameters);
if (TestSettings.Instance.DisableDiagnosticLogging)
{
return;
}
try
{
System.Diagnostics.Trace.TraceError(msg, parameters);
}
catch
{
}
}
/// <summary>The info.</summary>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public void Info(string message, params object[] parameters)
{
var callingProgram = GetMethodInfo();
var msg = string.Format("INFO {0}: {1}", callingProgram, message);
this.nlogger.Info(msg, parameters);
if (TestSettings.Instance.DisableDiagnosticLogging)
{
return;
}
try
{
System.Diagnostics.Trace.TraceInformation(msg, parameters);
}
catch
{
}
}
/// <summary>The trace.</summary>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public void Trace(string message, params object[] parameters)
{
var callingProgram = GetMethodInfo();
var msg = string.Format("TRACE {0}: {1}", callingProgram, message);
this.nlogger.Trace(msg, parameters);
if (TestSettings.Instance.DisableDiagnosticLogging)
{
return;
}
try
{
System.Diagnostics.Trace.TraceInformation(msg, parameters);
}
catch
{
}
}
/// <summary>The warn.</summary>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public void Warn(string message, params object[] parameters)
{
var callingProgram = GetMethodInfo();
var msg = string.Format("WARNING {0}: {1}", callingProgram, message);
this.nlogger.Warn(msg, parameters);
if (TestSettings.Instance.DisableDiagnosticLogging)
{
return;
}
try
{
System.Diagnostics.Trace.TraceWarning(msg, parameters);
}
catch
{
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Printing;
using System.Linq;
using bv.common.Core;
using bv.model.BLToolkit;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using eidss.model.Reports;
using eidss.model.Reports.AZ;
using eidss.model.Reports.Common;
using EIDSS.Reports.BaseControls;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets;
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports
{
[CanWorkWithArchive]
public sealed partial class VetLabReport : BaseReport
{
private const string TestNamePrefix = "strTestName_";
private const string TestCountPrefix = "intTest_";
private const string TempPrefix = "TEMP_";
private bool m_IsFirstRow = true;
private bool m_IsPrintGroup = true;
private int m_DiagnosisCounter;
public VetLabReport()
{
InitializeComponent();
}
public void SetParameters(DbManagerProxy manager, VetLabSurrogateModel model)
{
SetLanguage(manager, model);
ReportRebinder rebinder = ReportRebinder.GetDateRebinder(model.Language, this);
DateCell.Text = rebinder.ToDateTimeString(DateTime.Now);
ForDateCell.Text = model.Header;
string location = AddressModel.GetLocation(model.Language,
m_BaseDataSet.sprepGetBaseParameters[0].CountryName,
model.RegionId, model.RegionName,
model.RayonId, model.RayonName);
if (string.IsNullOrEmpty(model.OrganizationEnteredByName))
{
SentByCell.Text = location;
}
else
{
SentByCell.Text = model.RegionId.HasValue
? string.Format("{0} ({1})", model.OrganizationEnteredByName, location)
: model.OrganizationEnteredByName;
}
m_DiagnosisCounter = 1;
Action<SqlConnection> action = (connection =>
{
m_DataAdapter.Connection = connection;
m_DataAdapter.Transaction = (SqlTransaction) manager.Transaction;
m_DataAdapter.CommandTimeout = CommandTimeout;
m_DataSet.EnforceConstraints = false;
m_DataAdapter.Fill(m_DataSet.spRepVetLabReportAZ, model.Language,
model.StartDate.ToString("s"), model.EndDate.ToString("s"),
model.RegionId, model.RayonId, model.OrganizationEnteredById, model.UserId);
});
FillDataTableWithArchive(action, BeforeMergeWithArchive,
(SqlConnection) manager.Connection,
m_DataSet.spRepVetLabReportAZ,
model.Mode,
new[] {"strDiagnosisSpeciesKey", "strOIECode"},
new string[0],
new Dictionary<string, Func<double, double, double>>());
m_DataSet.spRepVetLabReportAZ.DefaultView.Sort = "DiagniosisOrder, strDiagnosisName, SpeciesOrder, strSpecies";
IEnumerable<DataColumn> columns = m_DataSet.spRepVetLabReportAZ.Columns.Cast<DataColumn>();
int testCount = columns.Count(c => c.ColumnName.Contains(TestCountPrefix));
AddCells(testCount - 1);
if (m_DataSet.spRepVetLabReportAZ.FirstOrDefault(r => r.idfsDiagnosis < 0) == null)
{
RowNumberCell.Text = 1.ToString();
}
}
private void BeforeMergeWithArchive(DataTable sourceData, DataTable archiveData)
{
RemoveTestColumnsIfEmpty(sourceData);
RemoveTestColumnsIfEmpty(archiveData);
List<string> sourceCaptions = SetTestNameCaptions(sourceData);
List<string> archiveCaptions = SetTestNameCaptions(archiveData);
MergeCaptions(sourceCaptions, archiveCaptions);
AddMissingColumns(sourceData, sourceCaptions);
AddMissingColumns(archiveData, sourceCaptions);
RemoveEmptyRowsIfRealDataExists(archiveData, sourceData);
}
internal static void RemoveTestColumnsIfEmpty(DataTable data)
{
if (data.Rows.Count == 0)
{
List<DataColumn> testColumns = data.Columns
.Cast<DataColumn>()
.Where(c => c.ColumnName.Contains(TestNamePrefix) || c.ColumnName.Contains(TestCountPrefix))
.ToList();
foreach (DataColumn column in testColumns)
{
data.Columns.Remove(column);
}
}
}
internal static List<string> SetTestNameCaptions(DataTable data)
{
var result = new List<string>();
if (data.Rows.Count > 0)
{
IEnumerable<DataColumn> testColumns = data.Columns
.Cast<DataColumn>()
.Where(c => c.ColumnName.Contains(TestNamePrefix));
foreach (DataColumn column in testColumns)
{
column.ReadOnly = false;
object firstValue = data.Rows[0][column];
if (!Utils.IsEmpty(firstValue))
{
column.Caption = firstValue.ToString();
if (result.Contains(column.Caption))
{
throw new ApplicationException(string.Format("Duplicate test name {0}", column.Caption));
}
result.Add(column.Caption);
}
}
}
return result;
}
private static void MergeCaptions(List<string> sourceCaptions, IEnumerable<string> archiveCaptions)
{
foreach (string caption in archiveCaptions)
{
if (!sourceCaptions.Contains(caption))
{
sourceCaptions.Add(caption);
}
}
sourceCaptions.Sort();
}
internal static void AddMissingColumns(DataTable data, List<string> sourceCaptions)
{
var columnList = new List<DataColumn>();
for (int i = 0; i < sourceCaptions.Count; i++)
{
string caption = sourceCaptions[i];
DataColumn testNameColumn = data.Columns
.Cast<DataColumn>()
.FirstOrDefault(c => c.Caption == caption);
string tempTestColumnName = TempPrefix + TestNamePrefix + (i + 1);
string tempCountColumnName = TempPrefix + TestCountPrefix + (i + 1);
DataColumn testCountColumn;
if (testNameColumn != null)
{
string oldCountColumnName = testNameColumn.ColumnName.Replace(TestNamePrefix, TestCountPrefix);
testCountColumn = data.Columns[oldCountColumnName];
testNameColumn.ColumnName = tempTestColumnName;
testCountColumn.ColumnName = tempCountColumnName;
}
else
{
testNameColumn = data.Columns.Add(tempTestColumnName, typeof (String));
testNameColumn.Caption = caption;
testCountColumn = data.Columns.Add(tempCountColumnName, typeof (Int32));
foreach (DataRow row in data.Rows)
{
row[testNameColumn] = caption;
}
}
columnList.Add(testNameColumn);
columnList.Add(testCountColumn);
}
for (int i = columnList.Count - 1; i >= 0; i--)
{
DataColumn column = columnList[i];
column.ColumnName = column.ColumnName.Replace(TempPrefix, string.Empty);
column.SetOrdinal(data.Columns.Count - columnList.Count + i);
}
}
private void RemoveEmptyRowsIfRealDataExists(DataTable archiveData, DataTable sourceData)
{
VetLabReportDataSet.spRepVetLabReportAZRow archiveRow =
archiveData.Rows.Cast<VetLabReportDataSet.spRepVetLabReportAZRow>().FirstOrDefault(r => r.strDiagnosisSpeciesKey == "1_1");
VetLabReportDataSet.spRepVetLabReportAZRow sourceRow =
sourceData.Rows.Cast<VetLabReportDataSet.spRepVetLabReportAZRow>().FirstOrDefault(r => r.strDiagnosisSpeciesKey == "1_1");
if (archiveRow == null && sourceRow != null)
{
sourceData.Rows.Remove(sourceRow);
}
if (archiveRow != null && sourceRow == null)
{
archiveData.Rows.Remove(archiveRow);
}
}
private void AddCells(int testCount)
{
if (testCount <= 0)
{
return;
}
try
{
((ISupportInitialize) (DetailsDataTable)).BeginInit();
((ISupportInitialize) (HeaderDataTable)).BeginInit();
((ISupportInitialize)(FooterDataTable)).BeginInit();
var resources = new ComponentResourceManager(typeof (VetLabReport));
float cellWidth = TestCountCell_1.WidthF * (float) Math.Pow(14.0 / 15, testCount - 1) / 2;
TestCountCell_1.WidthF = cellWidth;
TestCountCell_1.DataBindings.Clear();
TestCountCell_1.DataBindings.Add(CreateTestCountBinding(testCount + 1));
TestCountTotalCell_1.WidthF = cellWidth;
TestCountTotalCell_1.DataBindings.Clear();
TestCountTotalCell_1.DataBindings.Add(CreateTestCountBinding(testCount + 1));
TestCountTotalCell_1.Summary.Running = SummaryRunning.Report;
TestNameHeaderCell_1.WidthF = cellWidth;
TestNameHeaderCell_1.DataBindings.Clear();
TestNameHeaderCell_1.DataBindings.Add(CreateTestNameBinding(testCount + 1));
TestsConductedHeaderCell.WidthF = cellWidth * (testCount + 1);
for (int i = 0; i < testCount; i++)
{
int columnIndex = i + 1;
var testCountCell = new XRTableCell();
DetailsDataRow.InsertCell(testCountCell, DetailsDataRow.Cells.Count - 2);
resources.ApplyResources(testCountCell, TestCountCell_1.Name);
testCountCell.WidthF = cellWidth;
testCountCell.DataBindings.Add(CreateTestCountBinding(columnIndex));
var testCountTotalCell = new XRTableCell();
FooterDataRow.InsertCell(testCountTotalCell, FooterDataRow.Cells.Count - 2);
// testCountTotalCell.Text = columnIndex.ToString();
resources.ApplyResources(testCountTotalCell, TestCountTotalCell_1.Name);
testCountTotalCell.WidthF = cellWidth;
testCountTotalCell.DataBindings.Add(CreateTestCountBinding(columnIndex));
testCountTotalCell.Summary.Running = SummaryRunning.Report;
var testNameCell = new XRTableCell();
HeaderDataRow2.InsertCell(testNameCell, HeaderDataRow2.Cells.Count - 2);
resources.ApplyResources(testNameCell, TestCountCell_1.Name);
testNameCell.WidthF = cellWidth;
testNameCell.Angle = 90;
testNameCell.DataBindings.Add(CreateTestNameBinding(columnIndex));
}
}
finally
{
((ISupportInitialize)(FooterDataTable)).EndInit();
((ISupportInitialize) (HeaderDataTable)).EndInit();
((ISupportInitialize) (DetailsDataTable)).EndInit();
}
}
private static XRBinding CreateTestCountBinding(int columnIndex)
{
return new XRBinding("Text", null, "spRepVetLabReportAZ." + TestCountPrefix + columnIndex);
}
private static XRBinding CreateTestNameBinding(int columnIndex)
{
return new XRBinding("Text", null, "spRepVetLabReportAZ." + TestNamePrefix + columnIndex);
}
private void GroupFooterDiagnosis_BeforePrint(object sender, PrintEventArgs e)
{
m_IsPrintGroup = true;
m_DiagnosisCounter++;
RowNumberCell.Text = m_DiagnosisCounter.ToString();
}
private void RowNumberCell_BeforePrint(object sender, PrintEventArgs e)
{
AjustGroupBorders(RowNumberCell, m_IsPrintGroup);
AjustGroupBorders(DiseaseCell, m_IsPrintGroup);
AjustGroupBorders(OIECell, m_IsPrintGroup);
m_IsPrintGroup = false;
AjustNonGroupBorders(SpeciesCell);
}
private void AjustNonGroupBorders(XRTableCell firstNonGroupCell)
{
if (!m_IsFirstRow)
{
XRTableCellCollection cells = firstNonGroupCell.Row.Cells;
for (int i = cells.IndexOf(firstNonGroupCell); i < cells.Count; i++)
{
cells[i].Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right;
}
}
m_IsFirstRow = false;
}
private void AjustGroupBorders(XRTableCell cell, bool isPrinted)
{
if (!isPrinted)
{
cell.Text = string.Empty;
cell.Borders = BorderSide.Left | BorderSide.Right;
}
else
{
cell.Borders = m_DiagnosisCounter > 1
? BorderSide.Left | BorderSide.Top | BorderSide.Right
: BorderSide.Left | BorderSide.Right;
}
}
}
}
| |
<?cs
def:mobile_nav_toggle() ?>
<div class="dac-visible-mobile-block" data-toggle="section">
<span class="dac-toggle-expand dac-devdoc-toggle"><i class="dac-sprite dac-expand-more-black"></i> Show navigation</span>
<span class="dac-toggle-collapse dac-devdoc-toggle" data-toggle-section><i class="dac-sprite dac-expand-less-black"></i> Hide navigation</span>
</div>
<?cs /def ?><?cs
def:fullpage() ?>
<div id="body-content">
<div>
<?cs /def ?>
<?cs
def:sdk_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/sdk/sdk_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<?cs /def ?><?cs
def:no_nav() ?>
<div class="wrap clearfix" id="body-content">
<div>
<?cs /def ?><?cs
def:tools_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/tools/tools_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:training_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/training/training_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:googleplay_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/googleplay/googleplay_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:preview_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/preview/preview_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:essentials_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/essentials/essentials_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:users_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/users/users_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:engage_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/engage/engage_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:analyze_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/analyze/analyze_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:monetize_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/monetize/monetize_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:disttools_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/tools/disttools_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:stories_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/stories/stories_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?><?cs
def:guide_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/guide/guide_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:design_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/design/design_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:distribute_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/distribute/distribute_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:samples_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/samples/samples_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:google_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/google/google_toc.cs" ?>
</div>
</div>
<script type="text/javascript">
showGoogleRefTree();
</script>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:about_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/about/about_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:wear_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs include:"../../../../frameworks/base/docs/html/wear/wear_toc.cs" ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs # The default side navigation for the reference docs ?><?cs
def:default_left_nav() ?>
<?cs if:reference.gcm || reference.gms ?>
<?cs call:google_nav() ?>
<?cs else ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-4 dac-hidden-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled"
title="Select your target API level to dim unavailable APIs">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ <?cs
each:since = since ?>'<?cs
var:since.name ?>'<?cs
if:!last(since) ?>, <?cs /if ?><?cs
/each
?> ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<?cs call:package_link_list(docs.packages) ?>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<?cs
if:subcount(class.package) ?>
<ul>
<?cs call:list("Annotations", class.package.annotations) ?>
<?cs call:list("Interfaces", class.package.interfaces) ?>
<?cs call:list("Classes", class.package.classes) ?>
<?cs call:list("Enums", class.package.enums) ?>
<?cs call:list("Exceptions", class.package.exceptions) ?>
<?cs call:list("Errors", class.package.errors) ?>
</ul><?cs
elif:subcount(package) ?>
<ul>
<?cs call:class_link_list("Annotations", package.annotations) ?>
<?cs call:class_link_list("Interfaces", package.interfaces) ?>
<?cs call:class_link_list("Classes", package.classes) ?>
<?cs call:class_link_list("Enums", package.enums) ?>
<?cs call:class_link_list("Exceptions", package.exceptions) ?>
<?cs call:class_link_list("Errors", package.errors) ?>
</ul><?cs
else ?>
<p style="padding:10px">Select a package to view its members</p><?cs
/if ?><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("<?cs var:toroot ?>");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<?cs /if ?>
<?cs
/def ?>
<?cs
def:ndk_nav() ?>
<div class="wrap clearfix" id="body-content"><div class="cols">
<div class="col-3 dac-toggle dac-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<?cs call:mobile_nav_toggle() ?>
<div class="dac-toggle-content" id="devdoc-nav">
<div class="scroll-pane">
<?cs
if:guide ?><?cs include:"../../../../frameworks/base/docs/html/ndk/guides/guides_toc.cs" ?><?cs
elif:reference ?><?cs include:"../../../../frameworks/base/docs/html/ndk/reference/reference_toc.cs" ?><?cs
elif:downloads ?><?cs include:"../../../../frameworks/base/docs/html/ndk/downloads/downloads_toc.cs" ?><?cs
elif:samples ?><?cs include:"../../../../frameworks/base/docs/html/ndk/samples/samples_toc.cs" ?><?cs
/if ?>
</div>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:header_search_widget() ?>
<div class="dac-header-search" id="search-container">
<div class="dac-header-search-inner">
<div class="dac-sprite dac-search dac-header-search-btn" id="search-btn"></div>
<form class="dac-header-search-form" onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '<?cs var:toroot ?>')"
onkeyup="return search_changed(event, false, '<?cs var:toroot ?>')"
class="dac-header-search-input" placeholder="Search" />
<a class="dac-header-search-close hide" id="search-close">close</a>
</form>
</div><!-- end dac-header-search-inner -->
</div><!-- end dac-header-search -->
<div class="search_filtered_wrapper">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
<div class="child-card samples no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<?cs /def ?>
<?cs
def:custom_left_nav() ?><?cs
if:ndk ?><?cs
if:fullpage ?><?cs
call:fullpage() ?><?cs
elif:nonavpage ?><?cs
call:no_nav() ?><?cs
elif:guide || reference || samples || downloads ?><?cs
call:ndk_nav() ?><?cs
else ?><?cs
call:default_left_nav() ?> <?cs
/if ?><?cs
else ?><?cs
if:fullpage ?><?cs
call:fullpage() ?><?cs
elif:nonavpage ?><?cs
call:no_nav() ?><?cs
elif:guide ?><?cs
call:guide_nav() ?><?cs
elif:design ?><?cs
call:design_nav() ?><?cs
elif:training ?><?cs
call:training_nav() ?><?cs
elif:tools ?><?cs
call:tools_nav() ?><?cs
elif:google ?><?cs
call:google_nav() ?><?cs
elif:samples ?><?cs
call:samples_nav() ?><?cs
elif:preview ?><?cs
call:preview_nav() ?><?cs
elif:distribute ?><?cs
if:googleplay ?><?cs
call:googleplay_nav() ?><?cs
elif:essentials ?><?cs
call:essentials_nav() ?><?cs
elif:users ?><?cs
call:users_nav() ?><?cs
elif:engage ?><?cs
call:engage_nav() ?><?cs
elif:monetize ?><?cs
call:monetize_nav() ?><?cs
elif:analyze ?><?cs
call:analyze_nav() ?><?cs
elif:disttools ?><?cs
call:disttools_nav() ?><?cs
elif:stories ?><?cs
call:stories_nav() ?><?cs
/if ?><?cs
elif:about ?><?cs
call:about_nav() ?><?cs
elif:distribute ?><?cs
call:distribute_nav() ?><?cs
elif:wear ?><?cs
call:wear_nav() ?><?cs
else ?><?cs
call:default_left_nav() ?> <?cs
/if ?><?cs
/if ?><?cs
/def ?>
<?cs # appears at the bottom of every page ?><?cs
def:custom_cc_copyright() ?>
Except as noted, this content is
licensed under <a href="//creativecommons.org/licenses/by/2.5/">
Creative Commons Attribution 2.5</a>. For details and
restrictions, see the <a href="<?cs var:toroot ?>license.html">Content
License</a>.<?cs
/def ?>
<?cs
def:custom_copyright() ?>
Except as noted, this content is licensed under <a
href="//www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="<?cs var:toroot ?>license.html">
Content License</a>.<?cs
/def ?>
<?cs
def:custom_footerlinks() ?>
<a href="<?cs var:toroot ?>about/index.html">About Android</a>
<a href="<?cs var:toroot ?>auto/index.html">Auto</a>
<a href="<?cs var:toroot ?>tv/index.html">TV</a>
<a href="<?cs var:toroot ?>wear/index.html">Wear</a>
<a href="<?cs var:toroot ?>legal.html">Legal</a>
<?cs
/def ?>
<?cs # appears on the right side of the blue bar at the bottom off every page ?><?cs
def:custom_buildinfo() ?><?cs
if:!google && !reference.gcm && !reference.gms ?>
Android <?cs var:sdk.version ?> r<?cs var:sdk.rel.id ?> — <?cs
/if ?>
<script src="<?cs var:toroot ?>timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
<?cs /def ?>
| |
using System;
using System.Collections.Generic;
using Pixie.Markup;
namespace Pixie.Terminal.Devices
{
/// <summary>
/// A style manager that applies styles by setting the color
/// properties of the 'System.Console' class.
/// </summary>
public sealed class ConsoleStyleManager : StyleManager
{
/// <summary>
/// Creates a console style manager.
/// </summary>
public ConsoleStyleManager()
: this(
ConsoleStyle.ToPixieColor(Console.ForegroundColor, Colors.White),
ConsoleStyle.ToPixieColor(Console.BackgroundColor, Colors.Black))
{ }
/// <summary>
/// Creates a console style manager from a default foreground
/// and background color.
/// </summary>
/// <param name="defaultForegroundColor">The default foreground color.</param>
/// <param name="defaultBackgroundColor">The default background color.</param>
public ConsoleStyleManager(
Color defaultForegroundColor,
Color defaultBackgroundColor)
{
this.styleStack = new Stack<ConsoleStyle>();
this.styleStack.Push(
new ConsoleStyle(
defaultForegroundColor,
defaultBackgroundColor,
true));
}
private Stack<ConsoleStyle> styleStack;
private ConsoleStyle CurrentStyle => styleStack.Peek();
/// <inheritdoc/>
public override void PushForegroundColor(Color color)
{
var curStyle = CurrentStyle;
PushStyle(
new ConsoleStyle(
color.Over(curStyle.ForegroundColor),
curStyle.BackgroundColor));
}
/// <inheritdoc/>
public override void PushBackgroundColor(Color color)
{
var curStyle = CurrentStyle;
PushStyle(
new ConsoleStyle(
curStyle.ForegroundColor,
color.Over(curStyle.BackgroundColor)));
}
/// <inheritdoc/>
public override void PushDecoration(
TextDecoration decoration,
Func<TextDecoration, TextDecoration, TextDecoration> updateDecoration)
{
// 'System.Console' doesn't support text decorations. Just push
// the current style.
PushStyle(CurrentStyle);
}
private void PushStyle(ConsoleStyle style)
{
style.Apply(CurrentStyle);
styleStack.Push(style);
}
/// <inheritdoc/>
public override void PopStyle()
{
var popped = styleStack.Pop();
CurrentStyle.Apply(popped);
}
}
internal sealed class ConsoleStyle
{
public ConsoleStyle(
Color foregroundColor,
Color backgroundColor)
: this(foregroundColor, backgroundColor, false)
{ }
public ConsoleStyle(
Color foregroundColor,
Color backgroundColor,
bool isRootStyle)
{
this.ForegroundColor = foregroundColor;
this.BackgroundColor = backgroundColor;
this.IsRootStyle = isRootStyle;
}
public Color ForegroundColor { get; private set; }
public Color BackgroundColor { get; private set; }
public bool IsRootStyle { get; private set; }
/// <summary>
/// Applies this style, given a previous style.
/// </summary>
public void Apply(ConsoleStyle style)
{
var newFg = ToConsoleColor(ForegroundColor);
var newBg = ToConsoleColor(BackgroundColor);
if (IsRootStyle)
{
Console.ResetColor();
return;
}
if (Console.ForegroundColor != newFg)
{
Console.ForegroundColor = newFg;
}
if (Console.BackgroundColor != newBg)
{
Console.BackgroundColor = newBg;
}
}
static ConsoleStyle()
{
colorMap = new Dictionary<ConsoleColor, Color>()
{
{ ConsoleColor.Black, Colors.Black },
{ ConsoleColor.Blue, Colors.Blue },
{ ConsoleColor.Cyan, Colors.Cyan },
{ ConsoleColor.Gray, Colors.Gray },
{ ConsoleColor.Green, Colors.Green },
{ ConsoleColor.Magenta, Colors.Magenta },
{ ConsoleColor.Red, Colors.Red },
{ ConsoleColor.White, Colors.White },
{ ConsoleColor.Yellow, Colors.Yellow },
{ ConsoleColor.DarkBlue, MakeDark(Colors.Blue) },
{ ConsoleColor.DarkCyan, MakeDark(Colors.Cyan) },
{ ConsoleColor.DarkGray, MakeDark(Colors.Gray) },
{ ConsoleColor.DarkGreen, MakeDark(Colors.Green) },
{ ConsoleColor.DarkMagenta, MakeDark(Colors.Magenta) },
{ ConsoleColor.DarkRed, MakeDark(Colors.Red) },
{ ConsoleColor.DarkYellow, MakeDark(Colors.Yellow) }
};
}
private static Dictionary<ConsoleColor, Color> colorMap;
private static Color MakeDark(Color color)
{
double factor = 0.5;
return new Color(
factor * color.Red,
factor * color.Green,
factor * color.Blue,
color.Alpha);
}
public static Color ToPixieColor(ConsoleColor color, Color fallbackResult)
{
Color result;
if (colorMap.TryGetValue(color, out result))
{
return result;
}
else
{
return fallbackResult;
}
}
public static ConsoleColor ToConsoleColor(Color color)
{
var nearestColor = ConsoleColor.Gray;
var nearestColorDistSqr = 3.0;
foreach (var pair in colorMap)
{
var otherColor = pair.Value;
var distR = otherColor.Red - color.Red;
var distG = otherColor.Green - color.Green;
var distB = otherColor.Blue - color.Blue;
var distSqr = distR * distR + distG * distG + distB * distB;
if (distSqr < nearestColorDistSqr)
{
nearestColorDistSqr = distSqr;
nearestColor = pair.Key;
}
}
return nearestColor;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.OpenXmlFormats.Spreadsheet;
using System;
using NPOI.XSSF.Model;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using NPOI.Util;
using NPOI.SS;
using System.Collections;
namespace NPOI.XSSF.UserModel
{
/**
* High level representation of a row of a spreadsheet.
*/
public class XSSFRow : IRow, IComparable<XSSFRow>
{
private static POILogger _logger = POILogFactory.GetLogger(typeof(XSSFRow));
/**
* the xml bean Containing all cell defInitions for this row
*/
private CT_Row _row;
/**
* Cells of this row keyed by their column indexes.
* The TreeMap ensures that the cells are ordered by columnIndex in the ascending order.
*/
private SortedDictionary<int, ICell> _cells;
/**
* the parent sheet
*/
private XSSFSheet _sheet;
/**
* Construct a XSSFRow.
*
* @param row the xml bean Containing all cell defInitions for this row.
* @param sheet the parent sheet.
*/
public XSSFRow(CT_Row row, XSSFSheet sheet)
{
_row = row;
_sheet = sheet;
_cells = new SortedDictionary<int, ICell>();
if (0 < row.SizeOfCArray())
{
foreach (CT_Cell c in row.c)
{
XSSFCell cell = new XSSFCell(this, c);
_cells.Add(cell.ColumnIndex,cell);
sheet.OnReadCell(cell);
}
}
}
/**
* Returns the XSSFSheet this row belongs to
*
* @return the XSSFSheet that owns this row
*/
public ISheet Sheet
{
get
{
return this._sheet;
}
}
/**
* Cell iterator over the physically defined cells:
* <blockquote><pre>
* for (Iterator<Cell> it = row.cellIterator(); it.HasNext(); ) {
* Cell cell = it.next();
* ...
* }
* </pre></blockquote>
*
* @return an iterator over cells in this row.
*/
public SortedDictionary<int, ICell>.ValueCollection.Enumerator CellIterator()
{
return _cells.Values.GetEnumerator();
}
/**
* Alias for {@link #cellIterator()} to allow foreach loops:
* <blockquote><pre>
* for(Cell cell : row){
* ...
* }
* </pre></blockquote>
*
* @return an iterator over cells in this row.
*/
public IEnumerator GetEnumerator()
{
return CellIterator();
}
/**
* Compares two <code>XSSFRow</code> objects. Two rows are equal if they belong to the same worksheet and
* their row indexes are Equal.
*
* @param row the <code>XSSFRow</code> to be Compared.
* @return the value <code>0</code> if the row number of this <code>XSSFRow</code> is
* equal to the row number of the argument <code>XSSFRow</code>; a value less than
* <code>0</code> if the row number of this this <code>XSSFRow</code> is numerically less
* than the row number of the argument <code>XSSFRow</code>; and a value greater
* than <code>0</code> if the row number of this this <code>XSSFRow</code> is numerically
* greater than the row number of the argument <code>XSSFRow</code>.
* @throws ArgumentException if the argument row belongs to a different worksheet
*/
public int CompareTo(XSSFRow row)
{
int thisVal = this.RowNum;
if (row.Sheet != Sheet)
throw new ArgumentException("The Compared rows must belong to the same XSSFSheet");
int anotherVal = row.RowNum;
return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
}
/**
* Use this to create new cells within the row and return it.
* <p>
* The cell that is returned is a {@link Cell#CELL_TYPE_BLANK}. The type can be Changed
* either through calling <code>SetCellValue</code> or <code>SetCellType</code>.
* </p>
* @param columnIndex - the column number this cell represents
* @return Cell a high level representation of the Created cell.
* @throws ArgumentException if columnIndex < 0 or greater than 16384,
* the maximum number of columns supported by the SpreadsheetML format (.xlsx)
*/
public ICell CreateCell(int columnIndex)
{
return CreateCell(columnIndex, CellType.Blank);
}
/**
* Use this to create new cells within the row and return it.
*
* @param columnIndex - the column number this cell represents
* @param type - the cell's data type
* @return XSSFCell a high level representation of the Created cell.
* @throws ArgumentException if the specified cell type is invalid, columnIndex < 0
* or greater than 16384, the maximum number of columns supported by the SpreadsheetML format (.xlsx)
* @see Cell#CELL_TYPE_BLANK
* @see Cell#CELL_TYPE_BOOLEAN
* @see Cell#CELL_TYPE_ERROR
* @see Cell#CELL_TYPE_FORMULA
* @see Cell#CELL_TYPE_NUMERIC
* @see Cell#CELL_TYPE_STRING
*/
public ICell CreateCell(int columnIndex, CellType type)
{
CT_Cell ctCell;
XSSFCell prev = _cells.ContainsKey(columnIndex) ? (XSSFCell)_cells[columnIndex] : null;
if (prev != null)
{
ctCell = prev.GetCTCell();
ctCell.Set(new CT_Cell());
}
else
{
ctCell = _row.AddNewC();
}
XSSFCell xcell = new XSSFCell(this, ctCell);
xcell.SetCellNum(columnIndex);
if (type != CellType.Blank)
{
xcell.SetCellType(type);
}
_cells[columnIndex] = xcell;
return xcell;
}
/**
* Returns the cell at the given (0 based) index,
* with the {@link NPOI.SS.usermodel.Row.MissingCellPolicy} from the parent Workbook.
*
* @return the cell at the given (0 based) index
*/
public ICell GetCell(int cellnum)
{
return GetCell(cellnum, _sheet.Workbook.MissingCellPolicy);
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined, then
/// you Get a null.
/// This is the basic call, with no policies applied
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if Undefined.</returns>
private ICell RetrieveCell(int cellnum)
{
if (!_cells.ContainsKey(cellnum))
return null;
//if (cellnum < 0 || cellnum >= cells.Count) return null;
return _cells[cellnum];
}
/**
* Returns the cell at the given (0 based) index, with the specified {@link NPOI.SS.usermodel.Row.MissingCellPolicy}
*
* @return the cell at the given (0 based) index
* @throws ArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid
* @see Row#RETURN_NULL_AND_BLANK
* @see Row#RETURN_BLANK_AS_NULL
* @see Row#CREATE_NULL_AS_BLANK
*/
public ICell GetCell(int cellnum, MissingCellPolicy policy)
{
if (cellnum < 0) throw new ArgumentException("Cell index must be >= 0");
XSSFCell cell = (XSSFCell)RetrieveCell(cellnum);
if (policy == MissingCellPolicy.RETURN_NULL_AND_BLANK)
{
return cell;
}
if (policy == MissingCellPolicy.RETURN_BLANK_AS_NULL)
{
if (cell == null) return cell;
if (cell.CellType == CellType.Blank)
{
return null;
}
return cell;
}
if (policy == MissingCellPolicy.CREATE_NULL_AS_BLANK)
{
if (cell == null)
{
return CreateCell(cellnum, CellType.Blank);
}
return cell;
}
throw new ArgumentException("Illegal policy " + policy + " (" + policy.id + ")");
}
int GetFirstKey(SortedDictionary<int, ICell>.KeyCollection keys)
{
int i = 0;
foreach (int key in keys)
{
if (i == 0)
return key;
}
throw new ArgumentOutOfRangeException();
}
int GetLastKey(SortedDictionary<int, ICell>.KeyCollection keys)
{
int i = 0;
foreach (int key in keys)
{
if (i == keys.Count - 1)
return key;
i++;
}
throw new ArgumentOutOfRangeException();
}
/**
* Get the number of the first cell Contained in this row.
*
* @return short representing the first logical cell in the row,
* or -1 if the row does not contain any cells.
*/
public short FirstCellNum
{
get
{
return (short)(_cells.Count == 0 ? -1 : GetFirstKey(_cells.Keys));
}
}
/**
* Gets the index of the last cell Contained in this row <b>PLUS ONE</b>. The result also
* happens to be the 1-based column number of the last cell. This value can be used as a
* standard upper bound when iterating over cells:
* <pre>
* short minColIx = row.GetFirstCellNum();
* short maxColIx = row.GetLastCellNum();
* for(short colIx=minColIx; colIx<maxColIx; colIx++) {
* XSSFCell cell = row.GetCell(colIx);
* if(cell == null) {
* continue;
* }
* //... do something with cell
* }
* </pre>
*
* @return short representing the last logical cell in the row <b>PLUS ONE</b>,
* or -1 if the row does not contain any cells.
*/
public short LastCellNum
{
get
{
return (short)(_cells.Count == 0 ? -1 : (GetLastKey(_cells.Keys) + 1));
}
}
/**
* Get the row's height measured in twips (1/20th of a point). If the height is not Set, the default worksheet value is returned,
* See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()}
*
* @return row height measured in twips (1/20th of a point)
*/
public short Height
{
get
{
return (short)(HeightInPoints * 20);
}
set
{
if (value < 0)
{
if (_row.IsSetHt()) _row.unSetHt();
if (_row.IsSetCustomHeight()) _row.unSetCustomHeight();
}
else
{
_row.ht = ((double)value / 20);
_row.customHeight = (true);
}
}
}
/**
* Returns row height measured in point size. If the height is not Set, the default worksheet value is returned,
* See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()}
*
* @return row height measured in point size
* @see NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()
*/
public float HeightInPoints
{
get
{
if (this._row.IsSetHt())
{
return (float)this._row.ht;
}
return _sheet.DefaultRowHeightInPoints;
}
set
{
this.Height = (short)(value == -1 ? -1 : (value * 20));
}
}
/**
* Gets the number of defined cells (NOT number of cells in the actual row!).
* That is to say if only columns 0,4,5 have values then there would be 3.
*
* @return int representing the number of defined cells in the row.
*/
public int PhysicalNumberOfCells
{
get
{
return _cells.Count;
}
}
/**
* Get row number this row represents
*
* @return the row number (0 based)
*/
public int RowNum
{
get
{
return (int)_row.r-1;
}
set
{
int maxrow = SpreadsheetVersion.EXCEL2007.LastRowIndex;
if (value < 0 || value > maxrow)
{
throw new ArgumentException("Invalid row number (" + value
+ ") outside allowable range (0.." + maxrow + ")");
}
_row.r = (uint)(value+1);
}
}
/**
* Get whether or not to display this row with 0 height
*
* @return - height is zero or not.
*/
public bool ZeroHeight
{
get
{
return (bool)this._row.hidden;
}
set
{
this._row.hidden = value;
}
}
/**
* Is this row formatted? Most aren't, but some rows
* do have whole-row styles. For those that do, you
* can get the formatting from {@link #GetRowStyle()}
*/
public bool IsFormatted
{
get
{
return _row.IsSetS();
}
}
/**
* Returns the whole-row cell style. Most rows won't
* have one of these, so will return null. Call
* {@link #isFormatted()} to check first.
*/
public ICellStyle RowStyle
{
get
{
if (!IsFormatted) return null;
StylesTable stylesSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource();
if (stylesSource.NumCellStyles > 0)
{
return stylesSource.GetStyleAt((int)_row.s);
}
else
{
return null;
}
}
set
{
if (value == null)
{
if (_row.IsSetS())
{
_row.UnsetS();
_row.UnsetCustomFormat();
}
}
else
{
StylesTable styleSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource();
XSSFCellStyle xStyle = (XSSFCellStyle)value;
xStyle.VerifyBelongsToStylesSource(styleSource);
long idx = styleSource.PutStyle(xStyle);
_row.s = (uint)idx;
_row.customFormat = (true);
}
}
}
/**
* Applies a whole-row cell styling to the row.
* If the value is null then the style information is Removed,
* causing the cell to used the default workbook style.
*/
public void SetRowStyle(ICellStyle style)
{
}
/**
* Remove the Cell from this row.
*
* @param cell the cell to remove
*/
public void RemoveCell(ICell cell)
{
if (cell.Row != this)
{
throw new ArgumentException("Specified cell does not belong to this row");
}
XSSFCell xcell = (XSSFCell)cell;
if (xcell.IsPartOfArrayFormulaGroup)
{
xcell.NotifyArrayFormulaChanging();
}
if (cell.CellType == CellType.Formula)
{
((XSSFWorkbook)_sheet.Workbook).OnDeleteFormula(xcell);
}
_cells.Remove(cell.ColumnIndex);
}
/**
* Returns the underlying CT_Row xml bean Containing all cell defInitions in this row
*
* @return the underlying CT_Row xml bean
*/
public CT_Row GetCTRow()
{
return _row;
}
/**
* Fired when the document is written to an output stream.
*
* @see NPOI.XSSF.usermodel.XSSFSheet#Write(java.io.OutputStream) ()
*/
internal void OnDocumentWrite()
{
// check if cells in the CT_Row are ordered
bool isOrdered = true;
if (_row.SizeOfCArray() != _cells.Count) isOrdered = false;
else
{
int i = 0;
foreach (XSSFCell cell in _cells.Values)
{
CT_Cell c1 = cell.GetCTCell();
CT_Cell c2 = _row.GetCArray(i++);
String r1 = c1.r;
String r2 = c2.r;
if (!(r1 == null ? r2 == null : r1.Equals(r2)))
{
isOrdered = false;
break;
}
}
}
if (!isOrdered)
{
CT_Cell[] cArray = new CT_Cell[_cells.Count];
int i = 0;
foreach (XSSFCell c in _cells.Values)
{
cArray[i++] = c.GetCTCell();
}
_row.SetCArray(cArray);
}
}
/**
* @return formatted xml representation of this row
*/
public override String ToString()
{
return _row.ToString();
}
/**
* update cell references when Shifting rows
*
* @param n the number of rows to move
*/
internal void Shift(int n)
{
int rownum = RowNum + n;
CalculationChain calcChain = ((XSSFWorkbook)_sheet.Workbook).GetCalculationChain();
int sheetId = (int)_sheet.sheet.sheetId;
String msg = "Row[rownum=" + RowNum + "] contains cell(s) included in a multi-cell array formula. " +
"You cannot change part of an array.";
foreach (ICell c in this)
{
XSSFCell cell = (XSSFCell)c;
if (cell.IsPartOfArrayFormulaGroup)
{
cell.NotifyArrayFormulaChanging(msg);
}
//remove the reference in the calculation chain
if (calcChain != null)
calcChain.RemoveItem(sheetId, cell.GetReference());
CT_Cell CT_Cell = cell.GetCTCell();
String r = new CellReference(rownum, cell.ColumnIndex).FormatAsString();
CT_Cell.r = r;
}
RowNum = rownum;
}
#region IRow Members
public List<ICell> Cells
{
get {
List<ICell> cells = new List<ICell>();
foreach (ICell cell in _cells.Values)
{
cells.Add(cell);
}
return cells; }
}
public void MoveCell(ICell cell, int newColumn)
{
throw new NotImplementedException();
}
public IRow CopyRowTo(int targetIndex)
{
return this.Sheet.CopyRow(this.RowNum, targetIndex);
}
public ICell CopyCell(int sourceIndex, int targetIndex)
{
return CellUtil.CopyCell(this, sourceIndex, targetIndex);
}
#endregion
}
}
| |
//
// Afrodite.cs
//
// Author:
// Levi Bard <levi.bard@emhartglass.com>
//
// Copyright (c) 2010 Levi Bard
//
// 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.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MonoDevelop.Ide.Gui;
/// <summary>
/// Wrappers for Afrodite completion library
/// </summary>
namespace MonoDevelop.ValaBinding.Parser.Afrodite
{
/// <summary>
/// Afrodite completion engine - interface for queueing source and getting CodeDOMs
/// </summary>
internal class CompletionEngine
{
public CompletionEngine (string id)
{
instance = afrodite_completion_engine_new (id);
}
/// <summary>
/// Queue a new source file for parsing
/// </summary>
public void QueueSourcefile (string path)
{
QueueSourcefile (path, !string.IsNullOrEmpty (path) && path.EndsWith (".vapi", StringComparison.OrdinalIgnoreCase), false);
}
/// <summary>
/// Queue a new source file for parsing
/// </summary>
public void QueueSourcefile (string path, bool isVapi, bool isGlib)
{
afrodite_completion_engine_queue_sourcefile (instance, path, null, isVapi, isGlib);
}
/// <summary>
/// Attempt to acquire the current CodeDOM
/// </summary>
/// <returns>
/// A <see cref="CodeDom"/>: null if unable to acquire
/// </returns>
public CodeDom TryAcquireCodeDom ()
{
IntPtr codeDom = afrodite_completion_engine_get_codedom (instance);
return (codeDom == IntPtr.Zero)? null: new CodeDom (codeDom, this);
}
/// <summary>
/// Release the given CodeDOM (required for continued parsing)
/// </summary>
public void ReleaseCodeDom (CodeDom codeDom)
{
// Obsolete
}
#region P/Invokes
IntPtr instance;
[DllImport("afrodite")]
static extern IntPtr afrodite_completion_engine_new (string id);
[DllImport("afrodite")]
static extern void afrodite_completion_engine_queue_sourcefile (IntPtr instance, string path, string content,
bool is_vapi, bool is_glib);
[DllImport("afrodite")]
static extern IntPtr afrodite_completion_engine_get_codedom (IntPtr instance);
#endregion
}
/// <summary>
/// Represents a Vala symbol
/// </summary>
internal class Symbol
{
public Symbol (IntPtr instance)
{
this.instance = instance;
}
/// <summary>
/// Children of this symbol
/// </summary>
public List<Symbol> Children {
get {
List<Symbol> list = new List<Symbol> ();
IntPtr children = afrodite_symbol_get_children (instance);
if (IntPtr.Zero != children) {
list = new ValaList (children).ToTypedList (item => new Symbol (item));
}
return list;
}
}
/// <summary>
/// The type of this symbol
/// </summary>
public DataType SymbolType {
get {
IntPtr datatype = afrodite_symbol_get_symbol_type (instance);
return (IntPtr.Zero == datatype)? null: new DataType (afrodite_symbol_get_symbol_type (instance));
}
}
/// <summary>
/// The return type of this symbol, if applicable
/// </summary>
public DataType ReturnType {
get {
IntPtr datatype = afrodite_symbol_get_return_type (instance);
return (IntPtr.Zero == datatype)? null: new DataType (afrodite_symbol_get_return_type (instance));
}
}
/// <summary>
/// The name of this symbol
/// </summary>
public string Name {
get{ return Marshal.PtrToStringAuto (afrodite_symbol_get_display_name (instance)); }
}
/// <summary>
/// The fully qualified name of this symbol
/// </summary>
public string FullyQualifiedName {
get { return Marshal.PtrToStringAuto (afrodite_symbol_get_fully_qualified_name (instance)); }
}
/// <summary>
/// The parent of this symbol
/// </summary>
public Symbol Parent {
get {
IntPtr parent = afrodite_symbol_get_parent (instance);
return (IntPtr.Zero == parent)? null: new Symbol (parent);
}
}
/// <summary>
/// The places where this symbol is declared/defined
/// </summary>
public List<SourceReference> SourceReferences {
get {
List<SourceReference> list = new List<SourceReference> ();
IntPtr refs = afrodite_symbol_get_source_references (instance);
if (IntPtr.Zero != refs) {
list = new ValaList (refs).ToTypedList (item => new SourceReference (item));
}
return list;
}
}
/// <summary>
/// The symbol type (class, method, ...) of this symbol
/// </summary>
public string MemberType {
get{ return Utils.GetMemberType (afrodite_symbol_get_member_type (instance)); }
}
/// <summary>
/// The accessibility (public, private, ...) of this symbol
/// </summary>
public SymbolAccessibility Accessibility {
get{ return (SymbolAccessibility)afrodite_symbol_get_access (instance); }
}
/// <summary>
/// The parameters this symbol accepts, if applicable
/// </summary>
public List<DataType> Parameters {
get {
List<DataType> list = new List<DataType> ();
IntPtr parameters = afrodite_symbol_get_parameters (instance);
if (IntPtr.Zero != parameters) {
list = new ValaList (parameters).ToTypedList (delegate (IntPtr item){ return new DataType (item); });
}
return list;
}
}
/// <summary>
/// The icon to be used for this symbol
/// </summary>
public string Icon {
get{ return GetIconForType (MemberType, Accessibility); }
}
/// <summary>
/// Descriptive text for this symbol
/// </summary>
public string DisplayText {
get {
StringBuilder text = new StringBuilder (Name);
List<DataType> parameters = Parameters;
if (0 < parameters.Count) {
text.AppendFormat ("({0} {1}", parameters[0].TypeName, Parameters[0].Name);
for (int i = 1; i < parameters.Count; i++) {
text.AppendFormat (", {0} {1}", parameters[i].TypeName, Parameters[i].Name);
}
text.AppendFormat (")");
}
if (null != ReturnType && !string.IsNullOrEmpty (ReturnType.TypeName)) {
text.AppendFormat (": {0}", ReturnType.TypeName);
}
return text.ToString ();
}
}
#region Icons
private static Dictionary<string,string> publicIcons = new Dictionary<string, string> () {
{ "namespace", Stock.NameSpace },
{ "class", Stock.Class },
{ "struct", Stock.Struct },
{ "enum", Stock.Enum },
{ "error domain", Stock.Enum },
{ "field", Stock.Field },
{ "method", Stock.Method },
{ "constructor", Stock.Method },
{ "creationmethod", Stock.Method },
{ "property", Stock.Property },
{ "constant", Stock.Literal },
{ "enum value", Stock.Literal },
{ "error code", Stock.Literal },
{ "signal", Stock.Event },
{ "delegate", Stock.Delegate },
{ "interface", Stock.Interface },
{ "other", Stock.Delegate }
};
private static Dictionary<string,string> privateIcons = new Dictionary<string, string> () {
{ "namespace", Stock.NameSpace },
{ "class", Stock.PrivateClass },
{ "struct", Stock.PrivateStruct },
{ "enum", Stock.PrivateEnum },
{ "error domain", Stock.PrivateEnum },
{ "field", Stock.PrivateField },
{ "method", Stock.PrivateMethod },
{ "constructor", Stock.PrivateMethod },
{ "creationmethod", Stock.PrivateMethod },
{ "property", Stock.PrivateProperty },
{ "constant", Stock.Literal },
{ "enum value", Stock.Literal },
{ "error code", Stock.Literal },
{ "signal", Stock.PrivateEvent },
{ "delegate", Stock.PrivateDelegate },
{ "interface", Stock.PrivateInterface },
{ "other", Stock.PrivateDelegate }
};
private static Dictionary<string,string> protectedIcons = new Dictionary<string, string> () {
{ "namespace", Stock.NameSpace },
{ "class", Stock.ProtectedClass },
{ "struct", Stock.ProtectedStruct },
{ "enum", Stock.ProtectedEnum },
{ "error domain", Stock.ProtectedEnum },
{ "field", Stock.ProtectedField },
{ "method", Stock.ProtectedMethod },
{ "constructor", Stock.ProtectedMethod },
{ "creationmethod", Stock.ProtectedMethod },
{ "property", Stock.ProtectedProperty },
{ "constant", Stock.Literal },
{ "enum value", Stock.Literal },
{ "error code", Stock.Literal },
{ "signal", Stock.ProtectedEvent },
{ "delegate", Stock.ProtectedDelegate },
{ "interface", Stock.ProtectedInterface },
{ "other", Stock.ProtectedDelegate }
};
private static Dictionary<SymbolAccessibility,Dictionary<string,string>> iconTable = new Dictionary<SymbolAccessibility, Dictionary<string, string>> () {
{ SymbolAccessibility.Public, publicIcons },
{ SymbolAccessibility.Internal, publicIcons },
{ SymbolAccessibility.Private, privateIcons },
{ SymbolAccessibility.Protected, protectedIcons }
};
public static string GetIconForType (string nodeType, SymbolAccessibility visibility)
{
string icon = null;
iconTable[visibility].TryGetValue (nodeType.ToLower (), out icon);
return icon;
}
#endregion
#region P/Invokes
IntPtr instance;
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_type_name (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_display_name (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_children (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_parent (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_fully_qualified_name (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_source_references (IntPtr instance);
[DllImport("afrodite")]
static extern int afrodite_symbol_get_access (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_parameters (IntPtr instance);
[DllImport("afrodite")]
static extern int afrodite_symbol_get_member_type (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_symbol_type (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_symbol_get_return_type (IntPtr instance);
#endregion
}
/// <summary>
/// Represents a Vala CodeDOM
/// </summary>
/// <remarks>
/// MUST be disposed for parsing to continue
/// </remarks>
internal class CodeDom: IDisposable
{
CompletionEngine engine;
/// <summary>
/// Create a new CodeDOM wrapper
/// </summary>
/// <param name="instance">
/// A <see cref="IntPtr"/>: The native pointer for this CodeDOM
/// </param>
/// <param name="engine">
/// A <see cref="CompletionEngine"/>: The completion engine to which this CodeDOM belongs
/// </param>
public CodeDom (IntPtr instance, CompletionEngine engine)
{
this.instance = instance;
this.engine = engine;
}
public QueryResult GetSymbolsForPath (string path)
{
return new QueryResult (afrodite_code_dom_get_symbols_for_path (instance, new QueryOptions ().Instance, path));
}
/// <summary>
/// Lookup the symbol at a given location
/// </summary>
public Symbol LookupSymbolAt (string filename, int line, int column)
{
IntPtr symbol = afrodite_code_dom_lookup_symbol_at (instance, filename, line, column);
return (IntPtr.Zero == symbol)? null: new Symbol (symbol);
}
/// <summary>
/// Lookup a symbol and its parent by fully qualified name
/// </summary>
public Symbol Lookup (string fully_qualified_name, out Symbol parent)
{
IntPtr parentInstance = IntPtr.Zero,
result = IntPtr.Zero;
result = afrodite_code_dom_lookup (instance, fully_qualified_name, out parentInstance);
parent = (IntPtr.Zero == parentInstance)? null: new Symbol (parentInstance);
return (IntPtr.Zero == result)? null: new Symbol (result);
}
/// <summary>
/// Lookup a symbol, given a name and source location
/// </summary>
public Symbol GetSymbolForNameAndPath (string name, string path, int line, int column)
{
IntPtr result = afrodite_code_dom_get_symbol_for_name_and_path (instance, QueryOptions.Standard ().Instance,
name, path, line, column);
if (IntPtr.Zero != result) {
QueryResult qresult = new QueryResult (result);
if (null != qresult.Children && 0 < qresult.Children.Count)
return qresult.Children[0].Symbol;
}
return null;
}
/// <summary>
/// Get the source files used to create this CodeDOM
/// </summary>
public List<SourceFile> SourceFiles {
get {
List<SourceFile> files = new List<SourceFile> ();
IntPtr sourceFiles = afrodite_code_dom_get_source_files (instance);
if (IntPtr.Zero != sourceFiles) {
ValaList list = new ValaList (sourceFiles);
files = list.ToTypedList (delegate (IntPtr item){ return new SourceFile (item); });
}
return files;
}
}
/// <summary>
/// Lookup a source file by filename
/// </summary>
public SourceFile LookupSourceFile (string filename)
{
IntPtr sourceFile = afrodite_code_dom_lookup_source_file (instance, filename);
return (IntPtr.Zero == sourceFile)? null: new SourceFile (sourceFile);
}
#region P/Invokes
IntPtr instance;
internal IntPtr Instance {
get{ return instance; }
}
[DllImport("afrodite")]
static extern IntPtr afrodite_code_dom_get_symbols_for_path (IntPtr instance, IntPtr options, string path);
[DllImport("afrodite")]
static extern IntPtr afrodite_code_dom_lookup_symbol_at (IntPtr instance, string filename, int line, int column);
[DllImport("afrodite")]
static extern IntPtr afrodite_code_dom_lookup (IntPtr instance, string fully_qualified_name, out IntPtr parent);
[DllImport("afrodite")]
static extern IntPtr afrodite_code_dom_get_symbol_for_name_and_path (IntPtr instance, IntPtr options,
string symbol_qualified_name, string path,
int line, int column);
[DllImport("afrodite")]
static extern IntPtr afrodite_code_dom_get_source_files (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_code_dom_lookup_source_file (IntPtr instance, string filename);
#endregion
#region IDisposable implementation
/// <summary>
/// Release this CodeDOM for reuse
/// </summary>
public void Dispose ()
{
engine.ReleaseCodeDom (this);
}
#endregion
}
/// <summary>
/// Utility class for dumping a CodeDOM to Console.Out
/// </summary>
internal class CodeDomDumper
{
public CodeDomDumper ()
{
instance = afrodite_ast_dumper_new ();
}
public void Dump (CodeDom codeDom, string filterSymbol)
{
afrodite_ast_dumper_dump (instance, codeDom.Instance, filterSymbol);
}
#region P/Invokes
IntPtr instance;
[DllImport("afrodite")]
static extern IntPtr afrodite_ast_dumper_new ();
[DllImport("afrodite")]
static extern void afrodite_ast_dumper_dump (IntPtr instance, IntPtr codeDom, string filterSymbol);
#endregion
}
/// <summary>
/// Wrapper class for Afrodite query results
/// </summary>
internal class QueryResult
{
public QueryResult (IntPtr instance)
{
this.instance = instance;
}
/// <summary>
/// ResultItems contained in this query result
/// </summary>
public List<ResultItem> Children {
get {
List<ResultItem> list = new List<ResultItem> ();
IntPtr children = afrodite_query_result_get_children (instance);
if (IntPtr.Zero != children) {
list = new ValaList (children).ToTypedList (delegate (IntPtr item){ return new ResultItem (item); });
}
return list;
}
}
#region P/Invokes
IntPtr instance;
internal IntPtr Instance {
get{ return instance; }
}
[DllImport("afrodite")]
static extern IntPtr afrodite_query_result_get_children (IntPtr instance);
#endregion
}
/// <summary>
/// A single result from a query
/// </summary>
internal class ResultItem
{
public ResultItem (IntPtr instance)
{
this.instance = instance;
}
public Symbol Symbol {
get {
IntPtr symbol = afrodite_result_item_get_symbol (instance);
return (IntPtr.Zero == symbol)? null: new Symbol (symbol);
}
}
#region P/Invokes
IntPtr instance;
internal IntPtr Instance {
get{ return instance; }
}
[DllImport("afrodite")]
static extern IntPtr afrodite_result_item_get_symbol (IntPtr instance);
#endregion
}
/// <summary>
/// Options for querying a CodeDOM
/// </summary>
internal class QueryOptions
{
public QueryOptions (): this (afrodite_query_options_new ())
{
}
public QueryOptions (IntPtr instance)
{
this.instance = instance;
}
public static QueryOptions Standard ()
{
return new QueryOptions (afrodite_query_options_standard ());
}
#region P/Invokes
IntPtr instance;
internal IntPtr Instance {
get{ return instance; }
}
[DllImport("afrodite")]
static extern IntPtr afrodite_query_options_new ();
[DllImport("afrodite")]
static extern IntPtr afrodite_query_options_standard ();
#endregion
}
/// <summary>
/// IEnumerator wrapper for (Gee|Vala).Iterator
/// </summary>
internal class ValaEnumerator: IEnumerator<IntPtr>
{
public ValaEnumerator (IntPtr instance)
{
this.instance = instance;
}
#region IDisposable implementation
public void Dispose ()
{
}
#endregion
#region IEnumerator implementation
object IEnumerator.Current {
get { return ((IEnumerator<IntPtr>)this).Current; }
}
public bool MoveNext ()
{
return vala_iterator_next (instance);
}
public void Reset ()
{
throw new System.NotImplementedException();
}
#endregion
#region IEnumerator[System.IntPtr] implementation
IntPtr IEnumerator<IntPtr>.Current {
get { return vala_iterator_get (instance); }
}
#endregion
#region P/Invoke
IntPtr instance;
[DllImport("vala")]
static extern bool vala_iterator_next (IntPtr instance);
[DllImport("vala")]
static extern IntPtr vala_iterator_get (IntPtr instance);
#endregion
}
/// <summary>
/// IList wrapper for (Gee|Vala).List
/// </summary>
internal class ValaList: IList<IntPtr>
{
public ValaList (IntPtr instance)
{
this.instance = instance;
}
#region ICollection[System.IntPtr] implementation
public void Add (IntPtr item)
{
vala_collection_add (instance, item);
}
public void Clear ()
{
vala_collection_clear (instance);
}
public bool Contains (IntPtr item)
{
return vala_collection_contains (instance, item);
}
public void CopyTo (IntPtr[] array, int arrayIndex)
{
if (Count < array.Length - arrayIndex)
throw new ArgumentException ("Destination array too small", "array");
for (int i=0; i<Count; ++i)
array[i+arrayIndex] = this[i];
}
public int Count {
get {
return vala_collection_get_size (instance);
}
}
public bool IsReadOnly {
get { return false; }
}
public bool Remove (IntPtr item)
{
return vala_collection_remove (instance, item);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return ((IEnumerable<IntPtr>)this).GetEnumerator ();
}
#endregion
#region IList[System.IntPtr] implementation
public int IndexOf (IntPtr item)
{
return vala_list_index_of (instance, item);
}
public void Insert (int index, IntPtr item)
{
vala_list_insert (instance, index, item);
}
public IntPtr this[int index] {
get { return vala_list_get (instance, index); }
set { vala_list_set (instance, index, value); }
}
public void RemoveAt (int index)
{
vala_list_remove_at (instance, index);
}
#endregion
#region IEnumerable[System.IntPtr] implementation
IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator ()
{
return new ValaEnumerator (vala_iterable_iterator (instance));
}
#endregion
internal List<T> ToTypedList<T> (Func<IntPtr,T> factory)
{
List<T> list = new List<T> (Math.Max (0, Count));
foreach (IntPtr item in this) {
list.Add (factory (item));
}
return list;
}
#region P/Invoke
IntPtr instance;
[DllImport("vala")]
static extern bool vala_collection_add (IntPtr instance, IntPtr item);
[DllImport("vala")]
static extern void vala_collection_clear (IntPtr instance);
[DllImport("vala")]
static extern bool vala_collection_contains (IntPtr instance, IntPtr item);
[DllImport("vala")]
static extern int vala_collection_get_size (IntPtr instance);
[DllImport("vala")]
static extern bool vala_collection_remove (IntPtr instance, IntPtr item);
[DllImport("vala")]
static extern IntPtr vala_iterable_iterator (IntPtr instance);
[DllImport("vala")]
static extern int vala_list_index_of (IntPtr instance, IntPtr item);
[DllImport("vala")]
static extern void vala_list_insert (IntPtr instance, int index, IntPtr item);
[DllImport("vala")]
static extern IntPtr vala_list_get (IntPtr instance, int index);
[DllImport("vala")]
static extern void vala_list_set (IntPtr instance, int index, IntPtr item);
[DllImport("vala")]
static extern void vala_list_remove_at (IntPtr instance, int index);
#endregion
}
/// <summary>
/// Class to represent a CodeDOM source file
/// </summary>
internal class SourceFile
{
public SourceFile (string filename)
:this (afrodite_source_file_new (filename))
{
}
public SourceFile (IntPtr instance)
{
this.instance = instance;
}
/// <summary>
/// Symbols declared in this source file
/// </summary>
public List<Symbol> Symbols {
get {
List<Symbol> list = new List<Symbol> ();
IntPtr symbols = afrodite_source_file_get_symbols (instance);
if (IntPtr.Zero != symbols) {
list = new ValaList (symbols).ToTypedList (delegate (IntPtr item){ return new Symbol (item); });
}
return list;
}
}
/// <summary>
/// Using directives in this source file
/// </summary>
public List<DataType> UsingDirectives {
get {
List<DataType> list = new List<DataType> ();
IntPtr symbols = afrodite_source_file_get_using_directives (instance);
if (IntPtr.Zero != symbols) {
list = new ValaList (symbols).ToTypedList (item => new DataType (item));
}
return list;
}
}
/// <summary>
/// The name of this source file
/// </summary>
public string Name {
get{ return Marshal.PtrToStringAuto (afrodite_source_file_get_filename (instance)); }
}
#region P/Invoke
IntPtr instance;
[DllImport("afrodite")]
static extern IntPtr afrodite_source_file_new (string filename);
[DllImport("afrodite")]
static extern IntPtr afrodite_source_file_get_filename (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_source_file_get_symbols (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_source_file_get_using_directives (IntPtr instance);
#endregion
}
/// <summary>
/// Represents an Afrodite symbol data type
/// </summary>
internal class DataType
{
public DataType (IntPtr instance)
{
this.instance = instance;
}
/// <summary>
/// Get the raw name of this datatype
/// </summary>
public string Name {
get{ return Marshal.PtrToStringAuto (afrodite_data_type_get_name (instance)); }
}
/// <summary>
/// Get the descriptive type name (ref Gee.List<string>[]?) for this datatype
/// </summary>
public string TypeName {
get {
StringBuilder text = new StringBuilder ();
// prefix out/ref
if (IsOut) {
text.Append ("out ");
} else if (IsRef) {
text.Append ("ref ");
}
text.Append (Marshal.PtrToStringAuto (afrodite_data_type_get_type_name (instance)));
if (IsGeneric) {
text.Append ("<");
List<DataType> parameters = GenericTypes;
if (parameters != null && parameters.Count > 0) {
text.Append (parameters[0].TypeName);
for (int i = 0; i < parameters.Count; i++) {
text.AppendFormat (",{0}", parameters[i].TypeName);
}
}
text.Append (">");
}
if (IsArray) { text.Append ("[]"); }
if (IsNullable){ text.Append ("?"); }
if (IsPointer){ text.Append ("*"); }
return text.ToString ();
}
}
/// <summary>
/// Get the symbol for this datatype
/// </summary>
public Symbol Symbol {
get {
IntPtr symbol = afrodite_data_type_get_symbol (instance);
return (IntPtr.Zero == symbol)? null: new Symbol (symbol);
}
}
/// <summary>
/// Whether this datatype is an array
/// </summary>
public bool IsArray {
get{ return afrodite_data_type_get_is_array (instance); }
}
/// <summary>
/// Whether this datatype is a pointer
/// </summary>
public bool IsPointer {
get{ return afrodite_data_type_get_is_pointer (instance); }
}
/// <summary>
/// Whether this datatype is nullable
/// </summary>
public bool IsNullable {
get{ return afrodite_data_type_get_is_nullable (instance); }
}
/// <summary>
/// Whether this is an out datatype
/// </summary>
public bool IsOut {
get{ return afrodite_data_type_get_is_out (instance); }
}
/// <summary>
/// Whether this is a ref datatype
/// </summary>
public bool IsRef {
get{ return afrodite_data_type_get_is_ref (instance); }
}
/// <summary>
/// Whether this datatype is generic
/// </summary>
public bool IsGeneric {
get{ return afrodite_data_type_get_is_generic (instance); }
}
/// <summary>
/// Type list for generic datatypes (e.g. HashMap<KeyType,ValueType>)
/// </summary>
public List<DataType> GenericTypes {
get {
List<DataType> list = new List<DataType> ();
IntPtr types = afrodite_data_type_get_generic_types (instance);
if (IntPtr.Zero != types) {
list = new ValaList (types).ToTypedList (item => new DataType (item));
}
return list;
}
}
#region P/Invoke
IntPtr instance;
[DllImport("afrodite")]
static extern IntPtr afrodite_data_type_get_type_name (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_data_type_get_name (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_data_type_get_symbol (IntPtr instance);
[DllImport("afrodite")]
static extern IntPtr afrodite_data_type_get_generic_types (IntPtr instance);
[DllImport("afrodite")]
static extern bool afrodite_data_type_get_is_array (IntPtr instance);
[DllImport("afrodite")]
static extern bool afrodite_data_type_get_is_pointer (IntPtr instance);
[DllImport("afrodite")]
static extern bool afrodite_data_type_get_is_nullable (IntPtr instance);
[DllImport("afrodite")]
static extern bool afrodite_data_type_get_is_out (IntPtr instance);
[DllImport("afrodite")]
static extern bool afrodite_data_type_get_is_ref (IntPtr instance);
[DllImport("afrodite")]
static extern bool afrodite_data_type_get_is_generic (IntPtr instance);
#endregion
}
/// <summary>
/// Class to represent a reference area in a source file
/// </summary>
internal class SourceReference
{
public SourceReference (IntPtr instance)
{
this.instance = instance;
}
public string File {
get {
IntPtr sourcefile = afrodite_source_reference_get_file (instance);
return (IntPtr.Zero == sourcefile)? string.Empty: new SourceFile (sourcefile).Name;
}
}
public int FirstLine {
get{ return afrodite_source_reference_get_first_line (instance); }
}
public int LastLine {
get{ return afrodite_source_reference_get_last_line (instance); }
}
public int FirstColumn {
get{ return afrodite_source_reference_get_first_column (instance); }
}
public int LastColumn {
get{ return afrodite_source_reference_get_last_column (instance); }
}
#region P/Invoke
IntPtr instance;
[DllImport("afrodite")]
static extern IntPtr afrodite_source_reference_get_file (IntPtr instance);
[DllImport("afrodite")]
static extern int afrodite_source_reference_get_first_line (IntPtr instance);
[DllImport("afrodite")]
static extern int afrodite_source_reference_get_last_line (IntPtr instance);
[DllImport("afrodite")]
static extern int afrodite_source_reference_get_first_column (IntPtr instance);
[DllImport("afrodite")]
static extern int afrodite_source_reference_get_last_column (IntPtr instance);
#endregion
}
// From afrodite.vapi
public enum SymbolAccessibility {
Private = 0x1,
Internal = 0x2,
Protected = 0x4,
Public = 0x8,
Any = 0x10
}
/// <summary>
/// Wrapper class for Afrodite.Utils namespace
/// </summary>
internal static class Utils
{
/// <summary>
/// Get a list of vapi files for a given package
/// </summary>
public static List<string> GetPackagePaths (string package)
{
List<string> list = new List<string> ();
IntPtr paths = afrodite_utils_get_package_paths (package, IntPtr.Zero, null);
if (IntPtr.Zero != paths)
list = new ValaList (paths).ToTypedList (delegate(IntPtr item){ return Marshal.PtrToStringAuto (item); });
return list;
}
public static string GetMemberType (int memberType)
{
return Marshal.PtrToStringAuto (afrodite_utils_symbols_get_symbol_type_description (memberType));
}
[DllImport("afrodite")]
static extern IntPtr afrodite_utils_get_package_paths (string package, IntPtr codeContext, string[] vapiDirs);
[DllImport("afrodite")]
static extern IntPtr afrodite_utils_symbols_get_symbol_type_description (int memberType);
}
}
| |
namespace XenAdmin.Controls.NetworkingTab
{
partial class NetworkList
{
/// <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 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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NetworkList));
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.AddNetworkButton = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.removeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.EditButtonContainer = new XenAdmin.Controls.ToolTipContainer();
this.EditNetworkButton = new System.Windows.Forms.Button();
this.RemoveButtonContainer = new XenAdmin.Controls.ToolTipContainer();
this.RemoveNetworkButton = new System.Windows.Forms.Button();
this.toolTipContainerActivateToggle = new XenAdmin.Controls.ToolTipContainer();
this.buttonActivateToggle = new System.Windows.Forms.Button();
this.NetworksGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
this.ImageColumn = new System.Windows.Forms.DataGridViewImageColumn();
this.NameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.DescriptionColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.NicColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.VlanColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.AutoColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.LinkStatusColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.NetworkMacColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.VifMacColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.DeviceColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.LimitColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.NetworkColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.IpColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ActiveColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.MtuColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.flowLayoutPanel1.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.EditButtonContainer.SuspendLayout();
this.RemoveButtonContainer.SuspendLayout();
this.toolTipContainerActivateToggle.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NetworksGridView)).BeginInit();
this.SuspendLayout();
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.BackColor = System.Drawing.Color.Transparent;
this.flowLayoutPanel1.Controls.Add(this.AddNetworkButton);
this.flowLayoutPanel1.Controls.Add(this.EditButtonContainer);
this.flowLayoutPanel1.Controls.Add(this.RemoveButtonContainer);
this.flowLayoutPanel1.Controls.Add(this.groupBox1);
this.flowLayoutPanel1.Controls.Add(this.toolTipContainerActivateToggle);
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// AddNetworkButton
//
resources.ApplyResources(this.AddNetworkButton, "AddNetworkButton");
this.AddNetworkButton.Name = "AddNetworkButton";
this.AddNetworkButton.UseVisualStyleBackColor = true;
this.AddNetworkButton.Click += new System.EventHandler(this.AddNetworkButton_Click);
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.copyToolStripMenuItem,
this.addToolStripMenuItem,
this.removeToolStripMenuItem,
this.propertiesToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1");
this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.copy_16;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
resources.ApplyResources(this.copyToolStripMenuItem, "copyToolStripMenuItem");
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// addToolStripMenuItem
//
this.addToolStripMenuItem.Name = "addToolStripMenuItem";
resources.ApplyResources(this.addToolStripMenuItem, "addToolStripMenuItem");
this.addToolStripMenuItem.Click += new System.EventHandler(this.AddMenuItemHandler);
//
// removeToolStripMenuItem
//
this.removeToolStripMenuItem.Name = "removeToolStripMenuItem";
resources.ApplyResources(this.removeToolStripMenuItem, "removeToolStripMenuItem");
this.removeToolStripMenuItem.Click += new System.EventHandler(this.RemoveMenuItemHandler);
//
// propertiesToolStripMenuItem
//
this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem";
resources.ApplyResources(this.propertiesToolStripMenuItem, "propertiesToolStripMenuItem");
this.propertiesToolStripMenuItem.Click += new System.EventHandler(this.EditMenuItemHandler);
//
// EditButtonContainer
//
this.EditButtonContainer.Controls.Add(this.EditNetworkButton);
resources.ApplyResources(this.EditButtonContainer, "EditButtonContainer");
this.EditButtonContainer.Name = "EditButtonContainer";
//
// EditNetworkButton
//
resources.ApplyResources(this.EditNetworkButton, "EditNetworkButton");
this.EditNetworkButton.Name = "EditNetworkButton";
this.EditNetworkButton.UseVisualStyleBackColor = true;
this.EditNetworkButton.Click += new System.EventHandler(this.EditNetworkButton_Click);
//
// RemoveButtonContainer
//
resources.ApplyResources(this.RemoveButtonContainer, "RemoveButtonContainer");
this.RemoveButtonContainer.Controls.Add(this.RemoveNetworkButton);
this.RemoveButtonContainer.Name = "RemoveButtonContainer";
//
// RemoveNetworkButton
//
resources.ApplyResources(this.RemoveNetworkButton, "RemoveNetworkButton");
this.RemoveNetworkButton.Name = "RemoveNetworkButton";
this.RemoveNetworkButton.UseVisualStyleBackColor = true;
this.RemoveNetworkButton.Click += new System.EventHandler(this.RemoveNetworkButton_Click);
//
// toolTipContainerActivateToggle
//
this.toolTipContainerActivateToggle.Controls.Add(this.buttonActivateToggle);
resources.ApplyResources(this.toolTipContainerActivateToggle, "toolTipContainerActivateToggle");
this.toolTipContainerActivateToggle.Name = "toolTipContainerActivateToggle";
//
// buttonActivateToggle
//
resources.ApplyResources(this.buttonActivateToggle, "buttonActivateToggle");
this.buttonActivateToggle.Name = "buttonActivateToggle";
this.buttonActivateToggle.UseVisualStyleBackColor = true;
this.buttonActivateToggle.Click += new System.EventHandler(this.buttonActivateToggle_Click);
//
// NetworksGridView
//
this.NetworksGridView.AdjustColorsForClassic = false;
resources.ApplyResources(this.NetworksGridView, "NetworksGridView");
this.NetworksGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells;
this.NetworksGridView.BackgroundColor = System.Drawing.SystemColors.Window;
this.NetworksGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.NetworksGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.NetworksGridView.ContextMenuStrip = this.contextMenuStrip1;
this.NetworksGridView.Name = "NetworksGridView";
this.NetworksGridView.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.NetworksGridView_CellValueChanged);
this.NetworksGridView.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.NetworksGridView_SortCompare);
this.NetworksGridView.SelectionChanged += new System.EventHandler(this.NetworksGridView_SelectionChanged);
//
// ImageColumn
//
this.ImageColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ImageColumn, "ImageColumn");
this.ImageColumn.Name = "ImageColumn";
//
// NameColumn
//
this.NameColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.NameColumn, "NameColumn");
this.NameColumn.Name = "NameColumn";
//
// DescriptionColumn
//
this.DescriptionColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.DescriptionColumn, "DescriptionColumn");
this.DescriptionColumn.Name = "DescriptionColumn";
this.DescriptionColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False;
//
// NicColumn
//
this.NicColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.NicColumn, "NicColumn");
this.NicColumn.Name = "NicColumn";
//
// VlanColumn
//
this.VlanColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.VlanColumn, "VlanColumn");
this.VlanColumn.Name = "VlanColumn";
//
// AutoColumn
//
this.AutoColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.AutoColumn, "AutoColumn");
this.AutoColumn.Name = "AutoColumn";
//
// LinkStatusColumn
//
this.LinkStatusColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.LinkStatusColumn, "LinkStatusColumn");
this.LinkStatusColumn.Name = "LinkStatusColumn";
//
// NetworkMacColumn
//
this.NetworkMacColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.NetworkMacColumn, "NetworkMacColumn");
this.NetworkMacColumn.Name = "NetworkMacColumn";
//
// VifMacColumn
//
this.VifMacColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.VifMacColumn, "VifMacColumn");
this.VifMacColumn.Name = "VifMacColumn";
//
// DeviceColumn
//
this.DeviceColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.DeviceColumn, "DeviceColumn");
this.DeviceColumn.Name = "DeviceColumn";
//
// LimitColumn
//
this.LimitColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.LimitColumn, "LimitColumn");
this.LimitColumn.Name = "LimitColumn";
//
// NetworkColumn
//
this.NetworkColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.NetworkColumn, "NetworkColumn");
this.NetworkColumn.Name = "NetworkColumn";
this.NetworkColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False;
//
// IpColumn
//
this.IpColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.IpColumn, "IpColumn");
this.IpColumn.Name = "IpColumn";
this.IpColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False;
//
// ActiveColumn
//
this.ActiveColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ActiveColumn, "ActiveColumn");
this.ActiveColumn.Name = "ActiveColumn";
//
// MtuColumn
//
this.MtuColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.MtuColumn, "MtuColumn");
this.MtuColumn.Name = "MtuColumn";
//
// NetworkList
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.flowLayoutPanel1);
this.Controls.Add(this.NetworksGridView);
this.Name = "NetworkList";
this.flowLayoutPanel1.ResumeLayout(false);
this.contextMenuStrip1.ResumeLayout(false);
this.EditButtonContainer.ResumeLayout(false);
this.RemoveButtonContainer.ResumeLayout(false);
this.toolTipContainerActivateToggle.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.NetworksGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private ToolTipContainer RemoveButtonContainer;
private System.Windows.Forms.Button RemoveNetworkButton;
private ToolTipContainer EditButtonContainer;
private System.Windows.Forms.Button EditNetworkButton;
private System.Windows.Forms.Button AddNetworkButton;
private XenAdmin.Controls.DataGridViewEx.DataGridViewEx NetworksGridView;
private System.Windows.Forms.DataGridViewImageColumn ImageColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn NameColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn DescriptionColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn NicColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn VlanColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn AutoColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn LinkStatusColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn NetworkMacColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn VifMacColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn DeviceColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn LimitColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn NetworkColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn IpColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn ActiveColumn;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem removeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem;
private ToolTipContainer toolTipContainerActivateToggle;
private System.Windows.Forms.Button buttonActivateToggle;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.DataGridViewTextBoxColumn MtuColumn;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Omnius.Base;
namespace Omnius.Net.I2p
{
class SamCommand
{
private List<string> _commands = new List<string>();
private Dictionary<string, string> _parameters = new Dictionary<string, string>();
public SamCommand()
{
}
public SamCommand(string text)
{
var lines = SamCommand.Decode(text);
_commands.Add(lines[0]);
_commands.Add(lines[1]);
foreach (string pair in lines.Skip(2))
{
int equalsPosition = pair.IndexOf('=');
string key;
string value;
if (equalsPosition == -1)
{
key = pair;
value = null;
}
else
{
key = pair.Substring(0, equalsPosition);
value = pair.Substring(equalsPosition + 1);
}
key = !(string.IsNullOrWhiteSpace(key)) ? key : null;
value = !(string.IsNullOrWhiteSpace(value)) ? value : null;
_parameters.Add(key, value);
}
}
public List<string> Commands
{
get
{
return _commands;
}
}
public Dictionary<string, string> Parameters
{
get
{
return _parameters;
}
}
private static string[] Decode(string input)
{
if (input == null) throw new ArgumentNullException(nameof(input));
var builder = new StringBuilder(input.Length);
int begin = 0;
int end;
bool quoting = false;
for (;;)
{
end = input.IndexOf('\"', begin);
if (end == -1) end = input.Length;
string s = input.Substring(begin, end - begin);
if (!quoting) s = s.Replace(' ', '\n');
builder.Append(s);
if (end == input.Length) break;
begin = end + 1;
quoting = !quoting;
}
return builder.ToString().Split('\n');
}
public string GetText()
{
var sb = new StringBuilder();
foreach (string command in _commands)
{
sb.AppendFormat("{0} ", command);
}
foreach (var (key, value) in _parameters)
{
if (value != null)
{
if (!value.Contains(" "))
{
sb.AppendFormat("{0}={1} ", key, value);
}
else
{
sb.AppendFormat("{0}=\"{1}\" ", key, value);
}
}
else
{
sb.AppendFormat("{0} ", key);
}
}
sb.Length = (sb.Length - 1);
return sb.ToString();
}
}
abstract class SamBase
{
private Socket _socket;
private Stream _stream;
private SocketLineReader _reader;
private StreamWriter _writer;
public SamBase(Socket socket)
{
_socket = socket;
{
_stream = new NetworkStream(socket);
_stream.ReadTimeout = Timeout.Infinite;
_stream.WriteTimeout = Timeout.Infinite;
_reader = new SocketLineReader(socket, new UTF8Encoding(false));
_writer = new StreamWriter(_stream, new UTF8Encoding(false), 1024 * 32);
_writer.NewLine = "\n";
}
}
private void Send(SamCommand samCommand)
{
_writer.WriteLine(samCommand.GetText());
_writer.Flush();
}
private SamCommand Receive()
{
string line = _reader.ReadLine();
if (line == null) return null;
return new SamCommand(line);
}
public Socket GetSocket()
{
_stream.Dispose();
_reader.Dispose();
_writer.Dispose();
return _socket;
}
public void Handshake()
{
try
{
{
var samCommand = new SamCommand();
samCommand.Commands.Add("HELLO");
samCommand.Commands.Add("VERSION");
samCommand.Parameters.Add("MIN", "3.0");
samCommand.Parameters.Add("MAX", "3.0");
this.Send(samCommand);
}
{
var samCommand = this.Receive();
if (samCommand.Commands[0] != "HELLO" || samCommand.Commands[1] != "REPLY" || samCommand.Parameters["RESULT"] != "OK")
{
throw new SamException(samCommand.Parameters["RESULT"]);
}
}
}
catch (SamException e)
{
throw e;
}
catch (Exception e)
{
throw new SamException(e.Message, e);
}
}
public string SessionCreate(string sessionId, string caption)
{
try
{
{
var samCommand = new SamCommand();
samCommand.Commands.Add("SESSION");
samCommand.Commands.Add("CREATE");
samCommand.Parameters.Add("STYLE", "STREAM");
samCommand.Parameters.Add("ID", sessionId);
samCommand.Parameters.Add("DESTINATION", "TRANSIENT");
samCommand.Parameters.Add("inbound.nickname", caption);
samCommand.Parameters.Add("outbound.nickname", caption);
this.Send(samCommand);
}
{
var samCommand = this.Receive();
if (samCommand.Commands[0] != "SESSION" || samCommand.Commands[1] != "STATUS")
{
throw new SamException(samCommand.Parameters["RESULT"]);
}
return samCommand.Parameters["DESTINATION"];
}
}
catch (SamException e)
{
throw e;
}
catch (Exception e)
{
throw new SamException(e.Message, e);
}
}
public string NamingLookup(string name)
{
try
{
{
var samCommand = new SamCommand();
samCommand.Commands.Add("NAMING");
samCommand.Commands.Add("LOOKUP");
samCommand.Parameters.Add("NAME", name);
this.Send(samCommand);
}
{
var samCommand = this.Receive();
if (samCommand.Commands[0] != "NAMING" || samCommand.Commands[1] != "REPLY")
{
throw new SamException();
}
return samCommand.Parameters["VALUE"];
}
}
catch (SamException e)
{
throw e;
}
catch (Exception e)
{
throw new SamException(e.Message, e);
}
}
public void StreamConnect(string sessionId, string destination)
{
try
{
{
var samCommand = new SamCommand();
samCommand.Commands.Add("STREAM");
samCommand.Commands.Add("CONNECT");
samCommand.Parameters.Add("ID", sessionId);
samCommand.Parameters.Add("DESTINATION", destination);
samCommand.Parameters.Add("SILENCE", "false");
this.Send(samCommand);
}
{
var samCommand = this.Receive();
if (samCommand.Commands[0] != "STREAM" || samCommand.Commands[1] != "STATUS" || samCommand.Parameters["RESULT"] != "OK")
{
throw new SamException();
}
}
}
catch (SamException e)
{
throw e;
}
catch (Exception e)
{
throw new SamException(e.Message, e);
}
}
public string StreamAccept(string sessionId)
{
try
{
{
var samCommand = new SamCommand();
samCommand.Commands.Add("STREAM");
samCommand.Commands.Add("ACCEPT");
samCommand.Parameters.Add("ID", sessionId);
samCommand.Parameters.Add("SILENCE", "false");
this.Send(samCommand);
}
{
var samCommand = this.Receive();
if (samCommand.Commands[0] != "STREAM" || samCommand.Commands[1] != "STATUS" || samCommand.Parameters["RESULT"] != "OK")
{
throw new SamException();
}
}
return _reader.ReadLine().Split(' ')[0];
}
catch (SamException e)
{
throw e;
}
catch (Exception e)
{
throw new SamException(e.Message, e);
}
}
}
public class SamException : Exception
{
public SamException() : base() { }
public SamException(string message) : base(message) { }
public SamException(string message, Exception innerException) : base(message, innerException) { }
}
}
| |
using Gtk;
using System;
using System.Collections;
namespace Stetic {
internal class Grid : Gtk.Container {
public Grid () : base ()
{
BorderWidth = 2;
WidgetFlags |= WidgetFlags.NoWindow;
lines = new ArrayList ();
tips = new Gtk.Tooltips ();
group = null;
}
Gtk.Tooltips tips;
// Padding constants
const int groupPad = 6;
const int hPad = 6;
const int linePad = 3;
// Theme-based sizes; computed at first SizeRequest
static int indent = -1;
static int lineHeight = -1;
Grid[] group;
public static void Connect (params Grid[] grids)
{
for (int i = 0; i < grids.Length; i++) {
grids[i].group = new Grid[grids.Length - 1];
Array.Copy (grids, 0, grids[i].group, 0, i);
Array.Copy (grids, i + 1, grids[i].group, i, grids.Length - i - 1);
}
}
class Pair {
Gtk.Widget label;
Gtk.Widget editor;
public Pair (Grid grid, string name, Widget editor) : this (grid, name, editor, null) {}
public Pair (Grid grid, string name, Widget editor, string description)
{
Gtk.Label l = new Label (name);
l.UseMarkup = true;
l.Justify = Justification.Left;
l.Xalign = 0;
l.Show ();
if (description == null)
label = l;
else {
Gtk.EventBox ebox = new Gtk.EventBox ();
ebox.Add (l);
ebox.Show ();
grid.tips.SetTip (ebox, description, null);
label = ebox;
}
label.Parent = grid;
this.editor = editor;
editor.Parent = grid;
editor.Show ();
}
public Widget Label {
get {
return label;
}
}
public Widget Editor {
get {
return editor;
}
}
}
// list of widgets and Stetic.Grid.Pairs
ArrayList lines;
public void Append (Widget w)
{
w.Parent = this;
w.Show ();
lines.Add (w);
QueueDraw ();
}
public void Append (Widget w, string description)
{
if ((w.WidgetFlags & WidgetFlags.NoWindow) != 0) {
Gtk.EventBox ebox = new Gtk.EventBox ();
ebox.Add (w);
ebox.Show ();
w = ebox;
}
w.Parent = this;
w.Show ();
tips.SetTip (w, description, null);
lines.Add (w);
QueueDraw ();
}
public void AppendLabel (string text)
{
Gtk.Label label = new Label (text);
label.UseMarkup = true;
label.Justify = Justification.Left;
label.Xalign = 0;
Append (label);
}
public void AppendGroup (string name, bool expanded)
{
Gtk.Expander exp = new Expander ("<b>" + name + "</b>");
exp.UseMarkup = true;
exp.Expanded = expanded;
exp.AddNotification ("expanded", ExpansionChanged);
Append (exp);
}
public void AppendPair (string label, Widget editor, string description)
{
Stetic.Grid.Pair pair = new Pair (this, label, editor, description);
lines.Add (pair);
QueueDraw ();
}
protected override void OnRemoved (Widget w)
{
w.Unparent ();
}
void ExpansionChanged (object obj, GLib.NotifyArgs args)
{
Gtk.Expander exp = obj as Gtk.Expander;
int ind = lines.IndexOf (exp);
if (ind == -1)
return;
ind++;
while (ind < lines.Count && !(lines[ind] is Gtk.Expander)) {
if (lines[ind] is Widget) {
Widget w = (Widget)lines[ind];
if (exp.Expanded)
w.Show ();
else
w.Hide ();
} else if (lines[ind] is Pair) {
Pair p = (Pair)lines[ind];
if (exp.Expanded) {
p.Label.Show ();
p.Editor.Show ();
} else {
p.Label.Hide ();
p.Editor.Hide ();
}
}
ind++;
}
QueueDraw ();
}
protected void Clear ()
{
foreach (object obj in lines) {
if (obj is Widget)
((Widget)obj).Destroy ();
else if (obj is Pair) {
Pair p = (Pair)obj;
p.Label.Destroy ();
p.Editor.Destroy ();
}
}
lines.Clear ();
tips = new Gtk.Tooltips ();
}
protected override void ForAll (bool include_internals, Gtk.Callback callback)
{
if (!include_internals)
return;
foreach (object obj in lines) {
if (obj is Widget)
callback ((Widget)obj);
else if (obj is Pair) {
Pair p = (Pair)obj;
callback (p.Label);
callback (p.Editor);
}
}
}
// These are figured out at requisition time and used again at
// allocation time.
int lwidth, ewidth;
void SizeRequestGrid (Grid grid, ref Gtk.Requisition req)
{
bool visible = true;
req.Width = req.Height = 0;
foreach (object obj in grid.lines) {
if (obj is Expander) {
Gtk.Widget w = (Gtk.Widget)obj;
Gtk.Requisition childreq;
childreq = w.SizeRequest ();
if (req.Width < childreq.Width)
req.Width = childreq.Width;
req.Height += groupPad + childreq.Height;
visible = ((Gtk.Expander)obj).Expanded;
if (indent == -1) {
// Seems like there should be an easier way...
int focusWidth = (int)w.StyleGetProperty ("focus-line-width");
int focusPad = (int)w.StyleGetProperty ("focus-padding");
int expanderSize = (int)w.StyleGetProperty ("expander-size");
int expanderSpacing = (int)w.StyleGetProperty ("expander-spacing");
indent = focusWidth + focusPad + expanderSize + 2 * expanderSpacing;
}
} else if (obj is Widget) {
Gtk.Widget w = (Gtk.Widget)obj;
Gtk.Requisition childreq;
childreq = w.SizeRequest ();
if (lwidth < childreq.Width)
lwidth = childreq.Width;
if (visible)
req.Height += linePad + childreq.Height;
} else if (obj is Pair) {
Pair p = (Pair)obj;
Gtk.Requisition lreq, ereq;
lreq = p.Label.SizeRequest ();
ereq = p.Editor.SizeRequest ();
if (lineHeight == -1)
lineHeight = (int)(1.5 * lreq.Height);
if (lreq.Width > lwidth)
lwidth = lreq.Width;
if (ereq.Width > ewidth)
ewidth = ereq.Width;
if (visible)
req.Height += Math.Max (lineHeight, ereq.Height) + linePad;
}
}
req.Width = Math.Max (req.Width, indent + lwidth + hPad + ewidth);
req.Height += 2 * (int)BorderWidth;
req.Width += 2 * (int)BorderWidth;
}
protected override void OnSizeRequested (ref Gtk.Requisition req)
{
lwidth = ewidth = 0;
if (group != null) {
foreach (Grid grid in group)
SizeRequestGrid (grid, ref req);
}
SizeRequestGrid (this, ref req);
}
protected override void OnSizeAllocated (Gdk.Rectangle alloc)
{
int xbase = alloc.X + (int)BorderWidth;
int ybase = alloc.Y + (int)BorderWidth;
base.OnSizeAllocated (alloc);
int y = ybase;
bool visible = true;
foreach (object obj in lines) {
if (!visible && !(obj is Expander))
continue;
if (obj is Widget) {
Gtk.Widget w = (Gtk.Widget)obj;
if (!w.Visible)
continue;
Gdk.Rectangle childalloc;
Gtk.Requisition childreq;
childreq = w.ChildRequisition;
if (obj is Expander) {
childalloc.X = xbase;
childalloc.Width = alloc.Width - 2 * (int)BorderWidth;
visible = ((Gtk.Expander)obj).Expanded;
y += groupPad;
} else {
childalloc.X = xbase + indent;
childalloc.Width = lwidth;
y += linePad;
}
childalloc.Y = y;
childalloc.Height = childreq.Height;
w.SizeAllocate (childalloc);
y += childalloc.Height;
} else if (obj is Pair) {
Pair p = (Pair)obj;
if (!p.Editor.Visible) {
p.Label.Hide ();
continue;
} else if (!p.Label.Visible)
p.Label.Show ();
Gtk.Requisition lreq, ereq;
Gdk.Rectangle lalloc, ealloc;
lreq = p.Label.ChildRequisition;
ereq = p.Editor.ChildRequisition;
lalloc.X = xbase + indent;
if (ereq.Height < lineHeight * 2)
lalloc.Y = y + (ereq.Height - lreq.Height) / 2;
else
lalloc.Y = y + (lineHeight - lreq.Height) / 2;
lalloc.Width = lwidth;
lalloc.Height = lreq.Height;
p.Label.SizeAllocate (lalloc);
ealloc.X = lalloc.X + lwidth + hPad;
ealloc.Y = y + Math.Max (0, (lineHeight - ereq.Height) / 2);
ealloc.Width = Math.Max (ewidth, alloc.Width - 2 * (int)BorderWidth - ealloc.X);
ealloc.Height = ereq.Height;
p.Editor.SizeAllocate (ealloc);
y += Math.Max (ereq.Height, lineHeight) + linePad;
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Net;
using System.Text;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Nini.Config;
using log4net;
namespace OpenSim.Server.Handlers.Simulation
{
public class AgentHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
protected bool m_Proxy = false;
public AgentHandler() { }
public AgentHandler(ISimulationService sim)
{
m_SimulationService = sim;
}
public Hashtable Handler(Hashtable request)
{
// m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
//
// m_log.Debug("---------------------------");
// m_log.Debug(" >> uri=" + request["uri"]);
// m_log.Debug(" >> content-type=" + request["content-type"]);
// m_log.Debug(" >> http-method=" + request["http-method"]);
// m_log.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
responsedata["keepalive"] = false;
UUID agentID;
UUID regionID;
string action;
if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action))
{
m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
// Next, let's parse the verb
string method = (string)request["http-method"];
if (method.Equals("PUT"))
{
DoAgentPut(request, responsedata);
return responsedata;
}
else if (method.Equals("POST"))
{
DoAgentPost(request, responsedata, agentID);
return responsedata;
}
else if (method.Equals("GET"))
{
DoAgentGet(request, responsedata, agentID, regionID);
return responsedata;
}
else if (method.Equals("DELETE"))
{
DoAgentDelete(request, responsedata, agentID, action, regionID);
return responsedata;
}
else
{
m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method);
responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
responsedata["str_response_string"] = "Method not allowed";
return responsedata;
}
}
protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
{
OSDMap args = Utils.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
uint teleportFlags = 0;
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
else
m_log.WarnFormat(" -- request didn't have destination_x");
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
else
m_log.WarnFormat(" -- request didn't have destination_y");
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
teleportFlags = args["teleport_flags"].AsUInteger();
GridRegion destination = new GridRegion();
destination.RegionID = uuid;
destination.RegionLocX = x;
destination.RegionLocY = y;
destination.RegionName = regionname;
AgentCircuitData aCircuit = new AgentCircuitData();
try
{
aCircuit.UnpackAgentCircuitData(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
OSDMap resp = new OSDMap(2);
string reason = String.Empty;
// This is the meaning of POST agent
//m_regionClient.AdjustUserInformation(aCircuit);
//bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
bool result = CreateAgent(destination, aCircuit, teleportFlags, out reason);
resp["reason"] = OSD.FromString(reason);
resp["success"] = OSD.FromBoolean(result);
// Let's also send out the IP address of the caller back to the caller (HG 1.5)
resp["your_ip"] = OSD.FromString(GetCallerIP(request));
// TODO: add reason if not String.Empty?
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
}
private string GetCallerIP(Hashtable request)
{
if (!m_Proxy)
return Util.GetCallerIP(request);
// We're behind a proxy
Hashtable headers = (Hashtable)request["headers"];
if (headers.ContainsKey("X-Forwarded-For") && headers["X-Forwarded-For"] != null)
{
IPEndPoint ep = Util.GetClientIPFromXFF((string)headers["X-Forwarded-For"]);
if (ep != null)
return ep.Address.ToString();
}
// Oops
return Util.GetCallerIP(request);
}
// subclasses can override this
protected virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
{
return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
}
protected void DoAgentPut(Hashtable request, Hashtable responsedata)
{
OSDMap args = Utils.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
GridRegion destination = new GridRegion();
destination.RegionID = uuid;
destination.RegionLocX = x;
destination.RegionLocY = y;
destination.RegionName = regionname;
string messageType;
if (args["message_type"] != null)
messageType = args["message_type"].AsString();
else
{
m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
messageType = "AgentData";
}
bool result = true;
if ("AgentData".Equals(messageType))
{
AgentData agent = new AgentData();
try
{
agent.Unpack(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = UpdateAgent(destination, agent);
}
else if ("AgentPosition".Equals(messageType))
{
AgentPosition agent = new AgentPosition();
try
{
agent.Unpack(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = m_SimulationService.UpdateAgent(destination, agent);
}
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = result.ToString();
//responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead
}
// subclasses can override this
protected virtual bool UpdateAgent(GridRegion destination, AgentData agent)
{
return m_SimulationService.UpdateAgent(destination, agent);
}
protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID)
{
if (m_SimulationService == null)
{
m_log.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless.");
responsedata["content_type"] = "application/json";
responsedata["int_response_code"] = HttpStatusCode.NotImplemented;
responsedata["str_response_string"] = string.Empty;
return;
}
GridRegion destination = new GridRegion();
destination.RegionID = regionID;
IAgentData agent = null;
bool result = m_SimulationService.RetrieveAgent(destination, id, out agent);
OSDMap map = null;
if (result)
{
if (agent != null) // just to make sure
{
map = agent.Pack();
string strBuffer = "";
try
{
strBuffer = OSDParser.SerializeJsonString(map);
}
catch (Exception e)
{
m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.Message);
responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
// ignore. buffer will be empty, caller should check.
}
responsedata["content_type"] = "application/json";
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = strBuffer;
}
else
{
responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
responsedata["str_response_string"] = "Internal error";
}
}
else
{
responsedata["int_response_code"] = HttpStatusCode.NotFound;
responsedata["str_response_string"] = "Not Found";
}
}
protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID)
{
m_log.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID);
GridRegion destination = new GridRegion();
destination.RegionID = regionID;
if (action.Equals("release"))
ReleaseAgent(regionID, id);
else
m_SimulationService.CloseAgent(destination, id);
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
m_log.Debug("[AGENT HANDLER]: Agent Released/Deleted.");
}
protected virtual void ReleaseAgent(UUID regionID, UUID id)
{
m_SimulationService.ReleaseAgent(regionID, id, "");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Content.Server.Construction;
using Content.Server.Construction.Components;
using Content.Server.Ghost.Components;
using Content.Server.Tools;
using Content.Shared.Acts;
using Content.Shared.Body.Components;
using Content.Shared.Foldable;
using Content.Shared.Interaction;
using Content.Shared.Item;
using Content.Shared.Physics;
using Content.Shared.Placeable;
using Content.Shared.Popups;
using Content.Shared.Sound;
using Content.Shared.Storage;
using Content.Shared.Tools;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Player;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.ViewVariables;
namespace Content.Server.Storage.Components
{
[RegisterComponent]
[Virtual]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(IStorageComponent))]
public class EntityStorageComponent : Component, IActivate, IStorageComponent, IInteractUsing, IDestroyAct, IExAct
{
[Dependency] private readonly IEntityManager _entMan = default!;
private const float MaxSize = 1.0f; // maximum width or height of an entity allowed inside the storage.
public static readonly TimeSpan InternalOpenAttemptDelay = TimeSpan.FromSeconds(0.5);
public TimeSpan LastInternalOpenAttempt;
private const int OpenMask = (int) (
CollisionGroup.MobImpassable |
CollisionGroup.VaultImpassable |
CollisionGroup.SmallImpassable);
[ViewVariables]
[DataField("Capacity")]
private int _storageCapacityMax = 30;
[ViewVariables]
[DataField("IsCollidableWhenOpen")]
private bool _isCollidableWhenOpen;
[ViewVariables]
[DataField("EnteringRange")]
private float _enteringRange = -0.4f;
[DataField("showContents")]
private bool _showContents;
[DataField("occludesLight")]
private bool _occludesLight = true;
[DataField("open")]
private bool _open;
[DataField("weldingQuality", customTypeSerializer:typeof(PrototypeIdSerializer<ToolQualityPrototype>))]
private string _weldingQuality = "Welding";
[DataField("CanWeldShut")]
private bool _canWeldShut = true;
[DataField("IsWeldedShut")]
private bool _isWeldedShut;
[DataField("closeSound")]
private SoundSpecifier _closeSound = new SoundPathSpecifier("/Audio/Effects/closetclose.ogg");
[DataField("openSound")]
private SoundSpecifier _openSound = new SoundPathSpecifier("/Audio/Effects/closetopen.ogg");
[ViewVariables]
public Container Contents = default!;
/// <summary>
/// Determines if the container contents should be drawn when the container is closed.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public bool ShowContents
{
get => _showContents;
set
{
_showContents = value;
Contents.ShowContents = _showContents;
}
}
[ViewVariables(VVAccess.ReadWrite)]
public bool OccludesLight
{
get => _occludesLight;
set
{
_occludesLight = value;
Contents.OccludesLight = _occludesLight;
}
}
[ViewVariables(VVAccess.ReadWrite)]
public bool Open
{
get => _open;
private set => _open = value;
}
[ViewVariables(VVAccess.ReadWrite)]
public bool IsWeldedShut
{
get => _isWeldedShut;
set
{
if (_isWeldedShut == value) return;
_isWeldedShut = value;
UpdateAppearance();
}
}
private bool _beingWelded;
[ViewVariables(VVAccess.ReadWrite)]
public bool CanWeldShut
{
get => _canWeldShut;
set
{
if (_canWeldShut == value) return;
_canWeldShut = value;
UpdateAppearance();
}
}
[ViewVariables(VVAccess.ReadWrite)]
public float EnteringRange
{
get => _enteringRange;
set => _enteringRange = value;
}
/// <inheritdoc />
protected override void Initialize()
{
base.Initialize();
Contents = Owner.EnsureContainer<Container>(nameof(EntityStorageComponent));
Contents.ShowContents = _showContents;
Contents.OccludesLight = _occludesLight;
if(_entMan.TryGetComponent(Owner, out ConstructionComponent? construction))
EntitySystem.Get<ConstructionSystem>().AddContainer(Owner, Contents.ID, construction);
if (_entMan.TryGetComponent<PlaceableSurfaceComponent?>(Owner, out var surface))
{
EntitySystem.Get<PlaceableSurfaceSystem>().SetPlaceable(Owner, Open, surface);
}
UpdateAppearance();
}
public virtual void Activate(ActivateEventArgs eventArgs)
{
ToggleOpen(eventArgs.User);
}
public virtual bool CanOpen(EntityUid user, bool silent = false)
{
if (IsWeldedShut)
{
if (!silent && !Contents.Contains(user))
Owner.PopupMessage(user, Loc.GetString("entity-storage-component-welded-shut-message"));
return false;
}
if (_entMan.TryGetComponent<LockComponent?>(Owner, out var @lock) && @lock.Locked)
{
if (!silent) Owner.PopupMessage(user, Loc.GetString("entity-storage-component-locked-message"));
return false;
}
var @event = new StorageOpenAttemptEvent();
IoCManager.Resolve<IEntityManager>().EventBus.RaiseLocalEvent(Owner, @event);
return !@event.Cancelled;
}
public virtual bool CanClose(EntityUid user, bool silent = false)
{
var @event = new StorageCloseAttemptEvent();
IoCManager.Resolve<IEntityManager>().EventBus.RaiseLocalEvent(Owner, @event);
return !@event.Cancelled;
}
public void ToggleOpen(EntityUid user)
{
if (Open)
{
TryCloseStorage(user);
}
else
{
TryOpenStorage(user);
}
}
protected virtual void CloseStorage()
{
Open = false;
var count = 0;
foreach (var entity in DetermineCollidingEntities())
{
// prevents taking items out of inventories, out of containers, and orphaning child entities
if (entity.IsInContainer())
continue;
// conditions are complicated because of pizzabox-related issues, so follow this guide
// 0. Accomplish your goals at all costs.
// 1. AddToContents can block anything
// 2. maximum item count can block anything
// 3. ghosts can NEVER be eaten
// 4. items can always be eaten unless a previous law prevents it
// 5. if this is NOT AN ITEM, then mobs can always be eaten unless unless a previous law prevents it
// 6. if this is an item, then mobs must only be eaten if some other component prevents pick-up interactions while a mob is inside (e.g. foldable)
// Let's not insert admin ghosts, yeah? This is really a a hack and should be replaced by attempt events
if (_entMan.HasComponent<GhostComponent>(entity))
continue;
// checks
var targetIsItem = _entMan.HasComponent<SharedItemComponent>(entity);
var targetIsMob = _entMan.HasComponent<SharedBodyComponent>(entity);
var storageIsItem = _entMan.HasComponent<SharedItemComponent>(Owner);
var allowedToEat = false;
if (targetIsItem)
allowedToEat = true;
// BEFORE REPLACING THIS WITH, I.E. A PROPERTY:
// Make absolutely 100% sure you have worked out how to stop people ending up in backpacks.
// Seriously, it is insanely hacky and weird to get someone out of a backpack once they end up in there.
// And to be clear, they should NOT be in there.
// For the record, what you need to do is empty the backpack onto a PlacableSurface (table, rack)
if (targetIsMob)
{
if (!storageIsItem)
allowedToEat = true;
else
{
// make an exception if this is a foldable-item that is currently un-folded (e.g., body bags).
allowedToEat = _entMan.TryGetComponent(Owner, out FoldableComponent? foldable) && !foldable.IsFolded;
}
}
if (!allowedToEat)
continue;
// finally, AddToContents
if (!AddToContents(entity))
continue;
count++;
if (count >= _storageCapacityMax)
{
break;
}
}
ModifyComponents();
SoundSystem.Play(Filter.Pvs(Owner), _closeSound.GetSound(), Owner);
LastInternalOpenAttempt = default;
}
protected virtual void OpenStorage()
{
Open = true;
EmptyContents();
ModifyComponents();
SoundSystem.Play(Filter.Pvs(Owner), _openSound.GetSound(), Owner);
}
private void UpdateAppearance()
{
if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance))
{
appearance.SetData(StorageVisuals.CanWeld, _canWeldShut);
appearance.SetData(StorageVisuals.Welded, _isWeldedShut);
}
}
private void ModifyComponents()
{
if (!_isCollidableWhenOpen && _entMan.TryGetComponent<FixturesComponent?>(Owner, out var manager))
{
if (Open)
{
foreach (var (_, fixture) in manager.Fixtures)
{
fixture.CollisionLayer &= ~OpenMask;
}
}
else
{
foreach (var (_, fixture) in manager.Fixtures)
{
fixture.CollisionLayer |= OpenMask;
}
}
}
if (_entMan.TryGetComponent<PlaceableSurfaceComponent?>(Owner, out var surface))
{
EntitySystem.Get<PlaceableSurfaceSystem>().SetPlaceable(Owner, Open, surface);
}
if (_entMan.TryGetComponent(Owner, out AppearanceComponent? appearance))
{
appearance.SetData(StorageVisuals.Open, Open);
}
}
protected virtual bool AddToContents(EntityUid entity)
{
if (entity == Owner) return false;
if (_entMan.TryGetComponent(entity, out IPhysBody? entityPhysicsComponent))
{
if (MaxSize < entityPhysicsComponent.GetWorldAABB().Size.X
|| MaxSize < entityPhysicsComponent.GetWorldAABB().Size.Y)
{
return false;
}
}
return Contents.CanInsert(entity) && Insert(entity);
}
public virtual Vector2 ContentsDumpPosition()
{
return _entMan.GetComponent<TransformComponent>(Owner).WorldPosition;
}
private void EmptyContents()
{
foreach (var contained in Contents.ContainedEntities.ToArray())
{
if (Contents.Remove(contained))
{
_entMan.GetComponent<TransformComponent>(contained).WorldPosition = ContentsDumpPosition();
if (_entMan.TryGetComponent<IPhysBody?>(contained, out var physics))
{
physics.CanCollide = true;
}
}
}
}
public virtual bool TryOpenStorage(EntityUid user)
{
if (!CanOpen(user)) return false;
OpenStorage();
return true;
}
public virtual bool TryCloseStorage(EntityUid user)
{
if (!CanClose(user)) return false;
CloseStorage();
return true;
}
/// <inheritdoc />
public bool Remove(EntityUid entity)
{
return Contents.CanRemove(entity);
}
/// <inheritdoc />
public bool Insert(EntityUid entity)
{
// Trying to add while open just dumps it on the ground below us.
if (Open)
{
var entMan = _entMan;
entMan.GetComponent<TransformComponent>(entity).WorldPosition = entMan.GetComponent<TransformComponent>(Owner).WorldPosition;
return true;
}
return Contents.Insert(entity);
}
/// <inheritdoc />
public bool CanInsert(EntityUid entity)
{
if (Open)
{
return true;
}
if (Contents.ContainedEntities.Count >= _storageCapacityMax)
{
return false;
}
return Contents.CanInsert(entity);
}
async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs)
{
if (_beingWelded)
return false;
if (Open)
{
_beingWelded = false;
return false;
}
if (!CanWeldShut)
{
_beingWelded = false;
return false;
}
if (Contents.Contains(eventArgs.User))
{
_beingWelded = false;
Owner.PopupMessage(eventArgs.User, Loc.GetString("entity-storage-component-already-contains-user-message"));
return false;
}
if (_beingWelded)
return false;
_beingWelded = true;
var toolSystem = EntitySystem.Get<ToolSystem>();
if (!await toolSystem.UseTool(eventArgs.Using, eventArgs.User, Owner, 1f, 1f, _weldingQuality))
{
_beingWelded = false;
return false;
}
_beingWelded = false;
IsWeldedShut ^= true;
return true;
}
void IDestroyAct.OnDestroy(DestructionEventArgs eventArgs)
{
Open = true;
EmptyContents();
}
protected virtual IEnumerable<EntityUid> DetermineCollidingEntities()
{
var entityLookup = EntitySystem.Get<EntityLookupSystem>();
return entityLookup.GetEntitiesIntersecting(Owner, _enteringRange, LookupFlags.Approximate);
}
void IExAct.OnExplosion(ExplosionEventArgs eventArgs)
{
if (eventArgs.Severity < ExplosionSeverity.Heavy)
{
return;
}
var containedEntities = Contents.ContainedEntities.ToList();
foreach (var entity in containedEntities)
{
var exActs = _entMan.GetComponents<IExAct>(entity).ToArray();
foreach (var exAct in exActs)
{
exAct.OnExplosion(eventArgs);
}
}
}
}
public sealed class StorageOpenAttemptEvent : CancellableEntityEventArgs
{
}
public sealed class StorageCloseAttemptEvent : CancellableEntityEventArgs
{
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Web.Routing;
#if !MVC2
using HtmlHelperKludge = System.Web.Mvc.HtmlHelper;
#endif
namespace System.Web.Mvc.Html
{
/// <summary>
/// InputExtensionsEx
/// </summary>
public static class InputExtensionsEx
{
/// <summary>
/// Checks the box for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MvcHtmlString CheckBoxForEx<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression) { return CheckBoxForEx<TModel>(htmlHelper, expression, (IDictionary<string, object>)null); }
/// <summary>
/// Checks the box for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString CheckBoxForEx<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes) { return CheckBoxForEx<TModel>(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); }
/// <summary>
/// Checks the box for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString CheckBoxForEx<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, IDictionary<string, object> htmlAttributes)
{
IEnumerable<IInputViewModifier> modifier;
var metadata = ModelMetadata.FromLambdaExpression<TModel, bool>(expression, htmlHelper.ViewData);
if (metadata != null && metadata.TryGetExtent<IEnumerable<IInputViewModifier>>(out modifier))
modifier.MapInputToHtmlAttributes(ref expression, ref htmlAttributes);
return htmlHelper.CheckBoxFor<TModel>(expression, htmlAttributes);
}
/// <summary>
/// Hiddens for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MvcHtmlString HiddenForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { return HiddenForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)null); }
/// <summary>
/// Hiddens for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString HiddenForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { return HiddenForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); }
/// <summary>
/// Hiddens for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString HiddenForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
IEnumerable<IInputViewModifier> modifier;
var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
if (metadata != null && metadata.TryGetExtent<IEnumerable<IInputViewModifier>>(out modifier))
modifier.MapInputToHtmlAttributes(ref expression, ref htmlAttributes);
return htmlHelper.HiddenFor<TModel, TProperty>(expression, htmlAttributes);
}
/// <summary>
/// Passwords for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MvcHtmlString PasswordForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { return PasswordForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)null); }
/// <summary>
/// Passwords for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString PasswordForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { return PasswordForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); }
/// <summary>
/// Passwords for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString PasswordForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
IEnumerable<IInputViewModifier> modifier;
var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
if (metadata != null && metadata.TryGetExtent<IEnumerable<IInputViewModifier>>(out modifier))
modifier.MapInputToHtmlAttributes(ref expression, ref htmlAttributes);
return htmlHelper.PasswordFor<TModel, TProperty>(expression, htmlAttributes);
}
/// <summary>
/// Radioes the button for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static MvcHtmlString RadioButtonForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value) { return RadioButtonForEx<TModel, TProperty>(htmlHelper, expression, value, (IDictionary<string, object>)null); }
/// <summary>
/// Radioes the button for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="value">The value.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString RadioButtonForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes) { return RadioButtonForEx<TModel, TProperty>(htmlHelper, expression, value, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); }
/// <summary>
/// Radioes the button for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="value">The value.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString RadioButtonForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
{
IEnumerable<IInputViewModifier> modifier;
var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
if (metadata != null && metadata.TryGetExtent<IEnumerable<IInputViewModifier>>(out modifier))
modifier.MapInputToHtmlAttributes(ref expression, ref htmlAttributes);
return htmlHelper.RadioButtonFor<TModel, TProperty>(expression, value, htmlAttributes);
}
/// <summary>
/// Texts the box for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MvcHtmlString TextBoxForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { return TextBoxForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)null); }
/// <summary>
/// Texts the box for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString TextBoxForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { return TextBoxForEx<TModel, TProperty>(htmlHelper, expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); }
/// <summary>
/// Texts the box for ex.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <param name="htmlAttributes">The HTML attributes.</param>
/// <returns></returns>
public static MvcHtmlString TextBoxForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
IEnumerable<IInputViewModifier> modifier;
var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
if (metadata != null && metadata.TryGetExtent<IEnumerable<IInputViewModifier>>(out modifier))
modifier.MapInputToHtmlAttributes(ref expression, ref htmlAttributes);
return htmlHelper.TextBoxFor<TModel, TProperty>(expression, htmlAttributes);
}
}
}
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.OSM.OSMClassExtension;
using ESRI.ArcGIS.Display;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("091c4384-8aa5-4d4d-8c30-fafb1ca81b86")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.OSMGPCombineAttributes")]
public class OSMGPCombineAttributes : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = String.Empty;
int in_osmFeatureClassNumber, in_attributeSelectorNumber, out_osmFeatureClassNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
public OSMGPCombineAttributes()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
osmGPFactory = new OSMGPFactory();
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return default(ESRI.ArcGIS.esriSystem.UID);
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_CombineAttributesName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 execute_Utilities = new GPUtilitiesClass();
OSMUtility osmUtility = new OSMUtility();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClassNumber) as IGPParameter;
IGPValue inputOSMGPValue = execute_Utilities.UnpackGPValue(inputOSMParameter);
IGPParameter tagFieldsParameter = paramvalues.get_Element(in_attributeSelectorNumber) as IGPParameter;
IGPMultiValue tagCollectionGPValue = execute_Utilities.UnpackGPValue(tagFieldsParameter) as IGPMultiValue;
if (tagCollectionGPValue == null)
{
message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), tagFieldsParameter.Name));
return;
}
IFeatureClass osmFeatureClass = null;
ITable osmInputTable = null;
IQueryFilter osmQueryFilter = null;
try
{
execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
osmInputTable = osmFeatureClass as ITable;
}
catch { }
try
{
if (osmInputTable == null)
{
execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter);
}
}
catch { }
if (osmInputTable == null)
{
return;
}
// find the field that holds tag binary/xml field
int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags");
// if the Field doesn't exist - wasn't found (index = -1) get out
if (osmTagCollectionFieldIndex == -1)
{
message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound"));
return;
}
// set up the progress indicator
IStepProgressor stepProgressor = TrackCancel as IStepProgressor;
if (stepProgressor != null)
{
int featureCount = osmInputTable.RowCount(osmQueryFilter);
stepProgressor.MinRange = 0;
stepProgressor.MaxRange = featureCount;
stepProgressor.Position = 0;
stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPCombineAttributes_progressMessage");
stepProgressor.StepValue = 1;
stepProgressor.Show();
}
String illegalCharacters = String.Empty;
ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax;
if (sqlSyntax != null)
{
illegalCharacters = sqlSyntax.GetInvalidCharacters();
}
// establish the list of field indexes only once
Dictionary<string, int> fieldIndexes = new Dictionary<string, int>();
for (int selectedGPValueIndex = 0; selectedGPValueIndex < tagCollectionGPValue.Count; selectedGPValueIndex++)
{
// find the field index
int fieldIndex = osmInputTable.FindField(tagCollectionGPValue.get_Value(selectedGPValueIndex).GetAsText());
if (fieldIndex != -1)
{
string tagKeyName = osmInputTable.Fields.get_Field(fieldIndex).Name;
tagKeyName = OSMToolHelper.convert2OSMKey(tagKeyName, illegalCharacters);
fieldIndexes.Add(tagKeyName, fieldIndex);
}
}
ICursor updateCursor = null;
IRow osmRow = null;
using (ComReleaser comReleaser = new ComReleaser())
{
updateCursor = osmInputTable.Update(osmQueryFilter, false);
comReleaser.ManageLifetime(updateCursor);
osmRow = updateCursor.NextRow();
int progressIndex = 0;
while (osmRow != null)
{
// get the current tag collection from the row
ESRI.ArcGIS.OSM.OSMClassExtension.tag[] osmTags = osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace);
Dictionary<string, string> tagsDictionary = new Dictionary<string, string>();
for (int tagIndex = 0; tagIndex < osmTags.Length; tagIndex++)
{
tagsDictionary.Add(osmTags[tagIndex].k, osmTags[tagIndex].v);
}
// look if the tag needs to be updated or added
bool tagsUpdated = false;
foreach (var fieldItem in fieldIndexes)
{
object fldValue = osmRow.get_Value(fieldItem.Value);
if (fldValue != System.DBNull.Value)
{
if (tagsDictionary.ContainsKey(fieldItem.Key))
{
if (!tagsDictionary[fieldItem.Key].Equals(fldValue))
{
tagsDictionary[fieldItem.Key] = Convert.ToString(fldValue);
tagsUpdated = true;
}
}
else
{
tagsDictionary.Add(fieldItem.Key, Convert.ToString(fldValue));
tagsUpdated = true;
}
}
}
if (tagsUpdated)
{
List<ESRI.ArcGIS.OSM.OSMClassExtension.tag> updatedTags = new List<ESRI.ArcGIS.OSM.OSMClassExtension.tag>();
foreach (var tagItem in tagsDictionary)
{
ESRI.ArcGIS.OSM.OSMClassExtension.tag newTag = new ESRI.ArcGIS.OSM.OSMClassExtension.tag();
newTag.k = tagItem.Key;
newTag.v = tagItem.Value;
updatedTags.Add(newTag);
}
// insert the tags back into the collection field
if (updatedTags.Count != 0)
{
osmUtility.insertOSMTags(osmTagCollectionFieldIndex, osmRow, updatedTags.ToArray(), ((IDataset)osmInputTable).Workspace);
updateCursor.UpdateRow(osmRow);
}
}
progressIndex++;
if (stepProgressor != null)
{
stepProgressor.Position = progressIndex;
}
if (osmRow != null)
Marshal.ReleaseComObject(osmRow);
osmRow = updateCursor.NextRow();
}
if (stepProgressor != null)
{
stepProgressor.Hide();
}
}
}
catch (Exception ex)
{
message.AddError(120007, ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_CombineAttributesName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return null;
}
public int HelpContext
{
get
{
return 0;
}
}
public string HelpFile
{
get
{
return default(string);
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "osmgpcombineattributes.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpcombineattributes_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpcombineattributes_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_CombineAttributesName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
IArray parameterArray = new ArrayClass();
// input osm feature class
IGPParameterEdit3 inputFeatureClass = new GPParameterClass() as IGPParameterEdit3;
IGPCompositeDataType inputCompositeDataType = new GPCompositeDataTypeClass();
inputCompositeDataType.AddDataType(new GPFeatureLayerTypeClass());
inputCompositeDataType.AddDataType(new GPTableViewTypeClass());
inputFeatureClass.DataType = (IGPDataType)inputCompositeDataType;
inputFeatureClass.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputFeatureClass.DisplayName = resourceManager.GetString("GPTools_OSMGPCombineAttributes_inputlayer_displayname");
inputFeatureClass.Name = "in_osmfeatureclass";
inputFeatureClass.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_osmFeatureClassNumber = 0;
parameterArray.Add(inputFeatureClass);
//// attribute multi select parameter
IGPParameterEdit3 attributeSelect = new GPParameterClass() as IGPParameterEdit3;
IGPDataType tagKeyDataType = new GPStringTypeClass();
IGPMultiValue tagKeysMultiValue = new GPMultiValueClass();
tagKeysMultiValue.MemberDataType = tagKeyDataType;
IGPCodedValueDomain tagKeyDomains = new GPCodedValueDomainClass();
tagKeyDomains.AddStringCode("", "");
IGPMultiValueType tagKeyDataType2 = new GPMultiValueTypeClass();
tagKeyDataType2.MemberDataType = tagKeyDataType;
attributeSelect.Name = "in_attributeselect";
attributeSelect.DisplayName = resourceManager.GetString("GPTools_OSMGPCombineAttributes_inputAttributes_displayname");
attributeSelect.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
attributeSelect.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
attributeSelect.Domain = (IGPDomain)tagKeyDomains;
attributeSelect.DataType = (IGPDataType)tagKeyDataType2;
attributeSelect.Value = (IGPValue)tagKeysMultiValue;
in_attributeSelectorNumber = 1;
parameterArray.Add(attributeSelect);
// output is the derived feature class
IGPParameterEdit3 outputFeatureClass = new GPParameterClass() as IGPParameterEdit3;
outputFeatureClass.DataType = new GPFeatureLayerTypeClass();
outputFeatureClass.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
outputFeatureClass.DisplayName = resourceManager.GetString("GPTools_OSMGPAttributeSelector_outputFeatureClass");
outputFeatureClass.Name = "out_osmfeatureclass";
outputFeatureClass.ParameterType = esriGPParameterType.esriGPParameterTypeDerived;
outputFeatureClass.AddDependency("in_osmfeatureclass");
out_osmFeatureClassNumber = 2;
parameterArray.Add(outputFeatureClass);
return parameterArray;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
for (int i = 0; i < Messages.Count; i++)
{
IGPMessage blah = Messages.GetMessage(i);
if (blah.IsError())
{
IGPMessage something = new GPMessageClass();
something.Description = String.Empty;
something.Type = esriGPMessageType.esriGPMessageTypeInformative;
something.ErrorCode = 0;
Messages.Replace(i, something);
}
}
IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClassNumber) as IGPParameter;
IGPValue inputOSMGPValue = gpUtilities3.UnpackGPValue(inputOSMParameter);
if (inputOSMGPValue.IsEmpty() == false)
{
IFeatureClass osmFeatureClass = null;
ITable osmInputTable = null;
IQueryFilter osmQueryFilter = null;
try
{
gpUtilities3.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
osmInputTable = osmFeatureClass as ITable;
}
catch { }
try
{
if (osmInputTable == null)
{
gpUtilities3.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter);
}
}
catch { }
if (osmInputTable == null)
{
return;
}
// find the field that holds tag binary/xml field
int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags");
if (osmTagCollectionFieldIndex == -1)
{
Messages.ReplaceAbort(in_osmFeatureClassNumber, resourceManager.GetString("GPTools_OSMGPCombineAttributes_inputlayer_missingtagfield"));
return;
}
}
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
try
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClassNumber) as IGPParameter;
IGPValue inputOSMGPValue = gpUtilities3.UnpackGPValue(inputOSMParameter);
if (inputOSMGPValue.IsEmpty() == false)
{
if (inputOSMParameter.Altered == true)
{
IGPParameter attributeCollectionParameter = paramvalues.get_Element(in_attributeSelectorNumber) as IGPParameter;
IGPValue attributeCollectionGPValue = gpUtilities3.UnpackGPValue(attributeCollectionParameter);
if (inputOSMParameter.HasBeenValidated == false && ((IGPMultiValue)attributeCollectionGPValue).Count == 0)
{
IFeatureClass osmFeatureClass = null;
ITable osmInputTable = null;
IQueryFilter osmQueryFilter = null;
try
{
gpUtilities3.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
osmInputTable = osmFeatureClass as ITable;
}
catch { }
try
{
if (osmInputTable == null)
{
gpUtilities3.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter);
}
}
catch { }
if (osmInputTable == null)
{
return;
}
using (ComReleaser comReleaser = new ComReleaser())
{
ICursor osmCursor = osmInputTable.Search(osmQueryFilter, true);
comReleaser.ManageLifetime(osmCursor);
IRow osmRow = osmCursor.NextRow();
List<string> potentialOSMFields = new List<string>();
if (osmRow != null)
{
IFields osmFields = osmRow.Fields;
for (int fieldIndex = 0; fieldIndex < osmFields.FieldCount; fieldIndex++)
{
if (osmFields.get_Field(fieldIndex).Name.Substring(0, 4).Equals("osm_"))
{
potentialOSMFields.Add(osmFields.get_Field(fieldIndex).Name);
}
}
}
if (potentialOSMFields.Count == 0)
{
return;
}
IGPCodedValueDomain osmTagKeyCodedValues = new GPCodedValueDomainClass();
foreach (string tagOSMField in potentialOSMFields)
{
osmTagKeyCodedValues.AddStringCode(tagOSMField, tagOSMField);
}
((IGPParameterEdit)attributeCollectionParameter).Domain = (IGPDomain)osmTagKeyCodedValues;
}
}
}
}
}
catch { }
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BigFileTest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace DMLibTest
{
using System;
using DMLibTestCodeGen;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MS.Test.Common.MsTestLib;
[MultiDirectionTestClass]
public class BlockSizeTest : DMLibTestBase
#if DNXCORE50
, IDisposable
#endif
{
#region Initialization and cleanup methods
#if DNXCORE50
public BlockSizeTest()
{
MyTestInitialize();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
MyTestCleanup();
}
#endif
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
Test.Info("Class Initialize: BigFileTest");
DMLibTestBase.BaseClassInitialize(testContext);
}
[ClassCleanup()]
public static void MyClassCleanup()
{
DMLibTestBase.BaseClassCleanup();
}
[TestInitialize()]
public void MyTestInitialize()
{
base.BaseTestInitialize();
}
[TestCleanup()]
public void MyTestCleanup()
{
base.BaseTestCleanup();
}
#endregion
[TestCategory(Tag.Function)]
[DMLibTestMethod(DMLibDataType.Local | DMLibDataType.BlockBlob | DMLibDataType.CloudFile | DMLibDataType.Stream, DMLibDataType.BlockBlob)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
[DMLibTestMethod(DMLibDataType.CloudFile, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
public void ToLbb_8MBBlockSizeAndSmallFiles()
{
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, 36*1024); // 36MB
for (int i = 0; i < 10; i++)
{
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + i, i);
}
var options = new TestExecutionOptions<DMLibDataInfo>()
{
BlockSize = 8 * 1024 * 1024 // 8MB
};
var result = this.ExecuteTestCase(sourceDataInfo, options);
Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
this.ValidateDestinationMD5ByDownloading(result.DataInfo, options);
}
[TestCategory(Tag.Function)]
[DMLibTestMethod(DMLibDataType.Local | DMLibDataType.BlockBlob | DMLibDataType.CloudFile | DMLibDataType.Stream, DMLibDataType.BlockBlob)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
[DMLibTestMethod(DMLibDataType.CloudFile, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
public void ToLbb_16MBBlockSizeAndSmallFiles()
{
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + 36 + "MB", 36 * 1024); // 36MB, should use 16MB block size, PutBlock and PutBlockList
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + 16 + "MB", 16 * 1024); // 16MB, should use 16MB block size, PutBlob
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + 14 + "MB", 14 * 1024); // 14MB, should use 16MB block size, PutBlob
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + 8 + "MB", 8 * 1024); // 8MB, should use 8MB block size, PutBlob
for (int i = 0; i < 2; i++)
{
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + i, i); // 0 and 1KB file
}
var options = new TestExecutionOptions<DMLibDataInfo>()
{
BlockSize = 16 * 1024 * 1024 // 16MB
};
var result = this.ExecuteTestCase(sourceDataInfo, options);
Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
this.ValidateDestinationMD5ByDownloading(result.DataInfo, options);
}
[TestCategory(Tag.Function)]
[DMLibTestMethod(DMLibDataType.Local | DMLibDataType.BlockBlob | DMLibDataType.CloudFile | DMLibDataType.Stream, DMLibDataType.BlockBlob)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
[DMLibTestMethod(DMLibDataType.CloudFile, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
public void ToLbb_100MBBlockSizeAndSmallFiles()
{
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, 300 * 1024); // 300MB
for (int i = 0; i < 10; i++)
{
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + i, i);
}
var options = new TestExecutionOptions<DMLibDataInfo>()
{
BlockSize = 100 * 1024 * 1024 // 100MB
};
var result = this.ExecuteTestCase(sourceDataInfo, options);
Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
this.ValidateDestinationMD5ByDownloading(result.DataInfo, options);
}
[TestCategory(Tag.Function)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
public void LbbToLbb_From100MBBlockSizeTo100MBBlockSizeAndSmallFiles()
{
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, 300 * 1024, blockSize: 100 * 1024 * 1024); // 300MB with block size 100MB
for (int i = 0; i < 10; i++)
{
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + i, i);
}
var options = new TestExecutionOptions<DMLibDataInfo>()
{
BlockSize = 100 * 1024 * 1024 // 100MB
};
var result = this.ExecuteTestCase(sourceDataInfo, options);
Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
this.ValidateDestinationMD5ByDownloading(result.DataInfo, options);
}
[TestCategory(Tag.Function)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
public void LbbToLbb_From100MBBlockSizeTo8MBBlockSizeAndSmallFiles()
{
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, 300 * 1024, blockSize: 100 * 1024 * 1024); // 300MB with block size 100MB
for (int i = 0; i < 10; i++)
{
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + i, i);
}
var options = new TestExecutionOptions<DMLibDataInfo>()
{
BlockSize = 8 * 1024 * 1024 // 100MB
};
var result = this.ExecuteTestCase(sourceDataInfo, options);
Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
this.ValidateDestinationMD5ByDownloading(result.DataInfo, options);
}
[TestCategory(Tag.Function)]
[DMLibTestMethod(DMLibDataType.Local | DMLibDataType.BlockBlob | DMLibDataType.CloudFile | DMLibDataType.Stream, DMLibDataType.BlockBlob)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
[DMLibTestMethod(DMLibDataType.CloudFile, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
public void ToLbb_MultiFiles_40MBBlockSizeAndSmallFiles()
{
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, 36 * 1024); // 36MB
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_150MB", 150 * 1024); // 150MB
for (int i = 0; i < 10; i++)
{
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + i, i);
}
var options = new TestExecutionOptions<DMLibDataInfo>()
{
BlockSize = 40 * 1024 * 1024 // 100MB
};
var result = this.ExecuteTestCase(sourceDataInfo, options);
Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
this.ValidateDestinationMD5ByDownloading(result.DataInfo, options);
}
[TestCategory(Tag.Function)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob)]
[DMLibTestMethod(DMLibDataType.BlockBlob, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideSyncCopy)]
public void LbbToLbb_MultiFiles_60MBBlockSizeAndSmallFiles()
{
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, 36 * 1024); // 36MB
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_150MB", 150 * 1024, blockSize: 100 * 1024 * 1024); // 150MB with block size 100MB
for (int i = 0; i < 10; i++)
{
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName + "_" + i, i);
}
var options = new TestExecutionOptions<DMLibDataInfo>()
{
BlockSize = 60*1024*1024 // 100MB
};
var result = this.ExecuteTestCase(sourceDataInfo, options);
Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
this.ValidateDestinationMD5ByDownloading(result.DataInfo, options);
}
}
}
| |
// Created by Paul Gonzalez Becerra
using System;
using Saserdote.Animation;
using Saserdote.DataSystems;
using Saserdote.GamingServices;
using Saserdote.Mathematics;
using Saserdote.Mathematics.Collision;
using Tao.OpenGl;
namespace Saserdote.Graphics
{
public class Model:ICloneable<Model>
{
#region --- Field Variables ---
// Variables
public FList<BaseMesh> meshes;
public FList<BoundingVolume> bounds;
public string name;
public bool bVisible;
protected Matrix pMatrix;
#endregion // Field Variables
#region --- Constructors ---
public Model(string modelName)
{
meshes= new FList<BaseMesh>();
bounds= new FList<BoundingVolume>();
name= modelName;
pMatrix= Matrix.IDENTITY;
bVisible= true;
}
public Model():this("UNMk_1010101011101010") {}
public Model(string modelName, params BaseMesh[] pmMeshes):this(modelName)
{
meshes.addRange(pmMeshes);
}
public Model(params BaseMesh[] pmMeshes):this("UNMk_1010101011101010", pmMeshes) {}
protected Model(string pmName, BaseMesh[] pmMeshes, BoundingVolume[] pmBounds, Matrix pmMatrix)
{
name= pmName;
meshes= new FList<BaseMesh>(pmMeshes);
bounds= new FList<BoundingVolume>(pmBounds);
pMatrix= pmMatrix;
bVisible= true;
}
#endregion // Constructors
#region --- Properties ---
// Gets and sets the matrix of the model
public Matrix matrix
{
get { return pMatrix; }
set { pMatrix= value; applyMatrix(); }
}
// Gets and sets the position of the model
public Point3f position
{
get { return pMatrix.translation; }
set { pMatrix.setPosition(value); applyMatrix(); }//moveBounds(value); }
}
// Sets the texture to be used by the entire model
public Texture texture
{
set { applyTexture(value); }
}
#endregion // Properties
#region --- Methods ---
// Sets if all the meshes will render outlines
public void setOutline(bool outline)
{
for(int i= 0; i< meshes.size; i++)
meshes.items[i].bRenderOutline= outline;
}
// Sets all the meshes's outlines to the given width
public void setOutlineWidth(float width)
{
for(int i= 0; i< meshes.size; i++)
meshes.items[i].outlineWidth= width;
}
// Applies the model's matrix to the meshes
public void applyMatrix()
{
for(int i= 0; i< meshes.size; i++)
meshes.items[i].matrix= pMatrix;
}
// Moves the bounds to the given point in 3d space
public void moveBounds(Point3f position)
{
for(int i= 0; i< bounds.size; i++)
bounds.items[i].position= position;
}
// Applies the given matrix to the meshes
public void applyMatrix(Matrix m)
{
for(int i= 0; i< meshes.size; i++)
meshes.items[i].matrix= m;
}
// Applies the given color to all the meshes
public void applyColor(Color c)
{
for(int i= 0; i< meshes.size; i++)
meshes.items[i].applyColor(c);
}
// Applies the given texture to all the meshes
public void applyTexture(Texture texture)
{
for(int i= 0; i< meshes.size; i++)
meshes.items[i].texture= texture;
}
// Draws all the meshes in the model
public void render()
{
if(!bVisible)
return;
for(int i= 0; i< meshes.size; i++)
meshes.items[i].render();
}
// Draws the bounds of the model
public void renderBounds()
{
if(!bVisible)
return;
for(int i= 0; i< bounds.size; i++)
{
// Variables
LMesh boundsMesh= new LMesh(bounds.items[i]);
boundsMesh.render();
}
}
// Draws all the meshes in the model and uses the texture id from the renderer for multiple texture use
public void render(ref int textureID)
{
if(!bVisible)
return;
for(int i= 0; i< meshes.size; i++)
{
if(meshes[i].texture.ID!= textureID)
{
textureID= meshes[i].texture.ID;
Gl.glBindTexture(Gl.GL_TEXTURE_2D, textureID);
}
meshes.items[i].render();
}
}
// Updates the model's animation
public void updateAnimation(GameTime time)
{
}
// Cel shades the model using the given texture id
public void celshade(ref int textureID)
{
if(!bVisible)
return;
for(int i= 0; i< meshes.size; i++)
{
if(meshes[i].texture.ID!= textureID)
{
textureID= meshes.items[i].texture.ID;
Gl.glBindTexture(Gl.GL_TEXTURE_1D, textureID);
}
Gl.glTexParameteri(Gl.GL_TEXTURE_1D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_NEAREST);
Gl.glTexParameteri(Gl.GL_TEXTURE_1D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_NEAREST);
meshes.items[i].render();
}
}
// Finds if the name of the model is equal to the string
public bool equals(string str)
{
return (name== str);
}
// Finds if the two models are equal
public bool equals(Model mdl)
{
return (meshes== mdl.meshes);
}
#endregion // Methods
#region --- Inherited Methods ---
// Clones the given model making a new one
public Model clone()
{
// Variables
BaseMesh[] ms= new BaseMesh[meshes.size];
BoundingVolume[] bs= new BoundingVolume[bounds.size];
for(int i= 0; i< meshes.size; i++)
ms[i]= meshes[i].clone();
for(int i= 0; i< bounds.size; i++)
bs[i]= bounds[i];
return new Model(name, ms, bs, pMatrix);
}
// Finds if the given object is equal to the model
public override bool Equals(object obj)
{
if(obj== null)
return false;
if(obj is string)
return equals((string)obj);
if(obj is Model)
return equals((Model)obj);
return false;
}
// Gets the hash code
public override int GetHashCode()
{
return name.GetHashCode();
}
// Prints out the name of the model
public override string ToString()
{
return "Model: "+name;
}
#endregion // Inherited Methods
}
}
// End of File
| |
/*
* 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.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
using OpenSim.Services.Connectors.Hypergrid;
namespace OpenSim.Region.OptionalModules.Avatar.UserProfiles
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")]
public class UserProfileModule : IProfileModule, INonSharedRegionModule
{
/// <summary>
/// Logging
/// </summary>
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// The pair of Dictionaries are used to handle the switching of classified ads
// by maintaining a cache of classified id to creator id mappings and an interest
// count. The entries are removed when the interest count reaches 0.
Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>();
Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>();
public Scene Scene
{
get; private set;
}
/// <summary>
/// Gets or sets the ConfigSource.
/// </summary>
/// <value>
/// The configuration
/// </value>
public IConfigSource Config {
get;
set;
}
/// <summary>
/// Gets or sets the URI to the profile server.
/// </summary>
/// <value>
/// The profile server URI.
/// </value>
public string ProfileServerUri {
get;
set;
}
IProfileModule ProfileModule
{
get; set;
}
IUserManagement UserManagementModule
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether this
/// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled.
/// </summary>
/// <value>
/// <c>true</c> if enabled; otherwise, <c>false</c>.
/// </value>
public bool Enabled {
get;
set;
}
#region IRegionModuleBase implementation
/// <summary>
/// This is called to initialize the region module. For shared modules, this is called exactly once, after
/// creating the single (shared) instance. For non-shared modules, this is called once on each instance, after
/// the instace for the region has been created.
/// </summary>
/// <param name='source'>
/// Source.
/// </param>
public void Initialise(IConfigSource source)
{
Config = source;
ReplaceableInterface = typeof(IProfileModule);
IConfig profileConfig = Config.Configs["UserProfiles"];
if (profileConfig == null)
{
m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
Enabled = false;
return;
}
// If we find ProfileURL then we configure for FULL support
// else we setup for BASIC support
ProfileServerUri = profileConfig.GetString("ProfileServiceURL", "");
if (ProfileServerUri == "")
{
Enabled = false;
return;
}
m_log.Debug("[PROFILES]: Full Profiles Enabled");
ReplaceableInterface = null;
Enabled = true;
}
/// <summary>
/// Adds the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void AddRegion(Scene scene)
{
if(!Enabled)
return;
Scene = scene;
Scene.RegisterModuleInterface<IProfileModule>(this);
Scene.EventManager.OnNewClient += OnNewClient;
Scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent;
UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
}
void HandleOnMakeRootAgent (ScenePresence obj)
{
if(obj.PresenceType == PresenceType.Npc)
return;
Util.FireAndForget(delegate
{
GetImageAssets(((IScenePresence)obj).UUID);
});
}
/// <summary>
/// Removes the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RemoveRegion(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// This will be called once for every scene loaded. In a shared module this will be multiple times in one
/// instance, while a nonshared module instance will only be called once. This method is called after AddRegion
/// has been called in all modules for that scene, providing an opportunity to request another module's
/// interface, or hook an event from another module.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RegionLoaded(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// If this returns non-null, it is the type of an interface that this module intends to register. This will
/// cause the loader to defer loading of this module until all other modules have been loaded. If no other
/// module has registered the interface by then, this module will be activated, else it will remain inactive,
/// letting the other module take over. This should return non-null ONLY in modules that are intended to be
/// easily replaceable, e.g. stub implementations that the developer expects to be replaced by third party
/// provided modules.
/// </summary>
/// <value>
/// The replaceable interface.
/// </value>
public Type ReplaceableInterface
{
get; private set;
}
/// <summary>
/// Called as the instance is closed.
/// </summary>
public void Close()
{
}
/// <value>
/// The name of the module
/// </value>
/// <summary>
/// Gets the module name.
/// </summary>
public string Name
{
get { return "UserProfileModule"; }
}
#endregion IRegionModuleBase implementation
#region Region Event Handlers
/// <summary>
/// Raises the new client event.
/// </summary>
/// <param name='client'>
/// Client.
/// </param>
void OnNewClient(IClientAPI client)
{
//Profile
client.OnRequestAvatarProperties += RequestAvatarProperties;
client.OnUpdateAvatarProperties += AvatarPropertiesUpdate;
client.OnAvatarInterestUpdate += AvatarInterestsUpdate;
// Classifieds
client.AddGenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest);
client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
client.OnClassifiedInfoRequest += ClassifiedInfoRequest;
client.OnClassifiedDelete += ClassifiedDelete;
// Picks
client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest);
client.AddGenericPacketHandler("pickinforequest", PickInfoRequest);
client.OnPickInfoUpdate += PickInfoUpdate;
client.OnPickDelete += PickDelete;
// Notes
client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest);
client.OnAvatarNotesUpdate += NotesUpdate;
}
#endregion Region Event Handlers
#region Classified
///
/// <summary>
/// Handles the avatar classifieds request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void ClassifiedsRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetID;
UUID.TryParse(args[0], out targetID);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
UUID creatorId = UUID.Zero;
Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
UUID.TryParse(args[0], out creatorId);
parameters.Add("creatorId", OSD.FromUUID(creatorId));
OSD Params = (OSD)parameters;
if(!JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["classifieduuid"].AsUUID();
string name = m["name"].AsString();
classifieds[cid] = name;
lock (m_classifiedCache)
{
if (!m_classifiedCache.ContainsKey(cid))
{
m_classifiedCache.Add(cid,creatorId);
m_classifiedInterest.Add(cid, 0);
}
m_classifiedInterest[cid]++;
}
}
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
}
public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient)
{
UUID target = remoteClient.AgentId;
UserClassifiedAdd ad = new UserClassifiedAdd();
ad.ClassifiedId = queryClassifiedID;
lock (m_classifiedCache)
{
if (m_classifiedCache.ContainsKey(queryClassifiedID))
{
target = m_classifiedCache[queryClassifiedID];
m_classifiedInterest[queryClassifiedID] --;
if (m_classifiedInterest[queryClassifiedID] == 0)
{
m_classifiedInterest.Remove(queryClassifiedID);
m_classifiedCache.Remove(queryClassifiedID);
}
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(target, out serverURI);
object Ad = (object)ad;
if(!JsonRpcRequest(ref Ad, "classifieds_info_query", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error getting classified info", false);
return;
}
ad = (UserClassifiedAdd) Ad;
if(ad.CreatorId == UUID.Zero)
return;
Vector3 globalPos = new Vector3();
Vector3.TryParse(ad.GlobalPos, out globalPos);
remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate, (uint)ad.ExpirationDate,
(uint)ad.Category, ad.Name, ad.Description, ad.ParcelId, (uint)ad.ParentEstate,
ad.SnapshotId, ad.SimName, globalPos, ad.ParcelName, ad.Flags, ad.Price);
}
/// <summary>
/// Classifieds info update.
/// </summary>
/// <param name='queryclassifiedID'>
/// Queryclassified I.
/// </param>
/// <param name='queryCategory'>
/// Query category.
/// </param>
/// <param name='queryName'>
/// Query name.
/// </param>
/// <param name='queryDescription'>
/// Query description.
/// </param>
/// <param name='queryParcelID'>
/// Query parcel I.
/// </param>
/// <param name='queryParentEstate'>
/// Query parent estate.
/// </param>
/// <param name='querySnapshotID'>
/// Query snapshot I.
/// </param>
/// <param name='queryGlobalPos'>
/// Query global position.
/// </param>
/// <param name='queryclassifiedFlags'>
/// Queryclassified flags.
/// </param>
/// <param name='queryclassifiedPrice'>
/// Queryclassified price.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
int queryclassifiedPrice, IClientAPI remoteClient)
{
UserClassifiedAdd ad = new UserClassifiedAdd();
Scene s = (Scene) remoteClient.Scene;
Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
ScenePresence p = FindPresence(remoteClient.AgentId);
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
if (land == null)
{
ad.ParcelName = string.Empty;
}
else
{
ad.ParcelName = land.LandData.Name;
}
ad.CreatorId = remoteClient.AgentId;
ad.ClassifiedId = queryclassifiedID;
ad.Category = Convert.ToInt32(queryCategory);
ad.Name = queryName;
ad.Description = queryDescription;
ad.ParentEstate = Convert.ToInt32(queryParentEstate);
ad.SnapshotId = querySnapshotID;
ad.SimName = remoteClient.Scene.RegionInfo.RegionName;
ad.GlobalPos = queryGlobalPos.ToString ();
ad.Flags = queryclassifiedFlags;
ad.Price = queryclassifiedPrice;
ad.ParcelId = p.currentParcelUUID;
object Ad = ad;
OSD.SerializeMembers(Ad);
if(!JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating classified", false);
}
}
/// <summary>
/// Classifieds delete.
/// </summary>
/// <param name='queryClassifiedID'>
/// Query classified I.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
UUID classifiedId;
OSDMap parameters= new OSDMap();
UUID.TryParse(queryClassifiedID.ToString(), out classifiedId);
parameters.Add("classifiedId", OSD.FromUUID(classifiedId));
OSD Params = (OSD)parameters;
if(!JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error classified delete", false);
}
parameters = (OSDMap)Params;
}
#endregion Classified
#region Picks
/// <summary>
/// Handles the avatar picks request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PicksRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetId;
UUID.TryParse(args[0], out targetId);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetId, out serverURI);
Dictionary<UUID, string> picks = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
parameters.Add("creatorId", OSD.FromUUID(targetId));
OSD Params = (OSD)parameters;
if(!JsonRpcRequest(ref Params, "avatarpicksrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["pickuuid"].AsUUID();
string name = m["name"].AsString();
m_log.DebugFormat("[PROFILES]: PicksRequest {0}", name);
picks[cid] = name;
}
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
}
/// <summary>
/// Handles the pick info request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PickInfoRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
UUID targetID;
UUID.TryParse(args[0], out targetID);
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
IClientAPI remoteClient = (IClientAPI)sender;
UserProfilePick pick = new UserProfilePick();
UUID.TryParse(args[0], out pick.CreatorId);
UUID.TryParse(args[1], out pick.PickId);
object Pick = (object)pick;
if(!JsonRpcRequest(ref Pick, "pickinforequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error selecting pick", false);
}
pick = (UserProfilePick) Pick;
if(pick.SnapshotId == UUID.Zero)
{
// In case of a new UserPick, the data may not be ready and we would send wrong data, skip it...
m_log.DebugFormat("[PROFILES]: PickInfoRequest: SnapshotID is {0}", UUID.Zero.ToString());
return;
}
Vector3 globalPos;
Vector3.TryParse(pick.GlobalPos,out globalPos);
m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString());
remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
pick.Desc,pick.SnapshotId,pick.User,pick.OriginalName,pick.SimName,
globalPos,pick.SortOrder,pick.Enabled);
}
/// <summary>
/// Updates the userpicks
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='pickID'>
/// Pick I.
/// </param>
/// <param name='creatorID'>
/// the creator of the pick
/// </param>
/// <param name='topPick'>
/// Top pick.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
/// <param name='desc'>
/// Desc.
/// </param>
/// <param name='snapshotID'>
/// Snapshot I.
/// </param>
/// <param name='sortOrder'>
/// Sort order.
/// </param>
/// <param name='enabled'>
/// Enabled.
/// </param>
public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
{
m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString());
UserProfilePick pick = new UserProfilePick();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
ScenePresence p = FindPresence(remoteClient.AgentId);
Vector3 avaPos = p.AbsolutePosition;
// Getting the global position for the Avatar
Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.RegionLocX*Constants.RegionSize + avaPos.X,
remoteClient.Scene.RegionInfo.RegionLocY*Constants.RegionSize + avaPos.Y,
avaPos.Z);
string landOwnerName = string.Empty;
ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);
if(land.LandData.IsGroupOwned)
{
IGroupsModule groupMod = p.Scene.RequestModuleInterface<IGroupsModule>();
UUID groupId = land.LandData.GroupID;
GroupRecord groupRecord = groupMod.GetGroupRecord(groupId);
landOwnerName = groupRecord.GroupName;
}
else
{
IUserAccountService accounts = p.Scene.RequestModuleInterface<IUserAccountService>();
UserAccount user = accounts.GetUserAccount(p.Scene.RegionInfo.ScopeID, land.LandData.OwnerID);
landOwnerName = user.Name;
}
pick.PickId = pickID;
pick.CreatorId = creatorID;
pick.TopPick = topPick;
pick.Name = name;
pick.Desc = desc;
pick.ParcelId = p.currentParcelUUID;
pick.SnapshotId = snapshotID;
pick.User = landOwnerName;
pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
pick.GlobalPos = posGlobal.ToString();
pick.SortOrder = sortOrder;
pick.Enabled = enabled;
object Pick = (object)pick;
if(!JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating pick", false);
}
m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString());
}
/// <summary>
/// Delete a Pick
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryPickID'>
/// Query pick I.
/// </param>
public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
OSDMap parameters= new OSDMap();
parameters.Add("pickId", OSD.FromUUID(queryPickID));
OSD Params = (OSD)parameters;
if(!JsonRpcRequest(ref Params, "picks_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error picks delete", false);
}
}
#endregion Picks
#region Notes
/// <summary>
/// Handles the avatar notes request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void NotesRequest(Object sender, string method, List<String> args)
{
UserProfileNotes note = new UserProfileNotes();
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
note.TargetId = remoteClient.AgentId;
UUID.TryParse(args[0], out note.UserId);
object Note = (object)note;
if(!JsonRpcRequest(ref Note, "avatarnotesrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
return;
}
note = (UserProfileNotes) Note;
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
}
/// <summary>
/// Avatars the notes update.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryTargetID'>
/// Query target I.
/// </param>
/// <param name='queryNotes'>
/// Query notes.
/// </param>
public void NotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
{
UserProfileNotes note = new UserProfileNotes();
note.UserId = remoteClient.AgentId;
note.TargetId = queryTargetID;
note.Notes = queryNotes;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Note = note;
if(!JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString()))
{
return;
}
}
#endregion Notes
#region Avatar Properties
/// <summary>
/// Update the avatars interests .
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='wantmask'>
/// Wantmask.
/// </param>
/// <param name='wanttext'>
/// Wanttext.
/// </param>
/// <param name='skillsmask'>
/// Skillsmask.
/// </param>
/// <param name='skillstext'>
/// Skillstext.
/// </param>
/// <param name='languages'>
/// Languages.
/// </param>
public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WantToMask = (int)wantmask;
prop.WantToText = wanttext;
prop.SkillsMask = (int)skillsmask;
prop.SkillsText = skillstext;
prop.Language = languages;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Param = prop;
if(!JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating interests", false);
}
}
public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if ( String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString()))
{
// Looking for a reason that some viewers are sending null Id's
m_log.DebugFormat("[PROFILES]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID);
return;
}
// Can't handle NPC yet...
ScenePresence p = FindPresence(avatarID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
UserAccount account = null;
Dictionary<string,object> userInfo;
if (!foreign)
{
account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID);
}
else
{
userInfo = new Dictionary<string, object>();
}
Byte[] charterMember = new Byte[1];
string born = String.Empty;
uint flags = 0x00;
if (null != account)
{
if (account.UserTitle == "")
{
charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes(account.UserTitle);
}
born = Util.ToDateTime(account.Created).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
flags = (uint)(account.UserFlags & 0xff);
}
else
{
if (GetUserAccountData(avatarID, out userInfo) == true)
{
if ((string)userInfo["user_title"] == "")
{
charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes((string)userInfo["user_title"]);
}
int val_born = (int)userInfo["user_created"];
born = Util.ToDateTime(val_born).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
// picky, picky
int val_flags = (int)userInfo["user_flags"];
flags = (uint)(val_flags & 0xff);
}
}
UserProfileProperties props = new UserProfileProperties();
string result = string.Empty;
props.UserId = avatarID;
GetProfileData(ref props, out result);
remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, charterMember , props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText, (uint)props.SkillsMask,
props.SkillsText, props.Language);
}
/// <summary>
/// Updates the avatar properties.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='newProfile'>
/// New profile.
/// </param>
public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileData newProfile)
{
if (remoteClient.AgentId == newProfile.ID)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WebUrl = newProfile.ProfileUrl;
prop.ImageId = newProfile.Image;
prop.AboutText = newProfile.AboutText;
prop.FirstLifeImageId = newProfile.FirstLifeImage;
prop.FirstLifeText = newProfile.FirstLifeAboutText;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Prop = prop;
if(!JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating properties", false);
}
RequestAvatarProperties(remoteClient, newProfile.ID);
}
}
/// <summary>
/// Gets the profile data.
/// </summary>
/// <returns>
/// The profile data.
/// </returns>
/// <param name='userID'>
/// User I.
/// </param>
bool GetProfileData(ref UserProfileProperties properties, out string message)
{
// Can't handle NPC yet...
ScenePresence p = FindPresence(properties.UserId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
{
message = "Id points to NPC";
return false;
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(properties.UserId, out serverURI);
// This is checking a friend on the home grid
// Not HG friend
if ( String.IsNullOrEmpty(serverURI))
{
message = "No Presence - foreign friend";
return false;
}
object Prop = (object)properties;
JsonRpcRequest(ref Prop, "avatar_properties_request", serverURI, UUID.Random().ToString());
properties = (UserProfileProperties)Prop;
message = "Success";
return true;
}
#endregion Avatar Properties
#region Utils
bool GetImageAssets(UUID avatarId)
{
string profileServerURI = string.Empty;
string assetServerURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarId, out profileServerURI);
if(!foreign)
return true;
assetServerURI = UserManagementModule.GetUserServerURL(avatarId, "AssetServerURI");
OSDMap parameters= new OSDMap();
parameters.Add("avatarId", OSD.FromUUID(avatarId));
OSD Params = (OSD)parameters;
if(!JsonRpcRequest(ref Params, "image_assets_request", profileServerURI, UUID.Random().ToString()))
{
return false;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD asset in list)
{
OSDString assetId = (OSDString)asset;
Scene.AssetService.Get(string.Format("{0}/{1}",assetServerURI, assetId.AsString()));
}
return true;
}
/// <summary>
/// Gets the user account data.
/// </summary>
/// <returns>
/// The user profile data.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='userInfo'>
/// If set to <c>true</c> user info.
/// </param>
bool GetUserAccountData(UUID userID, out Dictionary<string, object> userInfo)
{
Dictionary<string,object> info = new Dictionary<string, object>();
if (UserManagementModule.IsLocalGridUser(userID))
{
// Is local
IUserAccountService uas = Scene.UserAccountService;
UserAccount account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID);
info["user_flags"] = account.UserFlags;
info["user_created"] = account.Created;
if (!String.IsNullOrEmpty(account.UserTitle))
info["user_title"] = account.UserTitle;
else
info["user_title"] = "";
userInfo = info;
return false;
}
else
{
// Is Foreign
string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI");
if (String.IsNullOrEmpty(home_url))
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "Unavailable";
userInfo = info;
return true;
}
UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);
Dictionary<string, object> account = uConn.GetUserInfo(userID);
if (account.Count > 0)
{
if (account.ContainsKey("user_flags"))
info["user_flags"] = account["user_flags"];
else
info["user_flags"] = "";
if (account.ContainsKey("user_created"))
info["user_created"] = account["user_created"];
else
info["user_created"] = "";
info["user_title"] = "HG Visitor";
}
else
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "HG Visitor";
}
userInfo = info;
return true;
}
}
/// <summary>
/// Gets the user profile server UR.
/// </summary>
/// <returns>
/// The user profile server UR.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server UR.
/// </param>
bool GetUserProfileServerURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI");
// Is Foreign
return true;
}
else
{
serverURI = ProfileServerUri;
// Is local
return false;
}
}
/// <summary>
/// Finds the presence.
/// </summary>
/// <returns>
/// The presence.
/// </returns>
/// <param name='clientID'>
/// Client I.
/// </param>
ScenePresence FindPresence(UUID clientID)
{
ScenePresence p;
p = Scene.GetScenePresence(clientID);
if (p != null && !p.IsChildAgent)
return p;
return null;
}
#endregion Util
#region Web Util
/// <summary>
/// Sends json-rpc request with a serializable type.
/// </summary>
/// <returns>
/// OSD Map.
/// </returns>
/// <param name='parameters'>
/// Serializable type .
/// </param>
/// <param name='method'>
/// Json-rpc method to call.
/// </param>
/// <param name='uri'>
/// URI of json-rpc service.
/// </param>
/// <param name='jsonId'>
/// Id for our call.
/// </param>
bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
{
if (jsonId == null)
throw new ArgumentNullException ("jsonId");
if (uri == null)
throw new ArgumentNullException ("uri");
if (method == null)
throw new ArgumentNullException ("method");
if (parameters == null)
throw new ArgumentNullException ("parameters");
// Prep our payload
OSDMap json = new OSDMap();
json.Add("jsonrpc", OSD.FromString("2.0"));
json.Add("id", OSD.FromString(jsonId));
json.Add("method", OSD.FromString(method));
json.Add("params", OSD.SerializeMembers(parameters));
string jsonRequestData = OSDParser.SerializeJsonString(json);
byte[] content = Encoding.UTF8.GetBytes(jsonRequestData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(content, 0, content.Length);
dataStream.Close();
WebResponse webResponse = null;
try
{
webResponse = webRequest.GetResponse();
}
catch (WebException e)
{
Console.WriteLine("Web Error" + e.Message);
Console.WriteLine ("Please check input");
return false;
}
Stream rstream = webResponse.GetResponseStream();
OSDMap mret = new OSDMap();
try
{
mret = (OSDMap)OSDParser.DeserializeJson(rstream);
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES]: JsonRpcRequest Error {0} - remote user with legacy profiles?", e.Message);
return false;
}
if (mret.ContainsKey("error"))
return false;
// get params...
OSD.DeserializeMembers(ref parameters, (OSDMap) mret["result"]);
return true;
}
/// <summary>
/// Sends json-rpc request with OSD parameter.
/// </summary>
/// <returns>
/// The rpc request.
/// </returns>
/// <param name='data'>
/// data - incoming as parameters, outgong as result/error
/// </param>
/// <param name='method'>
/// Json-rpc method to call.
/// </param>
/// <param name='uri'>
/// URI of json-rpc service.
/// </param>
/// <param name='jsonId'>
/// If set to <c>true</c> json identifier.
/// </param>
bool JsonRpcRequest(ref OSD data, string method, string uri, string jsonId)
{
OSDMap map = new OSDMap();
map["jsonrpc"] = "2.0";
if(string.IsNullOrEmpty(jsonId))
map["id"] = UUID.Random().ToString();
else
map["id"] = jsonId;
map["method"] = method;
map["params"] = data;
string jsonRequestData = OSDParser.SerializeJsonString(map);
byte[] content = Encoding.UTF8.GetBytes(jsonRequestData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(content, 0, content.Length);
dataStream.Close();
WebResponse webResponse = null;
try
{
webResponse = webRequest.GetResponse();
}
catch (WebException e)
{
Console.WriteLine("Web Error" + e.Message);
Console.WriteLine ("Please check input");
return false;
}
Stream rstream = webResponse.GetResponseStream();
OSDMap response = new OSDMap();
try
{
response = (OSDMap)OSDParser.DeserializeJson(rstream);
}
catch (Exception e)
{
m_log.DebugFormat("[PROFILES]: JsonRpcRequest Error {0} - remote user with legacy profiles?", e.Message);
return false;
}
if(response.ContainsKey("error"))
{
data = response["error"];
return false;
}
data = response;
return true;
}
#endregion Web Util
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using Azure;
using Management;
using Rest;
using 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>
/// DeletedWebAppsOperations operations.
/// </summary>
internal partial class DeletedWebAppsOperations : IServiceOperations<WebSiteManagementClient>, IDeletedWebAppsOperations
{
/// <summary>
/// Initializes a new instance of the DeletedWebAppsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DeletedWebAppsOperations(WebSiteManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the WebSiteManagementClient
/// </summary>
public WebSiteManagementClient Client { get; private set; }
/// <summary>
/// Get all deleted apps for a subscription.
/// </summary>
/// <remarks>
/// Get all deleted apps for a subscription.
/// </remarks>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DeletedSite>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Web/deletedSites").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DeletedSite>>();
_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<DeletedSite>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets deleted web apps in subscription.
/// </summary>
/// <remarks>
/// Gets deleted web apps in subscription.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DeletedSite>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$");
}
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/deletedSites").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DeletedSite>>();
_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<DeletedSite>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get all deleted apps for a subscription.
/// </summary>
/// <remarks>
/// Get all deleted apps for a subscription.
/// </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="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DeletedSite>>> 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 System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DeletedSite>>();
_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<DeletedSite>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets deleted web apps in subscription.
/// </summary>
/// <remarks>
/// Gets deleted web apps in subscription.
/// </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="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DeletedSite>>> ListByResourceGroupNextWithHttpMessagesAsync(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, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DeletedSite>>();
_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<DeletedSite>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// CodeContracts
//
// 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.
// File System.DateTimeOffset.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System
{
public partial struct DateTimeOffset : IComparable, IFormattable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>
{
#region Methods and constructors
public static System.DateTimeOffset operator - (System.DateTimeOffset dateTimeOffset, TimeSpan timeSpan)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static TimeSpan operator - (System.DateTimeOffset left, System.DateTimeOffset right)
{
return default(TimeSpan);
}
public static bool operator != (System.DateTimeOffset left, System.DateTimeOffset right)
{
return default(bool);
}
public static System.DateTimeOffset operator + (System.DateTimeOffset dateTimeOffset, TimeSpan timeSpan)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static bool operator < (System.DateTimeOffset left, System.DateTimeOffset right)
{
return default(bool);
}
public static bool operator <=(System.DateTimeOffset left, System.DateTimeOffset right)
{
return default(bool);
}
public static bool operator == (System.DateTimeOffset left, System.DateTimeOffset right)
{
return default(bool);
}
public static bool operator > (System.DateTimeOffset left, System.DateTimeOffset right)
{
return default(bool);
}
public static bool operator >= (System.DateTimeOffset left, System.DateTimeOffset right)
{
return default(bool);
}
public System.DateTimeOffset Add(TimeSpan timeSpan)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddDays(double days)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddHours(double hours)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddMilliseconds(double milliseconds)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddMinutes(double minutes)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddMonths(int months)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddSeconds(double seconds)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddTicks(long ticks)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset AddYears(int years)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static int Compare(System.DateTimeOffset first, System.DateTimeOffset second)
{
Contract.Ensures(-1 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() <= 1);
return default(int);
}
public int CompareTo(System.DateTimeOffset other)
{
return default(int);
}
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset)
{
Contract.Ensures(false);
}
public DateTimeOffset(DateTime dateTime, TimeSpan offset)
{
Contract.Ensures(false);
}
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar calendar, TimeSpan offset)
{
Contract.Ensures(false);
}
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset)
{
Contract.Ensures(false);
}
public DateTimeOffset(DateTime dateTime)
{
Contract.Ensures(false);
}
public DateTimeOffset(long ticks, TimeSpan offset)
{
Contract.Ensures(false);
}
public override bool Equals(Object obj)
{
return default(bool);
}
public static bool Equals(System.DateTimeOffset first, System.DateTimeOffset second)
{
return default(bool);
}
public bool Equals(System.DateTimeOffset other)
{
return default(bool);
}
public bool EqualsExact(System.DateTimeOffset other)
{
return default(bool);
}
public static System.DateTimeOffset FromFileTime(long fileTime)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public override int GetHashCode()
{
return default(int);
}
public static System.DateTimeOffset Parse(string input)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static System.DateTimeOffset Parse(string input, IFormatProvider formatProvider)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static System.DateTimeOffset Parse(string input, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static System.DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static System.DateTimeOffset ParseExact(string input, string[] formats, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static System.DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset Subtract(TimeSpan value)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public TimeSpan Subtract(System.DateTimeOffset value)
{
return default(TimeSpan);
}
public static implicit operator System.DateTimeOffset(DateTime dateTime)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
int System.IComparable.CompareTo(Object obj)
{
return default(int);
}
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender)
{
}
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
}
public long ToFileTime()
{
Contract.Ensures(0 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 8718460804854775808);
return default(long);
}
public System.DateTimeOffset ToLocalTime()
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public System.DateTimeOffset ToOffset(TimeSpan offset)
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public override string ToString()
{
return default(string);
}
public string ToString(IFormatProvider formatProvider)
{
Contract.Ensures(0 <= string.Empty.Length);
return default(string);
}
public string ToString(string format, IFormatProvider formatProvider)
{
return default(string);
}
public string ToString(string format)
{
Contract.Ensures(0 <= string.Empty.Length);
return default(string);
}
public System.DateTimeOffset ToUniversalTime()
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
public static bool TryParse(string input, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles, out System.DateTimeOffset result)
{
Contract.Ensures(false);
result = default(System.DateTimeOffset);
return default(bool);
}
public static bool TryParse(string input, out System.DateTimeOffset result)
{
Contract.Ensures(false);
result = default(System.DateTimeOffset);
return default(bool);
}
public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles, out System.DateTimeOffset result)
{
Contract.Ensures(false);
result = default(System.DateTimeOffset);
return default(bool);
}
public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles, out System.DateTimeOffset result)
{
Contract.Ensures(false);
result = default(System.DateTimeOffset);
return default(bool);
}
#endregion
#region Properties and indexers
public System.DateTime Date
{
get
{
return default(System.DateTime);
}
}
public DateTime DateTime
{
get
{
return default(DateTime);
}
}
public int Day
{
get
{
return default(int);
}
}
public DayOfWeek DayOfWeek
{
get
{
return default(DayOfWeek);
}
}
public int DayOfYear
{
get
{
return default(int);
}
}
public int Hour
{
get
{
Contract.Ensures(0 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() <= 23);
return default(int);
}
}
public System.DateTime LocalDateTime
{
get
{
return default(System.DateTime);
}
}
public int Millisecond
{
get
{
Contract.Ensures(0 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() <= 999);
return default(int);
}
}
public int Minute
{
get
{
Contract.Ensures(0 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() <= 59);
return default(int);
}
}
public int Month
{
get
{
return default(int);
}
}
public static System.DateTimeOffset Now
{
get
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
}
public TimeSpan Offset
{
get
{
return default(TimeSpan);
}
}
public int Second
{
get
{
Contract.Ensures(0 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() <= 59);
return default(int);
}
}
public long Ticks
{
get
{
Contract.Ensures(0 <= Contract.Result<long>());
return default(long);
}
}
public TimeSpan TimeOfDay
{
get
{
return default(TimeSpan);
}
}
public System.DateTime UtcDateTime
{
get
{
return default(System.DateTime);
}
}
public static System.DateTimeOffset UtcNow
{
get
{
Contract.Ensures(false);
return default(System.DateTimeOffset);
}
}
public long UtcTicks
{
get
{
Contract.Ensures(0 <= Contract.Result<long>());
return default(long);
}
}
public int Year
{
get
{
return default(int);
}
}
#endregion
#region Fields
public readonly static System.DateTimeOffset MaxValue;
public readonly static System.DateTimeOffset MinValue;
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyFile
{
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 Models;
/// <summary>
/// Files operations.
/// </summary>
public partial class Files : IServiceOperations<AutoRestSwaggerBATFileService>, IFiles
{
/// <summary>
/// Initializes a new instance of the Files class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Files(AutoRestSwaggerBATFileService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATFileService
/// </summary>
public AutoRestSwaggerBATFileService Client { get; private set; }
/// <summary>
/// Get file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.IO.Stream>> GetFileWithHttpMessagesAsync(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, "GetFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/nonempty").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, 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 HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a large file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.IO.Stream>> GetFileLargeWithHttpMessagesAsync(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, "GetFileLarge", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/verylarge").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, 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 HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get empty file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.IO.Stream>> GetEmptyFileWithHttpMessagesAsync(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, "GetEmptyFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/empty").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, 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 HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright ?2004, 2016, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// 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; version 2 of the License.
//
// 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.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using MySql.Data.Common;
using MySql.Data.Types;
using MySql.Data.MySqlClient.Properties;
using System.Diagnostics;
using System.Collections.Generic;
using System.Security;
namespace MySql.Data.MySqlClient
{
/// <summary>
/// Summary description for BaseDriver.
/// </summary>
internal class Driver : IDisposable
{
protected Encoding encoding;
protected MySqlConnectionStringBuilder connectionString;
protected bool isOpen;
protected DateTime creationTime;
protected string serverCharSet;
protected int serverCharSetIndex;
protected Dictionary<string,string> serverProps;
protected Dictionary<int,string> charSets;
protected long maxPacketSize;
internal int timeZoneOffset;
private DateTime idleSince;
#if !RT
protected MySqlPromotableTransaction currentTransaction;
protected bool inActiveUse;
#endif
protected MySqlPool pool;
private bool firstResult;
protected IDriver handler;
internal MySqlDataReader reader;
private bool disposed;
/// <summary>
/// For pooled connections, time when the driver was
/// put into idle queue
/// </summary>
public DateTime IdleSince
{
get { return idleSince; }
set { idleSince = value; }
}
public Driver(MySqlConnectionStringBuilder settings)
{
encoding = Encoding.GetEncoding("UTF-8");
if (encoding == null)
throw new MySqlException(Resources.DefaultEncodingNotFound);
connectionString = settings;
serverCharSet = "utf8";
serverCharSetIndex = -1;
maxPacketSize = 1024;
handler = new NativeDriver(this);
}
~Driver()
{
Dispose(false);
}
#region Properties
public int ThreadID
{
get { return handler.ThreadId; }
}
public DBVersion Version
{
get { return handler.Version; }
}
public MySqlConnectionStringBuilder Settings
{
get { return connectionString; }
set { connectionString = value; }
}
public Encoding Encoding
{
get { return encoding; }
set { encoding = value; }
}
#if !RT
public MySqlPromotableTransaction CurrentTransaction
{
get { return currentTransaction; }
set { currentTransaction = value; }
}
public bool IsInActiveUse
{
get { return inActiveUse; }
set { inActiveUse = value; }
}
#endif
public bool IsOpen
{
get { return isOpen; }
}
public MySqlPool Pool
{
get { return pool; }
set { pool = value; }
}
public long MaxPacketSize
{
get { return maxPacketSize; }
}
internal int ConnectionCharSetIndex
{
get { return serverCharSetIndex; }
set { serverCharSetIndex = value; }
}
internal Dictionary<int,string> CharacterSets
{
get { return charSets; }
}
public bool SupportsOutputParameters
{
get { return Version.isAtLeast(5, 5, 0); }
}
public bool SupportsBatch
{
get { return (handler.Flags & ClientFlags.MULTI_STATEMENTS) != 0; }
}
public bool SupportsConnectAttrs
{
get { return (handler.Flags & ClientFlags.CONNECT_ATTRS) != 0; }
}
public bool SupportsPasswordExpiration
{
get { return (handler.Flags & ClientFlags.CAN_HANDLE_EXPIRED_PASSWORD) != 0; }
}
public bool IsPasswordExpired { get; internal set; }
#endregion
public string Property(string key)
{
return (string)serverProps[key];
}
public bool ConnectionLifetimeExpired()
{
TimeSpan ts = DateTime.Now.Subtract(creationTime);
if (Settings.ConnectionLifeTime != 0 &&
ts.TotalSeconds > Settings.ConnectionLifeTime)
return true;
return false;
}
public static Driver Create(MySqlConnectionStringBuilder settings)
{
Driver d = null;
#if !RT
try
{
if (MySqlTrace.QueryAnalysisEnabled || settings.Logging || settings.UseUsageAdvisor)
d = new TracingDriver(settings);
}
catch (TypeInitializationException ex)
{
if (!(ex.InnerException is SecurityException))
throw ex;
//Only rethrow if InnerException is not a SecurityException. If it is a SecurityException then
//we couldn't initialize MySqlTrace because we don't have unmanaged code permissions.
}
#else
if (settings.Logging || settings.UseUsageAdvisor)
{
throw new NotImplementedException( "Logging not supported in this WinRT release." );
}
#endif
if (d == null)
d = new Driver(settings);
//this try was added as suggested fix submitted on MySql Bug 72025, socket connections are left in CLOSE_WAIT status when connector fails to open a new connection.
//the bug is present when the client try to get more connections that the server support or has configured in the max_connections variable.
try
{
d.Open();
}
catch
{
d.Dispose();
throw;
}
return d;
}
public bool HasStatus(ServerStatusFlags flag)
{
return (handler.ServerStatus & flag) != 0;
}
public virtual void Open()
{
creationTime = DateTime.Now;
handler.Open();
isOpen = true;
}
public virtual void Close()
{
Dispose();
}
public virtual void Configure(MySqlConnection connection)
{
bool firstConfigure = false;
// if we have not already configured our server variables
// then do so now
if (serverProps == null)
{
firstConfigure = true;
// if we are in a pool and the user has said it's ok to cache the
// properties, then grab it from the pool
try
{
if (Pool != null && Settings.CacheServerProperties)
{
if (Pool.ServerProperties == null)
Pool.ServerProperties = LoadServerProperties(connection);
serverProps = Pool.ServerProperties;
}
else
serverProps = LoadServerProperties(connection);
LoadCharacterSets(connection);
}
catch (MySqlException ex)
{
// expired password capability
if (ex.Number == 1820)
{
IsPasswordExpired = true;
return;
}
throw;
}
}
#if AUTHENTICATED
string licenseType = serverProps["license"];
if (licenseType == null || licenseType.Length == 0 ||
licenseType != "commercial")
throw new MySqlException( "This client library licensed only for use with commercially-licensed MySQL servers." );
#endif
// if the user has indicated that we are not to reset
// the connection and this is not our first time through,
// then we are done.
if (!Settings.ConnectionReset && !firstConfigure) return;
string charSet = connectionString.CharacterSet;
if (charSet == null || charSet.Length == 0)
{
if (serverCharSetIndex >= 0)
charSet = (string)charSets[serverCharSetIndex];
else
charSet = serverCharSet;
}
if (serverProps.ContainsKey("max_allowed_packet"))
maxPacketSize = Convert.ToInt64(serverProps["max_allowed_packet"]);
// now tell the server which character set we will send queries in and which charset we
// want results in
MySqlCommand charSetCmd = new MySqlCommand("SET character_set_results=NULL",
connection);
charSetCmd.InternallyCreated = true;
object clientCharSet = serverProps["character_set_client"];
object connCharSet = serverProps["character_set_connection"];
if ((clientCharSet != null && clientCharSet.ToString() != charSet) ||
(connCharSet != null && connCharSet.ToString() != charSet))
{
MySqlCommand setNamesCmd = new MySqlCommand("SET NAMES " + charSet, connection);
setNamesCmd.InternallyCreated = true;
setNamesCmd.ExecuteNonQuery();
}
charSetCmd.ExecuteNonQuery();
if (charSet != null)
Encoding = CharSetMap.GetEncoding(Version, charSet);
else
Encoding = CharSetMap.GetEncoding(Version, "utf-8");
handler.Configure();
}
/// <summary>
/// Loads the properties from the connected server into a hashtable
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
private Dictionary<string,string> LoadServerProperties(MySqlConnection connection)
{
// load server properties
Dictionary<string, string> hash = new Dictionary<string, string>();
MySqlCommand cmd = new MySqlCommand("SHOW VARIABLES", connection);
try
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string key = reader.GetString(0);
string value = reader.GetString(1);
hash[key] = value;
}
}
// Get time zone offset as numerical value
timeZoneOffset = GetTimeZoneOffset(connection);
return hash;
}
catch (Exception ex)
{
MySqlTrace.LogError(ThreadID, ex.Message);
throw;
}
}
private int GetTimeZoneOffset( MySqlConnection con )
{
MySqlCommand cmd = new MySqlCommand("SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP())", con);
string s = cmd.ExecuteScalar().ToString();
return int.Parse(s.Substring(0, s.IndexOf(':') ));
}
/// <summary>
/// Loads all the current character set names and ids for this server
/// into the charSets hashtable
/// </summary>
private void LoadCharacterSets(MySqlConnection connection)
{
MySqlCommand cmd = new MySqlCommand("SHOW COLLATION", connection);
// now we load all the currently active collations
try
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
charSets = new Dictionary<int, string>();
while (reader.Read())
{
charSets[Convert.ToInt32(reader["id"], NumberFormatInfo.InvariantInfo)] =
reader.GetString(reader.GetOrdinal("charset"));
}
}
}
catch (Exception ex)
{
MySqlTrace.LogError(ThreadID, ex.Message);
throw;
}
}
public virtual List<MySqlError> ReportWarnings(MySqlConnection connection)
{
List<MySqlError> warnings = new List<MySqlError>();
MySqlCommand cmd = new MySqlCommand("SHOW WARNINGS", connection);
cmd.InternallyCreated = true;
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
warnings.Add(new MySqlError(reader.GetString(0),
reader.GetInt32(1), reader.GetString(2)));
}
}
MySqlInfoMessageEventArgs args = new MySqlInfoMessageEventArgs();
args.errors = warnings.ToArray();
if (connection != null)
connection.OnInfoMessage(args);
return warnings;
}
public virtual void SendQuery(MySqlPacket p)
{
handler.SendQuery(p);
firstResult = true;
}
public virtual ResultSet NextResult(int statementId, bool force)
{
if (!force && !firstResult && !HasStatus(ServerStatusFlags.AnotherQuery | ServerStatusFlags.MoreResults))
return null;
firstResult = false;
int affectedRows = -1, warnings = 0;
long insertedId = -1;
int fieldCount = GetResult(statementId, ref affectedRows, ref insertedId);
if (fieldCount == -1)
return null;
if (fieldCount > 0)
return new ResultSet(this, statementId, fieldCount);
else
return new ResultSet(affectedRows, insertedId);
}
protected virtual int GetResult(int statementId, ref int affectedRows, ref long insertedId)
{
return handler.GetResult(ref affectedRows, ref insertedId);
}
public virtual bool FetchDataRow(int statementId, int columns)
{
return handler.FetchDataRow(statementId, columns);
}
public virtual bool SkipDataRow()
{
return FetchDataRow(-1, 0);
}
public virtual void ExecuteDirect(string sql)
{
MySqlPacket p = new MySqlPacket(Encoding);
p.WriteString(sql);
SendQuery(p);
NextResult(0, false);
}
public MySqlField[] GetColumns(int count)
{
MySqlField[] fields = new MySqlField[count];
for (int i = 0; i < count; i++)
fields[i] = new MySqlField(this);
handler.GetColumnsData(fields);
return fields;
}
public virtual int PrepareStatement(string sql, ref MySqlField[] parameters)
{
return handler.PrepareStatement(sql, ref parameters);
}
public IMySqlValue ReadColumnValue(int index, MySqlField field, IMySqlValue value)
{
return handler.ReadColumnValue(index, field, value);
}
public void SkipColumnValue(IMySqlValue valObject)
{
handler.SkipColumnValue(valObject);
}
public void ResetTimeout(int timeoutMilliseconds)
{
handler.ResetTimeout(timeoutMilliseconds);
}
public bool Ping()
{
return handler.Ping();
}
public virtual void SetDatabase(string dbName)
{
handler.SetDatabase(dbName);
}
public virtual void ExecuteStatement(MySqlPacket packetToExecute)
{
handler.ExecuteStatement(packetToExecute);
}
public virtual void CloseStatement(int id)
{
handler.CloseStatement(id);
}
public virtual void Reset()
{
handler.Reset();
}
public virtual void CloseQuery(MySqlConnection connection, int statementId)
{
if (handler.WarningCount > 0)
ReportWarnings(connection);
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
// Avoid cyclic calls to Dispose.
if (disposed)
return;
try
{
ResetTimeout(1000);
handler.Close(isOpen);
// if we are pooling, then release ourselves
if (connectionString.Pooling)
MySqlPoolManager.RemoveConnection(this);
}
catch (Exception)
{
if (disposing)
throw;
}
finally
{
reader = null;
isOpen = false;
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
internal interface IDriver
{
int ThreadId { get; }
DBVersion Version { get; }
ServerStatusFlags ServerStatus { get; }
ClientFlags Flags { get; }
void Configure();
void Open();
void SendQuery(MySqlPacket packet);
void Close(bool isOpen);
bool Ping();
int GetResult(ref int affectedRows, ref long insertedId);
bool FetchDataRow(int statementId, int columns);
int PrepareStatement(string sql, ref MySqlField[] parameters);
void ExecuteStatement(MySqlPacket packet);
void CloseStatement(int statementId);
void SetDatabase(string dbName);
void Reset();
IMySqlValue ReadColumnValue(int index, MySqlField field, IMySqlValue valObject);
void SkipColumnValue(IMySqlValue valueObject);
void GetColumnsData(MySqlField[] columns);
void ResetTimeout(int timeout);
int WarningCount { get; }
}
}
| |
using System;
using UnityEngine.Events;
using UnityEngine.Rendering;
namespace UnityEngine.UI
{
public abstract class MaskableGraphic : Graphic, IClippable, IMaskable, IMaterialModifier
{
[NonSerialized]
protected bool m_ShouldRecalculateStencil = true;
[NonSerialized]
protected Material m_MaskMaterial;
[NonSerialized]
private RectMask2D m_ParentMask;
// m_Maskable is whether this graphic is allowed to be masked or not. It has the matching public property maskable.
// The default for m_Maskable is true, so graphics under a mask are masked out of the box.
// The maskable property can be turned off from script by the user if masking is not desired.
// m_IncludeForMasking is whether we actually consider this graphic for masking or not - this is an implementation detail.
// m_IncludeForMasking should only be true if m_Maskable is true AND a parent of the graphic has an IMask component.
// Things would still work correctly if m_IncludeForMasking was always true when m_Maskable is, but performance would suffer.
[NonSerialized]
private bool m_Maskable = true;
[NonSerialized]
[Obsolete("Not used anymore.", true)]
protected bool m_IncludeForMasking = false;
[Serializable]
public class CullStateChangedEvent : UnityEvent<bool> {}
// Event delegates triggered on click.
[SerializeField]
private CullStateChangedEvent m_OnCullStateChanged = new CullStateChangedEvent();
public CullStateChangedEvent onCullStateChanged
{
get { return m_OnCullStateChanged; }
set { m_OnCullStateChanged = value; }
}
public bool maskable
{
get { return m_Maskable; }
set
{
if (value == m_Maskable)
return;
m_Maskable = value;
m_ShouldRecalculateStencil = true;
SetMaterialDirty();
}
}
[NonSerialized]
[Obsolete("Not used anymore", true)]
protected bool m_ShouldRecalculate = true;
[NonSerialized]
protected int m_StencilValue;
public virtual Material GetModifiedMaterial(Material baseMaterial)
{
var toUse = baseMaterial;
if (m_ShouldRecalculateStencil)
{
var rootCanvas = MaskUtilities.FindRootSortOverrideCanvas(transform);
m_StencilValue = maskable ? MaskUtilities.GetStencilDepth(transform, rootCanvas) : 0;
m_ShouldRecalculateStencil = false;
}
// if we have a Mask component then it will
// generate the mask material. This is an optimisation
// it adds some coupling between components though :(
if (m_StencilValue > 0 && GetComponent<Mask>() == null)
{
var maskMat = StencilMaterial.Add(toUse, (1 << m_StencilValue) - 1, StencilOp.Keep, CompareFunction.Equal, ColorWriteMask.All, (1 << m_StencilValue) - 1, 0);
StencilMaterial.Remove(m_MaskMaterial);
m_MaskMaterial = maskMat;
toUse = m_MaskMaterial;
}
return toUse;
}
public virtual void Cull(Rect clipRect, bool validRect)
{
if (!canvasRenderer.hasMoved)
return;
var cull = !validRect || !clipRect.Overlaps(canvasRect);
var cullingChanged = canvasRenderer.cull != cull;
canvasRenderer.cull = cull;
if (cullingChanged)
{
m_OnCullStateChanged.Invoke(cull);
SetVerticesDirty();
}
}
public virtual void SetClipRect(Rect clipRect, bool validRect)
{
if (validRect)
canvasRenderer.EnableRectClipping(clipRect);
else
canvasRenderer.DisableRectClipping();
}
protected override void OnEnable()
{
base.OnEnable();
m_ShouldRecalculateStencil = true;
UpdateClipParent();
SetMaterialDirty();
}
protected override void OnDisable()
{
base.OnDisable();
m_ShouldRecalculateStencil = true;
SetMaterialDirty();
UpdateClipParent();
StencilMaterial.Remove(m_MaskMaterial);
m_MaskMaterial = null;
}
#if UNITY_EDITOR
protected override void OnValidate()
{
base.OnValidate();
m_ShouldRecalculateStencil = true;
UpdateClipParent();
SetMaterialDirty();
}
#endif
protected override void OnTransformParentChanged()
{
base.OnTransformParentChanged();
m_ShouldRecalculateStencil = true;
UpdateClipParent();
SetMaterialDirty();
}
[Obsolete("Not used anymore.", true)]
public virtual void ParentMaskStateChanged() {}
protected override void OnCanvasHierarchyChanged()
{
base.OnCanvasHierarchyChanged();
m_ShouldRecalculateStencil = true;
UpdateClipParent();
SetMaterialDirty();
}
readonly Vector3[] m_Corners = new Vector3[4];
private Rect canvasRect
{
get
{
rectTransform.GetWorldCorners(m_Corners);
if (canvas)
{
for (int i = 0; i < 4; ++i)
m_Corners[i] = canvas.transform.InverseTransformPoint(m_Corners[i]);
}
return new Rect(m_Corners[0].x, m_Corners[0].y, m_Corners[2].x - m_Corners[0].x, m_Corners[2].y - m_Corners[0].y);
}
}
private void UpdateClipParent()
{
var newParent = (maskable && IsActive()) ? MaskUtilities.GetRectMaskForClippable(this) : null;
if (newParent != m_ParentMask && m_ParentMask != null)
m_ParentMask.RemoveClippable(this);
if (newParent != null)
newParent.AddClippable(this);
m_ParentMask = newParent;
}
public virtual void RecalculateClipping()
{
UpdateClipParent();
}
public virtual void RecalculateMasking()
{
m_ShouldRecalculateStencil = true;
SetMaterialDirty();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
//
internal partial class SslStreamInternal
{
private const int FrameOverhead = 32;
private const int ReadBufferSize = 4096 * 4 + FrameOverhead; // We read in 16K chunks + headers.
private readonly SslState _sslState;
private int _nestedWrite;
private int _nestedRead;
// Never updated directly, special properties are used. This is the read buffer.
private byte[] _internalBuffer;
private int _internalOffset;
private int _internalBufferCount;
private int _decryptedBytesOffset;
private int _decryptedBytesCount;
internal SslStreamInternal(SslState sslState)
{
_sslState = sslState;
_decryptedBytesOffset = 0;
_decryptedBytesCount = 0;
}
//We will only free the read buffer if it
//actually contains no decrypted or encrypted bytes
private void ReturnReadBufferIfEmpty()
{
if (_internalBuffer != null && _decryptedBytesCount == 0 && _internalBufferCount == 0)
{
ArrayPool<byte>.Shared.Return(_internalBuffer);
_internalBuffer = null;
_internalBufferCount = 0;
_internalOffset = 0;
_decryptedBytesCount = 0;
_decryptedBytesOffset = 0;
}
}
~SslStreamInternal()
{
if (_internalBuffer != null)
{
ArrayPool<byte>.Shared.Return(_internalBuffer);
_internalBuffer = null;
}
}
internal int ReadByte()
{
if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "ReadByte", "read"));
}
// If there's any data in the buffer, take one byte, and we're done.
try
{
if (_decryptedBytesCount > 0)
{
int b = _internalBuffer[_decryptedBytesOffset++];
_decryptedBytesCount--;
ReturnReadBufferIfEmpty();
return b;
}
}
finally
{
// Regardless of whether we were able to read a byte from the buffer,
// reset the read tracking. If we weren't able to read a byte, the
// subsequent call to Read will set the flag again.
_nestedRead = 0;
}
// Otherwise, fall back to reading a byte via Read, the same way Stream.ReadByte does.
// This allocation is unfortunate but should be relatively rare, as it'll only occur once
// per buffer fill internally by Read.
byte[] oneByte = new byte[1];
int bytesRead = Read(oneByte, 0, 1);
Debug.Assert(bytesRead == 0 || bytesRead == 1);
return bytesRead == 1 ? oneByte[0] : -1;
}
internal int Read(byte[] buffer, int offset, int count)
{
ValidateParameters(buffer, offset, count);
SslReadSync reader = new SslReadSync(_sslState);
return ReadAsyncInternal(reader, new Memory<byte>(buffer, offset, count)).GetAwaiter().GetResult();
}
internal void Write(byte[] buffer, int offset, int count)
{
ValidateParameters(buffer, offset, count);
SslWriteSync writeAdapter = new SslWriteSync(_sslState);
WriteAsyncInternal(writeAdapter, new ReadOnlyMemory<byte>(buffer, offset, count)).GetAwaiter().GetResult();
}
internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
}
internal Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateParameters(buffer, offset, count);
SslReadAsync read = new SslReadAsync(_sslState, cancellationToken);
return ReadAsyncInternal(read, new Memory<byte>(buffer, offset, count)).AsTask();
}
internal ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
SslReadAsync read = new SslReadAsync(_sslState, cancellationToken);
return ReadAsyncInternal(read, buffer);
}
internal int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult);
internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
}
internal void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult);
internal Task WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
SslWriteAsync writeAdapter = new SslWriteAsync(_sslState, cancellationToken);
return WriteAsyncInternal(writeAdapter, buffer);
}
internal Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateParameters(buffer, offset, count);
return WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
}
private void ResetReadBuffer()
{
Debug.Assert(_decryptedBytesCount == 0);
Debug.Assert(_internalBuffer == null || _internalBufferCount > 0);
if (_internalBuffer == null)
{
_internalBuffer = ArrayPool<byte>.Shared.Rent(ReadBufferSize);
}
else if (_internalOffset > 0)
{
// We have buffered data at a non-zero offset.
// To maximize the buffer space available for the next read,
// copy the existing data down to the beginning of the buffer.
Buffer.BlockCopy(_internalBuffer, _internalOffset, _internalBuffer, 0, _internalBufferCount);
_internalOffset = 0;
}
}
//
// Validates user parameters for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.net_offset_plus_count);
}
}
private async ValueTask<int> ReadAsyncInternal<TReadAdapter>(TReadAdapter adapter, Memory<byte> buffer)
where TReadAdapter : ISslReadAdapter
{
if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, nameof(ReadAsync), "read"));
}
while (true)
{
int copyBytes;
if (_decryptedBytesCount != 0)
{
copyBytes = CopyDecryptedData(buffer);
_sslState.FinishRead(null);
_nestedRead = 0;
return copyBytes;
}
copyBytes = await adapter.LockAsync(buffer).ConfigureAwait(false);
try
{
if (copyBytes > 0)
{
return copyBytes;
}
ResetReadBuffer();
int readBytes = await FillBufferAsync(adapter, SecureChannel.ReadHeaderSize).ConfigureAwait(false);
if (readBytes == 0)
{
return 0;
}
int payloadBytes = _sslState.GetRemainingFrameSize(_internalBuffer, _internalOffset, readBytes);
if (payloadBytes < 0)
{
throw new IOException(SR.net_frame_read_size);
}
readBytes = await FillBufferAsync(adapter, SecureChannel.ReadHeaderSize + payloadBytes).ConfigureAwait(false);
if (readBytes < 0)
{
throw new IOException(SR.net_frame_read_size);
}
// At this point, readBytes contains the size of the header plus body.
// Set _decrytpedBytesOffset/Count to the current frame we have (including header)
// DecryptData will decrypt in-place and modify these to point to the actual decrypted data, which may be smaller.
_decryptedBytesOffset = _internalOffset;
_decryptedBytesCount = readBytes;
SecurityStatusPal status = _sslState.DecryptData(_internalBuffer, ref _decryptedBytesOffset, ref _decryptedBytesCount);
// Treat the bytes we just decrypted as consumed
// Note, we won't do another buffer read until the decrypted bytes are processed
ConsumeBufferedBytes(readBytes);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
byte[] extraBuffer = null;
if (_decryptedBytesCount != 0)
{
extraBuffer = new byte[_decryptedBytesCount];
Buffer.BlockCopy(_internalBuffer, _decryptedBytesOffset, extraBuffer, 0, _decryptedBytesCount);
_decryptedBytesCount = 0;
}
ProtocolToken message = new ProtocolToken(null, status);
if (NetEventSource.IsEnabled)
NetEventSource.Info(null, $"***Processing an error Status = {message.Status}");
if (message.Renegotiate)
{
if (!_sslState._sslAuthenticationOptions.AllowRenegotiation)
{
throw new IOException(SR.net_ssl_io_renego);
}
_sslState.ReplyOnReAuthentication(extraBuffer);
// Loop on read.
continue;
}
if (message.CloseConnection)
{
_sslState.FinishRead(null);
return 0;
}
throw new IOException(SR.net_io_decrypt, message.GetException());
}
}
catch (Exception e)
{
_sslState.FinishRead(null);
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
_nestedRead = 0;
}
}
}
private Task WriteAsyncInternal<TWriteAdapter>(TWriteAdapter writeAdapter, ReadOnlyMemory<byte> buffer)
where TWriteAdapter : struct, ISslWriteAdapter
{
_sslState.CheckThrow(authSuccessCheck: true, shutdownCheck: true);
if (buffer.Length == 0 && !SslStreamPal.CanEncryptEmptyMessage)
{
// If it's an empty message and the PAL doesn't support that, we're done.
return Task.CompletedTask;
}
if (Interlocked.Exchange(ref _nestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, nameof(WriteAsync), "write"));
}
Task t = buffer.Length < _sslState.MaxDataSize ?
WriteSingleChunk(writeAdapter, buffer) :
WriteAsyncChunked(writeAdapter, buffer);
if (t.IsCompletedSuccessfully)
{
_nestedWrite = 0;
return t;
}
return ExitWriteAsync(t);
async Task ExitWriteAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception e)
{
_sslState.FinishWrite();
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
_nestedWrite = 0;
}
}
}
private Task WriteSingleChunk<TWriteAdapter>(TWriteAdapter writeAdapter, ReadOnlyMemory<byte> buffer)
where TWriteAdapter : struct, ISslWriteAdapter
{
// Request a write IO slot.
Task ioSlot = writeAdapter.LockAsync();
if (!ioSlot.IsCompletedSuccessfully)
{
// Operation is async and has been queued, return.
return WaitForWriteIOSlot(writeAdapter, ioSlot, buffer);
}
byte[] rentedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length + FrameOverhead);
byte[] outBuffer = rentedBuffer;
SecurityStatusPal status = _sslState.EncryptData(buffer, ref outBuffer, out int encryptedBytes);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
// Re-handshake status is not supported.
ArrayPool<byte>.Shared.Return(rentedBuffer);
ProtocolToken message = new ProtocolToken(null, status);
return Task.FromException(new IOException(SR.net_io_encrypt, message.GetException()));
}
Task t = writeAdapter.WriteAsync(outBuffer, 0, encryptedBytes);
if (t.IsCompletedSuccessfully)
{
ArrayPool<byte>.Shared.Return(rentedBuffer);
_sslState.FinishWrite();
return t;
}
else
{
return CompleteAsync(t, rentedBuffer);
}
async Task WaitForWriteIOSlot(TWriteAdapter wAdapter, Task lockTask, ReadOnlyMemory<byte> buff)
{
await lockTask.ConfigureAwait(false);
await WriteSingleChunk(wAdapter, buff).ConfigureAwait(false);
}
async Task CompleteAsync(Task writeTask, byte[] bufferToReturn)
{
try
{
await writeTask.ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(bufferToReturn);
_sslState.FinishWrite();
}
}
}
private async Task WriteAsyncChunked<TWriteAdapter>(TWriteAdapter writeAdapter, ReadOnlyMemory<byte> buffer)
where TWriteAdapter : struct, ISslWriteAdapter
{
do
{
int chunkBytes = Math.Min(buffer.Length, _sslState.MaxDataSize);
await WriteSingleChunk(writeAdapter, buffer.Slice(0, chunkBytes)).ConfigureAwait(false);
buffer = buffer.Slice(chunkBytes);
} while (buffer.Length != 0);
}
private ValueTask<int> FillBufferAsync<TReadAdapter>(TReadAdapter adapter, int minSize)
where TReadAdapter : ISslReadAdapter
{
if (_internalBufferCount >= minSize)
{
return new ValueTask<int>(minSize);
}
int initialCount = _internalBufferCount;
do
{
ValueTask<int> t = adapter.ReadAsync(_internalBuffer, _internalBufferCount, _internalBuffer.Length - _internalBufferCount);
if (!t.IsCompletedSuccessfully)
{
return new ValueTask<int>(InternalFillBufferAsync(adapter, t.AsTask(), minSize, initialCount));
}
int bytes = t.Result;
if (bytes == 0)
{
if (_internalBufferCount != initialCount)
{
// We read some bytes, but not as many as we expected, so throw.
throw new IOException(SR.net_io_eof);
}
return new ValueTask<int>(0);
}
_internalBufferCount += bytes;
} while (_internalBufferCount < minSize);
return new ValueTask<int>(minSize);
async Task<int> InternalFillBufferAsync(TReadAdapter adap, Task<int> task, int min, int initial)
{
while (true)
{
int b = await task.ConfigureAwait(false);
if (b == 0)
{
if (_internalBufferCount != initial)
{
throw new IOException(SR.net_io_eof);
}
return 0;
}
_internalBufferCount += b;
if (_internalBufferCount >= min)
{
return min;
}
task = adap.ReadAsync(_internalBuffer, _internalBufferCount, _internalBuffer.Length - _internalBufferCount).AsTask();
}
}
}
private void ConsumeBufferedBytes(int byteCount)
{
Debug.Assert(byteCount >= 0);
Debug.Assert(byteCount <= _internalBufferCount);
_internalOffset += byteCount;
_internalBufferCount -= byteCount;
ReturnReadBufferIfEmpty();
}
private int CopyDecryptedData(Memory<byte> buffer)
{
Debug.Assert(_decryptedBytesCount > 0);
int copyBytes = Math.Min(_decryptedBytesCount, buffer.Length);
if (copyBytes != 0)
{
new Span<byte>(_internalBuffer, _decryptedBytesOffset, copyBytes).CopyTo(buffer.Span);
_decryptedBytesOffset += copyBytes;
_decryptedBytesCount -= copyBytes;
}
ReturnReadBufferIfEmpty();
return copyBytes;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
namespace Diva.Editor.Gui {
using System;
using Mono.Unix;
using Gtk;
using Core;
using Widgets;
using Commands;
using Util;
public class Window : Gtk.Window {
// Translatable ////////////////////////////////////////////////
readonly static string divaSS = Catalog.GetString
("Diva - {0}");
// Fields /////////////////////////////////////////////////////
VBox totalVBox = null; // The core container
VBox mainVBox = null; // Second-to-total container
MenuBar menuBar = null; // The menu bar
VideoFrame videoFrame = null; // Video output controller
StuffVBox stuffVBox = null; // Stuff container
TimelineVBox timelineVBox = null; // Timeline container
HBox upperHBox = null; // Horizontal box
Model.Root modelRoot = null; // The root of the model
HistoryWindow historyWindow = null; // Window with undo/redo history
TagsWindow tagsWindow = null; // Window to edit tags
ExportWindow exportWindow = null; // Window showing the export progress
bool hadPipelineError = false; // If we had a pipeline error
// Public methods /////////////////////////////////////////////
/* CONSTRUCTOR */
public Window (Model.Root root) : base (String.Format (divaSS, root.ProjectDetails.Name))
{
modelRoot = root;
// VideoFrame
videoFrame = new VideoFrame (root);
// Stuff
stuffVBox = new StuffVBox (root);
// Top HBox
upperHBox = new HBox (false, 6);
upperHBox.PackStart (videoFrame, true, true, 0);
upperHBox.PackStart (stuffVBox, false, false, 0);
// Timeline
timelineVBox = new TimelineVBox (modelRoot);
// Main VBox
mainVBox = new VBox (false, 12);
mainVBox.PackStart (upperHBox, true, true, 0);
mainVBox.PackStart (timelineVBox, false, false, 0);
mainVBox.BorderWidth = 6;
// Menu
menuBar = new MenuBar (root);
// Total VBox
totalVBox = new VBox (false, 6);
totalVBox.PackStart (menuBar, false, false, 0);
totalVBox.PackStart (mainVBox, true, true, 0);
// Model bind
modelRoot.Window.WaitCursorRequest += OnWaitCursorRequest;
modelRoot.Window.HistoryWindowRequest += OnHistoryWindowRequest;
modelRoot.Window.TagsWindowRequest += OnTagsWindowRequest;
modelRoot.Window.AboutWindowRequest += OnAboutWindowRequest;
modelRoot.Window.FullscreenRequest += OnFullscreenRequest;
modelRoot.Window.LockRequest += OnLockRequest;
modelRoot.Window.ExportWindowRequest += OnExportWindowRequest;
modelRoot.Pipeline.Error += OnPipelineError;
modelRoot.SaveNag += OnSaveNag;
// Add it all
Add (totalVBox);
// Geometry
if (Config.Ui.EditorWindowGeometry != "-1")
GtkFu.ParseGeometry (this, Config.Ui.EditorWindowGeometry);
else
Maximize ();
ShowAll ();
}
public void SaveGeometry ()
{
Config.Ui.EditorWindowGeometry = GtkFu.GetGeometry (this);
}
// Private methods ////////////////////////////////////////////
/* The model requests the cursor to change shape to/from */
void OnWaitCursorRequest (object o, Model.RequisitionArgs args)
{
if (args.Requisition)
GdkWindow.Cursor = new Gdk.Cursor (Gdk.CursorType.Watch);
else
GdkWindow.Cursor = null;
}
/* History window */
void OnHistoryWindowRequest (object o, Model.RequisitionArgs args)
{
if (args.Requisition == true)
if (historyWindow == null)
historyWindow = new HistoryWindow (modelRoot, this);
else
historyWindow.Present ();
else
if (historyWindow != null) {
historyWindow.SaveGeometry ();
historyWindow.Unbind ();
historyWindow.Destroy ();
historyWindow = null;
}
}
/* Tags window */
void OnTagsWindowRequest (object o, Model.RequisitionArgs args)
{
if (args.Requisition == true)
if (tagsWindow == null)
tagsWindow = new TagsWindow (modelRoot, this);
else
tagsWindow.Present ();
else
if (tagsWindow != null) {
tagsWindow.SaveGeometry ();
tagsWindow.Unbind ();
tagsWindow.Destroy ();
tagsWindow = null;
}
}
/* About window */
void OnAboutWindowRequest (object o, Model.RequisitionArgs args)
{
if (args.Requisition == true) {
Dialog dialog = new AboutDialog ();
dialog.Run ();
dialog.Destroy ();
}
}
void OnLockRequest (object o, Model.RequisitionArgs args)
{
if (args.Requisition == true) {
stuffVBox.Sensitive = false;
timelineVBox.Sensitive = false;
menuBar.Sensitive = false;
videoFrame.Sensitive = false;
}
if (args.Requisition == false) {
stuffVBox.Sensitive = true;
timelineVBox.Sensitive = true;
menuBar.Sensitive = true;
videoFrame.Sensitive = true;
}
}
void OnExportWindowRequest (object o, Model.RequisitionArgs args)
{
if (args.Requisition == true && exportWindow == null) {
exportWindow = new ExportWindow (modelRoot, this);
exportWindow.ShowAll ();
}
if (args.Requisition == false && exportWindow != null) {
exportWindow.UnBind ();
exportWindow.Destroy ();
exportWindow = null;
}
}
void OnFullscreenRequest (object o, Model.RequisitionArgs args)
{
if (args.Requisition == true &&
videoFrame.Fullscreen == false) {
mainVBox.BorderWidth = 0;
stuffVBox.Hide ();
timelineVBox.Hide ();
menuBar.Hide ();
videoFrame.Fullscreen = true;
Fullscreen ();
return;
// FIXME: Idle to force re-exposition
}
if (args.Requisition == false &&
videoFrame.Fullscreen == true) {
mainVBox.BorderWidth = 6;
stuffVBox.ShowAll ();
timelineVBox.ShowAll ();
menuBar.ShowAll ();
videoFrame.Fullscreen = false;
Unfullscreen ();
return;
// FIXME: Idle to force re-exposition
}
}
void OnPipelineError (object o, Model.PipelineErrorArgs args)
{
// We display only first error, not to create a situation where
// user is blocked due to message dialog spam
if (hadPipelineError)
return;
hadPipelineError = true;
PipelineErrorDialog dialog = new PipelineErrorDialog (this, args.Error);
dialog.Run ();
dialog.Destroy ();
}
protected override bool OnDeleteEvent (Gdk.Event evnt)
{
modelRoot.QuitModel (Model.QuitMode.Complete);
return true;
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
if (evnt.Key == Gdk.Key.Escape &&
videoFrame.Fullscreen == true) {
modelRoot.Window.StopFullscreen ();
return true;
} else
return base.OnKeyPressEvent (evnt);
}
void OnSaveNag (object o, Model.SaveNagActionArgs args)
{
SaveNagDialog dialog = new SaveNagDialog (this, modelRoot.ProjectDetails.Name);
int response = dialog.Run ();
args.Action = dialog.ParseResponse (response);
dialog.Destroy ();
}
}
}
| |
#define PROTOTYPE
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ProBuilder2.Common;
using ProBuilder2.MeshOperations;
using ProBuilder2.Math;
namespace ProBuilder2.Examples
{
[RequireComponent(typeof(AudioSource))]
public class IcoBumpin : MonoBehaviour
{
pb_Object ico; // A reference to the icosphere pb_Object component
Mesh icoMesh; // A reference to the icosphere mesh (cached because we access the vertex array every frame)
Transform icoTransform; // A reference to the icosphere transform component. Cached because I can't remember if GameObject.transform is still a performance drain :|
AudioSource audioSource;// Cached reference to the audiosource.
/**
* Holds a pb_Face, the normal of that face, and the index of every vertex that touches it (sharedIndices).
*/
struct FaceRef
{
public pb_Face face;
public Vector3 nrm; // face normal
public int[] indices; // all vertex indices (including shared connected vertices)
public FaceRef(pb_Face f, Vector3 n, int[] i)
{
face = f;
nrm = n;
indices = i;
}
}
// All faces that have been extruded
FaceRef[] outsides;
// Keep a copy of the original vertex array to calculate the distance from origin.
Vector3[] original_vertices, displaced_vertices;
// The radius of the mesh icosphere on instantiation.
[Range(1f, 10f)]
public float icoRadius = 2f;
// The number of subdivisions to give the icosphere.
[Range(0, 3)]
public int icoSubdivisions = 2;
// How far along the normal should each face be extruded when at idle (no audio input).
[Range(0f, 1f)]
public float startingExtrusion = .1f;
// The material to apply to the icosphere.
public Material material;
// The max distance a frequency range will extrude a face.
[Range(1f, 50f)]
public float extrusion = 30f;
// An FFT returns a spectrum including frequencies that are out of human hearing range -
// this restricts the number of bins used from the spectrum to the lower @fftBounds.
[Range(8, 128)]
public int fftBounds = 32;
// How high the icosphere transform will bounce (sample volume determines height).
[Range(0f, 10f)]
public float verticalBounce = 4f;
// Optionally weights the frequency amplitude when calculating extrude distance.
public AnimationCurve frequencyCurve;
// A reference to the line renderer that will be used to render the raw waveform.
public LineRenderer waveform;
// The y size of the waveform.
public float waveformHeight = 2f;
// How far from the icosphere should the waveform be.
public float waveformRadius = 20f;
// If @rotateWaveformRing is true, this is the speed it will travel.
public float waveformSpeed = .1f;
// If true, the waveform ring will randomly orbit the icosphere.
public bool rotateWaveformRing = false;
// If true, the waveform will bounce up and down with the icosphere.
public bool bounceWaveform = false;
public GameObject missingClipWarning;
// Icosphere's starting position.
Vector3 icoPosition = Vector3.zero;
float faces_length;
const float TWOPI = 6.283185f; // 2 * PI
const int WAVEFORM_SAMPLES = 1024; // How many samples make up the waveform ring.
const int FFT_SAMPLES = 4096; // How many samples are used in the FFT. More means higher resolution.
// Keep copy of the last frame's sample data to average with the current when calculating
// deformation amounts. Smoothes the visual effect.
float[] fft = new float[FFT_SAMPLES],
fft_history = new float[FFT_SAMPLES],
data = new float[WAVEFORM_SAMPLES],
data_history = new float[WAVEFORM_SAMPLES];
// Root mean square of raw data (volume, but not in dB).
float rms = 0f, rms_history = 0f;
/**
* Creates the icosphere, and loads all the cache information.
*/
void Start()
{
audioSource = GetComponent<AudioSource>();
if( audioSource.clip == null )
missingClipWarning.SetActive(true);
// Create a new icosphere.
ico = pb_ShapeGenerator.IcosahedronGenerator(icoRadius, icoSubdivisions);
// Shell is all the faces on the new icosphere.
pb_Face[] shell = ico.faces;
// Materials are set per-face on pb_Object meshes. pb_Objects will automatically
// condense the mesh to the smallest set of subMeshes possible based on materials.
foreach(pb_Face f in shell)
f.SetMaterial( material );
pb_Face[] connectingFaces;
// Extrude all faces on the icosphere by a small amount. The third boolean parameter
// specifies that extrusion should treat each face as an individual, not try to group
// all faces together.
ico.Extrude(shell, startingExtrusion, false, out connectingFaces);
// ToMesh builds the mesh positions, submesh, and triangle arrays. Call after adding
// or deleting vertices, or changing face properties.
ico.ToMesh();
// Refresh builds the normals, tangents, and UVs.
ico.Refresh();
outsides = new FaceRef[shell.Length];
Dictionary<int, int> lookup = ico.sharedIndices.ToDictionary();
// Populate the outsides[] cache. This is a reference to the tops of each extruded column, including
// copies of the sharedIndices.
for(int i = 0; i < shell.Length; ++i)
outsides[i] = new FaceRef( shell[i],
pb_Math.Normal(ico, shell[i]),
ico.sharedIndices.AllIndicesWithValues(lookup, shell[i].distinctIndices).ToArray()
);
// Store copy of positions array un-modified
original_vertices = new Vector3[ico.vertices.Length];
System.Array.Copy(ico.vertices, original_vertices, ico.vertices.Length);
// displaced_vertices should mirror icosphere mesh vertices.
displaced_vertices = ico.vertices;
icoMesh = ico.msh;
icoTransform = ico.transform;
faces_length = (float)outsides.Length;
// Build the waveform ring.
icoPosition = icoTransform.position;
waveform.SetVertexCount(WAVEFORM_SAMPLES);
if( bounceWaveform )
waveform.transform.parent = icoTransform;
audioSource.Play();
}
void Update()
{
// fetch the fft spectrum
audioSource.GetSpectrumData(fft, 0, FFTWindow.BlackmanHarris);
// get raw data for waveform
audioSource.GetOutputData(data, 0);
// calculate root mean square (volume)
rms = RMS(data);
/**
* For each face, translate the vertices some distance depending on the frequency range assigned.
* Not using the TranslateVertices() pb_Object extension method because as a convenience, that method
* gathers the sharedIndices per-face on every call, which while not tremondously expensive in most
* contexts, is far too slow for use when dealing with audio, and especially so when the mesh is
* somewhat large.
*/
for(int i = 0; i < outsides.Length; i++)
{
float normalizedIndex = (i/faces_length);
int n = (int)(normalizedIndex*fftBounds);
Vector3 displacement = outsides[i].nrm * ( ((fft[n]+fft_history[n]) * .5f) * (frequencyCurve.Evaluate(normalizedIndex) * .5f + .5f)) * extrusion;
foreach(int t in outsides[i].indices)
{
displaced_vertices[t] = original_vertices[t] + displacement;
}
}
Vector3 vec = Vector3.zero;
// Waveform ring
for(int i = 0; i < WAVEFORM_SAMPLES; i++)
{
int n = i < WAVEFORM_SAMPLES-1 ? i : 0;
vec.x = Mathf.Cos((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight));
vec.z = Mathf.Sin((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight));
vec.y = 0f;
waveform.SetPosition(i, vec);
}
// Ring rotation
if( rotateWaveformRing )
{
Vector3 rot = waveform.transform.localRotation.eulerAngles;
rot.x = Mathf.PerlinNoise(Time.time * waveformSpeed, 0f) * 360f;
rot.y = Mathf.PerlinNoise(0f, Time.time * waveformSpeed) * 360f;
waveform.transform.localRotation = Quaternion.Euler(rot);
}
icoPosition.y = -verticalBounce + ((rms + rms_history) * verticalBounce);
icoTransform.position = icoPosition;
// Keep copy of last FFT samples so we can average with the current. Smoothes the movement.
System.Array.Copy(fft, fft_history, FFT_SAMPLES);
System.Array.Copy(data, data_history, WAVEFORM_SAMPLES);
rms_history = rms;
icoMesh.vertices = displaced_vertices;
}
/**
* Root mean square is a good approximation of perceived loudness.
*/
float RMS(float[] arr)
{
float v = 0f,
len = (float)arr.Length;
for(int i = 0; i < len; i++)
v += Mathf.Abs(arr[i]);
return Mathf.Sqrt(v / (float)len);
}
}
}
| |
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 Stardust.Interstellar.Test.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.NodejsTools.Jade
{
internal partial class JadeTokenizer : Tokenizer<JadeToken>
{
private void OnTag()
{
var ident = string.Empty;
var blockIndent = CalculateLineIndent();
// regular tag like
// html
// body
var range = ParseTagName();
if (range.Length > 0)
{
ident = this._cs.GetSubstringAt(range.Start, range.Length);
if (JadeTagKeywords.IsKeyword(ident))
{
// extends, javascripts:, stylesheets:
var length = this._cs.CurrentChar == ':' ? range.Length + 1 : range.Length;
AddToken(JadeTokenType.TagKeyword, range.Start, length);
if (this._cs.CurrentChar != ':' && StringComparer.Ordinal.Equals(ident, "mixin"))
{
SkipWhiteSpace();
if (!this._cs.IsAtNewLine())
{
OnTag();
}
}
else
{
SkipToEndOfLine();
}
return;
}
if (this._cs.CurrentChar == ':')
{
// Block expansion like
// li.first: a(href='#') foo
AddToken(JadeTokenType.TagName, range.Start, range.Length);
this._cs.MoveToNextChar();
SkipWhiteSpace();
if (!this._cs.IsAtNewLine())
{
OnTag();
}
return;
}
if (JadeCodeKeywords.IsKeyword(ident))
{
AddToken(JadeTokenType.CodeKeyword, range.Start, range.Length);
OnInlineCode();
return;
}
AddToken(JadeTokenType.TagName, range.Start, range.Length);
}
while (!this._cs.IsWhiteSpace() && !this._cs.IsEndOfStream())
{
if (this._cs.CurrentChar == '.' && char.IsWhiteSpace(this._cs.NextChar))
{
// If this is last ., then what follows is a text literal
if (StringComparer.OrdinalIgnoreCase.Equals(ident, "script"))
{
this._cs.MoveToNextChar();
OnScript(blockIndent);
}
else if (StringComparer.OrdinalIgnoreCase.Equals(ident, "style"))
{
this._cs.MoveToNextChar();
OnStyle(blockIndent);
}
else if (IsAllWhiteSpaceBeforeEndOfLine(this._cs.Position + 1))
{
SkipToEndOfBlock(blockIndent, text: true);
}
else
{
this._cs.MoveToNextChar();
}
return;
}
if (this._cs.CurrentChar == '(')
{
OnAttributes(')');
}
if (this._cs.CurrentChar == '#' || this._cs.CurrentChar == '.')
{
var isID = this._cs.CurrentChar == '#';
// container(a=b).bar or container(a=b)#bar
var selectorRange = GetNonWSSequence("(:=.#");
if (selectorRange.Length > 0)
{
AddToken(
isID ? JadeTokenType.IdLiteral : JadeTokenType.ClassLiteral,
selectorRange.Start,
selectorRange.Length
);
if (char.IsWhiteSpace(this._cs.CurrentChar) && this._cs.LookAhead(-1) == '.')
{
this._cs.Position--;
}
}
}
if (this._cs.CurrentChar != '.' && this._cs.CurrentChar != '#' && this._cs.CurrentChar != '(')
{
break;
}
}
if (this._cs.CurrentChar == ':')
{
// Block expansion like
// li.first: a(href='#') foo
this._cs.MoveToNextChar();
SkipWhiteSpace();
if (!this._cs.IsAtNewLine())
{
OnTag();
}
return;
}
// There may be ws between tag name and = sign. However, = must be on the same line.
var allWsToEol = IsAllWhiteSpaceBeforeEndOfLine(this._cs.Position);
if (!allWsToEol)
{
SkipWhiteSpace();
if (this._cs.CurrentChar == '=' || (this._cs.CurrentChar == '!' && this._cs.NextChar == '='))
{
// Something like 'foo ='
var length = this._cs.CurrentChar == '!' ? 2 : 1;
AddToken(JadeTokenType.Operator, this._cs.Position, length);
this._cs.Advance(length);
OnInlineCode();
}
else
{
OnText(strings: false, html: true, entities: true);
}
}
else
{
if (StringComparer.OrdinalIgnoreCase.Equals(ident, "script"))
{
OnScript(blockIndent);
}
else if (StringComparer.OrdinalIgnoreCase.Equals(ident, "style"))
{
OnStyle(blockIndent);
}
else
{
SkipToEndOfLine();
}
}
}
protected ITextRange ParseTagName()
{
var start = this._cs.Position;
var count = 0;
while (!this._cs.IsEndOfStream() && !this._cs.IsWhiteSpace() &&
(this._cs.IsAnsiLetter() || this._cs.IsDecimal() || this._cs.CurrentChar == '_' || (count > 0 && this._cs.CurrentChar == '-')))
{
if (this._cs.CurrentChar == ':')
{
if (this._cs.NextChar != '_' && (this._cs.NextChar < 'A' || this._cs.NextChar > 'z'))
{
break; // allow tags with namespaces
}
}
this._cs.MoveToNextChar();
count++;
}
return TextRange.FromBounds(start, this._cs.Position);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using DataTables.AspNet.Samples.WebApi2.BasicIntegration.Areas.HelpPage.ModelDescriptions;
using DataTables.AspNet.Samples.WebApi2.BasicIntegration.Areas.HelpPage.Models;
namespace DataTables.AspNet.Samples.WebApi2.BasicIntegration.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* 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
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.Diagnostics;
using System.IO;
namespace Sanford.Multimedia.Midi
{
/// <summary>
/// Defintes constants representing SMPTE frame rates.
/// </summary>
public enum SmpteFrameRate
{
Smpte24 = 24,
Smpte25 = 25,
Smpte30Drop = 29,
Smpte30 = 30
}
/// <summary>
/// The different types of sequences.
/// </summary>
public enum SequenceType
{
Ppqn,
Smpte
}
/// <summary>
/// Represents MIDI file properties.
/// </summary>
internal class MidiFileProperties
{
private const int PropertyLength = 2;
private static readonly byte[] MidiFileHeader =
{
(byte)'M',
(byte)'T',
(byte)'h',
(byte)'d',
0,
0,
0,
6
};
private int format = 1;
private int trackCount = 0;
private int division = PpqnClock.PpqnMinValue;
private SequenceType sequenceType = SequenceType.Ppqn;
public MidiFileProperties()
{
}
public void Read(Stream strm)
{
#region Require
if(strm == null)
{
throw new ArgumentNullException("strm");
}
#endregion
format = trackCount = division = 0;
FindHeader(strm);
Format = (int)ReadProperty(strm);
TrackCount = (int)ReadProperty(strm);
Division = (int)ReadProperty(strm);
#region Invariant
AssertValid();
#endregion
}
private void FindHeader(Stream stream)
{
bool found = false;
int result;
while(!found)
{
result = stream.ReadByte();
if(result == 'M')
{
result = stream.ReadByte();
if(result == 'T')
{
result = stream.ReadByte();
if(result == 'h')
{
result = stream.ReadByte();
if(result == 'd')
{
found = true;
}
}
}
}
if(result < 0)
{
throw new MidiFileException("Unable to find MIDI file header.");
}
}
// Eat the header length.
for(int i = 0; i < 4; i++)
{
if(stream.ReadByte() < 0)
{
throw new MidiFileException("Unable to find MIDI file header.");
}
}
}
private ushort ReadProperty(Stream strm)
{
byte[] data = new byte[PropertyLength];
int result = strm.Read(data, 0, data.Length);
if(result != data.Length)
{
throw new MidiFileException("End of MIDI file unexpectedly reached.");
}
if(BitConverter.IsLittleEndian)
{
Array.Reverse(data);
}
return BitConverter.ToUInt16(data, 0);
}
public void Write(Stream strm)
{
#region Require
if(strm == null)
{
throw new ArgumentNullException("strm");
}
#endregion
strm.Write(MidiFileHeader, 0, MidiFileHeader.Length);
WriteProperty(strm, (ushort)Format);
WriteProperty(strm, (ushort)TrackCount);
WriteProperty(strm, (ushort)Division);
}
private void WriteProperty(Stream strm, ushort property)
{
byte[] data = BitConverter.GetBytes(property);
if(BitConverter.IsLittleEndian)
{
Array.Reverse(data);
}
strm.Write(data, 0, PropertyLength);
}
private static bool IsSmpte(int division)
{
bool result;
byte[] data = BitConverter.GetBytes((short)division);
if(BitConverter.IsLittleEndian)
{
Array.Reverse(data);
}
if((sbyte)data[0] < 0)
{
result = true;
}
else
{
result = false;
}
return result;
}
[Conditional("DEBUG")]
private void AssertValid()
{
if(trackCount > 1)
{
Debug.Assert(Format == 1 || Format == 2);
}
if(IsSmpte(Division))
{
Debug.Assert(SequenceType == SequenceType.Smpte);
}
else
{
Debug.Assert(SequenceType == SequenceType.Ppqn);
Debug.Assert(Division >= PpqnClock.PpqnMinValue);
}
}
public int Format
{
get
{
return format;
}
set
{
#region Require
if(value < 0 || value > 2)
{
throw new ArgumentOutOfRangeException("Format", value,
"MIDI file format out of range.");
}
else if(value == 0 && trackCount > 1)
{
throw new ArgumentException(
"MIDI file format invalid for this track count.");
}
#endregion
format = value;
#region Invariant
AssertValid();
#endregion
}
}
public int TrackCount
{
get
{
return trackCount;
}
set
{
#region Require
if(value < 0)
{
throw new ArgumentOutOfRangeException("TrackCount", value,
"Track count out of range.");
}
else if(value > 1 && Format == 0)
{
throw new ArgumentException(
"Track count invalid for this format.");
}
#endregion
trackCount = value;
#region Invariant
AssertValid();
#endregion
}
}
public int Division
{
get
{
return division;
}
set
{
if(IsSmpte(value))
{
byte[] data = BitConverter.GetBytes((short)value);
if(BitConverter.IsLittleEndian)
{
Array.Reverse(data);
}
if((sbyte)data[0] != -(int)SmpteFrameRate.Smpte24 &&
(sbyte)data[0] != -(int)SmpteFrameRate.Smpte25 &&
(sbyte)data[0] != -(int)SmpteFrameRate.Smpte30 &&
(sbyte)data[0] != -(int)SmpteFrameRate.Smpte30Drop)
{
throw new ArgumentException("Invalid SMPTE frame rate.");
}
else
{
sequenceType = SequenceType.Smpte;
}
}
else
{
if(value < PpqnClock.PpqnMinValue)
{
throw new ArgumentOutOfRangeException("Ppqn", value,
"Pulses per quarter note is smaller than 24.");
}
else
{
sequenceType = SequenceType.Ppqn;
}
}
division = value;
#region Invariant
AssertValid();
#endregion
}
}
public SequenceType SequenceType
{
get
{
return sequenceType;
}
}
}
public class MidiFileException : ApplicationException
{
public MidiFileException(string message) : base(message)
{
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.Formula.Functions;
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
public class AVEDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.avedev(values);
}
}
public class AVERAGE : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return MathX.Average(values);
}
}
public class DEVSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.devsq(values);
}
}
public class SUM : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.Sum(values);
}
}
public class LARGE : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthLargest(values, k);
}
}
public class MAX : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.Max(values) : 0;
}
}
public class MIN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.Min(values) : 0;
}
}
public class MEDIAN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.median(values);
}
}
public class PRODUCT : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.Product(values);
}
}
public class SMALL : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthSmallest(values, k);
}
}
public class STDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.stdev(values);
}
}
public class SUMSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.Sumsq(values);
}
}
public class VAR : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.var(values);
}
};
public class VARP : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.varp(values);
}
};
public class SubtotalInstance : AggregateFunction
{
private AggregateFunction _func;
public SubtotalInstance(AggregateFunction func)
{
_func = func;
}
protected internal override double Evaluate(double[] values)
{
return _func.Evaluate(values);
}
/**
* ignore nested subtotals.
*/
public override bool IsSubtotalCounted
{
get
{
return false;
}
}
}
public class LargeSmall : Fixed2ArgFunction
{
private bool _isLarge;
protected LargeSmall(bool isLarge)
{
_isLarge = isLarge;
}
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0,
ValueEval arg1)
{
double dn;
try
{
ValueEval ve1 = OperandResolver.GetSingleValue(arg1, srcRowIndex, srcColumnIndex);
dn = OperandResolver.CoerceValueToDouble(ve1);
}
catch (EvaluationException)
{
// all errors in the second arg translate to #VALUE!
return ErrorEval.VALUE_INVALID;
}
// weird Excel behaviour on second arg
if (dn < 1.0)
{
// values between 0.0 and 1.0 result in #NUM!
return ErrorEval.NUM_ERROR;
}
// all other values are rounded up to the next integer
int k = (int)Math.Ceiling(dn);
double result;
try
{
double[] ds = NPOI.SS.Formula.Functions.AggregateFunction.ValueCollector.CollectValues(arg0);
if (k > ds.Length)
{
return ErrorEval.NUM_ERROR;
}
result = _isLarge ? StatsLib.kthLargest(ds, k) : StatsLib.kthSmallest(ds, k);
NumericFunction.CheckValue(result);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
return new NumberEval(result);
}
}
/**
* Returns the k-th percentile of values in a range. You can use this function to establish a threshold of
* acceptance. For example, you can decide to examine candidates who score above the 90th percentile.
*
* PERCENTILE(array,k)
* Array is the array or range of data that defines relative standing.
* K is the percentile value in the range 0..1, inclusive.
*
* <strong>Remarks</strong>
* <ul>
* <li>if array is empty or Contains more than 8,191 data points, PERCENTILE returns the #NUM! error value.</li>
* <li>If k is nonnumeric, PERCENTILE returns the #VALUE! error value.</li>
* <li>If k is < 0 or if k > 1, PERCENTILE returns the #NUM! error value.</li>
* <li>If k is not a multiple of 1/(n - 1), PERCENTILE interpolates to determine the value at the k-th percentile.</li>
* </ul>
*/
public class Percentile : Fixed2ArgFunction
{
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0,
ValueEval arg1)
{
double dn;
try
{
ValueEval ve1 = OperandResolver.GetSingleValue(arg1, srcRowIndex, srcColumnIndex);
dn = OperandResolver.CoerceValueToDouble(ve1);
}
catch (EvaluationException)
{
// all errors in the second arg translate to #VALUE!
return ErrorEval.VALUE_INVALID;
}
if (dn < 0 || dn > 1)
{ // has to be percentage
return ErrorEval.NUM_ERROR;
}
double result;
try
{
double[] ds = NPOI.SS.Formula.Functions.AggregateFunction.ValueCollector.CollectValues(arg0);
int N = ds.Length;
if (N == 0 || N > 8191)
{
return ErrorEval.NUM_ERROR;
}
double n = (N - 1) * dn + 1;
if (n == 1d)
{
result = StatsLib.kthSmallest(ds, 1);
}
else if (n == N)
{
result = StatsLib.kthLargest(ds, 1);
}
else
{
int k = (int)n;
double d = n - k;
result = StatsLib.kthSmallest(ds, k) + d
* (StatsLib.kthSmallest(ds, k + 1) - StatsLib.kthSmallest(ds, k));
}
NumericFunction.CheckValue(result);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
return new NumberEval(result);
}
}
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
public abstract class AggregateFunction : MultiOperandNumericFunction
{
public static Function SubtotalInstance(Function func)
{
AggregateFunction arg = (AggregateFunction)func;
return new SubtotalInstance(arg);
}
internal class ValueCollector : MultiOperandNumericFunction
{
private static ValueCollector instance = new ValueCollector();
public ValueCollector() :
base(false, false)
{
}
public static double[] CollectValues(params ValueEval[] operands)
{
return instance.GetNumberArray(operands);
}
protected internal override double Evaluate(double[] values)
{
throw new InvalidOperationException("should not be called");
}
}
protected AggregateFunction()
: base(false, false)
{
}
public static readonly Function AVEDEV = new AVEDEV();
public static readonly Function AVERAGE = new AVERAGE();
public static readonly Function DEVSQ = new DEVSQ();
public static readonly Function LARGE = new LARGE();
public static readonly Function MAX = new MAX();
public static readonly Function MEDIAN = new MEDIAN();
public static readonly Function MIN = new MIN();
public static readonly Function PRODUCT = new PRODUCT();
public static readonly Function SMALL = new SMALL();
public static readonly Function STDEV = new STDEV();
public static readonly Function SUM = new SUM();
public static readonly Function SUMSQ = new SUMSQ();
public static readonly Function VAR = new VAR();
public static readonly Function VARP = new VARP();
public static readonly Function PERCENTILE = new Percentile();
}
}
| |
using System;
using System.Collections;
using BigMath;
using Raksha.X509;
using Raksha.Asn1;
using Raksha.Asn1.X509;
using Raksha.Math;
using Raksha.Utilities;
using Raksha.Utilities.Date;
using Raksha.X509.Extension;
namespace Raksha.X509.Store
{
public class X509CrlStoreSelector
: IX509Selector
{
// TODO Missing criteria?
private X509Certificate certificateChecking;
private DateTimeObject dateAndTime;
private ICollection issuers;
private BigInteger maxCrlNumber;
private BigInteger minCrlNumber;
private IX509AttributeCertificate attrCertChecking;
private bool completeCrlEnabled;
private bool deltaCrlIndicatorEnabled;
private byte[] issuingDistributionPoint;
private bool issuingDistributionPointEnabled;
private BigInteger maxBaseCrlNumber;
public X509CrlStoreSelector()
{
}
public X509CrlStoreSelector(
X509CrlStoreSelector o)
{
this.certificateChecking = o.CertificateChecking;
this.dateAndTime = o.DateAndTime;
this.issuers = o.Issuers;
this.maxCrlNumber = o.MaxCrlNumber;
this.minCrlNumber = o.MinCrlNumber;
this.deltaCrlIndicatorEnabled = o.DeltaCrlIndicatorEnabled;
this.completeCrlEnabled = o.CompleteCrlEnabled;
this.maxBaseCrlNumber = o.MaxBaseCrlNumber;
this.attrCertChecking = o.AttrCertChecking;
this.issuingDistributionPointEnabled = o.IssuingDistributionPointEnabled;
this.issuingDistributionPoint = o.IssuingDistributionPoint;
}
public virtual object Clone()
{
return new X509CrlStoreSelector(this);
}
public X509Certificate CertificateChecking
{
get { return certificateChecking; }
set { certificateChecking = value; }
}
public DateTimeObject DateAndTime
{
get { return dateAndTime; }
set { dateAndTime = value; }
}
/// <summary>
/// An <code>ICollection</code> of <code>X509Name</code> objects
/// </summary>
public ICollection Issuers
{
get { return Platform.CreateArrayList(issuers); }
set { issuers = Platform.CreateArrayList(value); }
}
public BigInteger MaxCrlNumber
{
get { return maxCrlNumber; }
set { maxCrlNumber = value; }
}
public BigInteger MinCrlNumber
{
get { return minCrlNumber; }
set { minCrlNumber = value; }
}
/**
* The attribute certificate being checked. This is not a criterion.
* Rather, it is optional information that may help a {@link X509Store} find
* CRLs that would be relevant when checking revocation for the specified
* attribute certificate. If <code>null</code> is specified, then no such
* optional information is provided.
*
* @param attrCert the <code>IX509AttributeCertificate</code> being checked (or
* <code>null</code>)
* @see #getAttrCertificateChecking()
*/
public IX509AttributeCertificate AttrCertChecking
{
get { return attrCertChecking; }
set { this.attrCertChecking = value; }
}
/**
* If <code>true</code> only complete CRLs are returned. Defaults to
* <code>false</code>.
*
* @return <code>true</code> if only complete CRLs are returned.
*/
public bool CompleteCrlEnabled
{
get { return completeCrlEnabled; }
set { this.completeCrlEnabled = value; }
}
/**
* Returns if this selector must match CRLs with the delta CRL indicator
* extension set. Defaults to <code>false</code>.
*
* @return Returns <code>true</code> if only CRLs with the delta CRL
* indicator extension are selected.
*/
public bool DeltaCrlIndicatorEnabled
{
get { return deltaCrlIndicatorEnabled; }
set { this.deltaCrlIndicatorEnabled = value; }
}
/**
* The issuing distribution point.
* <p>
* The issuing distribution point extension is a CRL extension which
* identifies the scope and the distribution point of a CRL. The scope
* contains among others information about revocation reasons contained in
* the CRL. Delta CRLs and complete CRLs must have matching issuing
* distribution points.</p>
* <p>
* The byte array is cloned to protect against subsequent modifications.</p>
* <p>
* You must also enable or disable this criteria with
* {@link #setIssuingDistributionPointEnabled(bool)}.</p>
*
* @param issuingDistributionPoint The issuing distribution point to set.
* This is the DER encoded OCTET STRING extension value.
* @see #getIssuingDistributionPoint()
*/
public byte[] IssuingDistributionPoint
{
get { return Arrays.Clone(issuingDistributionPoint); }
set { this.issuingDistributionPoint = Arrays.Clone(value); }
}
/**
* Whether the issuing distribution point criteria should be applied.
* Defaults to <code>false</code>.
* <p>
* You may also set the issuing distribution point criteria if not a missing
* issuing distribution point should be assumed.</p>
*
* @return Returns if the issuing distribution point check is enabled.
*/
public bool IssuingDistributionPointEnabled
{
get { return issuingDistributionPointEnabled; }
set { this.issuingDistributionPointEnabled = value; }
}
/**
* The maximum base CRL number. Defaults to <code>null</code>.
*
* @return Returns the maximum base CRL number.
* @see #setMaxBaseCRLNumber(BigInteger)
*/
public BigInteger MaxBaseCrlNumber
{
get { return maxBaseCrlNumber; }
set { this.maxBaseCrlNumber = value; }
}
public virtual bool Match(
object obj)
{
X509Crl c = obj as X509Crl;
if (c == null)
return false;
if (dateAndTime != null)
{
DateTime dt = dateAndTime.Value;
DateTime tu = c.ThisUpdate;
DateTimeObject nu = c.NextUpdate;
if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0)
return false;
}
if (issuers != null)
{
X509Name i = c.IssuerDN;
bool found = false;
foreach (X509Name issuer in issuers)
{
if (issuer.Equivalent(i, true))
{
found = true;
break;
}
}
if (!found)
return false;
}
if (maxCrlNumber != null || minCrlNumber != null)
{
Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber);
if (extVal == null)
return false;
BigInteger cn = CrlNumber.GetInstance(
X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue;
if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0)
return false;
if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0)
return false;
}
DerInteger dci = null;
try
{
Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
if (bytes != null)
{
dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes));
}
}
catch (Exception)
{
return false;
}
if (dci == null)
{
if (DeltaCrlIndicatorEnabled)
return false;
}
else
{
if (CompleteCrlEnabled)
return false;
if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
return false;
}
if (issuingDistributionPointEnabled)
{
Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
if (issuingDistributionPoint == null)
{
if (idp != null)
return false;
}
else
{
if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint))
return false;
}
}
return true;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Composite Swagger for Recovery Services Client
/// </summary>
public partial class RecoveryServicesClient : ServiceClient<RecoveryServicesClient>, IRecoveryServicesClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.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>
/// The subscription Id.
/// </summary>
public string SubscriptionId { get; 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>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IBackupVaultConfigsOperations.
/// </summary>
public virtual IBackupVaultConfigsOperations BackupVaultConfigs { get; private set; }
/// <summary>
/// Gets the IBackupStorageConfigsOperations.
/// </summary>
public virtual IBackupStorageConfigsOperations BackupStorageConfigs { get; private set; }
/// <summary>
/// Gets the IVaultCertificatesOperations.
/// </summary>
public virtual IVaultCertificatesOperations VaultCertificates { get; private set; }
/// <summary>
/// Gets the IRegisteredIdentitiesOperations.
/// </summary>
public virtual IRegisteredIdentitiesOperations RegisteredIdentities { get; private set; }
/// <summary>
/// Gets the IReplicationUsagesOperations.
/// </summary>
public virtual IReplicationUsagesOperations ReplicationUsages { get; private set; }
/// <summary>
/// Gets the IVaultsOperations.
/// </summary>
public virtual IVaultsOperations Vaults { get; private set; }
/// <summary>
/// Gets the IVaultExtendedInfoOperations.
/// </summary>
public virtual IVaultExtendedInfoOperations VaultExtendedInfo { get; private set; }
/// <summary>
/// Gets the IUsagesOperations.
/// </summary>
public virtual IUsagesOperations Usages { get; private set; }
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected RecoveryServicesClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient 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 RecoveryServicesClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected RecoveryServicesClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected RecoveryServicesClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public RecoveryServicesClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public RecoveryServicesClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public RecoveryServicesClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesClient 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public RecoveryServicesClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Operations = new Operations(this);
BackupVaultConfigs = new BackupVaultConfigsOperations(this);
BackupStorageConfigs = new BackupStorageConfigsOperations(this);
VaultCertificates = new VaultCertificatesOperations(this);
RegisteredIdentities = new RegisteredIdentitiesOperations(this);
ReplicationUsages = new ReplicationUsagesOperations(this);
Vaults = new VaultsOperations(this);
VaultExtendedInfo = new VaultExtendedInfoOperations(this);
Usages = new UsagesOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ResourceCertificateDetails>("authType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ResourceCertificateDetails>("authType"));
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using System.Collections;
using NPOI.Util;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using NPOI.HSSF.Util;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula;
using SSFormula=NPOI.SS.Formula;
using NPOI.HSSF.Record.Cont;
using NPOI.SS.Formula.PTG;
/**
* Title: Name Record (aka Named Range)
* Description: Defines a named range within a workbook.
* REFERENCE:
* @author Libin Roman (Vista Portal LDT. Developer)
* @author Sergei Kozello (sergeikozello at mail.ru)
* @author Glen Stampoultzis (glens at apache.org)
* @version 1.0-pre
*/
internal class NameRecord : ContinuableRecord
{
private enum Option:short {
OPT_HIDDEN_NAME = 0x0001,
OPT_FUNCTION_NAME = 0x0002,
OPT_COMMAND_NAME = 0x0004,
OPT_MACRO = 0x0008,
OPT_COMPLEX = 0x0010,
OPT_BUILTIN = 0x0020,
OPT_BINDATA = 0x1000,
}
public static bool IsFormula(int optValue) {
return (optValue & 0x0F) == 0;
}
/**
*/
public const short sid = 0x18; //Docs says that it Is 0x218
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_CONSOLIDATE_AREA = (byte)0;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_AUTO_OPEN = (byte)1;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_AUTO_CLOSE = (byte)2;
public const byte BUILTIN_EXTRACT = (byte)3;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_DATABASE = (byte)4;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_CRITERIA = (byte)5;
public const byte BUILTIN_PRINT_AREA = (byte)6;
public const byte BUILTIN_PRINT_TITLE = (byte)7;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_RECORDER = (byte)8;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_DATA_FORM = (byte)9;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_AUTO_ACTIVATE = (byte)10;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_AUTO_DEACTIVATE = (byte)11;
/**Included for completeness sake, not implemented
*/
public const byte BUILTIN_SHEET_TITLE = (byte)12;
public const byte BUILTIN_FILTER_DB = 13;
//public const short OPT_HIDDEN_NAME = (short)0x0001;
//public const short OPT_FUNCTION_NAME = (short)0x0002;
//public const short OPT_COMMAND_NAME = (short)0x0004;
//public const short OPT_MACRO = (short)0x0008;
//public const short OPT_COMPLEX = (short)0x0010;
//public const short OPT_BUILTIN = (short)0x0020;
//public const short OPT_BINDATA = (short)0x1000;
private short field_1_option_flag;
private byte field_2_keyboard_shortcut;
//private byte field_3_Length_name_text;
//private short field_4_Length_name_definition;
//private short field_5_index_to_sheet; // Unused: see field_6
//private short field_6_Equals_to_index_to_sheet;
/** One-based extern index of sheet (resolved via LinkTable). Zero if this is a global name */
private short field_5_externSheetIndex_plus1;
/** the one based sheet number. */
private int field_6_sheetNumber;
//private byte field_7_Length_custom_menu;
//private byte field_8_Length_description_text;
//private byte field_9_Length_help_topic_text;
//private byte field_10_Length_status_bar_text;
//private byte field_11_compressed_unicode_flag; // not documented
private bool field_11_nameIsMultibyte;
private byte field_12_built_in_code;
private String field_12_name_text;
private SSFormula.Formula field_13_name_definition;
private String field_14_custom_menu_text;
private String field_15_description_text;
private String field_16_help_topic_text;
private String field_17_status_bar_text;
/** Creates new NameRecord */
public NameRecord()
{
field_13_name_definition = SSFormula.Formula.Create(Ptg.EMPTY_PTG_ARRAY);
field_12_name_text = "";
field_14_custom_menu_text = "";
field_15_description_text = "";
field_16_help_topic_text = "";
field_17_status_bar_text = "";
}
protected int DataSize
{
get {
return 13 // 3 shorts + 7 bytes
+ NameRawSize
+ field_14_custom_menu_text.Length
+ field_15_description_text.Length
+ field_16_help_topic_text.Length
+ field_17_status_bar_text.Length
+ field_13_name_definition.EncodedSize;
}
}
/**
* Constructs a Name record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public NameRecord(RecordInputStream ris)
{
byte[] remainder = ris.ReadAllContinuedRemainder();
ILittleEndianInput in1 = new LittleEndianByteArrayInputStream(remainder);
field_1_option_flag = in1.ReadShort();
field_2_keyboard_shortcut = (byte)in1.ReadByte();
int field_3_length_name_text = in1.ReadByte();
int field_4_length_name_definition = in1.ReadShort();
field_5_externSheetIndex_plus1 = in1.ReadShort();
field_6_sheetNumber = in1.ReadUShort();
int field_7_length_custom_menu = in1.ReadUByte();
int field_8_length_description_text = in1.ReadUByte();
int field_9_length_help_topic_text = in1.ReadUByte();
int field_10_length_status_bar_text = in1.ReadUByte();
//store the name in byte form if it's a built-in name
field_11_nameIsMultibyte = (in1.ReadByte() != 0);
if (IsBuiltInName) {
field_12_built_in_code = (byte)in1.ReadByte();
} else {
if (field_11_nameIsMultibyte) {
field_12_name_text = StringUtil.ReadUnicodeLE(in1, field_3_length_name_text);
} else {
field_12_name_text = StringUtil.ReadCompressedUnicode(in1, field_3_length_name_text);
}
}
int nBytesAvailable = in1.Available() - (field_7_length_custom_menu
+ field_8_length_description_text + field_9_length_help_topic_text + field_10_length_status_bar_text);
field_13_name_definition = SSFormula.Formula.Read(field_4_length_name_definition, in1, nBytesAvailable);
//Who says that this can only ever be compressed unicode???
field_14_custom_menu_text = StringUtil.ReadCompressedUnicode(in1, field_7_length_custom_menu);
field_15_description_text = StringUtil.ReadCompressedUnicode(in1, field_8_length_description_text);
field_16_help_topic_text = StringUtil.ReadCompressedUnicode(in1, field_9_length_help_topic_text);
field_17_status_bar_text = StringUtil.ReadCompressedUnicode(in1, field_10_length_status_bar_text);
}
/**
* Constructor to Create a built-in named region
* @param builtin Built-in byte representation for the name record, use the public constants
* @param index
*/
public NameRecord(byte builtin, int sheetNumber)
: this()
{
field_12_built_in_code = builtin;
OptionFlag=(short)(field_1_option_flag | (short)Option.OPT_BUILTIN);
field_6_sheetNumber = sheetNumber; //the extern sheets are set through references
}
/**
* @return function Group
* @see FnGroupCountRecord
*/
public byte FnGroup
{
get
{
int masked = field_1_option_flag & 0x0fc0;
return (byte)(masked >> 4);
}
}
/** Gets the option flag
* @return option flag
*/
public short OptionFlag
{
get { return field_1_option_flag; }
set { field_1_option_flag = value; }
}
/** returns the keyboard shortcut
* @return keyboard shortcut
*/
public byte KeyboardShortcut
{
get { return field_2_keyboard_shortcut; }
set { field_2_keyboard_shortcut = value; }
}
///**
// * Gets the name Length, in Chars
// * @return name Length
// */
public byte NameTextLength
{
get
{
if (IsBuiltInName)
{
return 1;
}
return (byte)field_12_name_text.Length;
}
}
private int NameRawSize
{
get
{
if (IsBuiltInName)
{
return 1;
}
int nChars = field_12_name_text.Length;
if (field_11_nameIsMultibyte)
{
return 2 * nChars;
}
return nChars;
}
}
/**
* Indicates that the defined name refers to a user-defined function.
* This attribute is used when there is an add-in or other code project associated with the file.
*
* @param function <c>true</c> indicates the name refers to a function.
*/
public void SetFunction(bool function)
{
if (function)
{
field_1_option_flag |= (short)Option.OPT_FUNCTION_NAME;
}
else
{
field_1_option_flag &= (short)(~Option.OPT_FUNCTION_NAME);
}
}
/**
* @return <c>true</c> if name has a formula (named range or defined value)
*/
public bool HasFormula
{
get
{
return IsFormula(field_1_option_flag) && field_13_name_definition.EncodedTokenSize > 0;
}
}
/**
* @return true if name Is hidden
*/
public bool IsHiddenName
{
get { return (field_1_option_flag & (short)Option.OPT_HIDDEN_NAME) != 0; }
set
{
if (value)
{
field_1_option_flag |= (short)Option.OPT_HIDDEN_NAME;
}
else
{
field_1_option_flag &= (short)(~Option.OPT_HIDDEN_NAME);
}
}
}
/**
* @return true if name Is a function
*/
public bool IsFunctionName
{
get { return (field_1_option_flag & (short)Option.OPT_FUNCTION_NAME) != 0; }
set
{
if (value)
{
field_1_option_flag |= (short)Option.OPT_FUNCTION_NAME;
}
else
{
field_1_option_flag &= (~(short)Option.OPT_FUNCTION_NAME);
}
}
}
/**
* @return true if name Is a command
*/
public bool IsCommandName
{
get { return (field_1_option_flag & (short)Option.OPT_COMMAND_NAME) != 0; }
}
/**
* @return true if function macro or command macro
*/
public bool IsMacro
{
get { return (field_1_option_flag & (short)Option.OPT_MACRO) != 0; }
}
/**
* @return true if array formula or user defined
*/
public bool IsComplexFunction
{
get { return (field_1_option_flag & (short)Option.OPT_COMPLEX) != 0; }
}
/**Convenience Function to determine if the name Is a built-in name
*/
public bool IsBuiltInName
{
get { return ((this.OptionFlag & (short)Option.OPT_BUILTIN) != 0); }
}
/** Gets the name
* @return name
*/
public String NameText
{
get
{
return this.IsBuiltInName ? this.TranslateBuiltInName(this.BuiltInName) : field_12_name_text;
}
set
{
field_12_name_text = value;
field_11_nameIsMultibyte = StringUtil.HasMultibyte(value);
}
}
/** Gets the Built In Name
* @return the built in Name
*/
public byte BuiltInName
{
get { return this.field_12_built_in_code; }
}
/** Gets the definition, reference (Formula)
* @return definition -- can be null if we cant Parse ptgs
*/
public Ptg[] NameDefinition
{
get { return field_13_name_definition.Tokens; }
set { field_13_name_definition = SSFormula.Formula.Create(value); }
}
/** Get the custom menu text
* @return custom menu text
*/
public String CustomMenuText
{
get { return field_14_custom_menu_text; }
set { field_14_custom_menu_text = value; }
}
/** Gets the description text
* @return description text
*/
public String DescriptionText
{
get { return field_15_description_text; }
set { field_15_description_text = value; }
}
/** Get the help topic text
* @return gelp topic text
*/
public String HelpTopicText
{
get { return field_16_help_topic_text; }
set { field_16_help_topic_text = value; }
}
/** Gets the status bar text
* @return status bar text
*/
public String StatusBarText
{
get { return field_17_status_bar_text; }
set { field_17_status_bar_text = value; }
}
/**
* For named ranges, and built-in names
* @return the 1-based sheet number.
*/
public int SheetNumber
{
get
{
return field_6_sheetNumber;
}
set { field_6_sheetNumber = value; }
}
/**
* called by the class that Is responsible for writing this sucker.
* Subclasses should implement this so that their data Is passed back in a
* @param offset to begin writing at
* @param data byte array containing instance data
* @return number of bytes written
*/
protected override void Serialize(ContinuableRecordOutput out1)
{
int field_7_length_custom_menu = field_14_custom_menu_text.Length;
int field_8_length_description_text = field_15_description_text.Length;
int field_9_length_help_topic_text = field_16_help_topic_text.Length;
int field_10_length_status_bar_text = field_17_status_bar_text.Length;
//int rawNameSize = NameRawSize;
// size defined below
out1.WriteShort(OptionFlag);
out1.WriteByte(KeyboardShortcut);
out1.WriteByte(NameTextLength);
// Note - formula size is not immediately before encoded formula, and does not include any array constant data
out1.WriteShort(field_13_name_definition.EncodedTokenSize);
out1.WriteShort(field_5_externSheetIndex_plus1);
out1.WriteShort(field_6_sheetNumber);
out1.WriteByte(field_7_length_custom_menu);
out1.WriteByte(field_8_length_description_text);
out1.WriteByte(field_9_length_help_topic_text);
out1.WriteByte(field_10_length_status_bar_text);
out1.WriteByte(field_11_nameIsMultibyte ? 1 : 0);
if (IsBuiltInName)
{
out1.WriteByte(field_12_built_in_code);
}
else
{
String nameText = field_12_name_text;
if (field_11_nameIsMultibyte)
{
StringUtil.PutUnicodeLE(nameText,out1);
}
else
{
StringUtil.PutCompressedUnicode(nameText, out1);
}
}
field_13_name_definition.SerializeTokens(out1);
field_13_name_definition.SerializeArrayConstantData(out1);
StringUtil.PutCompressedUnicode(CustomMenuText,out1);
StringUtil.PutCompressedUnicode(DescriptionText, out1);
StringUtil.PutCompressedUnicode(HelpTopicText, out1);
StringUtil.PutCompressedUnicode(StatusBarText, out1);
}
/** Gets the extern sheet number
* @return extern sheet index
*/
public int ExternSheetNumber
{
get
{
if (field_13_name_definition.EncodedSize < 1)
{
return 0;
}
Ptg ptg = field_13_name_definition.Tokens[0];
if (ptg.GetType() == typeof(Area3DPtg))
{
return ((Area3DPtg)ptg).ExternSheetIndex;
}
else if (ptg.GetType() == typeof(Ref3DPtg))
{
return ((Ref3DPtg)ptg).ExternSheetIndex;
}
return 0;
}
}
private Ptg CreateNewPtg()
{
return new Area3DPtg("A1:A1", 0); // TODO - change to not be partially initialised
}
/**
* return the non static version of the id for this record.
*/
public override short Sid
{
get { return sid; }
}
/*
20 00
00
01
1A 00 // sz = 0x1A = 26
00 00
01 00
00
00
00
00
00 // Unicode flag
07 // name
29 17 00 3B 00 00 00 00 FF FF 00 00 02 00 3B 00 //{ 26
00 07 00 07 00 00 00 FF 00 10 // }
20 00
00
01
0B 00 // sz = 0xB = 11
00 00
01 00
00
00
00
00
00 // Unicode flag
07 // name
3B 00 00 07 00 07 00 00 00 FF 00 // { 11 }
*/
/*
18, 00,
1B, 00,
20, 00,
00,
01,
0B, 00,
00,
00,
00,
00,
00,
07,
3B 00 00 07 00 07 00 00 00 FF 00 ]
*/
/**
* @see Object#ToString()
*/
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[NAME]\n");
buffer.Append(" .option flags = ").Append(HexDump.ToHex(field_1_option_flag))
.Append("\n");
buffer.Append(" .keyboard shortcut = ").Append(HexDump.ToHex(field_2_keyboard_shortcut))
.Append("\n");
buffer.Append(" .Length of the name = ").Append(NameTextLength)
.Append("\n");
buffer.Append(" .extSheetIx(1-based, 0=Global)= ").Append(field_5_externSheetIndex_plus1)
.Append("\n");
buffer.Append(" .sheetTabIx = ").Append(field_6_sheetNumber)
.Append("\n");
buffer.Append(" .Length of menu text (Char count) = ").Append(field_14_custom_menu_text.Length)
.Append("\n");
buffer.Append(" .Length of description text (Char count) = ").Append(field_15_description_text.Length)
.Append("\n");
buffer.Append(" .Length of help topic text (Char count) = ").Append(field_16_help_topic_text.Length)
.Append("\n");
buffer.Append(" .Length of status bar text (Char count) = ").Append(field_17_status_bar_text.Length)
.Append("\n");
buffer.Append(" .Name (Unicode flag) = ").Append(field_11_nameIsMultibyte)
.Append("\n");
buffer.Append(" .Name (Unicode text) = ").Append(NameText)
.Append("\n");
Ptg[] ptgs = field_13_name_definition.Tokens;
buffer.AppendLine(" .Formula (nTokens=" + ptgs.Length + "):");
for (int i = 0; i < ptgs.Length; i++)
{
Ptg ptg = ptgs[i];
buffer.Append(" " + ptg.ToString()).Append(ptg.RVAType).Append("\n");
}
buffer.Append(" .Menu text (Unicode string without Length field) = ").Append(field_14_custom_menu_text)
.Append("\n");
buffer.Append(" .Description text (Unicode string without Length field) = ").Append(field_15_description_text)
.Append("\n");
buffer.Append(" .Help topic text (Unicode string without Length field) = ").Append(field_16_help_topic_text)
.Append("\n");
buffer.Append(" .Status bar text (Unicode string without Length field) = ").Append(field_17_status_bar_text)
.Append("\n");
buffer.Append("[/NAME]\n");
return buffer.ToString();
}
/**Creates a human Readable name for built in types
* @return Unknown if the built-in name cannot be translated
*/
protected String TranslateBuiltInName(byte name)
{
switch (name)
{
case NameRecord.BUILTIN_AUTO_ACTIVATE: return "Auto_Activate";
case NameRecord.BUILTIN_AUTO_CLOSE: return "Auto_Close";
case NameRecord.BUILTIN_AUTO_DEACTIVATE: return "Auto_Deactivate";
case NameRecord.BUILTIN_AUTO_OPEN: return "Auto_Open";
case NameRecord.BUILTIN_CONSOLIDATE_AREA: return "Consolidate_Area";
case NameRecord.BUILTIN_CRITERIA: return "Criteria";
case NameRecord.BUILTIN_DATABASE: return "Database";
case NameRecord.BUILTIN_DATA_FORM: return "Data_Form";
case NameRecord.BUILTIN_PRINT_AREA: return "Print_Area";
case NameRecord.BUILTIN_PRINT_TITLE: return "Print_Titles";
case NameRecord.BUILTIN_RECORDER: return "Recorder";
case NameRecord.BUILTIN_SHEET_TITLE: return "Sheet_Title";
case NameRecord.BUILTIN_FILTER_DB: return "_FilterDatabase";
case NameRecord.BUILTIN_EXTRACT: return "Extract";
}
return "Unknown";
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Xml;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.LayoutRenderers;
using NLog.Time;
using System.Collections.ObjectModel;
#if SILVERLIGHT
// ReSharper disable once RedundantUsingDirective
using System.Windows;
#endif
/// <summary>
/// A class for configuring NLog through an XML configuration file
/// (App.config style or App.nlog style).
/// </summary>
///<remarks>This class is thread-safe.<c>.ToList()</c> is used for that purpose.</remarks>
public class XmlLoggingConfiguration : LoggingConfiguration
{
#if __ANDROID__
/// <summary>
/// Prefix for assets in Xamarin Android
/// </summary>
internal const string AssetsPrefix = "assets/";
#endif
#region private fields
private readonly Dictionary<string, bool> fileMustAutoReloadLookup = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private string originalFileName;
private LogFactory logFactory = null;
private ConfigurationItemFactory ConfigurationItemFactory
{
get { return ConfigurationItemFactory.Default; }
}
#endregion
#region contructors
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
public XmlLoggingConfiguration(string fileName)
: this(fileName, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
public XmlLoggingConfiguration(string fileName, LogFactory logFactory)
: this(fileName, false, logFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(string fileName, bool ignoreErrors)
: this(fileName, ignoreErrors, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
public XmlLoggingConfiguration(string fileName, bool ignoreErrors, LogFactory logFactory)
{
this.logFactory = logFactory;
using (XmlReader reader = CreateFileReader(fileName))
{
this.Initialize(reader, fileName, ignoreErrors);
}
}
/// <summary>
/// Create XML reader for (xml config) file.
/// </summary>
/// <param name="fileName">filepath</param>
/// <returns>reader or <c>null</c> if filename is empty.</returns>
private static XmlReader CreateFileReader(string fileName)
{
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName.Trim();
#if __ANDROID__
//suport loading config from special assets folder in nlog.config
if (fileName.StartsWith(AssetsPrefix, StringComparison.OrdinalIgnoreCase))
{
//remove prefix
fileName = fileName.Substring(AssetsPrefix.Length);
Stream stream = Android.App.Application.Context.Assets.Open(fileName);
return XmlReader.Create(stream);
}
#endif
return XmlReader.Create(fileName);
}
return null;
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName)
: this(reader, fileName, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName, LogFactory logFactory)
: this(reader, fileName, false, logFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors)
: this(reader, fileName, ignoreErrors, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors, LogFactory logFactory)
{
this.logFactory = logFactory;
this.Initialize(reader, fileName, ignoreErrors);
}
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName)
{
logFactory = LogManager.LogFactory;
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
/// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, ignoreErrors);
}
}
#endif
#endregion
#region public properties
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Gets the default <see cref="LoggingConfiguration" /> object by parsing
/// the application configuration file (<c>app.exe.config</c>).
/// </summary>
public static LoggingConfiguration AppConfig
{
get
{
object o = System.Configuration.ConfigurationManager.GetSection("nlog");
return o as LoggingConfiguration;
}
}
#endif
/// <summary>
/// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet.
/// </summary>
public bool? InitializeSucceeded { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether all of the configuration files
/// should be watched for changes and reloaded automatically when changed.
/// </summary>
public bool AutoReload
{
get
{
return this.fileMustAutoReloadLookup.Values.All(mustAutoReload => mustAutoReload);
}
set
{
var autoReloadFiles = this.fileMustAutoReloadLookup.Keys.ToList();
foreach (string nextFile in autoReloadFiles)
this.fileMustAutoReloadLookup[nextFile] = value;
}
}
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// This is the list of configuration files processed.
/// If the <c>autoReload</c> attribute is not set it returns empty collection.
/// </summary>
public override IEnumerable<string> FileNamesToWatch
{
get
{
return this.fileMustAutoReloadLookup.Where(entry => entry.Value).Select(entry => entry.Key);
}
}
#endregion
#region public methods
/// <summary>
/// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object.
/// </summary>
/// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns>
public override LoggingConfiguration Reload()
{
return new XmlLoggingConfiguration(this.originalFileName);
}
#endregion
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Remove all spaces, also in between text.
/// </summary>
/// <param name="s">text</param>
/// <returns>text without spaces</returns>
/// <remarks>Tabs and other whitespace is not removed!</remarks>
private static string CleanSpaces(string s)
{
s = s.Replace(" ", string.Empty); // get rid of the whitespace
return s;
}
/// <summary>
/// Remove the namespace (before :)
/// </summary>
/// <example>
/// x:a, will be a
/// </example>
/// <param name="attributeValue"></param>
/// <returns></returns>
private static string StripOptionalNamespacePrefix(string attributeValue)
{
if (attributeValue == null)
{
return null;
}
int p = attributeValue.IndexOf(':');
if (p < 0)
{
return attributeValue;
}
return attributeValue.Substring(p + 1);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
/// <summary>
/// Initializes the configuration.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
{
try
{
InitializeSucceeded = null;
reader.MoveToContent();
var content = new NLogXmlElement(reader);
if (fileName != null)
{
this.originalFileName = fileName;
this.ParseTopLevel(content, fileName, autoReloadDefault: false);
InternalLogger.Info("Configured from an XML element in {0}...", fileName);
}
else
{
this.ParseTopLevel(content, null, autoReloadDefault: false);
}
InitializeSucceeded = true;
this.CheckUnusedTargets();
}
catch (Exception exception)
{
InitializeSucceeded = false;
if (exception.MustBeRethrownImmediately())
{
throw;
}
var configurationException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
InternalLogger.Error(configurationException, "Error in Parsing Configuration File.");
if (!ignoreErrors)
{
if (exception.MustBeRethrown())
{
throw configurationException;
}
}
}
}
/// <summary>
/// Checks whether unused targets exist. If found any, just write an internal log at Warn level.
/// <remarks>If initializing not started or failed, then checking process will be canceled</remarks>
/// </summary>
private void CheckUnusedTargets()
{
if (this.InitializeSucceeded == null)
{
InternalLogger.Warn("Unused target checking is canceled -> initialize not started yet.");
return;
}
if (!this.InitializeSucceeded.Value)
{
InternalLogger.Warn("Unused target checking is canceled -> initialize not succeeded.");
return;
}
ReadOnlyCollection<Target> configuredNamedTargets = this.ConfiguredNamedTargets; //assign to variable because `ConfiguredNamedTargets` computes a new list every time.
InternalLogger.Debug("Unused target checking is started... Rule Count: {0}, Target Count: {1}", this.LoggingRules.Count, configuredNamedTargets.Count);
HashSet<string> targetNamesAtRules = new HashSet<string>(this.LoggingRules.SelectMany(r => r.Targets).Select(t => t.Name));
int unusedCount = 0;
configuredNamedTargets.ToList().ForEach((target) =>
{
if (!targetNamesAtRules.Contains(target.Name))
{
InternalLogger.Warn("Unused target detected. Add a rule for this target to the configuration. TargetName: {0}", target.Name);
unusedCount++;
}
});
InternalLogger.Debug("Unused target checking is completed. Total Rule Count: {0}, Total Target Count: {1}, Unused Target Count: {2}", this.LoggingRules.Count, configuredNamedTargets.Count, unusedCount);
}
private void ConfigureFromFile(string fileName, bool autoReloadDefault)
{
if (!this.fileMustAutoReloadLookup.ContainsKey(GetFileLookupKey(fileName)))
this.ParseTopLevel(new NLogXmlElement(fileName), fileName, autoReloadDefault);
}
#region parse methods
/// <summary>
/// Parse the root
/// </summary>
/// <param name="content"></param>
/// <param name="filePath">path to config file.</param>
/// <param name="autoReloadDefault">The default value for the autoReload option.</param>
private void ParseTopLevel(NLogXmlElement content, string filePath, bool autoReloadDefault)
{
content.AssertName("nlog", "configuration");
switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "CONFIGURATION":
this.ParseConfigurationElement(content, filePath, autoReloadDefault);
break;
case "NLOG":
this.ParseNLogElement(content, filePath, autoReloadDefault);
break;
}
}
/// <summary>
/// Parse {configuration} xml element.
/// </summary>
/// <param name="configurationElement"></param>
/// <param name="filePath">path to config file.</param>
/// <param name="autoReloadDefault">The default value for the autoReload option.</param>
private void ParseConfigurationElement(NLogXmlElement configurationElement, string filePath, bool autoReloadDefault)
{
InternalLogger.Trace("ParseConfigurationElement");
configurationElement.AssertName("configuration");
var nlogElements = configurationElement.Elements("nlog").ToList();
foreach (var nlogElement in nlogElements)
{
this.ParseNLogElement(nlogElement, filePath, autoReloadDefault);
}
}
/// <summary>
/// Parse {NLog} xml element.
/// </summary>
/// <param name="nlogElement"></param>
/// <param name="filePath">path to config file.</param>
/// <param name="autoReloadDefault">The default value for the autoReload option.</param>
private void ParseNLogElement(NLogXmlElement nlogElement, string filePath, bool autoReloadDefault)
{
InternalLogger.Trace("ParseNLogElement");
nlogElement.AssertName("nlog");
if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false))
{
this.DefaultCultureInfo = CultureInfo.InvariantCulture;
}
#pragma warning disable 618
this.ExceptionLoggingOldStyle = nlogElement.GetOptionalBooleanAttribute("exceptionLoggingOldStyle", false);
#pragma warning restore 618
bool autoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", autoReloadDefault);
if (filePath != null)
this.fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload;
logFactory.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", logFactory.ThrowExceptions);
logFactory.ThrowConfigExceptions = nlogElement.GetOptionalBooleanAttribute("throwConfigExceptions", logFactory.ThrowConfigExceptions);
InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
InternalLogger.LogToTrace = nlogElement.GetOptionalBooleanAttribute("internalLogToTrace", InternalLogger.LogToTrace);
#endif
InternalLogger.IncludeTimestamp = nlogElement.GetOptionalBooleanAttribute("internalLogIncludeTimestamp", InternalLogger.IncludeTimestamp);
logFactory.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", logFactory.GlobalThreshold.Name));
var children = nlogElement.Children.ToList();
//first load the extensions, as the can be used in other elements (targets etc)
var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase)).ToList();
foreach (var extensionsChild in extensionsChilds)
{
this.ParseExtensionsElement(extensionsChild, Path.GetDirectoryName(filePath));
}
//parse all other direct elements
foreach (var child in children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "EXTENSIONS":
//already parsed
break;
case "INCLUDE":
this.ParseIncludeElement(child, Path.GetDirectoryName(filePath), autoReloadDefault: autoReload);
break;
case "APPENDERS":
case "TARGETS":
this.ParseTargetsElement(child);
break;
case "VARIABLE":
this.ParseVariableElement(child);
break;
case "RULES":
this.ParseRulesElement(child, this.LoggingRules);
break;
case "TIME":
this.ParseTimeElement(child);
break;
default:
InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName);
break;
}
}
}
/// <summary>
/// Parse {Rules} xml element
/// </summary>
/// <param name="rulesElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
var loggerElements = rulesElement.Elements("logger").ToList();
foreach (var loggerElement in loggerElements)
{
this.ParseLoggerElement(loggerElement, rulesCollection);
}
}
/// <summary>
/// Parse {Logger} xml element
/// </summary>
/// <param name="loggerElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection)
{
loggerElement.AssertName("logger");
var namePattern = loggerElement.GetOptionalAttribute("name", "*");
var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true);
if (!enabled)
{
InternalLogger.Debug("The logger named '{0}' are disabled");
return;
}
var rule = new LoggingRule();
string appendTo = loggerElement.GetOptionalAttribute("appendTo", null);
if (appendTo == null)
{
appendTo = loggerElement.GetOptionalAttribute("writeTo", null);
}
rule.LoggerNamePattern = namePattern;
if (appendTo != null)
{
foreach (string t in appendTo.Split(','))
{
string targetName = t.Trim();
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
throw new NLogConfigurationException("Target " + targetName + " not found.");
}
}
}
rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false);
string levelString;
if (loggerElement.AttributeValues.TryGetValue("level", out levelString))
{
LogLevel level = LogLevel.FromString(levelString);
rule.EnableLoggingForLevel(level);
}
else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString))
{
levelString = CleanSpaces(levelString);
string[] tokens = levelString.Split(',');
foreach (string token in tokens)
{
if (!string.IsNullOrEmpty(token))
{
LogLevel level = LogLevel.FromString(token);
rule.EnableLoggingForLevel(level);
}
}
}
else
{
int minLevel = 0;
int maxLevel = LogLevel.MaxLevel.Ordinal;
string minLevelString;
string maxLevelString;
if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString))
{
minLevel = LogLevel.FromString(minLevelString).Ordinal;
}
if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString))
{
maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
}
for (int i = minLevel; i <= maxLevel; ++i)
{
rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
var children = loggerElement.Children.ToList();
foreach (var child in children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "FILTERS":
this.ParseFilters(rule, child);
break;
case "LOGGER":
this.ParseLoggerElement(child, rule.ChildRules);
break;
}
}
rulesCollection.Add(rule);
}
private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement)
{
filtersElement.AssertName("filters");
var children = filtersElement.Children.ToList();
foreach (var filterElement in children)
{
string name = filterElement.LocalName;
Filter filter = this.ConfigurationItemFactory.Filters.CreateInstance(name);
this.ConfigureObjectFromAttributes(filter, filterElement, false);
rule.Filters.Add(filter);
}
}
private void ParseVariableElement(NLogXmlElement variableElement)
{
variableElement.AssertName("variable");
string name = variableElement.GetRequiredAttribute("name");
string value = this.ExpandSimpleVariables(variableElement.GetRequiredAttribute("value"));
this.Variables[name] = value;
}
private void ParseTargetsElement(NLogXmlElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false);
NLogXmlElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>();
var children = targetsElement.Children.ToList();
foreach (var targetElement in children)
{
string name = targetElement.LocalName;
string typeAttributeVal = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null));
switch (name.ToUpper(CultureInfo.InvariantCulture))
{
case "DEFAULT-WRAPPER":
defaultWrapperElement = targetElement;
break;
case "DEFAULT-TARGET-PARAMETERS":
if (typeAttributeVal == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
typeNameToDefaultTargetParameters[typeAttributeVal] = targetElement;
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (typeAttributeVal == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(typeAttributeVal);
NLogXmlElement defaults;
if (typeNameToDefaultTargetParameters.TryGetValue(typeAttributeVal, out defaults))
{
this.ParseTargetElement(newTarget, defaults);
}
this.ParseTargetElement(newTarget, targetElement);
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}", newTarget);
AddTarget(newTarget.Name, newTarget);
break;
}
}
}
private void ParseTargetElement(Target target, NLogXmlElement targetElement)
{
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
this.ConfigureObjectFromAttributes(target, targetElement, true);
var children = targetElement.Children.ToList();
foreach (var childElement in children)
{
string name = childElement.LocalName;
if (compound != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
continue;
}
}
if (wrapper != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
wrapper.WrappedTarget = newTarget;
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
throw new NLogConfigurationException("Wrapped target already defined.");
}
wrapper.WrappedTarget = newTarget;
}
continue;
}
}
this.SetPropertyFromElement(target, childElement);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
var addElements = extensionsElement.Elements("add").ToList();
foreach (var addElement in addElements)
{
string prefix = addElement.GetOptionalAttribute("prefix", null);
if (prefix != null)
{
prefix = prefix + ".";
}
string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
if (type != null)
{
this.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
}
string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
if (assemblyFile != null)
{
try
{
#if SILVERLIGHT && !WINDOWS_PHONE
var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
string fullFileName = Path.Combine(baseDirectory, assemblyFile);
InternalLogger.Info("Loading assembly file: {0}", fullFileName);
Assembly asm = Assembly.LoadFrom(fullFileName);
#endif
this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
InternalLogger.Error(exception, "Error loading extensions.");
if (exception.MustBeRethrown())
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
}
}
continue;
}
string assemblyName = addElement.GetOptionalAttribute("assembly", null);
if (assemblyName != null)
{
try
{
InternalLogger.Info("Loading assembly name: {0}", assemblyName);
#if SILVERLIGHT && !WINDOWS_PHONE
var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
Assembly asm = Assembly.Load(assemblyName);
#endif
this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
InternalLogger.Error(exception, "Error loading extensions.");
if (exception.MustBeRethrown())
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
}
}
}
}
}
private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory, bool autoReloadDefault)
{
includeElement.AssertName("include");
string newFileName = includeElement.GetRequiredAttribute("file");
try
{
newFileName = this.ExpandSimpleVariables(newFileName);
newFileName = SimpleLayout.Evaluate(newFileName);
if (baseDirectory != null)
{
newFileName = Path.Combine(baseDirectory, newFileName);
}
#if SILVERLIGHT
newFileName = newFileName.Replace("\\", "/");
if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
if (File.Exists(newFileName))
#endif
{
InternalLogger.Debug("Including file '{0}'", newFileName);
this.ConfigureFromFile(newFileName, autoReloadDefault);
}
else
{
throw new FileNotFoundException("Included file not found: " + newFileName);
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error when including '{0}'.", newFileName);
if (exception.MustBeRethrown())
{
throw;
}
if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
{
return;
}
throw new NLogConfigurationException("Error when including: " + newFileName, exception);
}
}
private void ParseTimeElement(NLogXmlElement timeElement)
{
timeElement.AssertName("time");
string type = timeElement.GetRequiredAttribute("type");
TimeSource newTimeSource = this.ConfigurationItemFactory.TimeSources.CreateInstance(type);
this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true);
InternalLogger.Info("Selecting time source {0}", newTimeSource);
TimeSource.Current = newTimeSource;
}
#endregion
private static string GetFileLookupKey(string fileName)
{
#if SILVERLIGHT
// file names are relative to XAP
return fileName;
#else
return Path.GetFullPath(fileName);
#endif
}
private void SetPropertyFromElement(object o, NLogXmlElement element)
{
if (this.AddArrayItemFromElement(o, element))
{
return;
}
if (this.SetLayoutFromElement(o, element))
{
return;
}
PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandSimpleVariables(element.Value), this.ConfigurationItemFactory);
}
private bool AddArrayItemFromElement(object o, NLogXmlElement element)
{
string name = element.LocalName;
PropertyInfo propInfo;
if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
{
return false;
}
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
object arrayItem = FactoryHelper.CreateInstance(elementType);
this.ConfigureObjectFromAttributes(arrayItem, element, true);
this.ConfigureObjectFromElement(arrayItem, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
{
var attributeValues = element.AttributeValues.ToList();
foreach (var kvp in attributeValues)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
{
continue;
}
PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandSimpleVariables(childValue), this.ConfigurationItemFactory);
}
}
private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
{
PropertyInfo targetPropertyInfo;
string name = layoutElement.LocalName;
// if property exists
if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
{
// and is a Layout
if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType))
{
string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null));
// and 'type' attribute has been specified
if (layoutTypeName != null)
{
// configure it from current element
Layout layout = this.ConfigurationItemFactory.Layouts.CreateInstance(this.ExpandSimpleVariables(layoutTypeName));
this.ConfigureObjectFromAttributes(layout, layoutElement, true);
this.ConfigureObjectFromElement(layout, layoutElement);
targetPropertyInfo.SetValue(o, layout, null);
return true;
}
}
}
return false;
}
private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element)
{
var children = element.Children.ToList();
foreach (var child in children)
{
this.SetPropertyFromElement(targetObject, child);
}
}
private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters)
{
string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type"));
Target wrapperTargetInstance = this.ConfigurationItemFactory.Targets.CreateInstance(wrapperType);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
this.ParseTargetElement(wrapperTargetInstance, defaultParameters);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
wtb.WrappedTarget = t;
wrapperTargetInstance.Name = t.Name;
t.Name = t.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name);
return wrapperTargetInstance;
}
/// <summary>
/// Replace a simple variable with a value. The orginal value is removed and thus we cannot redo this in a later stage.
///
/// Use for that: <see cref="VariableLayoutRenderer"/>
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private string ExpandSimpleVariables(string input)
{
string output = input;
// TODO - make this case-insensitive, will probably require a different approach
var variables = this.Variables.ToList();
foreach (var kvp in variables)
{
var layout = kvp.Value;
//this value is set from xml and that's a string. Because of that, we can use SimpleLayout here.
if (layout != null) output = output.Replace("${" + kvp.Key + "}", layout.OriginalText);
}
return output;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToZeroDouble()
{
var test = new SimpleUnaryOpTest__RoundToZeroDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__RoundToZeroDouble
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector256<Double> _clsVar;
private Vector256<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static SimpleUnaryOpTest__RoundToZeroDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__RoundToZeroDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.RoundToZero(
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.RoundToZero(
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.RoundToZero(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToZero), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToZero), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.RoundToZero), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.RoundToZero(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr);
var result = Avx.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr));
var result = Avx.RoundToZero(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__RoundToZeroDouble();
var result = Avx.RoundToZero(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.RoundToZero(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits((firstOp[0] > 0) ? Math.Floor(firstOp[0]) : Math.Ceiling(firstOp[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits((firstOp[i] > 0) ? Math.Floor(firstOp[i]) : Math.Ceiling(firstOp[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.RoundToZero)}<Double>(Vector256<Double>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using GalaSoft.MvvmLight;
namespace Garmin12.ViewModel
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using GalaSoft.MvvmLight.Views;
using Garmin12.Models;
using Garmin12.Services;
using Garmin12.Store;
public class MainViewModel : ViewModelBase
{
private readonly CompassService compassService;
private readonly NavigationService navigationService;
private readonly DirectionService directionService;
private readonly TimerService timerService;
private GpsPosition position;
private CompassData compassDirection;
private double distanceToTarget;
private double offsetFromNorth;
private string timeNow;
private int pivotIndex;
public MainViewModel(LocationService locationService,
DataService dataDataService,
SelectedPositionStore selectedPositionStore,
CompassService compassService,
NavigationService navigationService,
DirectionService directionService,
TimerService timerService)
{
this.Position = new GpsPosition(0, 0);
this.CompassDirection = new CompassData(0);
this.OffsetFromNorth = 0;
this.LocationService = locationService;
this.compassService = compassService;
this.navigationService = navigationService;
this.directionService = directionService;
this.timerService = timerService;
this.PositionStore = selectedPositionStore;
this.DataService = dataDataService;
this.LocationService.LocationUpdate += this.OnLocationUpdate;
this.compassService.OnCompassReading += this.CompassReadingUpdate;
directionService.NavigationDataUpdate += this.OnNavigationDataUpdate;
timerService.TimerUpdate += this.TimerServiceOnTimerUpdate;
}
public string TimeNow
{
get
{
return this.timeNow;
}
set
{
this.Set(ref this.timeNow, value);
}
}
public double OffsetFromNorth
{
get
{
return this.offsetFromNorth;
}
set
{
this.Set(ref this.offsetFromNorth, value);
this.RaisePropertyChanged(() => this.TargetDirection);
}
}
public double DistanceToTarget
{
get
{
return this.distanceToTarget;
}
set
{
this.Set(ref this.distanceToTarget, value);
}
}
public GpsPosition Position
{
get
{
return this.position;
}
private set
{
this.Set(ref this.position, value);
this.RaisePropertyChanged(() => this.PositionFormatted);
this.RaisePropertyChanged(() => this.SpeedFormatted);
this.RaisePropertyChanged(() => this.AltitudeFormatted);
}
}
public string PositionFormatted => $"{this.GetLongitudeSign(this.Position.Longitude)} {Math.Round(Position.Longitude, 5)}\n{this.GetLatitudeSign(this.Position.Latitude)} {Math.Round(this.Position.Latitude, 5)}";
public string AltitudeFormatted => $"{Math.Round(this.Position.Altitude, 5)} m {this.GetAltitudeSign(this.Position.Altitude)}";
public string SpeedFormatted => $"{Math.Round(this.Position.Speed,2)} km/h";
public DataService DataService { get; }
public RelayCommand<PositionEntity> DeletePositionCommand
=> new RelayCommand<PositionEntity>(position => this.DataService.DeletePositon(position));
public RelayCommand ItemSelectionCommand => new RelayCommand(
() =>
{
Debug.WriteLine($"{this.PositionStore.SelectedPosition?.Name} : {this.PositionStore.SelectedPosition?.Longitude} x {this.PositionStore.SelectedPosition?.Latitude}");
});
public SelectedPositionStore PositionStore { get; }
public CompassData CompassDirection
{
get
{
return this.compassDirection;
}
set
{
this.Set(ref this.compassDirection, value);
this.RaisePropertyChanged(() => this.CompassDirectionDisplay);
this.RaisePropertyChanged(() => this.CompassDirectionNormalized);
this.RaisePropertyChanged(() => this.TargetDirection);
}
}
public string CompassDirectionDisplay => $"{this.CompassDirection.North}";
public double CompassDirectionNormalized => (360 + this.CompassDirection.North) % 360;
public double TargetDirection => this.PositionStore.IsPositionSelected ? (this.CompassDirection.North + this.OffsetFromNorth +360) % 360 : 0;
public RelayCommand GoToPointCreation => new RelayCommand(() => this.navigationService.NavigateTo("newPosition"));
public RelayCommand GoToPointUpdate => new RelayCommand(() => this.navigationService.NavigateTo("newPosition", this.PositionStore.SelectedPosition));
public RelayCommand ClearFilter => new RelayCommand(() => this.DataService.NameFilter = string.Empty);
public int PivotIndex
{
get { return pivotIndex; }
set { Set(ref pivotIndex, value); }
}
public LocationService LocationService { get; }
private async void OnLocationUpdate(GpsPosition gpsPosition)
{
await DispatcherHelper.RunAsync(
() =>
{
this.Position = gpsPosition;
});
}
private async void CompassReadingUpdate(CompassData compassData)
{
await DispatcherHelper.RunAsync(
() =>
{
this.CompassDirection = compassData;
});
}
private string GetLatitudeSign(double latitude) => latitude > 0 ? "E" : "W";
private string GetLongitudeSign(double longitude) => longitude > 0 ? "N" : "S";
private string GetAltitudeSign(double altitude) => altitude > 0 ? "npm" : "ppm";
private async void TimerServiceOnTimerUpdate()
{
await DispatcherHelper.RunAsync(
() =>
{
this.TimeNow = DateTime.Now.ToString("HH:mm:ss");
});
}
private async void OnNavigationDataUpdate(NavigationData navigationData)
{
await DispatcherHelper.RunAsync(
() =>
{
this.DistanceToTarget = navigationData.DistanceFromTarget;
this.OffsetFromNorth = navigationData.DirectionRelatedToNorth;
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Xunit;
namespace THNETII.Common.Linq.Test
{
[SuppressMessage("Naming", "CA1716:Identifiers should not match keywords")]
public abstract class LinqExtensionsTest<T>
{
protected abstract object GetEmpty();
protected abstract object GetMoreThan5ButLessThan100();
protected abstract T GetNonDefaultT();
protected virtual T PrimitiveFirst(object source) =>
(source as IEnumerable<T>).First();
protected virtual T PrimitiveLast(object source) =>
(source as IEnumerable<T>).Last();
protected virtual T PrimitiveElementAt(object source, int index) =>
(source as IEnumerable<T>).ElementAt(index);
protected abstract T First(object source);
protected abstract T FirstOrDefault(object source);
protected abstract T FirstOrDefault(object source, T @default);
protected abstract T FirstOrDefault(object source, Func<T> @defaultFactory);
protected abstract T Last(object source);
protected abstract T LastOrDefault(object source);
protected abstract T LastOrDefault(object source, T @default);
protected abstract T LastOrDefault(object source, Func<T> defaultFactory);
protected abstract T ElementAt(object source, int index);
protected abstract T ElementAtOrDefault(object source, int index);
protected abstract T ElementAtOrDefault(object source, int index, T @default);
protected abstract T ElementAtOrDefault(object source, int index, Func<T> defaultFactory);
#region First
[SkippableFact]
public void FirstOfNullThrows() =>
Assert.Throws<ArgumentNullException>(() => First(null!));
[SkippableFact]
public void FirstOfEmptyThrows() =>
Assert.Throws<InvalidOperationException>(() => First(GetEmpty()));
[SkippableFact]
public void FirstReturnsFirstT()
{
var test = GetMoreThan5ButLessThan100();
Assert.Equal(PrimitiveFirst(test), First(test));
}
[SkippableFact]
public void FirstOrDefaultOfNullThrows() =>
Assert.Throws<ArgumentNullException>(() => FirstOrDefault(null!));
[SkippableFact]
public void FirstOrDefaultOfEmptyReturnsDefaultT() =>
Assert.Equal(default!, FirstOrDefault(GetEmpty()));
[SkippableFact]
public void FirstOrDefaultOfEmptyReturnsArgument()
{
var expected = GetNonDefaultT();
Assert.Equal(expected, FirstOrDefault(GetEmpty(), expected));
}
[SkippableFact]
public void FirstOrDefaultOfEmptyReturnsFactoryValue()
{
var expected = GetNonDefaultT();
Assert.Equal(expected, FirstOrDefault(GetEmpty(), () => expected));
}
[SkippableFact]
public void FirstOrDefaultReturnsFirstT()
{
var test = GetMoreThan5ButLessThan100();
Assert.Equal(PrimitiveFirst(test), FirstOrDefault(test));
}
[SkippableFact]
public void FirstOrDefaultIgnoresArgumentIfNonEmpty()
{
var test = GetMoreThan5ButLessThan100();
var ignore = GetNonDefaultT();
Assert.Equal(PrimitiveFirst(test), FirstOrDefault(test, ignore));
}
[SkippableFact]
public void FirstOrDefaultIgnoresFactoryIfNonEmpty()
{
var test = GetMoreThan5ButLessThan100();
static T ignoredFactory() => throw new InvalidOperationException("The factory should never be invoked");
Assert.Equal(PrimitiveFirst(test), FirstOrDefault(test, ignoredFactory));
}
#endregion
#region Last
[SkippableFact]
public void LastOfNullThrows() =>
Assert.Throws<ArgumentNullException>(() => Last(null!));
[SkippableFact]
public void LastOfEmptyThrows() =>
Assert.Throws<InvalidOperationException>(() => Last(GetEmpty()));
[SkippableFact]
public void LastReturnsLastT()
{
var test = GetMoreThan5ButLessThan100();
Assert.Equal(PrimitiveLast(test), Last(test));
}
[SkippableFact]
public void LastOrDefaultOfNullThrows() =>
Assert.Throws<ArgumentNullException>(() => LastOrDefault(null!));
[SkippableFact]
public void LastOrDefaultOfEmptyReturnsDefaultT() =>
Assert.Equal(default!, LastOrDefault(GetEmpty()));
[SkippableFact]
public void LastOrDefaultOfEmptyReturnsArgument()
{
var expected = GetNonDefaultT();
Assert.Equal(expected, LastOrDefault(GetEmpty(), expected));
}
[SkippableFact]
public void LastOrDefaultOfEmptyReturnsFactoryValue()
{
var expected = GetNonDefaultT();
Assert.Equal(expected, LastOrDefault(GetEmpty(), () => expected));
}
[SkippableFact]
public void LastOrDefaultReturnsLastT()
{
var test = GetMoreThan5ButLessThan100();
Assert.Equal(PrimitiveLast(test), LastOrDefault(test));
}
[SkippableFact]
public void LastOrDefaultIgnoresArgumentIfNonEmpty()
{
var test = GetMoreThan5ButLessThan100();
var ignore = GetNonDefaultT();
Assert.Equal(PrimitiveLast(test), LastOrDefault(test, ignore));
}
[SkippableFact]
public void LastOrDefaultIgnoresFactoryIfNonEmpty()
{
var test = GetMoreThan5ButLessThan100();
static T ignoredFactory() => throw new InvalidOperationException("The factory should never be invoked");
Assert.Equal(PrimitiveLast(test), LastOrDefault(test, ignoredFactory));
}
#endregion
#region At
[SkippableFact]
public void ElementAtOfNullThrows()
{
Assert.Throws<ArgumentNullException>(() => ElementAt(null!, default));
}
[SkippableFact]
public void ElementAtOfEmptyThrows() =>
Assert.Throws<ArgumentOutOfRangeException>(() => ElementAt(GetEmpty(), default));
[SkippableFact]
public void ElementAtReturnsElementAtT()
{
const int index = 5;
var test = GetMoreThan5ButLessThan100();
Assert.Equal(PrimitiveElementAt(test, index), ElementAt(test, index));
}
[SkippableFact]
public void ElementAtOrDefaultOfNullThrows() =>
Assert.Throws<ArgumentNullException>(() => ElementAtOrDefault(null!, default));
[SkippableFact]
public void ElementAtOrDefaultOfEmptyReturnsDefaultT() =>
Assert.Equal(default!, ElementAtOrDefault(GetEmpty(), default));
[SkippableFact]
public void ElementAtOrDefaultOfEmptyReturnsArgument()
{
var expected = GetNonDefaultT();
Assert.Equal(expected, ElementAtOrDefault(GetEmpty(), default, expected));
}
[SkippableFact]
public void ElementAtOrDefaultOfEmptyReturnsFactoryValue()
{
var expected = GetNonDefaultT();
Assert.Equal(expected, ElementAtOrDefault(GetEmpty(), default, () => expected));
}
[SkippableFact]
public void ElementAtOrDefaultReturnsElementAtT()
{
const int index = 5;
var test = GetMoreThan5ButLessThan100();
Assert.Equal(PrimitiveElementAt(test, index), ElementAtOrDefault(test, index));
}
[SkippableFact]
public void ElementAtWithNegativeThrows()
{
var test = GetMoreThan5ButLessThan100();
Assert.Throws<ArgumentOutOfRangeException>("index", () => ElementAt(test, -1));
}
[SkippableFact]
public void ElementAtOrDefaultWithNegativeReturnsDefault()
{
var test = GetMoreThan5ButLessThan100();
T expected = default!;
Assert.Equal(expected, ElementAtOrDefault(test, -1));
}
[SkippableFact]
public void ElementAtOrDefaultWithNegativeReturnsArgument()
{
var test = GetMoreThan5ButLessThan100();
T expected = GetNonDefaultT();
Assert.Equal(expected, ElementAtOrDefault(test, -1, expected));
}
[SkippableFact]
public void ElementAtOrDefaultWithNegativeReturnsFactoryValue()
{
var test = GetMoreThan5ButLessThan100();
T expected = GetNonDefaultT();
Assert.Equal(expected, ElementAtOrDefault(test, -1, () => expected));
}
[SkippableFact]
public void ElementAtOrDefaultIgnoresArgumentIfNonEmpty()
{
const int index = 5;
var test = GetMoreThan5ButLessThan100();
var ignore = GetNonDefaultT();
Assert.Equal(PrimitiveElementAt(test, index), ElementAtOrDefault(test, index, ignore));
}
[SkippableFact]
public void ElementAtOrDefaultIgnoresFactoryIfNonEmpty()
{
const int index = 5;
var test = GetMoreThan5ButLessThan100();
static T ignoredFactory() => throw new InvalidOperationException("The factory should never be invoked");
Assert.Equal(PrimitiveElementAt(test, index), ElementAtOrDefault(test, index, ignoredFactory));
}
[SkippableFact]
public void ElementAtWithTooBigIndexThrows()
{
const int index = 100;
var test = GetMoreThan5ButLessThan100();
Assert.Throws<ArgumentOutOfRangeException>("index", () => ElementAt(test, index));
}
[SkippableFact]
public void ElementAtOrDefaultWithTooBigIndexReturnsDefault()
{
const int index = 100;
var test = GetMoreThan5ButLessThan100();
Assert.Equal(default!, ElementAtOrDefault(test, index));
}
[SkippableFact]
public void ElementAtOrDefaultWithTooBigIndexReturnsArgument()
{
const int index = 100;
var test = GetMoreThan5ButLessThan100();
var expected = GetNonDefaultT();
Assert.Equal(expected, ElementAtOrDefault(test, index, expected));
}
[SkippableFact]
public void ElementAtOrDefaultWithTooBigIndexReturnsFactoryValue()
{
const int index = 100;
var test = GetMoreThan5ButLessThan100();
var expected = GetNonDefaultT();
Assert.Equal(expected, ElementAtOrDefault(test, index, () => expected));
}
#endregion
}
public abstract class LinqExtensionsWithIntsTest : LinqExtensionsTest<int>
{
protected override int GetNonDefaultT() => 42;
}
public abstract class LinqExtensionsWithCharsTest : LinqExtensionsTest<char>
{
protected override char GetNonDefaultT() => 'Z';
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace FlexHtmlHelper.Render
{
public class Bootstrap3Render :DefaultRender, IFlexRender
{
public override string Name
{
get
{
return "Bootstrap3";
}
}
#region Helper
public override FlexTagBuilder LabelHelper(FlexTagBuilder tagBuilder, string @for, string text, IDictionary<string, object> htmlAttributes = null)
{
FlexTagBuilder tag = new FlexTagBuilder("label");
tag.TagAttributes.Add("for", @for);
tag.AddText(text);
tag.MergeAttributes(htmlAttributes, replaceExisting: true);
tagBuilder.AddTag(tag);
return tag;
}
public override FlexTagBuilder FormHelper(FlexTagBuilder tagBuilder, string tagName, string formAction, string formMethod, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder(tagName);
tag.MergeAttributes(htmlAttributes);
// action is implicitly generated, so htmlAttributes take precedence.
if (!string.IsNullOrEmpty(formAction))
{
tag.MergeAttribute("action", formAction);
}
// method is an explicit parameter, so it takes precedence over the htmlAttributes.
if (!string.IsNullOrEmpty(formMethod))
{
tag.MergeAttribute("method", formMethod, true);
}
tag.MergeAttribute("role", "form");
tagBuilder.AddTag(tag);
return tag;
}
public override FlexTagBuilder StaticHelper(FlexTagBuilder tagBuilder, string name, string value, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("p");
tag.MergeAttributes(htmlAttributes);
tag.AddText(value);
tagBuilder.AddTag(tag);
return tag;
}
private string GetInputType(FlexTagBuilder inputTag)
{
string inputType = null;
if (!inputTag.TagAttributes.Keys.Contains("type"))
{
if (inputTag.Tag().TagName.Equals("select", StringComparison.InvariantCultureIgnoreCase))
{
inputType = "select";
}
else if (inputTag.Tag().TagName.Equals("textarea", StringComparison.InvariantCultureIgnoreCase))
{
inputType = "textarea";
}
else if (inputTag.Tag().TagName.Equals("p", StringComparison.InvariantCultureIgnoreCase))
{
inputType = "static";
}
}
else
{
inputType = inputTag.TagAttributes["type"];
}
return inputType;
}
public override FlexTagBuilder FormGroupHelper(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder labelTag, FlexTagBuilder inputTag, FlexTagBuilder validationMessageTag)
{
FlexTagBuilder tag = new FlexTagBuilder("div");
string inputType = GetInputType(inputTag);
switch (formContext.LayoutStyle)
{
case FormLayoutStyle.Default:
labelTag.AddCssClass("control-label");
switch (inputType)
{
case "text":
case "email":
case "password":
case "select":
goto default;
case "radio":
tag.AddCssClass("radio");
tag.AddTag(labelTag);
labelTag.InsertTag(0, inputTag);
break;
case "checkbox":
tag.AddCssClass("checkbox");
tag.AddTag(labelTag);
labelTag.InsertTag(0, inputTag);
break;
case "hidden":
tag.AddTag(inputTag);
break;
case "file":
tag.AddCssClass("form-group");
tag.AddTag(labelTag);
tag.AddTag(inputTag);
tag.AddTag(validationMessageTag);
break;
case "static":
tag.AddCssClass("form-group");
tag.AddTag(labelTag);
tag.AddTag(inputTag.AddCssClass("form-control-static"));
break;
default:
tag.AddCssClass("form-group");
tag.AddTag(labelTag);
tag.AddTag(inputTag.AddCssClass("form-control"));
tag.AddTag(validationMessageTag);
break;
}
break;
case FormLayoutStyle.Horizontal:
switch (inputType)
{
case "text":
case "email":
case "password":
case "select":
goto default;
case "radio":
tag.AddCssClass("form-group");
FlexTagBuilder radioColTag = new FlexTagBuilder("div");
foreach (var col in formContext.LabelColumns)
{
GridColumnOffset(radioColTag, col.Key, col.Value);
}
foreach (var col in formContext.InputColumns)
{
GridColumns(radioColTag, col.Key, col.Value);
}
tag.AddTag(radioColTag);
FlexTagBuilder radioTag = new FlexTagBuilder("div");
radioTag.AddCssClass("radio");
radioColTag.AddTag(radioTag);
radioTag.AddTag(labelTag);
labelTag.InsertTag(0,inputTag);
break;
case "checkbox":
tag.AddCssClass("form-group");
FlexTagBuilder colTag = new FlexTagBuilder("div");
foreach (var col in formContext.LabelColumns)
{
GridColumnOffset(colTag, col.Key, col.Value);
}
foreach (var col in formContext.InputColumns)
{
GridColumns(colTag, col.Key, col.Value);
}
tag.AddTag(colTag);
FlexTagBuilder checkBoxTag = new FlexTagBuilder("div");
checkBoxTag.AddCssClass("checkbox");
colTag.AddTag(checkBoxTag);
checkBoxTag.AddTag(labelTag);
labelTag.InsertTag(0,inputTag);
break;
case "hidden":
tag.AddTag(inputTag);
break;
case "file":
tag.AddCssClass("form-group");
foreach (var col in formContext.LabelColumns)
{
GridColumns(labelTag, col.Key, col.Value);
}
labelTag.AddCssClass("control-label");
tag.AddTag(labelTag);
FlexTagBuilder fileDivTag = new FlexTagBuilder("div");
foreach (var col in formContext.InputColumns)
{
GridColumns(fileDivTag, col.Key, col.Value);
}
fileDivTag.AddTag(inputTag.AddCssClass("form-control"));
tag.AddTag(fileDivTag);
tag.AddTag(validationMessageTag);
break;
case "static":
tag.AddCssClass("form-group");
foreach (var col in formContext.LabelColumns)
{
GridColumns(labelTag, col.Key, col.Value);
}
labelTag.AddCssClass("control-label");
tag.AddTag(labelTag);
FlexTagBuilder staticDivTag = new FlexTagBuilder("div");
foreach (var col in formContext.InputColumns)
{
GridColumns(staticDivTag, col.Key, col.Value);
}
staticDivTag.AddTag(inputTag.AddCssClass("form-control-static"));
tag.AddTag(staticDivTag);
break;
default:
tag.AddCssClass("form-group");
foreach (var col in formContext.LabelColumns)
{
GridColumns(labelTag, col.Key, col.Value);
}
labelTag.AddCssClass("control-label");
tag.AddTag(labelTag);
FlexTagBuilder inputDivTag = new FlexTagBuilder("div");
foreach (var col in formContext.InputColumns)
{
GridColumns(inputDivTag, col.Key, col.Value);
}
inputDivTag.AddTag(inputTag.AddCssClass("form-control"));
inputDivTag.AddTag(validationMessageTag);
tag.AddTag(inputDivTag);
break;
}
break;
case FormLayoutStyle.Inline:
switch (inputType)
{
case "text":
case "email":
case "password":
case "select":
goto default;
case "radio":
tag.AddCssClass("radio");
tag.AddTag(labelTag);
labelTag.InsertTag(0, inputTag);
break;
case "checkbox":
tag.AddCssClass("checkbox");
tag.AddTag(labelTag);
labelTag.InsertTag(0, inputTag);
break;
case "hidden":
tag.AddTag(inputTag);
break;
case "file":
tag.AddCssClass("form-group");
labelTag.AddCssClass("sr-only");
tag.AddTag(labelTag);
tag.AddTag(inputTag);
tag.AddTag(validationMessageTag);
break;
case "static":
tag.AddCssClass("form-group");
labelTag.AddCssClass("sr-only");
tag.AddTag(labelTag);
tag.AddTag(inputTag.AddCssClass("form-control-static"));
break;
default:
tag.AddCssClass("form-group");
labelTag.AddCssClass("sr-only");
tag.AddTag(labelTag);
tag.AddTag(inputTag.AddCssClass("form-control"));
tag.AddTag(validationMessageTag);
break;
}
break;
}
tagBuilder.AddTag(tag);
return tag;
}
public override FlexTagBuilder ButtonHelper(FlexTagBuilder tagBuilder, string type, string text, string value, string name, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("button");
if (!string.IsNullOrEmpty(text))
{
tag.AddText(text);
}
tag.MergeAttributes(htmlAttributes);
if (!string.IsNullOrEmpty(type))
{
tag.MergeAttribute("type", type);
}
if (!string.IsNullOrEmpty(value))
{
tag.MergeAttribute("value", value);
}
if (!string.IsNullOrEmpty(name))
{
tag.MergeAttribute("name", name);
}
tag.AddCssClass("btn").AddCssClass("btn-default");
tagBuilder.AddTag(tag);
return tagBuilder;
}
public override FlexTagBuilder LinkButtonHelper(FlexTagBuilder tagBuilder)
{
tagBuilder.Tag().AddCssClass("btn").AddCssClass("btn-default");
return tagBuilder;
}
public override FlexTagBuilder PagingLinkHelper(FlexTagBuilder tagBuilder, int totalItemCount, int pageNumber, int pageSize, int maxPagingLinks, Func<int, string> pagingUrlResolver, IDictionary<string, object> htmlAttributes)
{
if (pageNumber < 1)
throw new ArgumentOutOfRangeException("pageNumber", pageNumber, "PageNumber cannot be below 1.");
if (pageSize < 1)
throw new ArgumentOutOfRangeException("pageSize", pageSize, "PageSize cannot be less than 1.");
if (totalItemCount < pageNumber)
throw new ArgumentOutOfRangeException("totalItemCount", totalItemCount, "totalItemCount can not be less than pageNumber");
// set source to blank list if superset is null to prevent exceptions
var pageCount = totalItemCount > 0
? (int)Math.Ceiling(totalItemCount / (double)pageSize)
: 0;
var hasPreviousPage = pageNumber > 1;
var hasNextPage = pageNumber < pageCount;
var isFirstPage = pageNumber == 1;
var isLastPage = pageNumber >= pageCount;
var firstItemOnPage = (pageNumber - 1) * pageSize + 1;
var numberOfLastItemOnPage = firstItemOnPage + pageSize - 1;
var lastItemOnPage = numberOfLastItemOnPage > totalItemCount
? totalItemCount
: numberOfLastItemOnPage;
int halfPagingLinks = maxPagingLinks / 2;
int startPageNumber = 1;
int endPageNumber = 1;
if (pageNumber < halfPagingLinks)
{
startPageNumber = 1;
endPageNumber = pageCount > maxPagingLinks ? maxPagingLinks : pageCount;
}
else
{
if (pageNumber + halfPagingLinks > pageCount)
{
endPageNumber = pageCount;
startPageNumber = pageCount > maxPagingLinks ? pageCount - maxPagingLinks + 1: 1 ;
}
else
{
startPageNumber = pageNumber - halfPagingLinks + 1;
endPageNumber = pageCount > (startPageNumber + maxPagingLinks - 1) ? (startPageNumber + maxPagingLinks - 1) : pageCount;
}
}
FlexTagBuilder ul = new FlexTagBuilder("ul");
ul.AddCssClass("pagination");
FlexTagBuilder preLi = new FlexTagBuilder("li");
if (hasPreviousPage)
{
preLi.AddTag("a").MergeAttributes(htmlAttributes).AddHtmlText(@"«").Attributes.Add("href", pagingUrlResolver(pageNumber - 1));
}
else
{
preLi.AddCssClass("disabled").AddTag("a").MergeAttributes(htmlAttributes).AddHtmlText(@"«").Attributes.Add("href", "#");
}
ul.AddTag(preLi);
for(int i=startPageNumber; i<=endPageNumber; i++)
{
FlexTagBuilder li = new FlexTagBuilder("li");
li.AddTag("a").MergeAttributes(htmlAttributes).AddText(i.ToString()).Attributes.Add("href", pagingUrlResolver(i));
if (i == pageNumber)
{
li.AddCssClass("active");
}
ul.AddTag(li);
}
if (endPageNumber < pageCount)
{
FlexTagBuilder moreLi = new FlexTagBuilder("li");
moreLi.AddCssClass("disabled").AddTag("a").MergeAttributes(htmlAttributes).AddHtmlText(@"...").Attributes.Add("href", "#");
ul.AddTag(moreLi);
}
FlexTagBuilder nextLi = new FlexTagBuilder("li");
if (hasNextPage)
{
nextLi.AddTag("a").MergeAttributes(htmlAttributes).AddHtmlText(@"»").Attributes.Add("href", pagingUrlResolver(pageNumber + 1));
}
else
{
nextLi.AddCssClass("disabled").AddTag("a").MergeAttributes(htmlAttributes).AddHtmlText(@"»").Attributes.Add("href", "#");
}
ul.AddTag(nextLi);
tagBuilder.AddTag(ul);
return tagBuilder;
}
public override FlexTagBuilder IconHelper(FlexTagBuilder tagBuilder, string name, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("span");
tag.AddCssClass("glyphicon ").AddCssClass("glyphicon-" + name);
tag.MergeAttributes(htmlAttributes);
tagBuilder.AddTag(tag);
return tagBuilder;
}
public override FlexTagBuilder ModalHelper(FlexTagBuilder tagBuilder, string title, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("div");
tag.AddCssClass("modal").AddCssClass("fade").AddAttribute("tabindex", "-1").AddAttribute("role", "dialog").AddAttribute("aria-hidden", "true")
.AddTag(new FlexTagBuilder("div").AddCssClass("modal-dialog")
.AddTag(new FlexTagBuilder("div").AddCssClass("modal-content")
.AddTag(new FlexTagBuilder("div").AddCssClass("modal-header")
.AddTag(new FlexTagBuilder("button").AddCssClass("close").AddAttribute("type", "button").AddAttribute("data-dismiss", "modal").AddAttribute("aria-hidden", "true").AddHtmlText("×"))
.AddTag(new FlexTagBuilder("h4").AddCssClass("modal-title").AddText(title??"")))
.AddTag(new FlexTagBuilder("div").AddCssClass("modal-body"))
.AddTag(new FlexTagBuilder("div").AddCssClass("modal-footer"))));
tag.MergeAttributes(htmlAttributes);
tagBuilder.AddTag(tag);
return tagBuilder;
}
public override FlexTagBuilder ModalHeaderHelper(FlexTagBuilder tagBuilder, FlexTagBuilder header)
{
var tag = tagBuilder.TagWithCssClass("modal-header");
if (tag != null)
{
tag.AddTag(header);
}
return tagBuilder;
}
public override FlexTagBuilder ModalBodyHelper(FlexTagBuilder tagBuilder, FlexTagBuilder body)
{
var tag = tagBuilder.TagWithCssClass("modal-body");
if (tag != null)
{
tag.AddTag(body);
}
return tagBuilder;
}
public override FlexTagBuilder ModalFooterHelper(FlexTagBuilder tagBuilder, FlexTagBuilder footer)
{
var tag = tagBuilder.TagWithCssClass("modal-footer");
if (tag != null)
{
tag.AddTag(footer);
}
return tagBuilder;
}
#endregion
#region Grid System
public override FlexTagBuilder GridRow(FlexTagBuilder tagBuilder)
{
FlexTagBuilder tag = new FlexTagBuilder("div");
tag.AddCssClass("row");
tag.AddTag(tagBuilder.Root);
return tagBuilder;
}
public override FlexTagBuilder GridColumns(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
string cssClass = "";
switch (style)
{
case GridStyle.ExtraSmall:
cssClass = "col-xs-";
break;
case GridStyle.Small:
cssClass = "col-sm-";
break;
case GridStyle.Medium:
cssClass = "col-md-";
break;
case GridStyle.Large:
cssClass = "col-lg-";
break;
}
tagBuilder.AddCssClass(cssClass + columns.ToString());
return tagBuilder;
}
public override FlexTagBuilder GridColumnOffset(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
string cssClass = "";
switch (style)
{
case GridStyle.ExtraSmall:
cssClass = "col-xs-offset-";
break;
case GridStyle.Small:
cssClass = "col-sm-offset-";
break;
case GridStyle.Medium:
cssClass = "col-md-offset-";
break;
case GridStyle.Large:
cssClass = "col-lg-offset-";
break;
}
tagBuilder.AddCssClass(cssClass + columns.ToString());
return tagBuilder;
}
public override FlexTagBuilder GridColumnPush(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
string cssClass = "";
switch (style)
{
case GridStyle.ExtraSmall:
cssClass = "col-xs-push-";
break;
case GridStyle.Small:
cssClass = "col-sm-push-";
break;
case GridStyle.Medium:
cssClass = "col-md-push-";
break;
case GridStyle.Large:
cssClass = "col-lg-push-";
break;
}
tagBuilder.AddCssClass(cssClass + columns.ToString());
return tagBuilder;
}
public override FlexTagBuilder GridColumnPull(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
string cssClass = "";
switch (style)
{
case GridStyle.ExtraSmall:
cssClass = "col-xs-pull-";
break;
case GridStyle.Small:
cssClass = "col-sm-pull-";
break;
case GridStyle.Medium:
cssClass = "col-md-pull-";
break;
case GridStyle.Large:
cssClass = "col-lg-pull-";
break;
}
tagBuilder.AddCssClass(cssClass + columns.ToString());
return tagBuilder;
}
public override FlexTagBuilder GridColumnVisible(FlexTagBuilder tagBuilder, GridStyle style, bool visible)
{
string s = string.Empty;
switch (style)
{
case GridStyle.ExtraSmall:
s = "xs";
break;
case GridStyle.Small:
s = "sm";
break;
case GridStyle.Medium:
s = "md";
break;
case GridStyle.Large:
s = "lg";
break;
case GridStyle.Print:
s = "print";
break;
}
string css = string.Format("{0}-{1}", visible ? "visible" : "hidden", s);
tagBuilder.AddCssClass(css);
return tagBuilder;
}
#endregion
#region Form
public override FlexTagBuilder FormLayout(FlexTagBuilder tagBuilder, FormLayoutStyle layout)
{
switch (layout)
{
case FormLayoutStyle.Horizontal:
tagBuilder.AddCssClass("form-horizontal");
break;
case FormLayoutStyle.Inline:
tagBuilder.AddCssClass("form-inline");
break;
}
return tagBuilder;
}
public override FlexTagBuilder FormGroupHelpText(FlexTagBuilder tagBuilder, string text)
{
tagBuilder.AddTag("span").AddCssClass("help-block").AddText(text);
return tagBuilder;
}
public override FlexTagBuilder FormGroupLabelText(FlexTagBuilder tagBuilder, string text)
{
var tag = tagBuilder.LastTag("label");
if (tag != null)
{
tag.TextTag.SetText(text);
}
return tagBuilder;
}
public override FlexTagBuilder FormGroupValidationState(FlexTagBuilder tagBuilder, ValidationState state)
{
switch (state)
{
case ValidationState.Warning:
tagBuilder.Tag().AddCssClass("has-warning");
break;
case ValidationState.Error:
tagBuilder.Tag().AddCssClass("has-error");
break;
case ValidationState.Succuss:
tagBuilder.Tag().AddCssClass("has-success");
break;
}
tagBuilder.Tag().AddCssClass("");
return tagBuilder;
}
public override FlexTagBuilder FormGroupAddInput(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder labelTag, FlexTagBuilder inputTag)
{
string inputType = GetInputType(inputTag);
switch (inputType)
{
case "checkbox":
labelTag.Tag().AddCssClass("checkbox-inline");
labelTag.Tag().InsertTag(0, inputTag);
break;
case "radio":
labelTag.Tag().AddCssClass("radio-inline");
labelTag.Tag().InsertTag(0, inputTag);
break;
default:
return tagBuilder;
}
FlexTagBuilder div = null;
switch (formContext.LayoutStyle)
{
case FormLayoutStyle.Default:
div = tagBuilder.TagWithCssClass("div", "checkbox");
if (div != null)
{
div.RemoveCssClass("checkbox");
div.ChildTag("label").AddCssClass("checkbox-inline");
}
else
{
div = tagBuilder.TagWithCssClass("div", "radio");
if (div != null)
{
div.RemoveCssClass("radio");
div.ChildTag("label").AddCssClass("radio-inline");
}
}
tagBuilder.AddCssClass("form-group",true);
tagBuilder.AddTag(labelTag);
break;
case FormLayoutStyle.Horizontal:
FlexTagBuilder colTag = tagBuilder.Tag().ChildTag("div");
if (colTag!= null)
{
div = colTag.Tag().ChildTagWithClass("div", "checkbox");
if (div != null)
{
var label = div.Tag().ChildTag("label");
if (label != null)
{
label.Tag().AddCssClass("checkbox-inline");
colTag.RemoveChildTag(div);
colTag.InsertTag(0, label);
}
}
else
{
div = colTag.Tag().ChildTagWithClass("div", "radio");
if (div != null)
{
var label = div.Tag().ChildTag("label");
if (label != null)
{
label.Tag().AddCssClass("radio-inline");
colTag.RemoveChildTag(div);
colTag.InsertTag(0, label);
}
}
}
colTag.AddTag(labelTag);
}
break;
case FormLayoutStyle.Inline:
tagBuilder.AddTag(labelTag);
break;
}
return tagBuilder;
}
public override FlexTagBuilder FormGroupInputGridColumns(FlexTagBuilder tagBuilder, FlexFormContext formContext, GridStyle style, int columns)
{
FlexTagBuilder div = null;
FlexTagBuilder input = null;
string inputType = string.Empty;
string cssClass = "";
switch (style)
{
case GridStyle.ExtraSmall:
cssClass = "col-xs-";
break;
case GridStyle.Small:
cssClass = "col-sm-";
break;
case GridStyle.Medium:
cssClass = "col-md-";
break;
case GridStyle.Large:
cssClass = "col-lg-";
break;
}
switch (formContext.LayoutStyle)
{
case FormLayoutStyle.Default:
input = tagBuilder.LastTag("input");
if (input != null)
{
inputType = GetInputType(input);
switch (inputType)
{
case "text":
case "password":
case "hidden":
case "email":
case "file":
div = new FlexTagBuilder("div");
input.Replace(div);
div.AddCssClass("row").AddTag("div").AddCssClass(cssClass + columns.ToString()).AddTag(input);
break;
}
}
else
{
input = tagBuilder.LastTag("select");
if (input != null)
{
div = new FlexTagBuilder("div");
input.Replace(div);
div.AddCssClass("row").AddTag("div").AddCssClass(cssClass + columns.ToString()).AddTag(input);
}
else
{
input = tagBuilder.LastTag("textarea");
if (input != null)
{
div = new FlexTagBuilder("div");
input.Replace(div);
div.AddCssClass("row").AddTag("div").AddCssClass(cssClass + columns.ToString()).AddTag(input);
}
}
}
break;
case FormLayoutStyle.Horizontal:
input = tagBuilder.LastTag("input");
if (input != null)
{
inputType = GetInputType(input);
switch (inputType)
{
case "text":
case "password":
case "hidden":
case "email":
case "file":
div = input.ParentTag;
div.RemoveCssClass(new Regex(@"\A"+cssClass+@"\d+"));
div.AddCssClass(cssClass + columns.ToString());
break;
}
}
else
{
input = tagBuilder.LastTag("select");
if (input != null)
{
div = input.ParentTag;
div.AddCssClass(cssClass + columns.ToString());
}
else
{
input = tagBuilder.LastTag("textarea");
if (input != null)
{
div = input.ParentTag;
div.AddCssClass(cssClass + columns.ToString());
}
}
}
break;
case FormLayoutStyle.Inline:
break;
}
return tagBuilder;
}
public override FlexTagBuilder FormGroupButton(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder buttonTag)
{
FlexTagBuilder tag = new FlexTagBuilder("div");
tag.AddCssClass("form-group");
switch (formContext.LayoutStyle)
{
case FormLayoutStyle.Default:
tag.AddTag(buttonTag);
break;
case FormLayoutStyle.Horizontal:
FlexTagBuilder colTag = new FlexTagBuilder("div");
foreach (var col in formContext.LabelColumns)
{
GridColumnOffset(colTag, col.Key, col.Value);
}
foreach (var col in formContext.InputColumns)
{
GridColumns(colTag, col.Key, col.Value);
}
tag.AddTag(colTag);
colTag.AddTag(buttonTag);
break;
case FormLayoutStyle.Inline:
break;
}
return tagBuilder.AddTag(tag);
}
public override FlexTagBuilder FormGroupAddButton(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder buttonTag)
{
FlexTagBuilder p = null;
var btn = tagBuilder.LastTag("button");
if (btn == null)
{
btn = tagBuilder.LastTag("a");
if (btn.TagWithCssClass("btn") != btn)
{
btn = null;
}
}
if (btn != null)
{
p = btn.ParentTag;
}
if (p != null)
{
p.AddText(" ");
p.AddTag(buttonTag);
}
return tagBuilder;
}
public override FlexTagBuilder FormGroupHeight(FlexTagBuilder tagBuilder, FormGroupHeightStyle size)
{
var groupTag = tagBuilder.TagWithCssClass("form-group");
if (groupTag != null)
{
switch (size)
{
case FormGroupHeightStyle.Small:
tagBuilder.Tag().AddCssClass("form-group-sm");
break;
case FormGroupHeightStyle.Normal:
break;
case FormGroupHeightStyle.Large:
tagBuilder.Tag().AddCssClass("form-group-lg");
break;
}
}
return tagBuilder;
}
public override FlexTagBuilder FormGroupLink(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder linkTag)
{
FlexTagBuilder tag = new FlexTagBuilder("div");
tag.AddCssClass("form-group");
switch (formContext.LayoutStyle)
{
case FormLayoutStyle.Default:
tag.AddTag(linkTag);
break;
case FormLayoutStyle.Horizontal:
FlexTagBuilder colTag = new FlexTagBuilder("div");
foreach (var col in formContext.LabelColumns)
{
GridColumnOffset(colTag, col.Key, col.Value);
}
foreach (var col in formContext.InputColumns)
{
GridColumns(colTag, col.Key, col.Value);
}
tag.AddTag(colTag);
colTag.AddTag(linkTag);
break;
case FormLayoutStyle.Inline:
break;
}
return tagBuilder.AddTag(tag);
}
public override FlexTagBuilder FormGroupAddLink(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder linkTag)
{
FlexTagBuilder p = null;
var link = tagBuilder.LastTag("a");
if (link != null)
{
p = link.ParentTag;
}
if (p != null)
{
p.AddText(" ");
p.AddTag(linkTag);
}
return tagBuilder;
}
#endregion
#region Input
public override FlexTagBuilder InputHeight(FlexTagBuilder tagBuilder, InputHeightStyle size)
{
switch (size)
{
case InputHeightStyle.Small:
tagBuilder.Tag().AddCssClass("input-sm");
break;
case InputHeightStyle.Normal:
break;
case InputHeightStyle.Large:
tagBuilder.Tag().AddCssClass("input-lg");
break;
}
return tagBuilder;
}
#endregion
#region Button
public override FlexTagBuilder ButtonSize(FlexTagBuilder tagBuilder, ButtonSizeStyle size)
{
switch (size)
{
case ButtonSizeStyle.Large:
tagBuilder.Tag().AddCssClass("btn-lg");
break;
case ButtonSizeStyle.Small:
tagBuilder.Tag().AddCssClass("btn-sm");
break;
case ButtonSizeStyle.ExtraSmall:
tagBuilder.Tag().AddCssClass("btn-xs");
break;
}
return tagBuilder;
}
public override FlexTagBuilder ButtonStyle(FlexTagBuilder tagBuilder, ButtonOptionStyle style)
{
tagBuilder.Tag().RemoveCssClass("btn-default");
switch (style)
{
case ButtonOptionStyle.Default:
tagBuilder.Tag().AddCssClass("btn-default");
break;
case ButtonOptionStyle.Primary:
tagBuilder.Tag().AddCssClass("btn-primary");
break;
case ButtonOptionStyle.Success:
tagBuilder.Tag().AddCssClass("btn-success");
break;
case ButtonOptionStyle.Warning:
tagBuilder.Tag().AddCssClass("btn-warning");
break;
case ButtonOptionStyle.Info:
tagBuilder.Tag().AddCssClass("btn-info");
break;
case ButtonOptionStyle.Danger:
tagBuilder.Tag().AddCssClass("btn-danger");
break;
case ButtonOptionStyle.Link:
tagBuilder.Tag().AddCssClass("btn-link");
break;
}
return tagBuilder;
}
public override FlexTagBuilder ButtonBlock(FlexTagBuilder tagBuilder)
{
tagBuilder.Tag().AddCssClass("btn-block");
return tagBuilder;
}
#endregion
#region Element
public override FlexTagBuilder Collapse(FlexTagBuilder tagBuilder, string target)
{
tagBuilder.Tag().MergeAttribute("data-toggle", "collapse");
tagBuilder.Tag().MergeAttribute("data-target", target);
return tagBuilder;
}
public override FlexTagBuilder Collapsible(FlexTagBuilder tagBuilder, bool show = false)
{
if (show)
{
tagBuilder.Tag().AddCssClass("collapse").AddCssClass("in");
}
else
{
tagBuilder.Tag().AddCssClass("collapse");
}
return tagBuilder;
}
#endregion
#region Text Helper
public override FlexTagBuilder TextAlignment(FlexTagBuilder tagBuilder, TextAlignment textAlignment)
{
switch (textAlignment)
{
case FlexHtmlHelper.TextAlignment.Left:
tagBuilder.Tag().AddCssClass("text-left");
break;
case FlexHtmlHelper.TextAlignment.Center:
tagBuilder.Tag().AddCssClass("text-center");
break;
case FlexHtmlHelper.TextAlignment.Right:
tagBuilder.Tag().AddCssClass("text-right");
break;
case FlexHtmlHelper.TextAlignment.Justify:
tagBuilder.Tag().AddCssClass("text-justify");
break;
case FlexHtmlHelper.TextAlignment.NoWrap:
tagBuilder.Tag().AddCssClass("text-nowrap");
break;
}
return tagBuilder;
}
public override FlexTagBuilder TextTransformation(FlexTagBuilder tagBuilder, TextTransformation textTransformation)
{
switch (textTransformation)
{
case FlexHtmlHelper.TextTransformation.LowerCase:
tagBuilder.Tag().AddCssClass("text-lowercase");
break;
case FlexHtmlHelper.TextTransformation.UpperCase:
tagBuilder.Tag().AddCssClass("text-uppercase");
break;
case FlexHtmlHelper.TextTransformation.Capitalize:
tagBuilder.Tag().AddCssClass("text-capitalize");
break;
}
return tagBuilder;
}
public override FlexTagBuilder TextContextualColor(FlexTagBuilder tagBuilder, TextContextualColor textContextualColor)
{
switch (textContextualColor)
{
case FlexHtmlHelper.TextContextualColor.Muted:
tagBuilder.Tag().AddCssClass("text-muted");
break;
case FlexHtmlHelper.TextContextualColor.Primary:
tagBuilder.Tag().AddCssClass("text-primary");
break;
case FlexHtmlHelper.TextContextualColor.Success:
tagBuilder.Tag().AddCssClass("text-success");
break;
case FlexHtmlHelper.TextContextualColor.Info:
tagBuilder.Tag().AddCssClass("text-info");
break;
case FlexHtmlHelper.TextContextualColor.Warning:
tagBuilder.Tag().AddCssClass("text-warning");
break;
case FlexHtmlHelper.TextContextualColor.Danger:
tagBuilder.Tag().AddCssClass("text-danger");
break;
}
return tagBuilder;
}
public override FlexTagBuilder ContextualBackground(FlexTagBuilder tagBuilder, ContextualBackground contextualBackground)
{
switch (contextualBackground)
{
case FlexHtmlHelper.ContextualBackground.Primary:
tagBuilder.Tag().AddCssClass("bg-primary");
break;
case FlexHtmlHelper.ContextualBackground.Success:
tagBuilder.Tag().AddCssClass("bg-success");
break;
case FlexHtmlHelper.ContextualBackground.Info:
tagBuilder.Tag().AddCssClass("bg-info");
break;
case FlexHtmlHelper.ContextualBackground.Warning:
tagBuilder.Tag().AddCssClass("bg-warning");
break;
case FlexHtmlHelper.ContextualBackground.Danger:
tagBuilder.Tag().AddCssClass("bg-danger");
break;
}
return tagBuilder;
}
#endregion
#region Link
public override FlexTagBuilder PagingLinkSize(FlexTagBuilder tagBuilder, PagingLinkSizeStyle size)
{
switch (size)
{
case PagingLinkSizeStyle.Large:
tagBuilder.Tag().AddCssClass("pagination-lg");
break;
case PagingLinkSizeStyle.Small:
tagBuilder.Tag().AddCssClass("pagination-sm");
break;
}
return tagBuilder;
}
#endregion
#region Modal
public override FlexTagBuilder ModalSize(FlexTagBuilder tagBuilder, ModalSizeStyle size)
{
var tag = tagBuilder.TagWithCssClass("modal-dialog");
if (tag != null)
{
switch (size)
{
case ModalSizeStyle.Large:
tag.AddCssClass("modal-lg");
break;
case ModalSizeStyle.Small:
tag.AddCssClass("modal-sm");
break;
}
}
return tagBuilder;
}
public override FlexTagBuilder ModalOption(FlexTagBuilder tagBuilder, string name, string value)
{
var tag = tagBuilder.TagWithCssClass("modal");
if (tag != null)
{
tag.AddAttribute("data-"+name, value);
}
return tagBuilder;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Logging.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Security.Permissions;
namespace System.Net.PeerToPeer
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Security;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Threading;
using System.Net.Sockets;
using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_PNRP_CLOUD_INFO
{
internal IntPtr pwzCloudName;
internal UInt32 dwScope;
internal UInt32 dwScopeId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_PNRP_REGISTRATION_INFO
{
internal string pwszCloudName;
internal string pwszPublishingIdentity;
internal UInt32 cAddresses;
internal IntPtr ArrayOfSOCKADDRIN6Pointers;
internal ushort wport;
internal string pwszComment;
internal PEER_DATA payLoad;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_PNRP_ENDPOINT_INFO
{
internal IntPtr pwszPeerName;
internal UInt32 cAddresses;
internal IntPtr ArrayOfSOCKADDRIN6Pointers;
internal IntPtr pwszComment;
internal PEER_DATA payLoad;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_DATA
{
internal UInt32 cbPayload;
internal IntPtr pbPayload;
}
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeP2PNativeMethods
{
internal const string P2P = "p2p.dll";
[DllImport(P2P, CharSet = CharSet.Unicode)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern static void PeerFreeData(IntPtr dataToFree);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static Int32 PeerPnrpGetCloudInfo(out UInt32 pNumClouds, out SafePeerData pArrayOfClouds);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static Int32 PeerPnrpStartup(ushort versionRequired);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static Int32
PeerCreatePeerName(string identity, string classfier, out SafePeerData peerName);
//[DllImport(P2P, CharSet = CharSet.Unicode)]
//internal extern static Int32 PeerCreatePeerName(string identity, string classfier, out SafePeerData peerName);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static Int32 PeerIdentityGetDefault(out SafePeerData defaultIdentity);
/*
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static Int32 PeerIdentityCreate(string classifier, string friendlyName, IntPtr hCryptoProv, out SafePeerData defaultIdentity);
*/
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static Int32 PeerNameToPeerHostName(string peerName, out SafePeerData peerHostName);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static Int32 PeerHostNameToPeerName(string peerHostName, out SafePeerData peerName);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static Int32 PeerPnrpRegister(string pcwzPeerName,
ref PEER_PNRP_REGISTRATION_INFO registrationInfo,
out SafePeerNameUnregister handle);
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static Int32 PeerPnrpUnregister(IntPtr handle);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static Int32 PeerPnrpUpdateRegistration(SafePeerNameUnregister hRegistration,
ref PEER_PNRP_REGISTRATION_INFO registrationInfo);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static Int32 PeerPnrpResolve(string pcwzPeerNAme,
string pcwzCloudName,
ref UInt32 pcEndPoints,
out SafePeerData pEndPoints);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static Int32 PeerPnrpStartResolve(string pcwzPeerNAme,
string pcwzCloudName,
UInt32 cEndPoints,
SafeWaitHandle hEvent,
out SafePeerNameEndResolve safePeerNameEndResolve);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static Int32 PeerPnrpGetEndpoint(IntPtr Handle,
out SafePeerData pEndPoint);
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static Int32 PeerPnrpEndResolve(IntPtr Handle);
private static object s_InternalSyncObject;
private static volatile bool s_Initialized;
private const int PNRP_VERSION = 2;
private static object InternalSyncObject {
get {
if (s_InternalSyncObject == null) {
object o = new object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="PeerPnrpStartup(UInt16):Int32" />
// <SatisfiesLinkDemand Name="Marshal.GetExceptionForHR(System.Int32):System.Exception" />
// </SecurityKernel>
[System.Security.SecurityCritical]
internal static void PnrpStartup()
{
if (!s_Initialized) {
lock (InternalSyncObject) {
if (!s_Initialized) {
Int32 result = PeerPnrpStartup(PNRP_VERSION);
if (result != 0) {
throw new PeerToPeerException(SR.GetString(SR.Pnrp_StartupFailed), Marshal.GetExceptionForHR(result));
}
s_Initialized = true;
}
}
}
} //end of method PnrpStartup
}
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafePeerData : SafeHandleZeroOrMinusOneIsInvalid
{
private SafePeerData() : base(true) { }
//private SafePeerData(bool ownsHandle) : base(ownsHandle) { }
internal string UnicodeString
{
get
{
return Marshal.PtrToStringUni(handle);
}
}
protected override bool ReleaseHandle()
{
UnsafeP2PNativeMethods.PeerFreeData(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafePeerNameUnregister : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafePeerNameUnregister() : base(true) { }
//internal SafePeerNameUnregister(bool ownsHandle) : base(ownsHandle) { }
protected override bool ReleaseHandle()
{
UnsafeP2PNativeMethods.PeerPnrpUnregister(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafePeerNameEndResolve : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafePeerNameEndResolve() : base(true) { }
//internal SafePeerNameEndResolve(bool ownsHandle) : base(ownsHandle) { }
protected override bool ReleaseHandle()
{
UnsafeP2PNativeMethods.PeerPnrpEndResolve(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
/// <remarks>
/// Determines whether P2P is installed
/// Note static constructors are guaranteed to be
/// run in a thread safe manner. so no locks are necessary
/// </remarks>
internal static class PeerToPeerOSHelper
{
private const string OSInstallTypeRegKey = @"Software\Microsoft\Windows NT\CurrentVersion";
private const string OSInstallTypeRegKeyPath = @"HKEY_LOCAL_MACHINE\" + OSInstallTypeRegKey;
private const string OSInstallTypeRegName = "InstallationType";
private const string InstallTypeStringServerCore = "Server Core";
private static bool s_supportsP2P = false;
private static SafeLoadLibrary s_P2PLibrary = null;
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeSystemNativeMethods.GetProcAddress(System.Net.SafeLoadLibrary,System.String):System.IntPtr" />
// <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" />
// <ReferencesCritical Name="Field: s_P2PLibrary" Ring="1" />
// <ReferencesCritical Name="Method: SafeLoadLibrary.LoadLibraryEx(System.String):System.Net.SafeLoadLibrary" Ring="1" />
// </SecurityKernel>
[System.Security.SecurityCritical]
static PeerToPeerOSHelper() {
if (IsSupportedOS()) {
// if OS is supported, but p2p.dll is not available, P2P is not supported (original behavior)
string dllFileName = Path.Combine(Environment.SystemDirectory, UnsafeP2PNativeMethods.P2P);
s_P2PLibrary = SafeLoadLibrary.LoadLibraryEx(dllFileName);
if (!s_P2PLibrary.IsInvalid) {
IntPtr Address = UnsafeSystemNativeMethods.GetProcAddress(s_P2PLibrary, "PeerCreatePeerName");
if (Address != IntPtr.Zero) {
s_supportsP2P = true;
}
}
}
//else --> the SafeLoadLibrary would have already been marked
// closed by the LoadLibraryEx call above.
}
[SecurityCritical]
private static bool IsSupportedOS()
{
// extend this method when adding further OS/install type restrictions
// P2P is not supported on Server Core installation type
if (IsServerCore()) {
return false;
}
return true;
}
[SecurityCritical]
[RegistryPermission(SecurityAction.Assert, Read = OSInstallTypeRegKeyPath)]
private static bool IsServerCore()
{
// This code does the same as System.Net.ComNetOS.GetWindowsInstallType(). Since ComNetOS is internal and
// we don't want to add InternalsVisibleToAttribute to System.dll, we have to duplicate the code.
try {
using (RegistryKey installTypeKey = Registry.LocalMachine.OpenSubKey(OSInstallTypeRegKey)) {
string installType = installTypeKey.GetValue(OSInstallTypeRegName) as string;
if (string.IsNullOrEmpty(installType)) {
Logging.P2PTraceSource.TraceEvent(TraceEventType.Warning, 0,
SR.GetString(SR.P2P_empty_osinstalltype, OSInstallTypeRegKey + "\\" + OSInstallTypeRegName));
}
else {
if (String.Compare(installType, InstallTypeStringServerCore, StringComparison.OrdinalIgnoreCase) == 0) {
return true;
}
}
}
}
catch (UnauthorizedAccessException e) {
Logging.P2PTraceSource.TraceEvent(TraceEventType.Warning, 0,
SR.GetString(SR.P2P_cant_determine_osinstalltype, OSInstallTypeRegKey, e.Message));
}
catch (SecurityException e) {
Logging.P2PTraceSource.TraceEvent(TraceEventType.Warning, 0,
SR.GetString(SR.P2P_cant_determine_osinstalltype, OSInstallTypeRegKey, e.Message));
}
return false;
}
internal static bool SupportsP2P {
get {
return s_supportsP2P;
}
}
internal static IntPtr P2PModuleHandle
{
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandle.get_IsClosed():System.Boolean" />
// <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" />
// <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" />
// <ReferencesCritical Name="Field: s_P2PLibrary" Ring="1" />
// </SecurityKernel>
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, UnmanagedCode=true)]
get
{
if (!s_P2PLibrary.IsClosed && !s_P2PLibrary.IsInvalid)
return s_P2PLibrary.DangerousGetHandle();
return IntPtr.Zero;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
namespace GSoft.Dynamite.Caml
{
/// <summary>
/// CAML builder interface.
/// </summary>
public interface ICamlBuilder
{
/// <summary>
/// Creates CAML and with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "And", Justification = "We mean to format a CAML AND statement. 'And' is the proper method name.")]
string And(string leftCondition, string rightCondition);
/// <summary>
/// Creates CAML begins with with the specified field reference and value.
/// </summary>
/// <param name="fieldRefElement">The field reference element.</param>
/// <param name="valueElement">The value element.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string BeginsWith(string fieldRefElement, string valueElement);
/// <summary>
/// Creates CAML contains with the specified field reference and value.
/// </summary>
/// <param name="fieldRefElement">The field reference element.</param>
/// <param name="valueElement">The value element.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Contains(string fieldRefElement, string valueElement);
/// <summary>
/// Creates CAML date ranges overlap with the specified field reference and value.
/// </summary>
/// <param name="fieldRefElement">The field reference element.</param>
/// <param name="valueElement">The value element.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string DateRangesOverlap(string fieldRefElement, string valueElement);
/// <summary>
/// Creates CAML equal with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Equal(string leftCondition, string rightCondition);
/// <summary>
/// Creates CAML field reference with the specified field name.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string FieldRef(string fieldName);
/// <summary>
/// Creates CAML field reference with the specified field name.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="sortType">Type of the sort.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string FieldRef(string fieldName, CamlEnums.SortType sortType);
/// <summary>
/// Creates CAML greater than or equal with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string GreaterThanOrEqual(string leftCondition, string rightCondition);
/// <summary>
/// Creates CAML group by with the specified field reference.
/// </summary>
/// <param name="fieldRefElement">The field reference element.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string GroupBy(string fieldRefElement);
/// <summary>
/// Creates CAML group by with the specified field reference.
/// </summary>
/// <param name="fieldRefElement">The field reference element.</param>
/// <param name="collapse">if set to <c>true</c> [collapse].</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string GroupBy(string fieldRefElement, bool collapse);
/// <summary>
/// Creates CAML greater than with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string GreaterThan(string leftCondition, string rightCondition);
/// <summary>
/// Creates a CAML query to determine whether [is content type] [the specified content type identifier].
/// </summary>
/// <param name="contentTypeId">The content type identifier.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string IsContentType(SPContentTypeId contentTypeId);
/// <summary>
/// Creates a CAML query to determine whether [is or inherits content type] [the specified content type identifier].
/// </summary>
/// <param name="contentTypeId">The content type identifier.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string IsOrInheritsContentType(SPContentTypeId contentTypeId);
/// <summary>
/// Creates CAML is null by with the specified field reference.
/// </summary>
/// <param name="fieldRefElement">The field reference element.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string IsNotNull(string fieldRefElement);
/// <summary>
/// Creates CAML is null by with the specified field reference.
/// </summary>
/// <param name="fieldRefElement">The field reference element.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string IsNull(string fieldRefElement);
/// <summary>
/// Creates CAML lesser than or equal by with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string LesserThanOrEqual(string leftCondition, string rightCondition);
/// <summary>
/// Creates CAML safe identifier by with the specified identifier value.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string SafeIdentifier(string identifier);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="listId">The list identifier.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string List(Guid listId);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="listElements">The list elements.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(string listElements);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="listElements">The list elements.</param>
/// <param name="includeHiddenLists">if set to <c>true</c> [include hidden lists].</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(string listElements, bool includeHiddenLists);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="listElements">The list elements.</param>
/// <param name="maxListLimit">The maximum list limit.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(string listElements, int maxListLimit);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="listElements">The list elements.</param>
/// <param name="serverTemplate">The server template.</param>
/// <param name="includeHiddenLists">if set to <c>true</c> [include hidden lists].</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(string listElements, string serverTemplate, bool includeHiddenLists);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="baseType">Type of the base.</param>
/// <param name="listElements">The list elements.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(CamlEnums.BaseType baseType, string listElements);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="baseType">Type of the base.</param>
/// <param name="listElements">The list elements.</param>
/// <param name="serverTemplate">The server template.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(CamlEnums.BaseType baseType, string listElements, string serverTemplate);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="baseType">Type of the base.</param>
/// <param name="listElements">The list elements.</param>
/// <param name="serverTemplate">The server template.</param>
/// <param name="includeHiddenLists">if set to <c>true</c> [include hidden lists].</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(CamlEnums.BaseType baseType, string listElements, string serverTemplate, bool includeHiddenLists);
/// <summary>
/// Creates CAML lists by with the specified arguments.
/// </summary>
/// <param name="baseType">Type of the base.</param>
/// <param name="listElements">The list elements.</param>
/// <param name="serverTemplate">The server template.</param>
/// <param name="includeHiddenLists">if set to <c>true</c> [include hidden lists].</param>
/// <param name="maxListLimit">The maximum list limit.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Lists(CamlEnums.BaseType baseType, string listElements, string serverTemplate, bool includeHiddenLists, int maxListLimit);
/// <summary>
/// Creates CAML with index than with the specified field ID and value.
/// </summary>
/// <param name="fieldId">The field identifier.</param>
/// <param name="fieldValue">The field value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string WithIndex(Guid fieldId, string fieldValue);
/// <summary>
/// Creates CAML lesser than by with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string LesserThan(string leftCondition, string rightCondition);
/// <summary>
/// Creates CAML membership by with the specified membership type and value.
/// </summary>
/// <param name="type">The membership type.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Membership(CamlEnums.MembershipType type);
/// <summary>
/// Creates CAML membership by with the specified membership type and value.
/// </summary>
/// <param name="type">The membership type.</param>
/// <param name="value">The value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Membership(CamlEnums.MembershipType type, string value);
/// <summary>
/// Creates CAML not equal by with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string NotEqual(string leftCondition, string rightCondition);
/// <summary>
/// Return the now CAML value.
/// </summary>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Now();
/// <summary>
/// Creates CAML or by with the specified left and right conditions.
/// </summary>
/// <param name="leftCondition">The left condition.</param>
/// <param name="rightCondition">The right condition.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Or", Justification = "We mean to format a CAML OR statement. 'Or' is the proper method name.")]
string Or(string leftCondition, string rightCondition);
/// <summary>
/// Creates CAML order by with the specified field references.
/// </summary>
/// <param name="fieldRefElements">The field reference elements.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string OrderBy(string fieldRefElements);
/// <summary>
/// Creates CAML order by with the specified arguments.
/// </summary>
/// <param name="arguments">The query arguments.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string OrderBy(params object[] arguments);
/// <summary>
/// Creates CAML value with the specified value.
/// </summary>
/// <param name="fieldValue">The field value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Value(string fieldValue);
/// <summary>
/// Creates CAML value with the specified value.
/// </summary>
/// <param name="fieldValue">The field value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Value(int fieldValue);
/// <summary>
/// Creates CAML value with the specified value.
/// </summary>
/// <param name="fieldValue">The field value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Value(DateTime fieldValue);
/// <summary>
/// Creates CAML value with the specified value.
/// </summary>
/// <param name="fieldValue">The field value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Value(bool fieldValue);
/// <summary>
/// Creates CAML value with the specified type and value.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <param name="fieldValue">The field value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Value(string valueType, string fieldValue);
/// <summary>
/// Creates CAML view fields with the specified fields.
/// </summary>
/// <param name="fields">The fields.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string ViewFields(params object[] fields);
/// <summary>
/// Creates CAML view fields with the specified entity type.
/// </summary>
/// <param name="entityType">Type of the entity.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string ViewFieldsForEntityType(Type entityType);
/// <summary>
/// Creates CAML webs with the specified scope.
/// </summary>
/// <param name="scope">The scope.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string Webs(CamlEnums.QueryScope scope);
/// <summary>
/// Creates CAML project property with the specified property name.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string ProjectProperty(string propertyName);
/// <summary>
/// Creates CAML project property with the specified property name and default value.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string ProjectProperty(string propertyName, string defaultValue);
/// <summary>
/// Creates CAML project property with the specified condition.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="autoHyperlinkType">Type of the automatic hyperlink.</param>
/// <param name="autoNewLine">if set to <c>true</c> [automatic new line].</param>
/// <param name="expandXml">if set to <c>true</c> [expand XML].</param>
/// <param name="htmlEncode">if set to <c>true</c> [HTML encode].</param>
/// <param name="stripWhiteSpace">if set to <c>true</c> [strip white space].</param>
/// <param name="urlEncodingType">Type of the URL encoding.</param>
/// <returns>
/// A string representation of the CAML query.
/// </returns>
string ProjectProperty(string propertyName, string defaultValue, CamlEnums.AutoHyperlinkType autoHyperlinkType, bool autoNewLine, bool expandXml, bool htmlEncode, bool stripWhiteSpace, CamlEnums.UrlEncodingType urlEncodingType);
/// <summary>
/// Creates CAML where with the specified condition.
/// </summary>
/// <param name="condition">The condition.</param>
/// <returns>A string representation of the CAML query.</returns>
string Where(string condition);
/// <summary>
/// Creates CAML XML with the specified condition.
/// </summary>
/// <param name="condition">The condition.</param>
/// <returns>A string representation of the CAML query.</returns>
string Xml(string condition);
/// <summary>
/// Generates a CAML filter for a Taxonomy Term
/// </summary>
/// <param name="list">The list over which the query will be done</param>
/// <param name="taxonomyFieldInternalName">The name of the site column associated with the term set</param>
/// <param name="term">Term to match for</param>
/// <param name="includeDescendants">Whether the Term's child terms should be query hits as well</param>
/// <returns>A string representation of the CAML query.</returns>
string TermFilter(SPList list, string taxonomyFieldInternalName, Term term, bool includeDescendants);
/// <summary>
/// Generates a CAML filter for a Taxonomy Term
/// </summary>
/// <param name="list">The list over which the query will be done</param>
/// <param name="taxonomyFieldInternalName">The name of the site column associated with the term set</param>
/// <param name="termId">Term identifier to match for</param>
/// <param name="includeDescendants">Whether the Term's child terms should be query hits as well</param>
/// <returns>A string representation of the CAML query.</returns>
string TermFilter(SPList list, string taxonomyFieldInternalName, Guid termId, bool includeDescendants);
/// <summary>
/// Generates a CAML filter for a Taxonomy Term
/// </summary>
/// <param name="list">The list over which the query will be done</param>
/// <param name="taxonomyFieldInternalName">The name of the site column associated with the term set</param>
/// <param name="terms">List of terms for why we want to match in an OR fashion</param>
/// <param name="includeDescendants">Whether the Term's child terms should be query hits as well</param>
/// <returns>A string representation of the CAML query.</returns>
string TermFilter(SPList list, string taxonomyFieldInternalName, IList<Term> terms, bool includeDescendants);
/// <summary>
/// Generates a CAML filter for a Taxonomy Term from the site-collection-reserved term store group
/// </summary>
/// <param name="list">The list over which the query will be done</param>
/// <param name="taxonomyFieldInternalName">The name of the site column associated with the term set</param>
/// <param name="termSetName">Name of the term set</param>
/// <param name="termLabel">Label by which to find the term (dupes not supported)</param>
/// <param name="includeDescendants">Whether the Term's child terms should be query hits as well</param>
/// <returns>A string representation of the CAML query.</returns>
string TermFilter(SPList list, string taxonomyFieldInternalName, string termSetName, string termLabel, bool includeDescendants);
/// <summary>
/// Generates a CAML filter for a Taxonomy Term in a global farm term store group
/// </summary>
/// <param name="list">The list over which the query will be done</param>
/// <param name="taxonomyFieldInternalName">The name of the site column associated with the term set</param>
/// <param name="termStoreGroupName">Name of the global farm term store group</param>
/// <param name="termSetName">Name of the term set</param>
/// <param name="termLabel">Label by which to find the term (dupes not supported)</param>
/// <param name="includeDescendants">Whether the Term's child terms should be query hits as well</param>
/// <returns>A string representation of the CAML query.</returns>
string TermFilter(SPList list, string taxonomyFieldInternalName, string termStoreGroupName, string termSetName, string termLabel, bool includeDescendants);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
namespace Python.Runtime
{
/// <summary>
/// Performs data conversions between managed types and Python types.
/// </summary>
[SuppressUnmanagedCodeSecurity]
internal class Converter
{
private Converter()
{
}
private static NumberFormatInfo nfi;
private static Type objectType;
private static Type stringType;
private static Type singleType;
private static Type doubleType;
private static Type decimalType;
private static Type int16Type;
private static Type int32Type;
private static Type int64Type;
private static Type flagsType;
private static Type boolType;
private static Type typeType;
static Converter()
{
nfi = NumberFormatInfo.InvariantInfo;
objectType = typeof(Object);
stringType = typeof(String);
int16Type = typeof(Int16);
int32Type = typeof(Int32);
int64Type = typeof(Int64);
singleType = typeof(Single);
doubleType = typeof(Double);
decimalType = typeof(Decimal);
flagsType = typeof(FlagsAttribute);
boolType = typeof(Boolean);
typeType = typeof(Type);
}
/// <summary>
/// Given a builtin Python type, return the corresponding CLR type.
/// </summary>
internal static Type GetTypeByAlias(IntPtr op)
{
if (op == Runtime.PyStringType)
return stringType;
if (op == Runtime.PyUnicodeType)
return stringType;
if (op == Runtime.PyIntType)
return int32Type;
if (op == Runtime.PyLongType)
return int64Type;
if (op == Runtime.PyFloatType)
return doubleType;
if (op == Runtime.PyBoolType)
return boolType;
return null;
}
internal static IntPtr GetPythonTypeByAlias(Type op)
{
if (op == stringType)
return Runtime.PyUnicodeType;
if (op == int16Type)
return Runtime.PyIntType;
if (op == int32Type)
return Runtime.PyIntType;
if (op == int64Type && Runtime.IsPython2)
return Runtime.PyLongType;
if (op == int64Type)
return Runtime.PyIntType;
if (op == doubleType)
return Runtime.PyFloatType;
if (op == singleType)
return Runtime.PyFloatType;
if (op == boolType)
return Runtime.PyBoolType;
return IntPtr.Zero;
}
/// <summary>
/// Return a Python object for the given native object, converting
/// basic types (string, int, etc.) into equivalent Python objects.
/// This always returns a new reference. Note that the System.Decimal
/// type has no Python equivalent and converts to a managed instance.
/// </summary>
internal static IntPtr ToPython<T>(T value)
{
return ToPython(value, typeof(T));
}
internal static IntPtr ToPython(object value, Type type)
{
if (value is PyObject)
{
IntPtr handle = ((PyObject)value).Handle;
Runtime.XIncref(handle);
return handle;
}
IntPtr result = IntPtr.Zero;
// Null always converts to None in Python.
if (value == null)
{
result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
if (value is IList && value.GetType().IsGenericType)
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
// it the type is a python subclass of a managed type then return the
// underlying python object rather than construct a new wrapper object.
var pyderived = value as IPythonDerivedType;
if (null != pyderived)
{
return ClassDerivedObject.ToPython(pyderived);
}
// hmm - from Python, we almost never care what the declared
// type is. we'd rather have the object bound to the actual
// implementing class.
type = value.GetType();
TypeCode tc = Type.GetTypeCode(type);
switch (tc)
{
case TypeCode.Object:
return CLRObject.GetInstHandle(value, type);
case TypeCode.String:
return Runtime.PyUnicode_FromString((string)value);
case TypeCode.Int32:
return Runtime.PyInt_FromInt32((int)value);
case TypeCode.Boolean:
if ((bool)value)
{
Runtime.XIncref(Runtime.PyTrue);
return Runtime.PyTrue;
}
Runtime.XIncref(Runtime.PyFalse);
return Runtime.PyFalse;
case TypeCode.Byte:
return Runtime.PyInt_FromInt32((int)((byte)value));
case TypeCode.Char:
return Runtime.PyUnicode_FromOrdinal((int)((char)value));
case TypeCode.Int16:
return Runtime.PyInt_FromInt32((int)((short)value));
case TypeCode.Int64:
return Runtime.PyLong_FromLongLong((long)value);
case TypeCode.Single:
// return Runtime.PyFloat_FromDouble((double)((float)value));
string ss = ((float)value).ToString(nfi);
IntPtr ps = Runtime.PyString_FromString(ss);
IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
Runtime.XDecref(ps);
return op;
case TypeCode.Double:
return Runtime.PyFloat_FromDouble((double)value);
case TypeCode.SByte:
return Runtime.PyInt_FromInt32((int)((sbyte)value));
case TypeCode.UInt16:
return Runtime.PyInt_FromInt32((int)((ushort)value));
case TypeCode.UInt32:
return Runtime.PyLong_FromUnsignedLong((uint)value);
case TypeCode.UInt64:
return Runtime.PyLong_FromUnsignedLongLong((ulong)value);
default:
if (value is IEnumerable)
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
result = CLRObject.GetInstHandle(value, type);
return result;
}
}
/// <summary>
/// In a few situations, we don't have any advisory type information
/// when we want to convert an object to Python.
/// </summary>
internal static IntPtr ToPythonImplicit(object value)
{
if (value == null)
{
IntPtr result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
return ToPython(value, objectType);
}
/// <summary>
/// Return a managed object for the given Python object, taking funny
/// byref types into account.
/// </summary>
internal static bool ToManaged(IntPtr value, Type type,
out object result, bool setError)
{
if (type.IsByRef)
{
type = type.GetElementType();
}
return Converter.ToManagedValue(value, type, out result, setError);
}
internal static bool ToManagedValue(IntPtr value, Type obType,
out object result, bool setError)
{
if (obType == typeof(PyObject))
{
Runtime.XIncref(value); // PyObject() assumes ownership
result = new PyObject(value);
return true;
}
// Common case: if the Python value is a wrapped managed object
// instance, just return the wrapped object.
ManagedType mt = ManagedType.GetManagedObject(value);
result = null;
if (mt != null)
{
if (mt is CLRObject)
{
object tmp = ((CLRObject)mt).inst;
if (obType.IsInstanceOfType(tmp))
{
result = tmp;
return true;
}
Exceptions.SetError(Exceptions.TypeError, $"value cannot be converted to {obType}");
return false;
}
if (mt is ClassBase)
{
result = ((ClassBase)mt).type;
return true;
}
// shouldn't happen
return false;
}
if (value == Runtime.PyNone && !obType.IsValueType)
{
result = null;
return true;
}
if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if( value == Runtime.PyNone )
{
result = null;
return true;
}
// Set type to underlying type
obType = obType.GetGenericArguments()[0];
}
if (obType.IsArray)
{
return ToArray(value, obType, out result, setError);
}
if (obType.IsEnum)
{
return ToEnum(value, obType, out result, setError);
}
// Conversion to 'Object' is done based on some reasonable default
// conversions (Python string -> managed string, Python int -> Int32 etc.).
if (obType == objectType)
{
if (Runtime.IsStringType(value))
{
return ToPrimitive(value, stringType, out result, setError);
}
if (Runtime.PyBool_Check(value))
{
return ToPrimitive(value, boolType, out result, setError);
}
if (Runtime.PyInt_Check(value))
{
return ToPrimitive(value, int32Type, out result, setError);
}
if (Runtime.PyLong_Check(value))
{
return ToPrimitive(value, int64Type, out result, setError);
}
if (Runtime.PyFloat_Check(value))
{
return ToPrimitive(value, doubleType, out result, setError);
}
if (Runtime.PySequence_Check(value))
{
return ToArray(value, typeof(object[]), out result, setError);
}
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Object");
}
return false;
}
// Conversion to 'Type' is done using the same mappings as above for objects.
if (obType == typeType)
{
if (value == Runtime.PyStringType)
{
result = stringType;
return true;
}
if (value == Runtime.PyBoolType)
{
result = boolType;
return true;
}
if (value == Runtime.PyIntType)
{
result = int32Type;
return true;
}
if (value == Runtime.PyLongType)
{
result = int64Type;
return true;
}
if (value == Runtime.PyFloatType)
{
result = doubleType;
return true;
}
if (value == Runtime.PyListType || value == Runtime.PyTupleType)
{
result = typeof(object[]);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type");
}
return false;
}
return ToPrimitive(value, obType, out result, setError);
}
/// <summary>
/// Convert a Python value to an instance of a primitive managed type.
/// </summary>
private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError)
{
IntPtr overflow = Exceptions.OverflowError;
TypeCode tc = Type.GetTypeCode(obType);
result = null;
IntPtr op;
int ival;
switch (tc)
{
case TypeCode.String:
string st = Runtime.GetManagedString(value);
if (st == null)
{
goto type_error;
}
result = st;
return true;
case TypeCode.Int32:
// Trickery to support 64-bit platforms.
if (Runtime.IsPython2 && Runtime.Is32Bit)
{
op = Runtime.PyNumber_Int(value);
// As of Python 2.3, large ints magically convert :(
if (Runtime.PyLong_Check(op))
{
Runtime.XDecref(op);
goto overflow;
}
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
result = ival;
return true;
}
else // Python3 always use PyLong API
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
Exceptions.Clear();
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
long ll = (long)Runtime.PyLong_AsLongLong(op);
Runtime.XDecref(op);
if (ll == -1 && Exceptions.ErrorOccurred())
{
goto overflow;
}
if (ll > Int32.MaxValue || ll < Int32.MinValue)
{
goto overflow;
}
result = (int)ll;
return true;
}
case TypeCode.Boolean:
result = Runtime.PyObject_IsTrue(value) != 0;
return true;
case TypeCode.Byte:
#if PYTHON3
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#elif PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
{
op = Runtime.PyString_AsString(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#endif
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > Byte.MaxValue || ival < Byte.MinValue)
{
goto overflow;
}
byte b = (byte)ival;
result = b;
return true;
case TypeCode.SByte:
#if PYTHON3
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#elif PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
{
op = Runtime.PyString_AsString(value);
result = (sbyte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#endif
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > SByte.MaxValue || ival < SByte.MinValue)
{
goto overflow;
}
sbyte sb = (sbyte)ival;
result = sb;
return true;
case TypeCode.Char:
#if PYTHON3
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#elif PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
{
op = Runtime.PyString_AsString(value);
result = (char)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#endif
else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType))
{
if (Runtime.PyUnicode_GetSize(value) == 1)
{
op = Runtime.PyUnicode_AsUnicode(value);
Char[] buff = new Char[1];
Marshal.Copy(op, buff, 0, 1);
result = buff[0];
return true;
}
goto type_error;
}
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
goto type_error;
}
ival = Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > Char.MaxValue || ival < Char.MinValue)
{
goto overflow;
}
result = (char)ival;
return true;
case TypeCode.Int16:
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > Int16.MaxValue || ival < Int16.MinValue)
{
goto overflow;
}
short s = (short)ival;
result = s;
return true;
case TypeCode.Int64:
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
long l = (long)Runtime.PyLong_AsLongLong(op);
Runtime.XDecref(op);
if ((l == -1) && Exceptions.ErrorOccurred())
{
goto overflow;
}
result = l;
return true;
case TypeCode.UInt16:
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > UInt16.MaxValue || ival < UInt16.MinValue)
{
goto overflow;
}
ushort us = (ushort)ival;
result = us;
return true;
case TypeCode.UInt32:
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
uint ui = (uint)Runtime.PyLong_AsUnsignedLong(op);
if (Exceptions.ErrorOccurred())
{
Runtime.XDecref(op);
goto overflow;
}
IntPtr check = Runtime.PyLong_FromUnsignedLong(ui);
int err = Runtime.PyObject_Compare(check, op);
Runtime.XDecref(check);
Runtime.XDecref(op);
if (0 != err || Exceptions.ErrorOccurred())
{
goto overflow;
}
result = ui;
return true;
case TypeCode.UInt64:
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ulong ul = (ulong)Runtime.PyLong_AsUnsignedLongLong(op);
Runtime.XDecref(op);
if (Exceptions.ErrorOccurred())
{
goto overflow;
}
result = ul;
return true;
case TypeCode.Single:
op = Runtime.PyNumber_Float(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
double dd = Runtime.PyFloat_AsDouble(op);
Runtime.CheckExceptionOccurred();
Runtime.XDecref(op);
if (dd > Single.MaxValue || dd < Single.MinValue)
{
if (!double.IsInfinity(dd))
{
goto overflow;
}
}
result = (float)dd;
return true;
case TypeCode.Double:
op = Runtime.PyNumber_Float(value);
if (op == IntPtr.Zero)
{
goto type_error;
}
double d = Runtime.PyFloat_AsDouble(op);
Runtime.CheckExceptionOccurred();
Runtime.XDecref(op);
result = d;
return true;
}
type_error:
if (setError)
{
string tpName = Runtime.PyObject_GetTypeName(value);
Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}");
}
return false;
overflow:
if (setError)
{
Exceptions.SetError(Exceptions.OverflowError, "value too large to convert");
}
return false;
}
private static void SetConversionError(IntPtr value, Type target)
{
IntPtr ob = Runtime.PyObject_Repr(value);
string src = Runtime.GetManagedString(ob);
Runtime.XDecref(ob);
Exceptions.SetError(Exceptions.TypeError, $"Cannot convert {src} to {target}");
}
/// <summary>
/// Convert a Python value to a correctly typed managed array instance.
/// The Python value must support the Python sequence protocol and the
/// items in the sequence must be convertible to the target array type.
/// </summary>
private static bool ToArray(IntPtr value, Type obType, out object result, bool setError)
{
Type elementType = obType.GetElementType();
int size = Runtime.PySequence_Size(value);
result = null;
if (size < 0)
{
if (setError)
{
SetConversionError(value, obType);
}
return false;
}
Array items = Array.CreateInstance(elementType, size);
// XXX - is there a better way to unwrap this if it is a real array?
for (var i = 0; i < size; i++)
{
object obj = null;
IntPtr item = Runtime.PySequence_GetItem(value, i);
if (item == IntPtr.Zero)
{
if (setError)
{
SetConversionError(value, obType);
return false;
}
}
if (!Converter.ToManaged(item, elementType, out obj, true))
{
Runtime.XDecref(item);
return false;
}
items.SetValue(obj, i);
Runtime.XDecref(item);
}
result = items;
return true;
}
/// <summary>
/// Convert a Python value to a correctly typed managed enum instance.
/// </summary>
private static bool ToEnum(IntPtr value, Type obType, out object result, bool setError)
{
Type etype = Enum.GetUnderlyingType(obType);
result = null;
if (!ToPrimitive(value, etype, out result, setError))
{
return false;
}
if (Enum.IsDefined(obType, result))
{
result = Enum.ToObject(obType, result);
return true;
}
if (obType.GetCustomAttributes(flagsType, true).Length > 0)
{
result = Enum.ToObject(obType, result);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.ValueError, "invalid enumeration value");
}
return false;
}
}
public static class ConverterExtension
{
public static PyObject ToPython(this object o)
{
return new PyObject(Converter.ToPython(o, o?.GetType()));
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FullNameControlTemplate.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web.UI.WebControls;
using Adxstudio.Xrm.Web.UI.WebForms;
using Adxstudio.Xrm.Globalization;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
/// <summary>
/// Fullname control
/// </summary>
/// <seealso cref="Adxstudio.Xrm.Web.UI.CrmEntityFormView.CellTemplate" />
/// <seealso cref="Adxstudio.Xrm.Web.UI.CrmEntityFormView.ICustomFieldControlTemplate" />
public class FullNameControlTemplate : CellTemplate, ICustomFieldControlTemplate
{
/// <summary>
/// The first name
/// </summary>
private const string FirstName = "firstname";
/// <summary>
/// The last name
/// </summary>
private const string LastName = "lastname";
/// <summary>
/// The entity metadata
/// </summary>
private readonly EntityMetadata entityMetadata;
/// <summary>
/// The is editable
/// </summary>
private bool isEditable;
/// <summary>
/// Initializes a new instance of the <see cref="FullNameControlTemplate"/> class.
/// </summary>
/// <param name="field">The field.</param>
/// <param name="metadata">The metadata.</param>
/// <param name="validationGroup">The validation group.</param>
/// <param name="bindings">The bindings.</param>
/// <param name="entityMetadata">The entity metadata.</param>
/// <param name="mode">The mode.</param>
public FullNameControlTemplate(
CrmEntityFormViewField field,
FormXmlCellMetadata metadata,
string validationGroup,
IDictionary<string, CellBinding> bindings,
EntityMetadata entityMetadata,
FormViewMode? mode)
: base(metadata, validationGroup, bindings)
{
this.Field = field;
this.isEditable = (mode == FormViewMode.ReadOnly) ? false : true;
this.entityMetadata = entityMetadata;
}
/// <summary>
/// CSS Class name assigned.
/// </summary>
public override string CssClass
{
get
{
return "text form-control";
}
}
/// <summary>
/// Gets the field.
/// </summary>
/// <value>
/// The field.
/// </value>
public CrmEntityFormViewField Field { get; private set; }
/// <summary>
/// Gets the validation text.
/// </summary>
/// <value>
/// The validation text.
/// </value>
private string ValidationText
{
get
{
return this.Metadata.ValidationText;
}
}
/// <summary>
/// Gets the validator display.
/// </summary>
/// <value>
/// The validator display.
/// </value>
private ValidatorDisplay ValidatorDisplay
{
get
{
return string.IsNullOrWhiteSpace(this.ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic;
}
}
/// <summary>
/// Instantiates the control in.
/// </summary>
/// <param name="container">The container.</param>
protected override void InstantiateControlIn(Control container)
{
var contentId = Guid.NewGuid();
if (this.Metadata.ReadOnly)
{
this.isEditable = false;
}
var textboxFullname = new TextBox
{
ID = this.ControlID,
CssClass = string.Join(" ", "trigger", this.CssClass, this.Metadata.CssClass, "fullNameCompositeControl"),
ToolTip = this.Metadata.ToolTip
};
textboxFullname.Attributes.Add("data-composite-control", string.Empty);
textboxFullname.Attributes.Add("data-content-id", contentId.ToString());
textboxFullname.Attributes.Add("data-editable", this.isEditable.ToString());
switch (CultureInfo.CurrentUICulture.LCID)
{
case LocaleIds.Japanese:
case LocaleIds.Hebrew:
textboxFullname.Attributes.Add("data-content-template", "{fullnamelastname} {fullnamefirstname}");
break;
default:
textboxFullname.Attributes.Add("data-content-template", "{fullnamefirstname} {fullnamelastname}");
break;
}
var firstNameAttribute = this.entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == FirstName);
var lastNameAttribute = this.entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == LastName);
// Creating container for all popover elements
var divContainer = new HtmlGenericControl("div");
divContainer.Attributes["class"] = "content hide fullNameCompositeControlContainer";
divContainer.ID = contentId.ToString();
var labelFirstname = new Label
{
ID = "FirstNameLabel",
Text = this.GetLocalizedLabel(firstNameAttribute, "First_Name_DefaultText"),
CssClass = "content "
};
var labelLastname = new Label
{
ID = "LastNameLabel",
Text = this.GetLocalizedLabel(lastNameAttribute, "Last_Name_DefaultText"),
CssClass = "content "
};
container.Controls.Add(textboxFullname);
// Creating textboxes for First ans Last name respectfully to localization
if (Localization.IsWesternType())
{
this.Generatefield(FirstName, firstNameAttribute, divContainer, labelFirstname);
this.Generatefield(LastName, lastNameAttribute, divContainer, labelLastname);
}
else
{
this.Generatefield(LastName, lastNameAttribute, divContainer, labelLastname);
this.Generatefield(FirstName, firstNameAttribute, divContainer, labelFirstname);
}
var buttonFullname = new HtmlGenericControl("input");
buttonFullname.Attributes["class"] = "btn btn-primary btn-block";
buttonFullname.Attributes["readonly"] = "true";
buttonFullname.Attributes["role"] = "button";
buttonFullname.ID = "fullNameUpdateButton";
buttonFullname.Attributes.Add("value", ResourceManager.GetString("Composite_Control_Done"));
textboxFullname.Attributes.Add("onchange", "setIsDirty(this.id);");
if (this.Metadata.MaxLength > 0)
{
textboxFullname.MaxLength = this.Metadata.MaxLength;
}
if (this.Metadata.IsRequired || this.Metadata.WebFormForceFieldIsRequired)
{
textboxFullname.Attributes.Add("required", string.Empty);
}
if (this.isEditable)
{
textboxFullname.Attributes.Add("aria-label", string.Format("{0}*. {1}", this.Metadata.Label, ResourceManager.GetString("Narrator_Label_For_Composite_Controls")));
divContainer.Controls.Add(buttonFullname);
container.Controls.Add(divContainer);
}
else
{
textboxFullname.CssClass = textboxFullname.CssClass += " readonly";
}
this.Bindings["fullname_fullname"] = new CellBinding
{
Get = () =>
{
var str = textboxFullname.Text;
return str != null ? str.Replace("\r\n", "\n") : string.Empty;
},
Set = obj =>
{
var entity = obj as Entity;
if (entity != null)
{
textboxFullname.Text = Localization.LocalizeFullName(
entity.GetAttributeValue<string>(FirstName),
entity.GetAttributeValue<string>(LastName));
}
}
};
}
/// <summary>
/// Instantiates the validators in.
/// </summary>
/// <param name="container">The container.</param>
protected override void InstantiateValidatorsIn(Control container)
{
if (this.Metadata.IsRequired || this.Metadata.WebFormForceFieldIsRequired || this.Metadata.IsFullNameControl)
{
container.Controls.Add(this.ConfigureFieldValidator(this.ControlID, this.Metadata.Label));
}
if (this.IsAttributeNeedRequiredValidation(this.entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == LastName)))
{
container.Controls.Add(this.ConfigureFieldValidator(this.ControlID + LastName, this.GetLocalizedLabel(LastName)));
}
if (this.IsAttributeNeedRequiredValidation(this.entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == FirstName)))
{
container.Controls.Add(this.ConfigureFieldValidator(this.ControlID + FirstName, this.GetLocalizedLabel(FirstName)));
}
this.InstantiateCustomValidatorsIn(container);
}
/// <summary>
/// Check if field need required validation based on attribute metadata
/// </summary>
/// <param name="attributeMetadata">attribute metadata</param>
/// <returns>Returns true if control is editable and attribute is required</returns>
private bool IsAttributeNeedRequiredValidation(AttributeMetadata attributeMetadata)
{
return attributeMetadata != null && this.isEditable &&
(attributeMetadata.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired ||
attributeMetadata.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired);
}
/// <summary>
/// Configures the field validator.
/// </summary>
/// <param name="controlId">The control identifier.</param>
/// <param name="localizedLabel">The localized label.</param>
/// <returns>Field validator for Full Name control and it's required fields</returns>
private RequiredFieldValidator ConfigureFieldValidator(string controlId, string localizedLabel)
{
return new RequiredFieldValidator
{
ID = string.Format("RequiredFieldValidator{0}", controlId),
ControlToValidate = controlId,
ValidationGroup = this.ValidationGroup,
Display = this.ValidatorDisplay,
ErrorMessage =
this.ValidationSummaryMarkup(
string.IsNullOrWhiteSpace(this.Metadata.RequiredFieldValidationErrorMessage)
? (this.Metadata.Messages == null || !this.Metadata.Messages.ContainsKey("Required"))
? ResourceManager.GetString("Required_Field_Error").FormatWith(localizedLabel)
: this.Metadata.Messages["Required"].FormatWith(this.Metadata.Label)
: this.Metadata.RequiredFieldValidationErrorMessage),
Text = this.Metadata.ValidationText
};
}
/// <summary>
/// Generatefields the specified field name.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="fieldMetaData">The field meta data.</param>
/// <param name="divContainer">The div container.</param>
/// <param name="labelFirstname">The label firstname.</param>
private void Generatefield(
string fieldName,
AttributeMetadata fieldMetaData,
HtmlGenericControl divContainer,
Label labelFirstname)
{
var textBox = new TextBox
{
ID = this.ControlID + fieldName,
CssClass = string.Join(" content ", " ", this.CssClass, this.Metadata.CssClass),
ToolTip = this.Metadata.ToolTip
};
labelFirstname.AssociatedControlID = textBox.ID;
if (this.isEditable)
{
// Applying required parameters to first name if it's application required
if (fieldMetaData != null
&& (fieldMetaData.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired
|| fieldMetaData.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired))
{
textBox.Attributes.Add("required", string.Empty);
var requierdContainer = new HtmlGenericControl("div");
requierdContainer.Attributes["class"] = "info required";
requierdContainer.Controls.Add(labelFirstname);
divContainer.Controls.Add(requierdContainer);
}
else
{
divContainer.Controls.Add(labelFirstname);
}
divContainer.Controls.Add(textBox);
}
textBox.Attributes.Add("onchange", "setIsDirty(this.id);");
this.Bindings["fullname_" + fieldName] = new CellBinding
{
Get = () =>
{
var str = textBox.Text;
return str != null ? str.Replace("\r\n", "\n") : string.Empty;
},
Set = obj =>
{
var entity = obj as Entity;
if (entity != null)
{
textBox.Text = entity.GetAttributeValue<string>(fieldName);
}
}
};
}
/// <summary>
/// Gets the localized label.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="resourceString">The resource string.</param>
/// <returns>Localized label string</returns>
private string GetLocalizedLabel(AttributeMetadata attribute, string resourceString)
{
var localizedLabel =
attribute.DisplayName.LocalizedLabels.FirstOrDefault(lcid => lcid.LanguageCode == CultureInfo.CurrentUICulture.LCID);
if (localizedLabel != null)
{
return localizedLabel.Label;
}
return ResourceManager.GetString(resourceString);
}
/// <summary>
/// Gets the localized label.
/// </summary>
/// <param name="logicalName">Name of the logical.</param>
/// <returns>Localized logical name</returns>
private string GetLocalizedLabel(string logicalName)
{
return this.entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == logicalName)
.DisplayName.UserLocalizedLabel.Label;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace LCAToolAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* Trimmed down version of SimpleJSON from Bunny83 tailored for the API use */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace GameJolt.External.SimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node;
private string m_Key;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
/* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */
using System;
using System.IO;
using System.Text;
namespace Razorvine.Pickle
{
/// <summary>
/// Utility stuff for dealing with pickle data streams.
/// </summary>
public class PickleUtils {
private Stream input;
/**
* Create a pickle utils instance and remember the given input stream.
*/
public PickleUtils(Stream stream) {
this.input = stream;
}
/**
* read a line of text, excluding the terminating LF char
*/
public string readline() {
return readline(false);
}
/**
* read a line of text, possibly including the terminating LF char
*/
public string readline(bool includeLF) {
StringBuilder sb = new StringBuilder();
while (true) {
int c = input.ReadByte();
if (c == -1) {
if (sb.Length == 0)
throw new IOException("premature end of file");
break;
}
if (c != '\n' || includeLF)
sb.Append((char) c);
if (c == '\n')
break;
}
return sb.ToString();
}
/**
* read a single unsigned byte
*/
public byte readbyte() {
int b = input.ReadByte();
if(b<0) {
throw new IOException("premature end of input stream");
}
return (byte)b;
}
/**
* read a number of signed bytes
*/
public byte[] readbytes(int n) {
byte[] buffer = new byte[n];
readbytes_into(buffer, 0, n);
return buffer;
}
/**
* read a number of signed bytes into the specified location in an existing byte array
*/
public void readbytes_into(byte[] buffer, int offset, int length) {
while (length > 0) {
int read = this.input.Read(buffer, offset, length);
if (read <= 0)
throw new IOException("read error; expected more bytes");
offset += read;
length -= read;
}
}
/**
* Convert a couple of bytes into the corresponding integer number.
* Can deal with 2-bytes unsigned int and 4-bytes signed int.
*/
public static int bytes_to_integer(byte[] bytes) {
return bytes_to_integer(bytes, 0, bytes.Length);
}
public static int bytes_to_integer(byte[] bytes, int offset, int size) {
// this operates on little-endian bytes
if (size == 2) {
// 2-bytes unsigned int
if(!BitConverter.IsLittleEndian) {
// need to byteswap because the converter needs big-endian...
byte[] bigendian=new byte[2] {bytes[1+offset], bytes[0+offset]};
return BitConverter.ToUInt16(bigendian, 0);
}
return BitConverter.ToUInt16(bytes,offset);
} else if (size == 4) {
// 4-bytes signed int
if(!BitConverter.IsLittleEndian) {
// need to byteswap because the converter needs big-endian...
byte[] bigendian=new byte[4] {bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]};
return BitConverter.ToInt32(bigendian, 0);
}
return BitConverter.ToInt32(bytes,offset);
} else
throw new PickleException("invalid amount of bytes to convert to int: " + size);
}
/**
* Convert 8 little endian bytes into a long
*/
public static long bytes_to_long(byte[] bytes, int offset) {
if(bytes.Length-offset<8)
throw new PickleException("too few bytes to convert to long");
if(BitConverter.IsLittleEndian) {
return BitConverter.ToInt64(bytes, offset);
}
// need to byteswap because the converter needs big-endian...
byte[] bigendian=new byte[8] {bytes[7+offset], bytes[6+offset], bytes[5+offset], bytes[4+offset], bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]};
return BitConverter.ToInt64(bigendian, 0);
}
/**
* Convert 4 little endian bytes into an unsigned int
*/
public static uint bytes_to_uint(byte[] bytes, int offset) {
if(bytes.Length-offset<4)
throw new PickleException("too few bytes to convert to long");
if(BitConverter.IsLittleEndian) {
return BitConverter.ToUInt32(bytes, offset);
}
// need to byteswap because the converter needs big-endian...
byte[] bigendian=new byte[4] {bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset]};
return BitConverter.ToUInt32(bigendian, 0);
}
/**
* Convert a signed integer to its 4-byte representation. (little endian)
*/
public byte[] integer_to_bytes(int i) {
byte[] bytes=BitConverter.GetBytes(i);
if(!BitConverter.IsLittleEndian) {
// reverse the bytes to make them little endian
Array.Reverse(bytes);
}
return bytes;
}
/**
* Convert a double to its 8-byte representation (big endian).
*/
public byte[] double_to_bytes(double d) {
byte[] bytes=BitConverter.GetBytes(d);
if(BitConverter.IsLittleEndian) {
// reverse the bytes to make them big endian for the output
Array.Reverse(bytes);
}
return bytes;
}
/**
* Convert a big endian 8-byte to a double.
*/
public static double bytes_to_double(byte[] bytes, int offset) {
if (bytes.Length-offset<8) {
throw new PickleException("decoding double: too few bytes");
}
if(BitConverter.IsLittleEndian) {
// reverse the bytes to make them littleendian for the bitconverter
byte[] littleendian=new byte[8] { bytes[7+offset], bytes[6+offset], bytes[5+offset], bytes[4+offset], bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset] };
return BitConverter.ToDouble(littleendian,0);
}
return BitConverter.ToDouble(bytes,offset);
}
/**
* Convert a big endian 4-byte to a float.
*/
public static float bytes_to_float(byte[] bytes, int offset) {
if (bytes.Length-offset<4) {
throw new PickleException("decoding float: too few bytes");
}
if(BitConverter.IsLittleEndian) {
// reverse the bytes to make them littleendian for the bitconverter
byte[] littleendian=new byte[4] { bytes[3+offset], bytes[2+offset], bytes[1+offset], bytes[0+offset] };
return BitConverter.ToSingle(littleendian,0);
}
return BitConverter.ToSingle(bytes,offset);
}
/**
* read an arbitrary 'long' number.
* because c# doesn't have a bigint, we look if stuff fits into a regular long,
* and raise an exception if it's bigger.
*/
public long decode_long(byte[] data) {
if (data.Length == 0)
return 0L;
if (data.Length>8)
throw new PickleException("value to large for long, biginteger needed");
if( data.Length<8) {
// bitconverter requires exactly 8 bytes so we need to extend it
byte[] larger=new byte[8];
Array.Copy(data,larger,data.Length);
// check if we need to sign-extend (if the original number was negative)
if((data[data.Length-1]&0x80) == 0x80) {
for(int i=data.Length; i<8; ++i) {
larger[i]=0xff;
}
}
data=larger;
}
if(!BitConverter.IsLittleEndian) {
// reverse the byte array because pickle stores it little-endian
Array.Reverse(data);
}
return BitConverter.ToInt64(data,0);
}
/**
* Construct a string from the given bytes where these are directly
* converted to the corresponding chars, without using a given character
* encoding
*/
public static string rawStringFromBytes(byte[] data) {
StringBuilder str = new StringBuilder(data.Length);
foreach (byte b in data) {
str.Append((char)b);
}
return str.ToString();
}
/**
* Convert a string to a byte array, no encoding is used. String must only contain characters <256.
*/
public static byte[] str2bytes(string str) {
byte[] b=new byte[str.Length];
for(int i=0; i<str.Length; ++i) {
char c=str[i];
if(c>255) throw new ArgumentException("string contained a char > 255, cannot convert to bytes");
b[i]=(byte)c;
}
return b;
}
/**
* Decode a string with possible escaped char sequences in it (\x??).
*/
public string decode_escaped(string str) {
if(str.IndexOf('\\')==-1)
return str;
StringBuilder sb=new StringBuilder(str.Length);
for(int i=0; i<str.Length; ++i) {
char c=str[i];
if(c=='\\') {
// possible escape sequence
char c2=str[++i];
switch(c2) {
case '\\':
// double-escaped '\\'--> '\'
sb.Append(c);
break;
case 'x':
// hex escaped "\x??"
char h1=str[++i];
char h2=str[++i];
c2=(char)Convert.ToInt32(""+h1+h2, 16);
sb.Append(c2);
break;
default:
throw new PickleException("invalid escape sequence in string");
}
} else {
sb.Append(str[i]);
}
}
return sb.ToString();
}
/**
* Decode a string with possible escaped unicode in it (\u20ac)
*/
public string decode_unicode_escaped(string str) {
if(str.IndexOf('\\')==-1)
return str;
StringBuilder sb=new StringBuilder(str.Length);
for(int i=0; i<str.Length; ++i) {
char c=str[i];
if(c=='\\') {
// possible escape sequence
char c2=str[++i];
switch(c2) {
case '\\':
// double-escaped '\\'--> '\'
sb.Append(c);
break;
case 'u':
// hex escaped unicode "\u20ac"
char h1=str[++i];
char h2=str[++i];
char h3=str[++i];
char h4=str[++i];
c2=(char)Convert.ToInt32(""+h1+h2+h3+h4, 16);
sb.Append(c2);
break;
default:
throw new PickleException("invalid escape sequence in string");
}
} else {
sb.Append(str[i]);
}
}
return sb.ToString();
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Baseline;
using Baseline.Dates;
using Jasper;
using Jasper.ErrorHandling;
using Jasper.Persistence;
using Jasper.Serialization;
using Jasper.Tracking;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Shouldly;
using TestingSupport.ErrorHandling;
using TestMessages;
using Xunit;
namespace TestingSupport.Compliance
{
public abstract class SendingComplianceFixture : IDisposable
{
public IHost Sender { get; private set; }
public IHost Receiver { get; private set; }
public Uri OutboundAddress { get; protected set; }
public readonly TimeSpan DefaultTimeout = 5.Seconds();
protected SendingComplianceFixture(Uri destination, int defaultTimeInSeconds = 5)
{
OutboundAddress = destination;
DefaultTimeout = defaultTimeInSeconds.Seconds();
}
protected Task SenderIs<T>() where T : JasperOptions, new()
{
Sender = JasperHost.For<T>(configureSender);
return Sender.RebuildMessageStorage();
}
protected Task TheOnlyAppIs<T>() where T : JasperOptions, new()
{
AllLocally = true;
var options = new T();
configureReceiver(options);
configureSender(options);
Sender = JasperHost.For(options);
return Sender.RebuildMessageStorage();
}
public bool AllLocally { get; set; }
protected Task SenderIs(JasperOptions options)
{
configureSender(options);
Sender = JasperHost.For(options);
return Sender.RebuildMessageStorage();
}
private void configureSender<T>(T options) where T : JasperOptions, new()
{
options.Handlers
.DisableConventionalDiscovery()
.IncludeType<PongHandler>();
options.Serializers.Add(new GreenTextWriter());
options.Extensions.UseMessageTrackingTestingSupport();
options.ServiceName = "SenderService";
options.Endpoints.PublishAllMessages().To(OutboundAddress);
options.Services.AddSingleton<IMessageSerializer, GreenTextWriter>();
}
public Task ReceiverIs<T>() where T : JasperOptions, new()
{
Receiver = JasperHost.For<T>(configureReceiver);
return Receiver.RebuildMessageStorage();
}
public Task ReceiverIs(JasperOptions options)
{
configureReceiver(options);
Receiver = JasperHost.For(options);
return Receiver.RebuildMessageStorage();
}
private static void configureReceiver<T>(T options) where T : JasperOptions, new()
{
options.Handlers.Retries.MaximumAttempts = 3;
options.Handlers
.DisableConventionalDiscovery()
.IncludeType<MessageConsumer>()
.IncludeType<ExecutedMessageGuy>()
.IncludeType<ColorHandler>()
.IncludeType<ErrorCausingMessageHandler>()
.IncludeType<BlueHandler>()
.IncludeType<PingHandler>();
options.Serializers.Add(new BlueTextReader());
options.Handlers.OnException<DivideByZeroException>()
.MoveToErrorQueue();
options.Handlers.OnException<DataMisalignedException>()
.Requeue(3);
options.Handlers.OnException<BadImageFormatException>()
.RetryLater(3.Seconds());
options.Extensions.UseMessageTrackingTestingSupport();
options.Services.AddSingleton(new ColorHistory());
}
public void Dispose()
{
Sender?.Dispose();
if (!object.ReferenceEquals(Sender, Receiver))
{
Receiver?.Dispose();
}
}
public virtual void BeforeEach(){}
}
public abstract class SendingCompliance<T> : IAsyncLifetime where T : SendingComplianceFixture, new()
{
protected IHost theSender;
protected IHost theReceiver;
protected Uri theOutboundAddress;
protected readonly ErrorCausingMessage theMessage = new ErrorCausingMessage();
private ITrackedSession _session;
protected SendingCompliance()
{
Fixture = new T();
}
public async Task InitializeAsync()
{
if (Fixture is IAsyncLifetime lifetime)
{
await lifetime.InitializeAsync();
}
theSender = Fixture.Sender;
theReceiver = Fixture.Receiver;
theOutboundAddress = Fixture.OutboundAddress;
await Fixture.Sender.ClearAllPersistedMessages();
if (Fixture.Receiver != null && !object.ReferenceEquals(Fixture.Sender, Fixture.Receiver))
{
await Fixture.Receiver.ClearAllPersistedMessages();
}
Fixture.BeforeEach();
}
public Task DisposeAsync()
{
Fixture.SafeDispose();
return Task.CompletedTask;
}
public T Fixture { get; }
[Fact]
public virtual async Task can_apply_requeue_mechanics()
{
var session = await theSender.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.DoNotAssertOnExceptionsDetected()
.Timeout(15.Seconds())
.ExecuteAndWait(c => c.SendToDestination(theOutboundAddress, new Message2()));
session.FindSingleTrackedMessageOfType<Message2>(EventType.MessageSucceeded)
.ShouldNotBeNull();
}
[Fact]
public async Task can_send_from_one_node_to_another_by_destination()
{
var session = await theSender.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.DoNotAssertOnExceptionsDetected()
.ExecuteAndWait(c => c.SendToDestination(theOutboundAddress, new Message1()));
session.FindSingleTrackedMessageOfType<Message1>(EventType.MessageSucceeded)
.ShouldNotBeNull();
}
[Fact]
public async Task can_send_from_one_node_to_another_by_publishing_rule()
{
var message1 = new Message1();
var session = await theSender.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.DoNotAssertOnExceptionsDetected()
.Timeout(30.Seconds())
.SendMessageAndWait(message1);
session.FindSingleTrackedMessageOfType<Message1>(EventType.MessageSucceeded)
.Id.ShouldBe(message1.Id);
}
[Fact]
public async Task tags_the_envelope_with_the_source()
{
var session = await theSender.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.DoNotAssertOnExceptionsDetected()
.ExecuteAndWait(c => c.SendToDestination(theOutboundAddress, new Message1()));
var record = session.FindEnvelopesWithMessageType<Message1>(EventType.MessageSucceeded).Single();
record
.ShouldNotBeNull();
record.Envelope.Source.ShouldBe(theSender.Get<JasperOptions>().ServiceName);
}
[Fact]
public async Task tracking_correlation_id_on_everything()
{
var id2 = string.Empty;
var session2 = await theSender
.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.ExecuteAndWait(async context =>
{
id2 = context.CorrelationId;
await context.Send(new ExecutedMessage());
await context.Publish(new ExecutedMessage());
//await context.ScheduleSend(new ExecutedMessage(), DateTime.UtcNow.AddDays(5));
});
var envelopes = session2
.AllRecordsInOrder(EventType.Sent)
.Select(x => x.Envelope)
.ToArray();
foreach (var envelope in envelopes) envelope.CorrelationId.ShouldBe(id2);
}
[Fact]
public async Task schedule_send()
{
var session = await theSender
.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.Timeout(15.Seconds())
.WaitForMessageToBeReceivedAt<ColorChosen>(theReceiver ?? theSender)
.ExecuteAndWait(c => c.ScheduleSend(new ColorChosen {Name = "Orange"}, 5.Seconds()));
var message = session.FindSingleTrackedMessageOfType<ColorChosen>(EventType.MessageSucceeded);
message.Name.ShouldBe("Orange");
}
protected void throwOnAttempt<T>(int attempt) where T : Exception, new()
{
theMessage.Errors.Add(attempt, new T());
}
protected async Task<EnvelopeRecord> afterProcessingIsComplete()
{
_session = await theSender
.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.DoNotAssertOnExceptionsDetected()
.SendMessageAndWait(theMessage);
return _session.AllRecordsInOrder().LastOrDefault(x =>
x.EventType == EventType.MessageSucceeded || x.EventType == EventType.MovedToErrorQueue);
}
protected async Task shouldSucceedOnAttempt(int attempt)
{
var session = await theSender
.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.Timeout(15.Seconds())
.DoNotAssertOnExceptionsDetected()
.SendMessageAndWait(theMessage);
var record = session.AllRecordsInOrder().LastOrDefault(x =>
x.EventType == EventType.MessageSucceeded || x.EventType == EventType.MovedToErrorQueue);
if (record == null) throw new Exception("No ending activity detected");
if (record.EventType == EventType.MessageSucceeded && record.AttemptNumber == attempt)
{
return;
}
var writer = new StringWriter();
await writer.WriteLineAsync($"Actual ending was '{record.EventType}' on attempt {record.AttemptNumber}");
foreach (var envelopeRecord in session.AllRecordsInOrder())
{
writer.WriteLine(envelopeRecord);
if (envelopeRecord.Exception != null)
{
await writer.WriteLineAsync(envelopeRecord.Exception.Message);
}
}
throw new Exception(writer.ToString());
}
protected async Task shouldMoveToErrorQueueOnAttempt(int attempt)
{
var session = await theSender
.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.DoNotAssertOnExceptionsDetected()
.Timeout(30.Seconds())
.SendMessageAndWait(theMessage);
var record = session.AllRecordsInOrder().LastOrDefault(x =>
x.EventType == EventType.MessageSucceeded || x.EventType == EventType.MovedToErrorQueue);
if (record == null) throw new Exception("No ending activity detected");
if (record.EventType == EventType.MovedToErrorQueue && record.AttemptNumber == attempt)
{
return;
}
var writer = new StringWriter();
writer.WriteLine($"Actual ending was '{record.EventType}' on attempt {record.AttemptNumber}");
foreach (var envelopeRecord in session.AllRecordsInOrder())
{
writer.WriteLine(envelopeRecord);
if (envelopeRecord.Exception != null)
{
writer.WriteLine(envelopeRecord.Exception.Message);
}
}
throw new Exception(writer.ToString());
}
[Fact]
public virtual async Task will_move_to_dead_letter_queue_without_any_exception_match()
{
throwOnAttempt<InvalidOperationException>(1);
throwOnAttempt<InvalidOperationException>(2);
throwOnAttempt<InvalidOperationException>(3);
await shouldMoveToErrorQueueOnAttempt(3);
}
[Fact]
public virtual async Task will_move_to_dead_letter_queue_with_exception_match()
{
throwOnAttempt<DivideByZeroException>(1);
throwOnAttempt<DivideByZeroException>(2);
throwOnAttempt<DivideByZeroException>(3);
await shouldMoveToErrorQueueOnAttempt(1);
}
[Fact]
public virtual async Task will_requeue_and_increment_attempts()
{
throwOnAttempt<DataMisalignedException>(1);
throwOnAttempt<DataMisalignedException>(2);
await shouldSucceedOnAttempt(3);
}
[Fact]
public async Task can_retry_later()
{
throwOnAttempt<BadImageFormatException>(1);
await shouldSucceedOnAttempt(2);
}
[Fact]
public async Task explicit_respond_to_sender()
{
var ping = new PingMessage();
var session = await theSender
.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.Timeout(30.Seconds())
.SendMessageAndWait(ping);
session.FindSingleTrackedMessageOfType<PongMessage>(EventType.MessageSucceeded)
.Id.ShouldBe(ping.Id);
}
[Fact]
public async Task requested_response()
{
var ping = new ImplicitPing();
var session = await theSender
.TrackActivity(Fixture.DefaultTimeout)
.AlsoTrack(theReceiver)
.Timeout(30.Seconds())
.ExecuteAndWait(x => x.SendAndExpectResponseFor<ImplicitPong>(ping));
session.FindSingleTrackedMessageOfType<ImplicitPong>(EventType.MessageSucceeded)
.Id.ShouldBe(ping.Id);
}
[Fact] // This test isn't always the most consistent test
public async Task send_green_as_text_and_receive_as_blue()
{
if (Fixture.AllLocally) return; // this just doesn't apply when running all with local queues
var greenMessage = new GreenMessage {Name = "Magic Johnson"};
var envelope = new Envelope(greenMessage)
{
ContentType = "text/plain"
};
var session = await theSender
.TrackActivity()
.AlsoTrack(theReceiver)
.ExecuteAndWait(c => c.SendEnvelope(envelope));
session.FindSingleTrackedMessageOfType<BlueMessage>()
.Name.ShouldBe("Magic Johnson");
}
[Fact]
public async Task send_green_that_gets_received_as_blue()
{
if (Fixture.AllLocally) return; // this just doesn't apply when running all with local queues
var session = await theSender
.TrackActivity()
.AlsoTrack(theReceiver)
.ExecuteAndWait(c =>
c.Send(new GreenMessage {Name = "Kareem Abdul-Jabbar"}));
session.FindSingleTrackedMessageOfType<BlueMessage>()
.Name.ShouldBe("Kareem Abdul-Jabbar");
}
}
// SAMPLE: BlueTextReader
public class BlueTextReader : IMessageSerializer
{
public BlueTextReader()
{
}
public object ReadData(byte[] data)
{
var name = Encoding.UTF8.GetString(data);
return new BlueMessage {Name = name};
}
public string ContentType { get; } = "text/plain";
public byte[] Write(object message)
{
throw new NotImplementedException();
}
public object ReadFromData(Type messageType, byte[] data)
{
return ReadFromData(data);
}
public object ReadFromData(byte[] data)
{
throw new NotImplementedException();
}
}
// ENDSAMPLE
// SAMPLE: GreenTextWriter
public class GreenTextWriter : IMessageSerializer
{
public string ContentType { get; } = "text/plain";
public object ReadFromData(Type messageType, byte[] data)
{
throw new NotImplementedException();
}
public object ReadFromData(byte[] data)
{
throw new NotImplementedException();
}
public byte[] Write(object model)
{
if (model is GreenMessage green) return Encoding.UTF8.GetBytes(green.Name);
throw new NotSupportedException("This serializer only writes GreenMessage");
}
}
// ENDSAMPLE
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using Microsoft.Win32;
namespace NQuery.Demo
{
internal class TanColorTable : ProfessionalColorTable
{
private const string blueColorScheme = "NormalColor";
private const string oliveColorScheme = "HomeStead";
private Dictionary<KnownColors, Color> tanRGB;
public TanColorTable()
{
}
internal Color FromKnownColor(KnownColors color)
{
return ColorTable[color];
}
internal static void InitTanLunaColors(ref Dictionary<KnownColors, Color> rgbTable)
{
rgbTable[KnownColors.GripDark] = Color.FromArgb(0xc1, 190, 0xb3);
rgbTable[KnownColors.SeparatorDark] = Color.FromArgb(0xc5, 0xc2, 0xb8);
rgbTable[KnownColors.MenuItemSelected] = Color.FromArgb(0xc1, 210, 0xee);
rgbTable[KnownColors.ButtonPressedBorder] = Color.FromArgb(0x31, 0x6a, 0xc5);
rgbTable[KnownColors.CheckBackground] = Color.FromArgb(0xe1, 230, 0xe8);
rgbTable[KnownColors.MenuItemBorder] = Color.FromArgb(0x31, 0x6a, 0xc5);
rgbTable[KnownColors.CheckBackgroundMouseOver] = Color.FromArgb(0x31, 0x6a, 0xc5);
rgbTable[KnownColors.MenuItemBorderMouseOver] = Color.FromArgb(0x4b, 0x4b, 0x6f);
rgbTable[KnownColors.ToolStripDropDownBackground] = Color.FromArgb(0xfc, 0xfc, 0xf9);
rgbTable[KnownColors.MenuBorder] = Color.FromArgb(0x8a, 0x86, 0x7a);
rgbTable[KnownColors.SeparatorLight] = Color.FromArgb(0xff, 0xff, 0xff);
rgbTable[KnownColors.ToolStripBorder] = Color.FromArgb(0xa3, 0xa3, 0x7c);
rgbTable[KnownColors.MenuStripGradientBegin] = Color.FromArgb(0xe5, 0xe5, 0xd7);
rgbTable[KnownColors.MenuStripGradientEnd] = Color.FromArgb(0xf4, 0xf2, 0xe8);
rgbTable[KnownColors.ImageMarginGradientBegin] = Color.FromArgb(0xfe, 0xfe, 0xfb);
rgbTable[KnownColors.ImageMarginGradientMiddle] = Color.FromArgb(0xec, 0xe7, 0xe0);
rgbTable[KnownColors.ImageMarginGradientEnd] = Color.FromArgb(0xbd, 0xbd, 0xa3);
rgbTable[KnownColors.OverflowButtonGradientBegin] = Color.FromArgb(0xf3, 0xf2, 240);
rgbTable[KnownColors.OverflowButtonGradientMiddle] = Color.FromArgb(0xe2, 0xe1, 0xdb);
rgbTable[KnownColors.OverflowButtonGradientEnd] = Color.FromArgb(0x92, 0x92, 0x76);
rgbTable[KnownColors.MenuItemPressedGradientBegin] = Color.FromArgb(0xfc, 0xfc, 0xf9);
rgbTable[KnownColors.MenuItemPressedGradientEnd] = Color.FromArgb(0xf6, 0xf4, 0xec);
rgbTable[KnownColors.ImageMarginRevealedGradientBegin] = Color.FromArgb(0xf7, 0xf6, 0xef);
rgbTable[KnownColors.ImageMarginRevealedGradientMiddle] = Color.FromArgb(0xf2, 240, 0xe4);
rgbTable[KnownColors.ImageMarginRevealedGradientEnd] = Color.FromArgb(230, 0xe3, 210);
rgbTable[KnownColors.ButtonCheckedGradientBegin] = Color.FromArgb(0xe1, 230, 0xe8);
rgbTable[KnownColors.ButtonCheckedGradientMiddle] = Color.FromArgb(0xe1, 230, 0xe8);
rgbTable[KnownColors.ButtonCheckedGradientEnd] = Color.FromArgb(0xe1, 230, 0xe8);
rgbTable[KnownColors.ButtonSelectedGradientBegin] = Color.FromArgb(0xc1, 210, 0xee);
rgbTable[KnownColors.ButtonSelectedGradientMiddle] = Color.FromArgb(0xc1, 210, 0xee);
rgbTable[KnownColors.ButtonSelectedGradientEnd] = Color.FromArgb(0xc1, 210, 0xee);
rgbTable[KnownColors.ButtonPressedGradientBegin] = Color.FromArgb(0x98, 0xb5, 0xe2);
rgbTable[KnownColors.ButtonPressedGradientMiddle] = Color.FromArgb(0x98, 0xb5, 0xe2);
rgbTable[KnownColors.ButtonPressedGradientEnd] = Color.FromArgb(0x98, 0xb5, 0xe2);
rgbTable[KnownColors.GripLight] = Color.FromArgb(0xff, 0xff, 0xff);
}
public override Color ButtonCheckedGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonCheckedGradientBegin);
}
return base.ButtonCheckedGradientBegin;
}
}
public override Color ButtonCheckedGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonCheckedGradientEnd);
}
return base.ButtonCheckedGradientEnd;
}
}
public override Color ButtonCheckedGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonCheckedGradientMiddle);
}
return base.ButtonCheckedGradientMiddle;
}
}
public override Color ButtonPressedBorder
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonPressedBorder);
}
return base.ButtonPressedBorder;
}
}
public override Color ButtonPressedGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonPressedGradientBegin);
}
return base.ButtonPressedGradientBegin;
}
}
public override Color ButtonPressedGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonPressedGradientEnd);
}
return base.ButtonPressedGradientEnd;
}
}
public override Color ButtonPressedGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonPressedGradientMiddle);
}
return base.ButtonPressedGradientMiddle;
}
}
public override Color ButtonSelectedBorder
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonPressedBorder);
}
return base.ButtonSelectedBorder;
}
}
public override Color ButtonSelectedGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonSelectedGradientBegin);
}
return base.ButtonSelectedGradientBegin;
}
}
public override Color ButtonSelectedGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonSelectedGradientEnd);
}
return base.ButtonSelectedGradientEnd;
}
}
public override Color ButtonSelectedGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonSelectedGradientMiddle);
}
return base.ButtonSelectedGradientMiddle;
}
}
public override Color CheckBackground
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.CheckBackground);
}
return base.CheckBackground;
}
}
public override Color CheckPressedBackground
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.CheckBackgroundMouseOver);
}
return base.CheckPressedBackground;
}
}
public override Color CheckSelectedBackground
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.CheckBackgroundMouseOver);
}
return base.CheckSelectedBackground;
}
}
internal static string ColorScheme
{
get { return DisplayInformation.ColorScheme; }
}
private Dictionary<KnownColors, Color> ColorTable
{
get
{
if (tanRGB == null)
{
tanRGB = new Dictionary<KnownColors, Color>((int) KnownColors.LastKnownColor);
InitTanLunaColors(ref tanRGB);
}
return tanRGB;
}
}
public override Color GripDark
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.GripDark);
}
return base.GripDark;
}
}
public override Color GripLight
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.GripLight);
}
return base.GripLight;
}
}
public override Color ImageMarginGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginGradientBegin);
}
return base.ImageMarginGradientBegin;
}
}
public override Color ImageMarginGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginGradientEnd);
}
return base.ImageMarginGradientEnd;
}
}
public override Color ImageMarginGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginGradientMiddle);
}
return base.ImageMarginGradientMiddle;
}
}
public override Color ImageMarginRevealedGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginRevealedGradientBegin);
}
return base.ImageMarginRevealedGradientBegin;
}
}
public override Color ImageMarginRevealedGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginRevealedGradientEnd);
}
return base.ImageMarginRevealedGradientEnd;
}
}
public override Color ImageMarginRevealedGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginRevealedGradientMiddle);
}
return base.ImageMarginRevealedGradientMiddle;
}
}
public override Color MenuBorder
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuBorder);
}
return base.MenuItemBorder;
}
}
public override Color MenuItemBorder
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuItemBorder);
}
return base.MenuItemBorder;
}
}
public override Color MenuItemPressedGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuItemPressedGradientBegin);
}
return base.MenuItemPressedGradientBegin;
}
}
public override Color MenuItemPressedGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuItemPressedGradientEnd);
}
return base.MenuItemPressedGradientEnd;
}
}
public override Color MenuItemPressedGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginRevealedGradientMiddle);
}
return base.MenuItemPressedGradientMiddle;
}
}
public override Color MenuItemSelected
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuItemSelected);
}
return base.MenuItemSelected;
}
}
public override Color MenuItemSelectedGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonSelectedGradientBegin);
}
return base.MenuItemSelectedGradientBegin;
}
}
public override Color MenuItemSelectedGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ButtonSelectedGradientEnd);
}
return base.MenuItemSelectedGradientEnd;
}
}
public override Color MenuStripGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuStripGradientBegin);
}
return base.MenuStripGradientBegin;
}
}
public override Color MenuStripGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuStripGradientEnd);
}
return base.MenuStripGradientEnd;
}
}
public override Color OverflowButtonGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.OverflowButtonGradientBegin);
}
return base.OverflowButtonGradientBegin;
}
}
public override Color OverflowButtonGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.OverflowButtonGradientEnd);
}
return base.OverflowButtonGradientEnd;
}
}
public override Color OverflowButtonGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.OverflowButtonGradientMiddle);
}
return base.OverflowButtonGradientMiddle;
}
}
public override Color RaftingContainerGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuStripGradientBegin);
}
return base.RaftingContainerGradientBegin;
}
}
public override Color RaftingContainerGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuStripGradientEnd);
}
return base.RaftingContainerGradientEnd;
}
}
public override Color SeparatorDark
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.SeparatorDark);
}
return base.SeparatorDark;
}
}
public override Color SeparatorLight
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.SeparatorLight);
}
return base.SeparatorLight;
}
}
public override Color ToolStripBorder
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ToolStripBorder);
}
return base.ToolStripBorder;
}
}
public override Color ToolStripDropDownBackground
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ToolStripDropDownBackground);
}
return base.ToolStripDropDownBackground;
}
}
public override Color ToolStripGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginGradientBegin);
}
return base.ToolStripGradientBegin;
}
}
public override Color ToolStripGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginGradientEnd);
}
return base.ToolStripGradientEnd;
}
}
public override Color ToolStripGradientMiddle
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.ImageMarginGradientMiddle);
}
return base.ToolStripGradientMiddle;
}
}
public override Color ToolStripPanelGradientBegin
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuStripGradientBegin);
}
return base.MenuStripGradientBegin;
}
}
public override Color ToolStripPanelGradientEnd
{
get
{
if (!UseBaseColorTable)
{
return FromKnownColor(KnownColors.MenuStripGradientEnd);
}
return base.MenuStripGradientEnd;
}
}
private bool UseBaseColorTable
{
get
{
bool flag1 = !DisplayInformation.IsLunaTheme || ((ColorScheme != oliveColorScheme) && (ColorScheme != blueColorScheme));
if (flag1 && (tanRGB != null))
{
tanRGB.Clear();
tanRGB = null;
}
return flag1;
}
}
private static class DisplayInformation
{
[ThreadStatic]
private static string colorScheme;
[ThreadStatic]
private static bool isLunaTheme;
private const string lunaFileName = "luna.msstyles";
[DllImport("uxtheme.dll", CharSet = CharSet.Auto)]
public static extern int GetCurrentThemeName(StringBuilder pszThemeFileName, int dwMaxNameChars, StringBuilder pszColorBuff, int dwMaxColorChars, StringBuilder pszSizeBuff, int cchMaxSizeChars);
static DisplayInformation()
{
SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
SetScheme();
}
private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
SetScheme();
}
private static void SetScheme()
{
isLunaTheme = false;
if (VisualStyleRenderer.IsSupported)
{
colorScheme = VisualStyleInformation.ColorScheme;
if (!VisualStyleInformation.IsEnabledByUser)
{
return;
}
StringBuilder builder1 = new StringBuilder(0x200);
GetCurrentThemeName(builder1, builder1.Capacity, null, 0, null, 0);
string text1 = builder1.ToString();
isLunaTheme = string.Equals(lunaFileName, Path.GetFileName(text1), StringComparison.InvariantCultureIgnoreCase);
}
else
{
colorScheme = null;
}
}
public static string ColorScheme
{
get { return colorScheme; }
}
internal static bool IsLunaTheme
{
get { return isLunaTheme; }
}
}
internal enum KnownColors
{
ButtonPressedBorder,
MenuItemBorder,
MenuItemBorderMouseOver,
MenuItemSelected,
CheckBackground,
CheckBackgroundMouseOver,
GripDark,
GripLight,
MenuStripGradientBegin,
MenuStripGradientEnd,
ImageMarginRevealedGradientBegin,
ImageMarginRevealedGradientEnd,
ImageMarginRevealedGradientMiddle,
MenuItemPressedGradientBegin,
MenuItemPressedGradientEnd,
ButtonPressedGradientBegin,
ButtonPressedGradientEnd,
ButtonPressedGradientMiddle,
ButtonSelectedGradientBegin,
ButtonSelectedGradientEnd,
ButtonSelectedGradientMiddle,
OverflowButtonGradientBegin,
OverflowButtonGradientEnd,
OverflowButtonGradientMiddle,
ButtonCheckedGradientBegin,
ButtonCheckedGradientEnd,
ButtonCheckedGradientMiddle,
ImageMarginGradientBegin,
ImageMarginGradientEnd,
ImageMarginGradientMiddle,
MenuBorder,
ToolStripDropDownBackground,
ToolStripBorder,
SeparatorDark,
SeparatorLight,
LastKnownColor = SeparatorLight,
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.DocumentationComments;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class ISymbolExtensions2
{
public static Glyph GetGlyph(this ISymbol symbol)
{
Glyph publicIcon;
switch (symbol.Kind)
{
case SymbolKind.Alias:
return ((IAliasSymbol)symbol).Target.GetGlyph();
case SymbolKind.Assembly:
return Glyph.Assembly;
case SymbolKind.ArrayType:
return ((IArrayTypeSymbol)symbol).ElementType.GetGlyph();
case SymbolKind.DynamicType:
return Glyph.ClassPublic;
case SymbolKind.Event:
publicIcon = Glyph.EventPublic;
break;
case SymbolKind.Field:
var containingType = symbol.ContainingType;
if (containingType != null && containingType.TypeKind == TypeKind.Enum)
{
return Glyph.EnumMember;
}
publicIcon = ((IFieldSymbol)symbol).IsConst ? Glyph.ConstantPublic : Glyph.FieldPublic;
break;
case SymbolKind.Label:
return Glyph.Label;
case SymbolKind.Local:
return Glyph.Local;
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
{
switch (((INamedTypeSymbol)symbol).TypeKind)
{
case TypeKind.Class:
publicIcon = Glyph.ClassPublic;
break;
case TypeKind.Delegate:
publicIcon = Glyph.DelegatePublic;
break;
case TypeKind.Enum:
publicIcon = Glyph.EnumPublic;
break;
case TypeKind.Interface:
publicIcon = Glyph.InterfacePublic;
break;
case TypeKind.Module:
publicIcon = Glyph.ModulePublic;
break;
case TypeKind.Struct:
publicIcon = Glyph.StructurePublic;
break;
case TypeKind.Error:
return Glyph.Error;
default:
throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol));
}
break;
}
case SymbolKind.Method:
{
var methodSymbol = (IMethodSymbol)symbol;
if (methodSymbol.MethodKind == MethodKind.UserDefinedOperator || methodSymbol.MethodKind == MethodKind.Conversion)
{
return Glyph.Operator;
}
else if (methodSymbol.IsExtensionMethod || methodSymbol.MethodKind == MethodKind.ReducedExtension)
{
publicIcon = Glyph.ExtensionMethodPublic;
}
else
{
publicIcon = Glyph.MethodPublic;
}
}
break;
case SymbolKind.Namespace:
return Glyph.Namespace;
case SymbolKind.NetModule:
return Glyph.Assembly;
case SymbolKind.Parameter:
return symbol.IsValueParameter()
? Glyph.Keyword
: Glyph.Parameter;
case SymbolKind.PointerType:
return ((IPointerTypeSymbol)symbol).PointedAtType.GetGlyph();
case SymbolKind.Property:
{
var propertySymbol = (IPropertySymbol)symbol;
if (propertySymbol.IsWithEvents)
{
publicIcon = Glyph.FieldPublic;
}
else
{
publicIcon = Glyph.PropertyPublic;
}
}
break;
case SymbolKind.RangeVariable:
return Glyph.RangeVariable;
case SymbolKind.TypeParameter:
return Glyph.TypeParameter;
default:
throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol));
}
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Private:
publicIcon += Glyph.ClassPrivate - Glyph.ClassPublic;
break;
case Accessibility.Protected:
case Accessibility.ProtectedAndInternal:
case Accessibility.ProtectedOrInternal:
publicIcon += Glyph.ClassProtected - Glyph.ClassPublic;
break;
case Accessibility.Internal:
publicIcon += Glyph.ClassInternal - Glyph.ClassPublic;
break;
}
return publicIcon;
}
public static IEnumerable<SymbolDisplayPart> GetDocumentationParts(this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken)
{
var documentation = symbol.TypeSwitch(
(IParameterSymbol parameter) => parameter.ContainingSymbol.OriginalDefinition.GetDocumentationComment(cancellationToken: cancellationToken).GetParameterText(symbol.Name),
(ITypeParameterSymbol typeParam) => typeParam.ContainingSymbol.GetDocumentationComment(cancellationToken: cancellationToken).GetTypeParameterText(symbol.Name),
(IMethodSymbol method) => GetMethodDocumentation(method),
(IAliasSymbol alias) => alias.Target.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText,
_ => symbol.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText);
return documentation != null
? formatter.Format(documentation, semanticModel, position, CrefFormat)
: SpecializedCollections.EmptyEnumerable<SymbolDisplayPart>();
}
public static Func<CancellationToken, IEnumerable<SymbolDisplayPart>> GetDocumentationPartsFactory(this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter)
{
return c => symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken: c);
}
public static readonly SymbolDisplayFormat CrefFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static string GetMethodDocumentation(IMethodSymbol method)
{
switch (method.MethodKind)
{
case MethodKind.EventAdd:
case MethodKind.EventRaise:
case MethodKind.EventRemove:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
return method.ContainingSymbol.GetDocumentationComment().SummaryText;
default:
return method.GetDocumentationComment().SummaryText;
}
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_8_12_1 : EcmaTest
{
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyPropertyDoesNotExist()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_1.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableConfigurableNonEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_10.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableConfigurableEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_11.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableNonConfigurableNonEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_12.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableNonConfigurableEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_13.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableConfigurableNonEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_14.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableNonConfigurableNonEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_15.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableConfigurableEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_16.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableNonConfigurableEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_17.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableConfigurableNonEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_18.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableConfigurableEnumerableInheritedValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_19.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyOldStyleOwnProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_2.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyLiteralOwnGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_20.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyLiteralOwnSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_21.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyLiteralOwnGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_22.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyLiteralInheritedGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_23.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyLiteralInheritedSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_24.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyLiteralInheritedGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_25.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableNonEnumerableOwnGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_26.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableEnumerableOwnGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_27.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableNonEnumerableOwnGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_28.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableEnumerableOwnGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_29.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyOldStyleInheritedProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_3.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableNonEnumerableOwnSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_30.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableEnumerableOwnSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_31.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableNonEnumerableOwnSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_32.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableEnumerableOwnSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_33.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableNonEnumerableOwnGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_34.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableEnumerableOwnGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_35.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableNonEnumerableOwnGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_36.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableEnumerableOwnGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_37.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableNonEnumerableInheritedGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_38.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableEnumerableInheritedGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_39.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableNonConfigurableNonEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_4.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableNonEnumerableInheritedGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_40.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableEnumerableInheritedGetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_41.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableNonEnumerableInheritedSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_42.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableEnumerableInheritedSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_43.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableNonEnumerableInheritedSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_44.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableEnumerableInheritedSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_45.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableNonEnumerableInheritedGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_46.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonConfigurableEnumerableInheritedGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_47.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableNonEnumerableInheritedGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_48.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyConfigurableEnumerableInheritedGetterSetterProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_49.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableNonConfigurableEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_5.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableConfigurableNonEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_6.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableNonConfigurableNonEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_7.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyNonWritableConfigurableEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_8.js", false);
}
[Fact]
[Trait("Category", "8.12.1")]
public void PropertiesHasownpropertyWritableNonConfigurableEnumerableOwnValueProperty()
{
RunTest(@"TestCases/ch08/8.12/8.12.1/8.12.1-1_9.js", false);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.Messages.Linden;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Assets;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Communications.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.Physics.Manager;
using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
using OSDArray = OpenMetaverse.StructuredData.OSDArray;
using Amib.Threading;
namespace OpenSim.Region.CoreModules.Capabilities
{
public delegate void UpLoadedAsset(
string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
byte[] data, string inventoryType, string assetType);
public delegate UpdateItemResponse UpdateItem(UUID itemID, byte[] data);
public delegate UpdateItemResponse UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data);
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class InventoryCapsModule : INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IConfigSource m_Config;
private Scene m_Scene;
#region INonSharedRegionModule
public string Name
{
get { return "InventoryCapsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
m_Config = source;
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
m_Scene = scene;
}
public void RemoveRegion(Scene scene)
{
m_Scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
m_Scene.EventManager.OnDeregisterCaps -= OnDeregisterCaps;
}
public void RegionLoaded(Scene scene)
{
m_Scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_Scene.EventManager.OnDeregisterCaps += OnDeregisterCaps;
}
public void PostInitialise()
{
}
#endregion
private Dictionary<UUID, InventoryCapsHandler> m_userInventoryHandlers = new Dictionary<UUID, InventoryCapsHandler>();
private void OnRegisterCaps(UUID agentID, Caps caps)
{
InventoryCapsHandler handler = new InventoryCapsHandler(m_Scene, agentID, caps);
handler.RegisterHandlers();
lock (m_userInventoryHandlers)
{
m_userInventoryHandlers[agentID] = handler;
}
}
private void OnDeregisterCaps(UUID agentID, Caps caps)
{
InventoryCapsHandler handler;
lock (m_userInventoryHandlers)
{
if (m_userInventoryHandlers.TryGetValue(agentID, out handler))
{
m_userInventoryHandlers.Remove(agentID);
}
}
if (handler != null)
{
handler.Close();
}
}
protected class InventoryCapsHandler
{
private static readonly string m_newInventory = "0002/";
private static readonly string m_notecardUpdatePath = "0004/";
private static readonly string m_notecardTaskUpdatePath = "0005/";
private static readonly string m_fetchInventoryPath = "0006/";
private UUID m_agentID;
private Caps m_Caps;
private Scene m_Scene;
private IHttpServer m_httpServer;
private string m_regionName;
private IAssetCache m_assetCache;
private InventoryFolderImpl m_libraryFolder = null;
private IInventoryProviderSelector m_inventoryProviderSelector;
private ICheckedInventoryStorage m_checkedStorageProvider;
private SmartThreadPool m_inventoryPool = new SmartThreadPool(60 * 1000, 2, 0);
public InventoryCapsHandler(Scene scene, UUID agentID, Caps caps)
{
m_agentID = agentID;
m_Caps = caps;
m_Scene = scene;
m_httpServer = m_Caps.HttpListener;
m_regionName = m_Scene.RegionInfo.RegionName;
m_assetCache = m_Scene.CommsManager.AssetCache;
m_inventoryProviderSelector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
m_checkedStorageProvider = m_inventoryProviderSelector.GetCheckedProvider(m_Caps.AgentID);
m_libraryFolder = m_Scene.CommsManager.UserProfileCacheService.LibraryRoot;
m_inventoryPool.Name = "Inventory Caps " + agentID;
}
/// <summary>
/// Register a bunch of CAPS http service handlers
/// </summary>
public void RegisterHandlers()
{
try
{
IRequestHandler requestHandler;
requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + m_notecardTaskUpdatePath, ScriptTaskInventory);
m_Caps.RegisterHandler("UpdateScriptTaskInventory", requestHandler);
m_Caps.RegisterHandler("UpdateScriptTask", requestHandler);
requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + m_notecardUpdatePath, NoteCardAgentInventory);
m_Caps.RegisterHandler("UpdateNotecardAgentInventory", requestHandler);
m_Caps.RegisterHandler("UpdateScriptAgentInventory", requestHandler);
m_Caps.RegisterHandler("UpdateScriptAgent", requestHandler);
requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + "/NewFileAgentInventory/", NewAgentInventoryRequest);
m_Caps.RegisterHandler("NewFileAgentInventory", requestHandler);
//requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + "/NewFileAgentInventoryVariablePrice/", NewAgentInventoryRequestVariablePrice);
//m_Caps.RegisterHandler("NewFileAgentInventoryVariablePrice", requestHandler);
requestHandler = new AsyncRequestHandler("POST", m_Caps.CapsBase + m_fetchInventoryPath, AsyncFetchInventoryDescendents);
m_Caps.RegisterHandler("FetchInventoryDescendents", requestHandler);
m_Caps.RegisterHandler("WebFetchInventoryDescendents", requestHandler);
m_Caps.RegisterHandler("FetchInventoryDescendents2", requestHandler);
m_Caps.RegisterHandler("FetchLibDescendents", requestHandler);
m_Caps.RegisterHandler("FetchLibDescendents2", requestHandler);
requestHandler = new RestStreamHandler("POST", "/CAPS/" + UUID.Random(), FetchInventoryRequest);
m_Caps.RegisterHandler("FetchInventory", requestHandler);
m_Caps.RegisterHandler("FetchInventory2", requestHandler);
requestHandler = new RestStreamHandler("POST", "/CAPS/" + UUID.Random(), FetchLibraryRequest);
m_Caps.RegisterHandler("FetchLib", requestHandler);
m_Caps.RegisterHandler("FetchLib2", requestHandler);
requestHandler = new RestStreamHandler("POST", "/CAPS/" + UUID.Random(), CopyInventoryFromNotecard);
m_Caps.RegisterHandler("CopyInventoryFromNotecard", requestHandler);
//requestHandler = new RestStreamHandler("POST", m_Caps.CapsBase + UUID.Random(), CreateInventoryCategory);
//m_Caps.RegisterHandler("CreateInventoryCategory", requestHandler);
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
}
/// <summary>
/// Called when new asset data for an agent inventory item update has been uploaded.
/// </summary>
/// <param name="itemID">Item to update</param>
/// <param name="data">New asset data</param>
/// <returns></returns>
public UpdateItemResponse ItemUpdated(UUID itemID, byte[] data)
{
return (m_Scene.CapsUpdateInventoryItemAsset(m_Caps.AgentID, itemID, data));
}
/// <summary>
/// Handle a request from the client for a Uri to upload a baked texture.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <returns>The upload response if the request is successful, null otherwise.</returns>
public string ScriptTaskInventory(
string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
//m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
try
{
string capsBase = m_Caps.CapsBase;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
TaskInventoryScriptUpdater uploader =
new TaskInventoryScriptUpdater(
llsdUpdateRequest.item_id,
llsdUpdateRequest.task_id,
llsdUpdateRequest.is_script_running,
capsBase + uploaderPath,
m_httpServer);
uploader.OnUpLoad += TaskScriptUpdated;
m_httpServer.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
string uploaderURL = m_httpServer.ServerURI + capsBase + uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
// m_log.InfoFormat("[CAPS]: " +"ScriptTaskInventory response: {0}", LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
}
catch (Exception e)
{
m_log.ErrorFormat("[UPLOAD SCRIPT TASK HANDLER]: {0}{1}", e.Message, e.StackTrace);
}
return null;
}
/// <summary>
/// Called when new asset data for an agent inventory item update has been uploaded.
/// </summary>
/// <param name="itemID">Item to update</param>
/// <param name="primID">Prim containing item to update</param>
/// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
/// <param name="data">New asset data</param>
public UpdateItemResponse TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data)
{
return (m_Scene.CapsUpdateTaskInventoryScriptAsset(m_agentID, itemID, primID, isScriptRunning, data));
}
/// <summary>
/// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string NoteCardAgentInventory(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
//m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName + "\n" + request);
//m_log.Debug("[CAPS]: NoteCardAgentInventory Request is: " + request);
//OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest);
string capsBase = m_Caps.CapsBase;
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
ItemUpdater uploader =
new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_httpServer);
uploader.OnUpLoad += ItemUpdated;
m_httpServer.AddStreamHandler(new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
string uploaderURL = m_httpServer.ServerURI + capsBase + uploaderPath;
LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload";
// m_log.InfoFormat("[CAPS]: " +
// "NoteCardAgentInventory response: {0}",
// LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
}
/// <summary>
/// Calculate (possibly variable priced) charges.
/// </summary>
/// <param name="asset_type"></param>
/// <param name="map"></param>
/// <param name="charge"></param>
/// <param name="resourceCost"></param>
/// <returns>upload charge to user</returns>
private void CalculateCosts(IMoneyModule mm, string asset_type, OSDMap map, out int uploadCost, out int resourceCost)
{
uploadCost = 0;
resourceCost = 0;
if (mm != null)
{
int upload_price = mm.GetEconomyData().PriceUpload;
if (asset_type == "texture" ||
asset_type == "animation" ||
asset_type == "snapshot" ||
asset_type == "sound")
{
uploadCost = upload_price;
resourceCost = 0;
}
else if (asset_type == "mesh" ||
asset_type == "object")
{
OSDMap meshMap = (OSDMap)map["asset_resources"];
int meshCount = meshMap.ContainsKey("mesh_list") ?
((OSDArray)meshMap["mesh_list"]).Count : 0;
int textureCount = meshMap.ContainsKey("texture_list") ?
((OSDArray)meshMap["texture_list"]).Count : 0;
uploadCost = mm.MeshUploadCharge(meshCount, textureCount);
// simplified resource cost, for now
// see http://wiki.secondlife.com/wiki/Mesh/Mesh_physics for LL implementation
resourceCost = meshCount * upload_price;
}
}
}
private void ApplyMeshCharges(UUID agentID, int meshCount, int textureCount)
{
IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
if (mm != null)
mm.ApplyMeshUploadCharge(agentID, meshCount, textureCount);
}
/// <summary>
/// Handle the NewAgentInventory Upload request.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <returns></returns>
public string NewAgentInventoryRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
string asset_type = map["asset_type"].AsString();
int uploadCost = 0;
int resourceCost = 0;
// Check to see if mesh uploads are enabled.
if (asset_type == "mesh")
{
ISimulatorFeaturesModule m_SimulatorFeatures = m_Scene.RequestModuleInterface<ISimulatorFeaturesModule>();
if ((m_SimulatorFeatures == null) || (m_SimulatorFeatures.MeshEnabled == false))
{
OSDMap errorResponse = new OSDMap();
errorResponse["uploader"] = "";
errorResponse["state"] = "error";
return (errorResponse);
}
}
string assetName = map["name"].AsString();
string assetDes = map["description"].AsString();
UUID parentFolder = map["folder_id"].AsUUID();
string inventory_type = map["inventory_type"].AsString();
uint everyone_mask = map["everyone_mask"].AsUInteger();
uint group_mask = map["group_mask"].AsUInteger();
uint next_owner_mask = map["next_owner_mask"].AsUInteger();
UUID newAsset = UUID.Random();
UUID newInvItem = UUID.Random();
IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
CalculateCosts(mm, asset_type, map, out uploadCost, out resourceCost);
IClientAPI client = m_Scene.SceneContents.GetControllingClient(m_agentID);
if (!mm.AmountCovered(client.AgentId, uploadCost))
{
if (client != null)
client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
OSDMap errorResponse = new OSDMap();
errorResponse["uploader"] = "";
errorResponse["state"] = "error";
return OSDParser.SerializeLLSDXmlString(errorResponse);
}
// Build the response
OSDMap uploadResponse = new OSDMap();
try
{
// Handle mesh asset "data" block
if (asset_type == "mesh")
{
OSDMap meshMap = (OSDMap)map["asset_resources"];
OSDArray mesh_list = (OSDArray)meshMap["mesh_list"];
OSDArray instance_list = (OSDArray)meshMap["instance_list"];
float streaming_cost = 0.0f;
float server_weight = 0.0f;
for (int i = 0; i < mesh_list.Count; i++)
{
OSDMap inner_instance_list = (OSDMap)instance_list[i];
byte[] mesh_data = mesh_list[i].AsBinary();
Vector3 scale = inner_instance_list["scale"].AsVector3();
int vertex_count = 0;
int hibytes = 0;
int midbytes = 0;
int lowbytes = 0;
int lowestbytes = 0;
SceneObjectPartMeshCost.GetMeshVertexCount(mesh_data, out vertex_count);
SceneObjectPartMeshCost.GetMeshLODByteCounts(mesh_data, out hibytes, out midbytes, out lowbytes, out lowestbytes);
server_weight += PrimitiveBaseShape.GetServerWeight(vertex_count);
streaming_cost += PrimitiveBaseShape.GetStreamingCost(scale, hibytes, midbytes, lowbytes, lowestbytes);
}
OSDMap data = new OSDMap();
data["resource_cost"] = Math.Min(server_weight, streaming_cost);
data["model_streaming_cost"] = streaming_cost;
data["simulation_cost"] = server_weight;
data["physics_cost"] = 0.0f;
uploadResponse["data"] = data;
}
}
catch (Exception e)
{
OSDMap errorResponse = new OSDMap();
errorResponse["uploader"] = "";
errorResponse["state"] = "error";
return OSDParser.SerializeLLSDXmlString(errorResponse);
}
string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
string uploaderURL = m_Caps.HttpListener.ServerURI + m_Caps.CapsBase + uploaderPath;
AssetUploader uploader =
new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, inventory_type,
asset_type, m_Caps.CapsBase + uploaderPath, m_Caps.HttpListener);
uploader.OnUpLoad += UploadCompleteHandler;
m_Caps.HttpListener.AddStreamHandler(
new BinaryStreamHandler("POST", m_Caps.CapsBase + uploaderPath, uploader.uploaderCaps));
uploadResponse["uploader"] = uploaderURL;
uploadResponse["state"] = "upload";
uploadResponse["resource_cost"] = resourceCost;
uploadResponse["upload_price"] = uploadCost;
return OSDParser.SerializeLLSDXmlString(uploadResponse);
}
/// <summary>
/// Upload Complete CAP handler. Instantiated from the upload request above.
/// </summary>
/// <param name="assetName"></param>
/// <param name="assetDescription"></param>
/// <param name="assetID"></param>
/// <param name="inventoryItem"></param>
/// <param name="parentFolder"></param>
/// <param name="data"></param>
/// <param name="inventoryType"></param>
/// <param name="assetType"></param>
public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
string assetType)
{
sbyte assType = (sbyte)AssetType.Texture;
sbyte inType = (sbyte)InventoryType.Texture;
if (inventoryType == "sound")
{
inType = (sbyte)InventoryType.Sound;
assType = (sbyte)AssetType.Sound;
}
else if (inventoryType == "animation")
{
inType = (sbyte)InventoryType.Animation;
assType = (sbyte)AssetType.Animation;
}
else if (inventoryType == "snapshot")
{
inType = (sbyte)InventoryType.Snapshot;
assType = (sbyte)AssetType.Texture;
}
else if (inventoryType == "wearable")
{
inType = (sbyte)InventoryType.Wearable;
switch (assetType)
{
case "bodypart":
assType = (sbyte)AssetType.Bodypart;
break;
case "clothing":
assType = (sbyte)AssetType.Clothing;
break;
}
}
else if (inventoryType == "object")
{
inType = (sbyte)InventoryType.Object;
assType = (sbyte)AssetType.Object;
data = ObjectUploadComplete(assetName, data);
}
// Bill for upload (mesh is separately billed).
IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
if (mm != null)
{
if (mm.UploadChargeApplies((AssetType)assType))
mm.ApplyUploadCharge(m_Caps.AgentID);
}
AssetBase asset;
asset = new AssetBase();
asset.FullID = assetID;
asset.Type = assType;
asset.Name = assetName;
asset.Data = data;
try
{
if (m_assetCache != null)
{
m_assetCache.AddAsset(asset, AssetRequestInfo.InternalRequest());
}
}
catch (AssetServerException e)
{
m_log.ErrorFormat("[CAPS UPLOAD] Asset write failed: {0}", e);
return;
}
InventoryItemBase item = new InventoryItemBase();
item.Owner = m_Caps.AgentID;
item.CreatorId = m_Caps.AgentID.ToString();
item.ID = inventoryItem;
item.AssetID = asset.FullID;
item.Description = assetDescription;
item.Name = assetName;
item.AssetType = assType;
item.InvType = inType;
item.Folder = parentFolder;
item.CreationDate = Util.UnixTimeSinceEpoch();
item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.CurrentPermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.GroupPermissions = (uint)PermissionMask.None;
item.EveryOnePermissions = (uint)PermissionMask.None;
item.NextPermissions = (uint)PermissionMask.All;
m_Scene.AddInventoryItem(m_Caps.AgentID, item);
}
private byte[] ObjectUploadComplete(string assetName, byte[] data)
{
List<Vector3> positions = new List<Vector3>();
List<Quaternion> rotations = new List<Quaternion>();
OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
OSDArray instance_list = (OSDArray)request["instance_list"];
OSDArray mesh_list = (OSDArray)request["mesh_list"];
OSDArray texture_list = (OSDArray)request["texture_list"];
SceneObjectGroup grp = null;
InventoryFolderBase textureFolder =
m_checkedStorageProvider.FindFolderForType(m_Caps.AgentID, AssetType.Texture);
ScenePresence avatar;
IClientAPI remoteClient = null;
if (m_Scene.TryGetAvatar(m_Caps.AgentID, out avatar))
remoteClient = avatar.ControllingClient;
List<UUID> textures = new List<UUID>();
for (int i = 0; i < texture_list.Count; i++)
{
AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, "");
textureAsset.Data = texture_list[i].AsBinary();
try
{
m_assetCache.AddAsset(textureAsset, AssetRequestInfo.GenericNetRequest());
}
catch (AssetServerException e)
{
if (remoteClient != null) remoteClient.SendAgentAlertMessage("Unable to upload asset. Please try again later.", false);
throw;
}
textures.Add(textureAsset.FullID);
if (textureFolder == null)
continue;
InventoryItemBase item =
new InventoryItemBase(UUID.Random(), m_Caps.AgentID)
{
AssetType = (int)AssetType.Texture,
AssetID = textureAsset.FullID,
CreatorId = m_Caps.AgentID.ToString(),
CreationDate = Util.UnixTimeSinceEpoch(),
Folder = textureFolder.ID,
InvType = (int)InventoryType.Texture,
Name = assetName + " - " + i.ToString(),
BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export),
CurrentPermissions = (uint)(PermissionMask.All | PermissionMask.Export),
GroupPermissions = (uint)PermissionMask.None,
EveryOnePermissions = (uint)PermissionMask.None,
NextPermissions = (uint)PermissionMask.All
};
m_Scene.AddInventoryItem(m_Caps.AgentID, item);
if (remoteClient != null)
remoteClient.SendBulkUpdateInventory(item);
}
for (int i = 0; i < mesh_list.Count; i++)
{
PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
Primitive.TextureEntry textureEntry
= new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
OSDMap inner_instance_list = (OSDMap)instance_list[i];
byte[] mesh_data = mesh_list[i].AsBinary();
OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
for (uint face = 0; face < face_list.Count; face++)
{
OSDMap faceMap = (OSDMap)face_list[(int)face];
Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
if (faceMap.ContainsKey("fullbright"))
f.Fullbright = faceMap["fullbright"].AsBoolean();
if (faceMap.ContainsKey("diffuse_color"))
f.RGBA = faceMap["diffuse_color"].AsColor4();
int textureNum = faceMap["image"].AsInteger();
float imagerot = faceMap["imagerot"].AsInteger();
float offsets = (float)faceMap["offsets"].AsReal();
float offsett = (float)faceMap["offsett"].AsReal();
float scales = (float)faceMap["scales"].AsReal();
float scalet = (float)faceMap["scalet"].AsReal();
if (imagerot != 0)
f.Rotation = imagerot;
if (offsets != 0)
f.OffsetU = offsets;
if (offsett != 0)
f.OffsetV = offsett;
if (scales != 0)
f.RepeatU = scales;
if (scalet != 0)
f.RepeatV = scalet;
if (textures.Count > textureNum)
f.TextureID = textures[textureNum];
else
f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
textureEntry.FaceTextures[face] = f;
}
pbs.Textures = textureEntry;
AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, "");
meshAsset.Data = mesh_data;
try
{
m_assetCache.AddAsset(meshAsset, AssetRequestInfo.GenericNetRequest());
}
catch (AssetServerException)
{
if (remoteClient != null) remoteClient.SendAgentAlertMessage("Unable to upload asset. Please try again later.", false);
throw;
}
pbs.SculptEntry = true;
pbs.SculptType = (byte)SculptType.Mesh;
pbs.SculptTexture = meshAsset.FullID;
pbs.SculptData = mesh_data;
pbs.Scale = inner_instance_list["scale"].AsVector3();
int vertex_count = 0;
int hibytes = 0;
int midbytes = 0;
int lowbytes = 0;
int lowestbytes = 0;
SceneObjectPartMeshCost.GetMeshVertexCount(mesh_data, out vertex_count);
SceneObjectPartMeshCost.GetMeshLODByteCounts(mesh_data, out hibytes, out midbytes, out lowbytes, out lowestbytes);
pbs.VertexCount = vertex_count;
pbs.HighLODBytes = hibytes;
pbs.MidLODBytes = midbytes;
pbs.LowLODBytes = lowbytes;
pbs.LowestLODBytes = lowestbytes;
Vector3 position = inner_instance_list["position"].AsVector3();
Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
UUID owner_id = m_Caps.AgentID;
//m_log.DebugFormat("[MESH] Meshing high_lod returned vertex count of {0} at index {1}", vertex_count, i);
SceneObjectPart prim = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero, false);
prim.Name = assetName;
prim.Description = "";
rotations.Add(rotation);
positions.Add(position);
prim.UUID = UUID.Random();
prim.CreatorID = owner_id;
prim.OwnerID = owner_id;
prim.GroupID = UUID.Zero;
prim.LastOwnerID = prim.OwnerID;
prim.CreationDate = Util.UnixTimeSinceEpoch();
prim.ServerWeight = pbs.GetServerWeight();
prim.StreamingCost = pbs.GetStreamingCost();
if (grp == null)
grp = new SceneObjectGroup(prim);
else
grp.AddPart(prim);
}
Vector3 rootPos = positions[0];
SceneObjectPart[] parts = grp.GetParts();
// Fix first link number
if (parts.Length > 1)
{
grp.RootPart.LinkNum++;
Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
Quaternion tmprot;
Vector3 offset;
// Fix child rotations and positions
for (int i = 1; i < rotations.Count; i++)
{
tmprot = rotations[i];
tmprot = rootRotConj * tmprot;
parts[i].RotationOffset = tmprot;
offset = positions[i] - rootPos;
offset *= rootRotConj;
parts[i].OffsetPosition = offset;
}
grp.AbsolutePosition = rootPos;
grp.UpdateGroupRotation(rotations[0], false);
}
else
{
grp.AbsolutePosition = rootPos;
grp.UpdateGroupRotation(rotations[0], false);
}
// This also notifies the user.
ApplyMeshCharges(m_Caps.AgentID, mesh_list.Count, texture_list.Count);
ISerializationEngine engine;
if (ProviderRegistry.Instance.TryGet<ISerializationEngine>(out engine))
{
return engine.InventoryObjectSerializer.SerializeGroupToInventoryBytes(grp, SerializationFlags.None);
}
else
{
return Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp, StopScriptReason.None));
}
}
const ulong INVENTORY_FETCH_TIMEOUT = 60 * 1000;
public void Close()
{
m_inventoryPool.Shutdown(false, 0);
}
private void AsyncFetchInventoryDescendents(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
AsyncHttpRequest request = new AsyncHttpRequest(server, httpRequest, httpResponse, m_agentID, null, 0);
m_inventoryPool.QueueWorkItem((AsyncHttpRequest req) =>
{
try
{
ulong age = Util.GetLongTickCount() - req.RequestTime;
if (age >= INVENTORY_FETCH_TIMEOUT)
{
SendFetchTimeout(req, age);
return;
}
byte[] ret = this.FetchInventoryDescendentsRequest((string)req.RequestData["body"],
(string)req.RequestData["uri"], "", req.HttpRequest, req.HttpResponse);
var respData = new Hashtable();
respData["response_binary"] = ret;
respData["int_response_code"] = 200;
respData["content_type"] = "application/llsd+xml";
req.SendResponse(respData);
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS/INVENTORY]: HandleAsyncFetchInventoryDescendents threw an exception: {0}", e);
var respData = new Hashtable();
respData["response_binary"] = new byte[0];
respData["int_response_code"] = 500;
req.SendResponse(respData);
}
},
request
);
}
private void SendFetchTimeout(AsyncHttpRequest pRequest, ulong age)
{
var timeout = new Hashtable();
timeout["response_binary"] = new byte[0];
timeout["int_response_code"] = 504; //gateway timeout
m_log.WarnFormat("[CAPS/INVENTORY]: HandleAsyncFetchInventoryDescendents: Request was too old to be processed {0}ms for {1}", age, m_agentID);
pRequest.SendResponse(timeout);
}
/// <summary>
/// Stores a list of folders we've blacklisted with a fail count and timestamp
/// </summary>
private Dictionary<UUID, TimestampedItem<int>> m_blackListedFolders = new Dictionary<UUID, TimestampedItem<int>>();
private const int MAX_FOLDER_FAIL_COUNT = 5;
private const int FOLDER_FAIL_TRACKING_TIME = 15 * 60; //15 minutes
public byte[] FetchInventoryDescendentsRequest(
string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
OpenMetaverse.StructuredData.OSDMap map = (OpenMetaverse.StructuredData.OSDMap)OSDParser.DeserializeLLSDXml(request);
OpenMetaverse.StructuredData.OSDArray osdFoldersRequested = (OpenMetaverse.StructuredData.OSDArray)map["folders"];
// m_log.ErrorFormat("[CAPS/INVENTORY] Handling a FetchInventoryDescendents Request for {0}: {1}", m_Caps.AgentID, map.ToString());
LLSDSerializationDictionary contents = new LLSDSerializationDictionary();
contents.WriteStartMap("llsd"); //Start llsd
contents.WriteKey("folders"); //Start array items
contents.WriteStartArray("folders"); //Start array folders
foreach (OSD folderInfo in osdFoldersRequested)
{
OpenMetaverse.StructuredData.OSDMap fiMap = folderInfo as OpenMetaverse.StructuredData.OSDMap;
if (fiMap == null)
continue;
UUID folderId = fiMap["folder_id"].AsUUID();
bool fetchItems = fiMap["fetch_items"].AsBoolean();
bool fetchFolders = fiMap["fetch_folders"].AsBoolean();
int count = 0;
InventoryFolderBase folder = null;
try
{
if (folderId == UUID.Zero)
{
//indicates the client wants the root for this user
folder = m_checkedStorageProvider.FindFolderForType(m_Caps.AgentID, AssetType.RootFolder);
folderId = folder.ID;
}
else
{
lock (m_blackListedFolders)
{
TimestampedItem<int> entry;
if (m_blackListedFolders.TryGetValue(folderId, out entry))
{
if (entry.ElapsedSeconds > FOLDER_FAIL_TRACKING_TIME)
{
m_blackListedFolders.Remove(folderId);
}
else
{
if (entry.Item >= MAX_FOLDER_FAIL_COUNT)
{
//we're at the fail threshold. return a fake folder
folder = new InventoryFolderBase { ID = folderId, Name = "[unable to load folder]", Owner = m_agentID };
m_log.ErrorFormat("[CAPS/INVENTORY]: Fail threshold reached for {0}, sending empty folder", folderId);
}
}
}
}
if (folder == null)
{
// See if its a library folder
if (m_libraryFolder != null)
folder = m_libraryFolder.FindFolder(folderId);
if (folder == null)
{
// Nope, Look for it in regular folders
folder = m_checkedStorageProvider.GetFolder(m_Caps.AgentID, folderId);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS/INVENTORY] Could not retrieve requested folder {0} for {1}: {2}",
folderId, m_Caps.AgentID, e);
if (folderId != UUID.Zero)
{
lock (m_blackListedFolders)
{
TimestampedItem<int> entry;
if (m_blackListedFolders.TryGetValue(folderId, out entry))
{
entry.ResetTimestamp();
entry.Item = entry.Item + 1;
}
else
{
m_blackListedFolders.Add(folderId, new TimestampedItem<int>(1));
}
}
}
continue;
}
contents.WriteStartMap("internalContents"); //Start internalContents kvp
//Set the normal stuff
contents["agent_id"] = folder.Owner;
contents["owner_id"] = folder.Owner;
contents["folder_id"] = folder.ID;
contents.WriteKey("items"); //Start array items
contents.WriteStartArray("items");
List<UUID> linkedFolders = new List<UUID>();
if (fetchItems)
{
foreach (InventoryItemBase item in folder.Items)
{
item.SerializeToLLSD(contents);
count++;
if (item.AssetType == (int)AssetType.LinkFolder)
{
// Add this when we do categories below
linkedFolders.Add(item.AssetID);
}
else if (item.AssetType == (int)AssetType.Link)
{
try
{
InventoryItemBase linkedItem = m_checkedStorageProvider.GetItem(m_agentID, item.AssetID, UUID.Zero);
if (linkedItem != null)
{
linkedItem.SerializeToLLSD(contents);
}
else
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Failed to resolve link to item {0} for {1}",
item.AssetID, m_Caps.AgentID);
}
// Don't add it to the count. It was accounted for with the link.
//count++;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Failed to resolve link to item {0} for {1}: {2}",
item.AssetID, m_Caps.AgentID, e);
}
}
}
}
contents.WriteEndArray(/*"items"*/); //end array items
contents.WriteKey("categories"); //Start array cats
contents.WriteStartArray("categories"); //We don't send any folders
// If there were linked folders include the folders referenced here
if (linkedFolders.Count > 0)
{
foreach (UUID linkedFolderID in linkedFolders)
{
try
{
InventoryFolderBase linkedFolder = m_checkedStorageProvider.GetFolderAttributes(m_agentID, linkedFolderID);
if (linkedFolder != null)
{
linkedFolder.SerializeToLLSD(contents);
// Don't add it to the count.. it was accounted for with the link.
//count++;
}
}
catch (InventoryObjectMissingException iome)
{
m_log.ErrorFormat("[CAPS/INVENTORY] Failed to resolve link to folder {0} for {1}",
linkedFolderID, m_agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Failed to resolve link to folder {0} for {1}: {2}",
linkedFolderID, m_agentID, e);
}
}
}
if (fetchFolders)
{
foreach (InventorySubFolderBase subFolder in folder.SubFolders)
{
subFolder.SerializeToLLSD(contents, folder.ID);
count++;
}
}
contents.WriteEndArray(/*"categories"*/);
contents["descendents"] = count;
contents["version"] = folder.Version;
//Now add it to the folder array
contents.WriteEndMap(); //end array internalContents
}
contents.WriteEndArray(); //end array folders
contents.WriteEndMap(/*"llsd"*/); //end llsd
return (contents.GetSerializer());
}
/// <summary>
/// Stores a list of items we've blacklisted with a fail count and timestamp
/// </summary>
private Dictionary<UUID, TimestampedItem<int>> m_BlacklistedItems = new Dictionary<UUID, TimestampedItem<int>>();
private const int MAX_ITEM_FAIL_COUNT = 5;
private const int ITEM_FAIL_TRACKING_TIME = 5 * 60; //5 minutes
/// <summary>
/// Tracks that there was an error fetching an item
/// </summary>
/// <param name="itemId"></param>
private void AccountItemFetchFailure(UUID itemId)
{
lock (m_BlacklistedItems)
{
TimestampedItem<int> entry;
if (m_BlacklistedItems.TryGetValue(itemId, out entry))
{
entry.ResetTimestamp();
entry.Item = entry.Item + 1;
}
else
{
//add this brand new one
m_BlacklistedItems.Add(itemId, new TimestampedItem<int>(1));
//also clean out old ones
System.Lazy<List<UUID>> deadKeys = new System.Lazy<List<UUID>>();
foreach (var kvp in m_BlacklistedItems)
{
if (kvp.Value.ElapsedSeconds > ITEM_FAIL_TRACKING_TIME)
{
deadKeys.Value.Add(kvp.Key);
}
}
if (deadKeys.IsValueCreated)
{
foreach (UUID id in deadKeys.Value)
{
m_BlacklistedItems.Remove(id);
}
}
}
}
}
public string FetchInventoryRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capabilty request");
OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
OSDArray itemsRequested = (OSDArray)requestmap["items"];
string reply;
LLSDFetchInventory llsdReply = new LLSDFetchInventory();
llsdReply.agent_id = m_agentID;
foreach (OSDMap osdItemId in itemsRequested)
{
UUID itemId = osdItemId["item_id"].AsUUID();
if (itemId == UUID.Zero)
continue; // don't bother
try
{
//see if we already know that this is a fail
lock (m_BlacklistedItems)
{
TimestampedItem<int> val;
if (m_BlacklistedItems.TryGetValue(itemId, out val))
{
//expired?
if (val.ElapsedSeconds > ITEM_FAIL_TRACKING_TIME)
{
m_BlacklistedItems.Remove(itemId);
}
else
{
if (val.Item >= MAX_ITEM_FAIL_COUNT)
{
//at the max fail count, don't even try to look this one up
continue;
}
}
}
}
InventoryItemBase item = m_checkedStorageProvider.GetItem(m_agentID, itemId, UUID.Zero);
if (item != null)
{
llsdReply.items.Array.Add(ConvertInventoryItem(item));
}
else
{
AccountItemFetchFailure(itemId);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS/FETCH INVENTORY HANDLER] Could not retrieve requested inventory item {0} for {1}: {2}",
itemId, m_Caps.AgentID, e);
AccountItemFetchFailure(itemId);
}
}
reply = LLSDHelpers.SerialiseLLSDReply(llsdReply);
return reply;
}
public string FetchLibraryRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// m_log.DebugFormat("[FETCH LIBRARY HANDLER]: Received FetchInventory capabilty request");
OSDMap requestmap = (OSDMap)OSDParser.DeserializeLLSDXml(Utils.StringToBytes(request));
OSDArray itemsRequested = (OSDArray)requestmap["items"];
string reply;
LLSDFetchInventory llsdReply = new LLSDFetchInventory();
foreach (OSDMap osdItemId in itemsRequested)
{
UUID itemId = osdItemId["item_id"].AsUUID();
try
{
InventoryItemBase item = m_libraryFolder.FindItem(itemId);
if (item != null)
{
llsdReply.agent_id = item.Owner;
llsdReply.items.Array.Add(ConvertInventoryItem(item));
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/FETCH LIBRARY HANDLER] Could not retrieve requested library item {0} for {1}: {2}",
itemId, m_Caps.AgentID, e);
}
}
reply = LLSDHelpers.SerialiseLLSDReply(llsdReply);
return reply;
}
/// <summary>
/// Called by the CopyInventoryFromNotecard caps handler.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
public string CopyInventoryFromNotecard(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
Hashtable response = new Hashtable();
response["int_response_code"] = 404;
response["content_type"] = "text/plain";
response["str_response_string"] = "";
IClientAPI client = null;
m_Scene.TryGetClient(m_Caps.AgentID, out client);
if (client == null)
return LLSDHelpers.SerialiseLLSDReply(response);
try
{
OSDMap content = (OSDMap)OSDParser.DeserializeLLSDXml(request);
UUID objectID = content["object-id"].AsUUID();
UUID notecardID = content["notecard-id"].AsUUID();
UUID folderID = content["folder-id"].AsUUID();
UUID itemID = content["item-id"].AsUUID();
// m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, FolderID:{0}, ItemID:{1}, NotecardID:{2}, ObjectID:{3}", folderID, itemID, notecardID, objectID);
InventoryItemBase notecardItem = null;
IInventoryStorage inventoryService = m_inventoryProviderSelector.GetProvider(m_Caps.AgentID);
// Is this an objects task inventory?
if (objectID != UUID.Zero)
{
SceneObjectPart part = m_Scene.GetSceneObjectPart(objectID);
if (part != null)
{
TaskInventoryItem item = part.Inventory.GetInventoryItem(notecardID);
if (m_Scene.Permissions.CanCopyObjectInventory(notecardID, objectID, m_Caps.AgentID))
{
notecardItem = new InventoryItemBase(notecardID, m_agentID) { AssetID = item.AssetID };
}
}
}
// else its in inventory directly
else
{
notecardItem = inventoryService.GetItem(notecardID, UUID.Zero);
}
if ((notecardItem != null) && (notecardItem.Owner == m_agentID))
{
// Lookup up the notecard asset
IAssetCache assetCache = m_Scene.CommsManager.AssetCache;
AssetBase asset = assetCache.GetAsset(notecardItem.AssetID, AssetRequestInfo.InternalRequest());
if (asset != null)
{
AssetNotecard notecardAsset = new AssetNotecard(UUID.Zero, asset.Data);
notecardAsset.Decode();
InventoryItemBase item = null;
foreach (InventoryItem notecardObjectItem in notecardAsset.EmbeddedItems)
{
if (notecardObjectItem.UUID == itemID)
{
item = new InventoryItemBase(UUID.Random(), m_Caps.AgentID);
item.CreatorId = notecardObjectItem.CreatorID.ToString();
item.CreationDate = Util.UnixTimeSinceEpoch();
item.GroupID = notecardObjectItem.GroupID;
item.AssetID = notecardObjectItem.AssetUUID;
item.Name = notecardObjectItem.Name;
item.Description = notecardObjectItem.Description;
item.AssetType = (int)notecardObjectItem.AssetType;
item.InvType = (int)notecardObjectItem.InventoryType;
item.Folder = folderID;
//item.BasePermissions = (uint)notecardObjectItem.Permissions.BaseMask;
item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.CurrentPermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.GroupPermissions = (uint)PermissionMask.None;
item.EveryOnePermissions = (uint)PermissionMask.None;
item.NextPermissions = (uint)PermissionMask.All;
break;
}
}
if (item != null)
{
m_Scene.AddInventoryItem(m_Caps.AgentID, item);
// m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0}, FolderID:{1}", copyItem.ID, copyItem.Folder);
client.SendInventoryItemCreateUpdate(item,0);
response["int_response_code"] = 200;
return LLSDHelpers.SerialiseLLSDReply(response);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard : {0}", e.ToString());
}
// Failure case
client.SendAlertMessage("Failed to retrieve item");
return LLSDHelpers.SerialiseLLSDReply(response);
}
public string CreateInventoryCategory(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
Hashtable response = new Hashtable();
response["int_response_code"] = 404;
response["content_type"] = "text/plain";
response["str_response_string"] = "";
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(request);
UUID folder_id = map["folder_id"].AsUUID();
UUID parent_id = map["parent_id"].AsUUID();
int type = map["type"].AsInteger();
string name = map["name"].AsString();
try
{
UUID newFolderId = UUID.Random();
InventoryFolderBase newFolder =
new InventoryFolderBase(newFolderId, name, m_Caps.AgentID, (short)type, parent_id, 1);
m_checkedStorageProvider.CreateFolder(m_Caps.AgentID, newFolder);
OSDMap resp = new OSDMap();
resp["folder_id"] = folder_id;
resp["parent_id"] = parent_id;
resp["type"] = type;
resp["name"] = name;
response["int_response_code"] = 200;
response["str_response_string"] = OSDParser.SerializeLLSDXmlString(resp);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[CAPS/INVENTORY] Could not create requested folder {0} in parent {1}: {2}", folder_id, m_Caps.AgentID, e);
}
return LLSDHelpers.SerialiseLLSDReply(response);
}
/// <summary>
/// Convert an internal inventory item object into an LLSD object.
/// </summary>
/// <param name="invItem"></param>
/// <returns></returns>
private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem)
{
LLSDInventoryItem llsdItem = new LLSDInventoryItem();
llsdItem.asset_id = invItem.AssetID;
llsdItem.created_at = invItem.CreationDate;
llsdItem.desc = invItem.Description;
llsdItem.flags = (int)invItem.Flags;
llsdItem.item_id = invItem.ID;
llsdItem.name = invItem.Name;
llsdItem.parent_id = invItem.Folder;
llsdItem.type = invItem.AssetType;
llsdItem.inv_type = invItem.InvType;
llsdItem.permissions = new LLSDPermissions();
llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid;
llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions;
llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions;
llsdItem.permissions.group_id = invItem.GroupID;
llsdItem.permissions.group_mask = (int)invItem.GroupPermissions;
llsdItem.permissions.is_owner_group = invItem.GroupOwned;
llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions;
llsdItem.permissions.owner_id = invItem.Owner;
llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions;
llsdItem.sale_info = new LLSDSaleInfo();
llsdItem.sale_info.sale_price = invItem.SalePrice;
llsdItem.sale_info.sale_type = invItem.SaleType;
return llsdItem;
}
public class AssetUploader
{
public event UpLoadedAsset OnUpLoad;
private UpLoadedAsset handlerUpLoad = null;
private string uploaderPath = String.Empty;
private UUID newAssetID;
private UUID inventoryItemID;
private UUID parentFolder;
private IHttpServer httpListener;
private string m_assetName = String.Empty;
private string m_assetDes = String.Empty;
private string m_invType = String.Empty;
private string m_assetType = String.Empty;
public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
UUID parentFolderID, string invType, string assetType, string path,
IHttpServer httpServer)
{
m_assetName = assetName;
m_assetDes = description;
newAssetID = assetID;
inventoryItemID = inventoryItem;
uploaderPath = path;
httpListener = httpServer;
parentFolder = parentFolderID;
m_assetType = assetType;
m_invType = invType;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
UUID inv = inventoryItemID;
string res = String.Empty;
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = newAssetID.ToString();
uploadComplete.new_inventory_item = inv;
uploadComplete.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
httpListener.RemoveStreamHandler("POST", uploaderPath);
handlerUpLoad = OnUpLoad;
if (handlerUpLoad != null)
{
handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
}
return res;
}
}
/// <summary>
/// This class is a callback invoked when a client sends asset data to
/// an agent inventory notecard update url
/// </summary>
public class ItemUpdater
{
public event UpdateItem OnUpLoad;
private UpdateItem handlerUpdateItem = null;
private string uploaderPath = String.Empty;
private UUID inventoryItemID;
private IHttpServer httpListener;
public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer)
{
inventoryItemID = inventoryItem;
uploaderPath = path;
httpListener = httpServer;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
UUID inv = inventoryItemID;
string res = String.Empty;
UpdateItemResponse response = new UpdateItemResponse();
handlerUpdateItem = OnUpLoad;
if (handlerUpdateItem != null)
{
response = handlerUpdateItem(inv, data);
}
if (response.AssetKind == AssetType.LSLText)
{
if (response.SaveErrors != null && response.SaveErrors.Count > 0)
{
LLSDScriptCompileFail compFail = new LLSDScriptCompileFail();
compFail.new_asset = response.AssetId.ToString();
compFail.new_inventory_item = inv;
compFail.state = "complete";
foreach (string str in response.SaveErrors)
{
compFail.errors.Array.Add(str);
}
res = LLSDHelpers.SerialiseLLSDReply(compFail);
}
else
{
LLSDScriptCompileSuccess compSuccess = new LLSDScriptCompileSuccess();
compSuccess.new_asset = response.AssetId.ToString();
compSuccess.new_inventory_item = inv;
compSuccess.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(compSuccess);
}
}
else
{
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = response.AssetId.ToString();
uploadComplete.new_inventory_item = inv;
uploadComplete.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
}
httpListener.RemoveStreamHandler("POST", uploaderPath);
return res;
}
}
}
/// <summary>
/// This class is a callback invoked when a client sends asset data to
/// a task inventory script update url
/// </summary>
protected class TaskInventoryScriptUpdater
{
public event UpdateTaskScript OnUpLoad;
private UpdateTaskScript handlerUpdateTaskScript = null;
private string uploaderPath = String.Empty;
private UUID inventoryItemID;
private UUID primID;
private bool isScriptRunning;
private IHttpServer httpListener;
public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
string path, IHttpServer httpServer)
{
this.inventoryItemID = inventoryItemID;
this.primID = primID;
// This comes in over the packet as an integer, but actually appears to be treated as a bool
this.isScriptRunning = (0 == isScriptRunning ? false : true);
uploaderPath = path;
httpListener = httpServer;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <returns></returns>
public string uploaderCaps(byte[] data, string path, string param)
{
try
{
// m_log.InfoFormat("[CAPS]: " +
// "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
// data, path, param));
string res = String.Empty;
UpdateItemResponse response = new UpdateItemResponse();
handlerUpdateTaskScript = OnUpLoad;
if (handlerUpdateTaskScript != null)
{
response = handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data);
}
if (response.AssetKind == AssetType.LSLText)
{
if (response.SaveErrors != null && response.SaveErrors.Count > 0)
{
LLSDScriptCompileFail compFail = new LLSDScriptCompileFail();
compFail.new_asset = response.AssetId.ToString();
compFail.state = "complete";
foreach (string str in response.SaveErrors)
{
compFail.errors.Array.Add(str);
}
res = LLSDHelpers.SerialiseLLSDReply(compFail);
}
else
{
LLSDScriptCompileSuccess compSuccess = new LLSDScriptCompileSuccess();
compSuccess.new_asset = response.AssetId.ToString();
compSuccess.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(compSuccess);
}
}
else
{
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = response.AssetId.ToString();
uploadComplete.state = "complete";
res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
}
httpListener.RemoveStreamHandler("POST", uploaderPath);
// m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
return res;
}
catch (Exception e)
{
m_log.Error("[CAPS]: " + e.ToString());
}
// XXX Maybe this should be some meaningful error packet
return null;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.POIFS.Common;
using NPOI.POIFS.FileSystem;
using System;
using System.Collections.Generic;
using System.IO;
using NPOI.Util;
namespace NPOI.POIFS.FileSystem
{
/**
* This handles Reading and writing a stream within a
* {@link NPOIFSFileSystem}. It can supply an iterator
* to read blocks, and way to write out to existing and
* new blocks.
* Most users will want a higher level version of this,
* which deals with properties to track which stream
* this is.
* This only works on big block streams, it doesn't
* handle small block ones.
* This uses the new NIO code
*
* TODO Implement a streaming write method, and append
*/
public class NPOIFSStream : IEnumerable<ByteBuffer>
{
private BlockStore blockStore;
private int startBlock;
private MemoryStream outStream;
/**
* Constructor for an existing stream. It's up to you
* to know how to Get the start block (eg from a
* {@link HeaderBlock} or a {@link Property})
*/
public NPOIFSStream(BlockStore blockStore, int startBlock)
{
this.blockStore = blockStore;
this.startBlock = startBlock;
}
/**
* Constructor for a new stream. A start block won't
* be allocated until you begin writing to it.
*/
public NPOIFSStream(BlockStore blockStore)
{
this.blockStore = blockStore;
this.startBlock = POIFSConstants.END_OF_CHAIN;
}
/**
* What block does this stream start at?
* Will be {@link POIFSConstants#END_OF_CHAIN} for a
* new stream that hasn't been written to yet.
*/
public int GetStartBlock()
{
return startBlock;
}
#region IEnumerable<byte[]> Members
//public IEnumerator<byte[]> GetEnumerator()
public IEnumerator<ByteBuffer> GetEnumerator()
{
return GetBlockIterator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetBlockIterator();
}
#endregion
/**
* Returns an iterator that'll supply one {@link ByteBuffer}
* per block in the stream.
*/
public IEnumerator<ByteBuffer> GetBlockIterator()
{
if (startBlock == POIFSConstants.END_OF_CHAIN)
{
throw new InvalidOperationException(
"Can't read from a new stream before it has been written to"
);
}
return new StreamBlockByteBufferIterator(this, startBlock);
}
/**
* Updates the contents of the stream to the new
* Set of bytes.
* Note - if this is property based, you'll still
* need to update the size in the property yourself
*/
public void UpdateContents(byte[] contents)
{
Stream os = GetOutputStream();
os.Write(contents, 0, contents.Length);
os.Close();
}
public Stream GetOutputStream()
{
if (outStream == null)
{
outStream = new StreamBlockByteBuffer(this);
}
return outStream;
}
// TODO Streaming write support
// TODO then convert fixed sized write to use streaming internally
// TODO Append write support (probably streaming)
/**
* Frees all blocks in the stream
*/
public void Free()
{
ChainLoopDetector loopDetector = blockStore.GetChainLoopDetector();
Free(loopDetector);
}
internal void Free(ChainLoopDetector loopDetector)
{
int nextBlock = startBlock;
while (nextBlock != POIFSConstants.END_OF_CHAIN)
{
int thisBlock = nextBlock;
loopDetector.Claim(thisBlock);
nextBlock = blockStore.GetNextBlock(thisBlock);
blockStore.SetNextBlock(thisBlock, POIFSConstants.UNUSED_BLOCK);
}
this.startBlock = POIFSConstants.END_OF_CHAIN;
}
/*
* Class that handles a streaming read of one stream
*/
public class StreamBlockByteBuffer : MemoryStream
{
byte[] oneByte = new byte[1];
ByteBuffer buffer;
// Make sure we don't encounter a loop whilst overwriting
// the existing blocks
ChainLoopDetector loopDetector;
int prevBlock, nextBlock;
NPOIFSStream pStream;
protected internal StreamBlockByteBuffer(NPOIFSStream pStream)
{
this.pStream = pStream;
loopDetector = pStream.blockStore.GetChainLoopDetector();
prevBlock = POIFSConstants.END_OF_CHAIN;
nextBlock = pStream.startBlock;
}
protected void CreateBlockIfNeeded()
{
if (buffer != null && buffer.HasRemaining()) return;
int thisBlock = nextBlock;
// Allocate a block if needed, otherwise figure
// out what the next block will be
if (thisBlock == POIFSConstants.END_OF_CHAIN)
{
thisBlock = pStream.blockStore.GetFreeBlock();
loopDetector.Claim(thisBlock);
// We're on the end of the chain
nextBlock = POIFSConstants.END_OF_CHAIN;
// Mark the previous block as carrying on to us if needed
if (prevBlock != POIFSConstants.END_OF_CHAIN)
{
pStream.blockStore.SetNextBlock(prevBlock, thisBlock);
}
pStream.blockStore.SetNextBlock(thisBlock, POIFSConstants.END_OF_CHAIN);
// If we've just written the first block on a
// new stream, save the start block offset
if (pStream.startBlock == POIFSConstants.END_OF_CHAIN)
{
pStream.startBlock = thisBlock;
}
}
else
{
loopDetector.Claim(thisBlock);
nextBlock = pStream.blockStore.GetNextBlock(thisBlock);
}
buffer = pStream.blockStore.CreateBlockIfNeeded(thisBlock);
// Update pointers
prevBlock = thisBlock;
}
public void Write(int b)
{
oneByte[0] = (byte)(b & 0xFF);
base.Write(oneByte, 0, oneByte.Length);
}
public override void Write(byte[] b, int off, int len)
{
if ((off < 0) || (off > b.Length) || (len < 0) ||
((off + len) > b.Length) || ((off + len) < 0))
{
throw new IndexOutOfRangeException();
}
else if (len == 0)
{
return;
}
do
{
CreateBlockIfNeeded();
int writeBytes = Math.Min(buffer.Remaining(), len);
buffer.Write(b, off, writeBytes);
off += writeBytes;
len -= writeBytes;
} while (len > 0);
}
public override void Close()
{
// If we're overwriting, free any remaining blocks
NPOIFSStream toFree = new NPOIFSStream(pStream.blockStore, nextBlock);
toFree.Free(loopDetector);
// Mark the end of the stream
pStream.blockStore.SetNextBlock(prevBlock, POIFSConstants.END_OF_CHAIN);
base.Close();
}
}
public class StreamBlockByteBufferIterator : IEnumerator<ByteBuffer>
{
private ChainLoopDetector loopDetector;
private int nextBlock;
//private BlockStore blockStore;
private ByteBuffer current;
private NPOIFSStream pStream;
public StreamBlockByteBufferIterator(NPOIFSStream pStream, int firstBlock)
{
this.pStream = pStream;
this.nextBlock = firstBlock;
try
{
this.loopDetector = pStream.blockStore.GetChainLoopDetector();
}
catch (IOException e)
{
//throw new System.RuntimeException(e);
throw new Exception(e.Message);
}
}
public bool HasNext()
{
if (nextBlock == POIFSConstants.END_OF_CHAIN)
{
return false;
}
return true;
}
public ByteBuffer Next()
{
if (nextBlock == POIFSConstants.END_OF_CHAIN)
{
throw new IndexOutOfRangeException("Can't read past the end of the stream");
}
try
{
loopDetector.Claim(nextBlock);
//byte[] data = blockStore.GetBlockAt(nextBlock);
ByteBuffer data = pStream.blockStore.GetBlockAt(nextBlock);
nextBlock = pStream.blockStore.GetNextBlock(nextBlock);
return data;
}
catch (IOException e)
{
throw new RuntimeException(e.Message);
}
}
public void Remove()
{
//throw new UnsupportedOperationException();
throw new NotImplementedException("Unsupported Operations!");
}
public ByteBuffer Current
{
get { return current; }
}
Object System.Collections.IEnumerator.Current
{
get { return current; }
}
void System.Collections.IEnumerator.Reset()
{
throw new NotImplementedException();
}
bool System.Collections.IEnumerator.MoveNext()
{
if (nextBlock == POIFSConstants.END_OF_CHAIN)
{
return false;
}
try
{
loopDetector.Claim(nextBlock);
// byte[] data = blockStore.GetBlockAt(nextBlock);
current = pStream.blockStore.GetBlockAt(nextBlock);
nextBlock = pStream.blockStore.GetNextBlock(nextBlock);
return true;
}
catch (IOException)
{
return false;
}
}
public void Dispose()
{
}
}
}
//public class StreamBlockByteBufferIterator : IEnumerator<byte[]>
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Cluster
{
using System;
/// <summary>
/// Represents runtime information of a cluster. Apart from obvious
/// statistical value, this information is used for implementation of
/// load balancing, failover, and collision SPIs. For example, collision SPI
/// in combination with fail-over SPI could check if other nodes don't have
/// any active or waiting jobs and fail-over some jobs to those nodes.
/// <para />
/// Node metrics for any node can be accessed via <see cref="IClusterNode.Metrics()"/>
/// method. Keep in mind that there will be a certain network delay (usually
/// equal to heartbeat delay) for the accuracy of node metrics. However, when accessing
/// metrics on local node the metrics are always accurate and up to date.
/// </summary>
public interface IClusterMetrics
{
/// <summary>
/// Last update time of this node metrics.
/// </summary>
DateTime LastUpdateTime
{
get;
}
/// <summary>
/// Maximum number of jobs that ever ran concurrently on this node.
/// </summary>
int MaximumActiveJobs
{
get;
}
/// <summary>
/// Number of currently active jobs concurrently executing on the node.
/// </summary>
int CurrentActiveJobs
{
get;
}
/// <summary>
/// Average number of active jobs.
/// </summary>
float AverageActiveJobs
{
get;
}
/// <summary>
/// Maximum number of waiting jobs.
/// </summary>
int MaximumWaitingJobs
{
get;
}
/// <summary>
/// Number of queued jobs currently waiting to be executed.
/// </summary>
int CurrentWaitingJobs
{
get;
}
/// <summary>
/// Average number of waiting jobs.
/// </summary>
float AverageWaitingJobs
{
get;
}
/// <summary>
/// Maximum number of jobs rejected at once.
/// </summary>
int MaximumRejectedJobs
{
get;
}
/// <summary>
/// Number of jobs rejected after more recent collision resolution operation.
/// </summary>
int CurrentRejectedJobs
{
get;
}
/// <summary>
/// Average number of jobs this node rejects during collision resolution operations.
/// </summary>
float AverageRejectedJobs
{
get;
}
/// <summary>
/// Total number of jobs this node rejects during collision resolution operations since node startup.
/// </summary>
int TotalRejectedJobs
{
get;
}
/// <summary>
/// Maximum number of cancelled jobs ever had running concurrently.
/// </summary>
int MaximumCancelledJobs
{
get;
}
/// <summary>
/// Number of cancelled jobs that are still running.
/// </summary>
int CurrentCancelledJobs
{
get;
}
/// <summary>
/// Average number of cancelled jobs.
/// </summary>
float AverageCancelledJobs
{
get;
}
/// <summary>
/// Total number of cancelled jobs since node startup.
/// </summary>
int TotalCancelledJobs
{
get;
}
/// <summary>
/// Total number of jobs handled by the node since node startup.
/// </summary>
int TotalExecutedJobs
{
get;
}
/// <summary>
/// Maximum time a job ever spent waiting in a queue to be executed.
/// </summary>
long MaximumJobWaitTime
{
get;
}
/// <summary>
/// Current time an oldest jobs has spent waiting to be executed.
/// </summary>
long CurrentJobWaitTime
{
get;
}
/// <summary>
/// Average time jobs spend waiting in the queue to be executed.
/// </summary>
double AverageJobWaitTime
{
get;
}
/// <summary>
/// Time it took to execute the longest job on the node.
/// </summary>
long MaximumJobExecuteTime
{
get;
}
/// <summary>
/// Longest time a current job has been executing for.
/// </summary>
long CurrentJobExecuteTime
{
get;
}
/// <summary>
/// Average job execution time.
/// </summary>
double AverageJobExecuteTime
{
get;
}
/// <summary>
/// Total number of jobs handled by the node.
/// </summary>
int TotalExecutedTasks
{
get;
}
/// <summary>
/// Total time this node spent executing jobs.
/// </summary>
long TotalBusyTime
{
get;
}
/// <summary>
/// Total time this node spent idling.
/// </summary>
long TotalIdleTime
{
get;
}
/// <summary>
/// Time this node spend idling since executing last job.
/// </summary>
long CurrentIdleTime
{
get;
}
/// <summary>
/// Percentage of time this node is busy.
/// </summary>
float BusyTimePercentage
{
get;
}
/// <summary>
/// Percentage of time this node is idle
/// </summary>
float IdleTimePercentage
{
get;
}
/// <summary>
/// Returns the number of CPUs available to the Java Virtual Machine.
/// </summary>
int TotalCpus
{
get;
}
/// <summary>
/// Returns the CPU usage usage in [0, 1] range.
/// </summary>
double CurrentCpuLoad
{
get;
}
/// <summary>
/// Average of CPU load values in [0, 1] range over all metrics kept in the history.
/// </summary>
double AverageCpuLoad
{
get;
}
/// <summary>
/// Average time spent in CG since the last update.
/// </summary>
double CurrentGcCpuLoad
{
get;
}
/// <summary>
/// Amount of heap memory in bytes that the JVM
/// initially requests from the operating system for memory management.
/// This method returns <code>-1</code> if the initial memory size is undefined.
/// <para />
/// This value represents a setting of the heap memory for Java VM and is
/// not a sum of all initial heap values for all memory pools.
/// </summary>
long HeapMemoryInitialized
{
get;
}
/// <summary>
/// Current heap size that is used for object allocation.
/// The heap consists of one or more memory pools. This value is
/// the sum of used heap memory values of all heap memory pools.
/// <para />
/// The amount of used memory in the returned is the amount of memory
/// occupied by both live objects and garbage objects that have not
/// been collected, if any.
/// </summary>
long HeapMemoryUsed
{
get;
}
/// <summary>
/// Amount of heap memory in bytes that is committed for the JVM to use. This amount of memory is
/// guaranteed for the JVM to use. The heap consists of one or more memory pools. This value is
/// the sum of committed heap memory values of all heap memory pools.
/// </summary>
long HeapMemoryCommitted
{
get;
}
/// <summary>
/// Mmaximum amount of heap memory in bytes that can be used for memory management.
/// This method returns <code>-1</code> if the maximum memory size is undefined.
/// <para />
/// This amount of memory is not guaranteed to be available for memory management if
/// it is greater than the amount of committed memory. The JVM may fail to allocate
/// memory even if the amount of used memory does not exceed this maximum size.
/// <para />
/// This value represents a setting of the heap memory for Java VM and is
/// not a sum of all initial heap values for all memory pools.
/// </summary>
long HeapMemoryMaximum
{
get;
}
/// <summary>
/// Total amount of heap memory in bytes. This method returns <code>-1</code>
/// if the total memory size is undefined.
/// <para />
/// This amount of memory is not guaranteed to be available for memory management if it is
/// greater than the amount of committed memory. The JVM may fail to allocate memory even
/// if the amount of used memory does not exceed this maximum size.
/// <para />
/// This value represents a setting of the heap memory for Java VM and is
/// not a sum of all initial heap values for all memory pools.
/// </summary>
long HeapMemoryTotal
{
get;
}
/// <summary>
/// Amount of non-heap memory in bytes that the JVM initially requests from the operating
/// system for memory management.
/// </summary>
long NonHeapMemoryInitialized
{
get;
}
/// <summary>
/// Current non-heap memory size that is used by Java VM.
/// </summary>
long NonHeapMemoryUsed
{
get;
}
/// <summary>
/// Amount of non-heap memory in bytes that is committed for the JVM to use.
/// </summary>
long NonHeapMemoryCommitted
{
get;
}
/// <summary>
/// Maximum amount of non-heap memory in bytes that can be used for memory management.
/// </summary>
long NonHeapMemoryMaximum
{
get;
}
/// <summary>
/// Total amount of non-heap memory in bytes that can be used for memory management.
/// </summary>
long NonHeapMemoryTotal
{
get;
}
/// <summary>
/// Uptime of the JVM in milliseconds.
/// </summary>
long UpTime
{
get;
}
/// <summary>
/// Start time of the JVM in milliseconds.
/// </summary>
DateTime StartTime
{
get;
}
/// <summary>
/// Start time of the Ignite node in milliseconds.
/// </summary>
DateTime NodeStartTime
{
get;
}
/// <summary>
/// Current number of live threads.
/// </summary>
int CurrentThreadCount
{
get;
}
/// <summary>
/// The peak live thread count.
/// </summary>
int MaximumThreadCount
{
get;
}
/// <summary>
/// The total number of threads started.
/// </summary>
long TotalStartedThreadCount
{
get;
}
/// <summary>
/// Current number of live daemon threads.
/// </summary>
int CurrentDaemonThreadCount
{
get;
}
/// <summary>
/// Ignite assigns incremental versions to all cache operations. This property provides
/// the latest data version on the node.
/// </summary>
long LastDataVersion
{
get;
}
/// <summary>
/// Sent messages count
/// </summary>
int SentMessagesCount
{
get;
}
/// <summary>
/// Sent bytes count.
/// </summary>
long SentBytesCount
{
get;
}
/// <summary>
/// Received messages count.
/// </summary>
int ReceivedMessagesCount
{
get;
}
/// <summary>
/// Received bytes count.
/// </summary>
long ReceivedBytesCount
{
get;
}
/// <summary>
/// Outbound messages queue size.
/// </summary>
int OutboundMessagesQueueSize
{
get;
}
/// <summary>
/// Gets total number of nodes.
/// </summary>
int TotalNodes
{
get;
}
}
}
| |
// ------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------
namespace Amqp
{
using System;
using System.Threading;
using Amqp.Framing;
using Amqp.Sasl;
using Amqp.Types;
/// <summary>
/// The callback that is invoked when an open frame is received from peer.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="open">The received open frame.</param>
public delegate void OnOpened(Connection connection, Open open);
/// <summary>
/// The Connection class represents an AMQP connection.
/// </summary>
public class Connection : AmqpObject
{
enum State
{
Start,
HeaderSent,
OpenPipe,
OpenClosePipe,
HeaderReceived,
HeaderExchanged,
OpenSent,
OpenReceived,
Opened,
CloseReceived,
ClosePipe,
CloseSent,
End
}
/// <summary>
/// A flag to disable server certificate validation when TLS is used.
/// </summary>
public static bool DisableServerCertValidation;
internal const uint DefaultMaxFrameSize = 256 * 1024;
internal const ushort DefaultMaxSessions = 256;
internal const int DefaultMaxLinksPerSession = 64;
const uint MaxIdleTimeout = 30 * 60 * 1000;
static readonly TimerCallback onHeartBeatTimer = OnHeartBeatTimer;
readonly Address address;
readonly OnOpened onOpened;
Session[] localSessions;
Session[] remoteSessions;
ushort channelMax;
State state;
ITransport transport;
uint maxFrameSize;
Pump reader;
Timer heartBeatTimer;
Connection(ushort channelMax, uint maxFrameSize)
{
this.channelMax = channelMax;
this.maxFrameSize = maxFrameSize;
this.localSessions = new Session[1];
this.remoteSessions = new Session[1];
}
/// <summary>
/// Initializes a connection from the address.
/// </summary>
/// <param name="address">The address.</param>
/// <remarks>
/// The connection initialization includes establishing the underlying transport,
/// which typically has blocking network I/O. Depending on the current synchronization
/// context, it may cause deadlock or UI freeze. Please use the ConnectionFactory.CreateAsync
/// method instead.
/// </remarks>
public Connection(Address address)
: this(address, null, null, null)
{
}
/// <summary>
/// Initializes a connection with SASL profile, open and open callback.
/// </summary>
/// <param name="address">The address.</param>
/// <param name="saslProfile">The SASL profile to do authentication (optional). If it is
/// null and address has user info, SASL PLAIN profile is used.</param>
/// <param name="open">The open frame to send (optional). If not null, all mandatory
/// fields must be set. Ensure that other fields are set to desired values.</param>
/// <param name="onOpened">The callback to handle remote open frame (optional).</param>
/// <remarks>
/// The connection initialization includes establishing the underlying transport,
/// which typically has blocking network I/O. Depending on the current synchronization
/// context, it may cause deadlock or UI freeze. Please use the ConnectionFactory.CreateAsync
/// method instead.
/// </remarks>
public Connection(Address address, SaslProfile saslProfile, Open open, OnOpened onOpened)
: this(DefaultMaxSessions, DefaultMaxFrameSize)
{
this.address = address;
this.onOpened = onOpened;
if (open != null)
{
this.maxFrameSize = open.MaxFrameSize;
this.channelMax = open.ChannelMax;
}
else
{
open = new Open()
{
ContainerId = Guid.NewGuid().ToString(),
HostName = this.address.Host,
MaxFrameSize = this.maxFrameSize,
ChannelMax = this.channelMax
};
}
this.Connect(saslProfile, open);
}
object ThisLock
{
get { return this; }
}
internal Connection(IBufferManager bufferManager, AmqpSettings amqpSettings, Address address,
IAsyncTransport transport, Open open, OnOpened onOpened)
: this((ushort)(amqpSettings.MaxSessionsPerConnection - 1), (uint)amqpSettings.MaxFrameSize)
{
this.BufferManager = bufferManager;
this.MaxLinksPerSession = amqpSettings.MaxLinksPerSession;
this.address = address;
this.onOpened = onOpened;
this.transport = transport;
transport.SetConnection(this);
// after getting the transport, move state to open pipe before starting the pump
if (open == null)
{
open = new Open()
{
ContainerId = amqpSettings.ContainerId,
HostName = amqpSettings.HostName ?? this.address.Host,
ChannelMax = this.channelMax,
MaxFrameSize = this.maxFrameSize
};
}
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
}
/// <summary>
/// Gets a factory with default settings.
/// </summary>
public static ConnectionFactory Factory
{
get { return new ConnectionFactory(); }
}
internal IBufferManager BufferManager
{
get;
private set;
}
internal int MaxLinksPerSession;
ByteBuffer AllocateBuffer(int size)
{
return this.BufferManager.GetByteBuffer(size);
}
ByteBuffer WrapBuffer(ByteBuffer buffer, int offset, int length)
{
return new WrappedByteBuffer(buffer, offset, length);
}
internal ushort AddSession(Session session)
{
this.ThrowIfClosed("AddSession");
lock (this.ThisLock)
{
int count = this.localSessions.Length;
for (int i = 0; i < count; ++i)
{
if (this.localSessions[i] == null)
{
this.localSessions[i] = session;
return (ushort)i;
}
}
if (count - 1 < this.channelMax)
{
int size = Math.Min(count * 2, this.channelMax + 1);
Session[] expanded = new Session[size];
Array.Copy(this.localSessions, expanded, count);
this.localSessions = expanded;
this.localSessions[count] = session;
return (ushort)count;
}
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax));
}
}
internal void SendCommand(ushort channel, DescribedList command)
{
this.ThrowIfClosed("Send");
ByteBuffer buffer = this.AllocateBuffer(Frame.CmdBufferSize);
Frame.Encode(buffer, FrameType.Amqp, channel, command);
this.transport.Send(buffer);
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1}", channel, command);
}
internal int SendCommand(ushort channel, Transfer transfer, bool first, ByteBuffer payload, int reservedBytes)
{
this.ThrowIfClosed("Send");
ByteBuffer buffer = this.AllocateBuffer(Frame.CmdBufferSize);
Frame.Encode(buffer, FrameType.Amqp, channel, transfer);
int payloadSize = payload.Length;
int frameSize = buffer.Length + payloadSize;
bool more = frameSize > this.maxFrameSize;
if (more)
{
transfer.More = true;
buffer.Reset();
Frame.Encode(buffer, FrameType.Amqp, channel, transfer);
frameSize = (int)this.maxFrameSize;
payloadSize = frameSize - buffer.Length;
}
AmqpBitConverter.WriteInt(buffer.Buffer, buffer.Offset, frameSize);
ByteBuffer frameBuffer;
if (first && !more && reservedBytes >= buffer.Length)
{
// optimize for most common case: single-transfer message
frameBuffer = this.WrapBuffer(payload, payload.Offset - buffer.Length, frameSize);
Array.Copy(buffer.Buffer, buffer.Offset, frameBuffer.Buffer, frameBuffer.Offset, buffer.Length);
buffer.ReleaseReference();
}
else
{
AmqpBitConverter.WriteBytes(buffer, payload.Buffer, payload.Offset, payloadSize);
frameBuffer = buffer;
}
payload.Complete(payloadSize);
this.transport.Send(frameBuffer);
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1} payload {2}", channel, transfer, payloadSize);
return payloadSize;
}
/// <summary>
/// Closes the connection.
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
protected override bool OnClose(Error error)
{
lock (this.ThisLock)
{
State newState = State.Start;
if (this.state == State.OpenPipe )
{
newState = State.OpenClosePipe;
}
else if (state == State.OpenSent)
{
newState = State.ClosePipe;
}
else if (this.state == State.Opened)
{
newState = State.CloseSent;
}
else if (this.state == State.CloseReceived)
{
newState = State.End;
}
else if (this.state == State.End)
{
return true;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "Close", this.state));
}
this.SendClose(error);
this.state = newState;
return this.state == State.End;
}
}
static void OnHeartBeatTimer(object state)
{
var thisPtr = (Connection)state;
byte[] frame = new byte[] { 0, 0, 0, 8, 2, 0, 0, 0 };
thisPtr.transport.Send(new ByteBuffer(frame, 0, frame.Length, frame.Length));
Trace.WriteLine(TraceLevel.Frame, "SEND (ch=0) empty");
}
void Connect(SaslProfile saslProfile, Open open)
{
ITransport transport;
#if NETFX
if (WebSocketTransport.MatchScheme(address.Scheme))
{
WebSocketTransport wsTransport = new WebSocketTransport();
wsTransport.ConnectAsync(address).GetAwaiter().GetResult();
transport = wsTransport;
}
else
#endif
{
TcpTransport tcpTransport = new TcpTransport();
tcpTransport.Connect(this, this.address, DisableServerCertValidation);
transport = tcpTransport;
}
if (saslProfile != null)
{
transport = saslProfile.Open(this.address.Host, transport);
}
else if (this.address.User != null)
{
transport = new SaslPlainProfile(this.address.User, this.address.Password).Open(this.address.Host, transport);
}
this.transport = transport;
// after getting the transport, move state to open pipe before starting the pump
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
this.reader = new Pump(this);
this.reader.Start();
}
void ThrowIfClosed(string operation)
{
if (this.state >= State.ClosePipe)
{
throw new AmqpException(this.Error ??
new Error()
{
Condition = ErrorCode.IllegalState,
Description = Fx.Format(SRAmqp.AmqpIllegalOperationState, operation, this.state)
});
}
}
void SendHeader()
{
byte[] header = new byte[] { (byte)'A', (byte)'M', (byte)'Q', (byte)'P', 0, 1, 0, 0 };
this.transport.Send(new ByteBuffer(header, 0, header.Length, header.Length));
Trace.WriteLine(TraceLevel.Frame, "SEND AMQP 0 1.0.0");
}
void SendOpen(Open open)
{
this.SendCommand(0, open);
}
void SendClose(Error error)
{
this.SendCommand(0, new Close() { Error = error });
}
void OnOpen(Open open)
{
lock (this.ThisLock)
{
if (this.state == State.OpenSent)
{
this.state = State.Opened;
}
else if (this.state == State.ClosePipe)
{
this.state = State.CloseSent;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnOpen", this.state));
}
}
if (open.ChannelMax < this.channelMax)
{
this.channelMax = open.ChannelMax;
}
if (open.MaxFrameSize < this.maxFrameSize)
{
this.maxFrameSize = open.MaxFrameSize;
}
uint idleTimeout = open.IdleTimeOut;
if (idleTimeout > 0 && idleTimeout < uint.MaxValue)
{
idleTimeout -= 3000;
if (idleTimeout > MaxIdleTimeout)
{
idleTimeout = MaxIdleTimeout;
}
this.heartBeatTimer = new Timer(onHeartBeatTimer, this, (int)idleTimeout, (int)idleTimeout);
}
if (this.onOpened != null)
{
this.onOpened(this, open);
}
}
void OnClose(Close close)
{
lock (this.ThisLock)
{
if (this.state == State.Opened)
{
this.SendClose(null);
}
else if (this.state == State.CloseSent)
{
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnClose", this.state));
}
this.state = State.End;
this.OnEnded(close.Error);
}
}
internal virtual void OnBegin(ushort remoteChannel, Begin begin)
{
lock (this.ThisLock)
{
if (remoteChannel > this.channelMax)
{
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax + 1));
}
Session session = this.GetSession(this.localSessions, begin.RemoteChannel);
session.OnBegin(remoteChannel, begin);
int count = this.remoteSessions.Length;
if (count - 1 < remoteChannel)
{
int size = Math.Min(count * 2, this.channelMax + 1);
Session[] expanded = new Session[size];
Array.Copy(this.remoteSessions, expanded, count);
this.remoteSessions = expanded;
}
var remoteSession = this.remoteSessions[remoteChannel];
if (remoteSession != null)
{
throw new AmqpException(ErrorCode.HandleInUse,
Fx.Format(SRAmqp.AmqpHandleInUse, remoteChannel, remoteSession.GetType().Name));
}
this.remoteSessions[remoteChannel] = session;
}
}
void OnEnd(ushort remoteChannel, End end)
{
Session session = this.GetSession(this.remoteSessions, remoteChannel);
if (session.OnEnd(end))
{
lock (this.ThisLock)
{
this.localSessions[session.Channel] = null;
this.remoteSessions[remoteChannel] = null;
}
}
}
void OnSessionCommand(ushort remoteChannel, DescribedList command, ByteBuffer buffer)
{
this.GetSession(this.remoteSessions, remoteChannel).OnCommand(command, buffer);
}
Session GetSession(Session[] sessions, ushort channel)
{
lock (this.ThisLock)
{
Session session = null;
if (channel < sessions.Length)
{
session = sessions[channel];
}
if (session == null)
{
throw new AmqpException(ErrorCode.NotFound,
Fx.Format(SRAmqp.AmqpChannelNotFound, channel));
}
return session;
}
}
internal bool OnHeader(ProtocolHeader header)
{
Trace.WriteLine(TraceLevel.Frame, "RECV AMQP {0}", header);
lock (this.ThisLock)
{
if (this.state == State.OpenPipe)
{
this.state = State.OpenSent;
}
else if (this.state == State.OpenClosePipe)
{
this.state = State.ClosePipe;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnHeader", this.state));
}
if (header.Major != 1 || header.Minor != 0 || header.Revision != 0)
{
throw new AmqpException(ErrorCode.NotImplemented, header.ToString());
}
}
return true;
}
internal bool OnFrame(ByteBuffer buffer)
{
bool shouldContinue = true;
try
{
ushort channel;
DescribedList command;
Frame.Decode(buffer, out channel, out command);
if (buffer.Length > 0)
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1} payload {2}", channel, command, buffer.Length);
}
else
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1}", channel, command);
}
if (command != null)
{
if (command.Descriptor.Code == Codec.Open.Code)
{
this.OnOpen((Open)command);
}
else if (command.Descriptor.Code == Codec.Close.Code)
{
this.OnClose((Close)command);
shouldContinue = false;
}
else if (command.Descriptor.Code == Codec.Begin.Code)
{
this.OnBegin(channel, (Begin)command);
}
else if (command.Descriptor.Code == Codec.End.Code)
{
this.OnEnd(channel, (End)command);
}
else
{
this.OnSessionCommand(channel, command, buffer);
}
}
}
catch (Exception exception)
{
this.OnException(exception);
shouldContinue = false;
}
return shouldContinue;
}
void OnException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", exception.ToString());
AmqpException amqpException = exception as AmqpException;
Error error = amqpException != null ?
amqpException.Error :
new Error() { Condition = ErrorCode.InternalError, Description = exception.Message };
if (this.state < State.ClosePipe)
{
try
{
this.Close(0, error);
}
catch
{
this.state = State.End;
}
}
else
{
this.state = State.End;
}
if (this.state == State.End)
{
this.OnEnded(error);
}
}
internal void OnIoException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "I/O: {0}", exception.ToString());
if (this.state != State.End)
{
this.state = State.End;
Error error = new Error() { Condition = ErrorCode.ConnectionForced };
this.OnEnded(error);
}
}
void OnEnded(Error error)
{
if (this.heartBeatTimer != null)
{
this.heartBeatTimer.Dispose();
}
if (this.transport != null)
{
this.transport.Close();
}
for (int i = 0; i < this.localSessions.Length; i++)
{
var session = this.localSessions[i];
if (session != null)
{
session.Abort(error);
}
}
this.NotifyClosed(error);
}
sealed class Pump
{
readonly Connection connection;
public Pump(Connection connection)
{
this.connection = connection;
}
public void Start()
{
Fx.StartThread(this.PumpThread);
}
void PumpThread()
{
try
{
ProtocolHeader header = Reader.ReadHeader(this.connection.transport);
this.connection.OnHeader(header);
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
return;
}
byte[] sizeBuffer = new byte[FixedWidth.UInt];
while (sizeBuffer != null && this.connection.state != State.End)
{
try
{
ByteBuffer buffer = Reader.ReadFrameBuffer(this.connection.transport, sizeBuffer, this.connection.maxFrameSize);
if (buffer != null)
{
this.connection.OnFrame(buffer);
}
else
{
sizeBuffer = null;
}
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics; //Assert
using System.IO;
using System.Collections.Generic;
namespace OLEDB.Test.ModuleCore
{
public class CTestModule : CTestBase
{
//Data
private string _clsid;
private CTestCase _curtestcase;
private int _pass = 0;
private int _fail = 0;
private int _skip = 0;
public int PassCount
{
get { return _pass; }
set { _pass = value; }
}
public int FailCount
{
get { return _fail; }
set { _fail = value; }
}
public int SkipCount
{
get { return _skip; }
set { _skip = value; }
}
//Constructors
public CTestModule()
: this(null, "Microsoft", 1)
{
}
public CTestModule(string desc)
: this(desc, "Microsoft", 1)
{
//Delegate
}
public CTestModule(string desc, string owner, int version)
: base(desc)
{
_clsid = GetType().ToString();
//The attribute should take precedence
if (this.Owner == null)
this.Owner = owner;
if (this.Version <= 0)
this.Version = version;
//Population
DetermineIncludes();
DetermineChildren();
DetermineFilters();
}
static CTestModule()
{
}
//Accessors
public new virtual TestModule Attribute
{
get { return (TestModule)base.Attribute; }
set { base.Attribute = value; }
}
public string Owner
{
get { return Attribute.Owner; }
set { Attribute.Owner = value; }
}
public string[] Owners
{
get { return Attribute.Owners; }
set { Attribute.Owners = value; }
}
public int Version
{
get { return Attribute.Version; }
set { Attribute.Version = value; }
}
public string Created
{
get { return Attribute.Created; }
set { Attribute.Created = value; }
}
public string Modified
{
get { return Attribute.Modified; }
set { Attribute.Modified = value; }
}
public override int Init(object o)
{
//Delegate
int result = base.Init(o);
return result;
}
public override int Terminate(object o)
{
//Delegate
return base.Terminate(o);
}
//Helpers
public void AddTestCase(CTestCase testcase)
{
//Delegate
this.AddChild(testcase);
}
public virtual string GetCLSID()
{
return _clsid;
}
public virtual string GetOwnerName()
{
return Attribute.Owner;
}
public virtual int GetVersion()
{
return Attribute.Version;
}
public void SetErrorInterface(IError rIError)
{
//Delegate to our global object
CError.Error = rIError;
CError.WriteLine();
}
public IError GetErrorInterface()
{
//Delegate to our global object
return CError.Error;
}
public int GetCaseCount()
{
return Children.Count;
}
public ITestCases GetCase(int index)
{
return (ITestCases)Children[index];
}
protected override CAttrBase CreateAttribute()
{
return new TestModule();
}
protected override void DetermineChildren()
{
try
{
DetermineTestCases();
}
catch (Exception e)
{
//Make this easier to debug
Console.WriteLine(e);
Common.Assert(false, e.ToString());
throw e;
}
}
public virtual void DetermineTestCases()
{
//Default - no sort
//int idPrev = Int32.MinValue;
bool bSort = false;
//Normally the reflection Type.GetMethods() api returns the methods in order
//of how they appear in the code. But it will change that order depending
//upon if there are virtual functions, which are returned first before other
//non-virtual functions. Then there are also many times were people want multiple
//source files, so its totally up the compiler on how it pulls in the files (*.cs).
//So we have added the support of specifying an id=x, as an attribute so you can have
//then sorted and displayed however your see fit.
if (bSort)
Children.Sort(/*Default sort is based upon IComparable of each item*/);
}
protected virtual void DetermineIncludes()
{
}
protected virtual void DetermineFilters()
{
}
protected virtual string FilterScope(string xpath)
{
//Basically we want to allow either simply filtering at the variation node (i.e.: no scope),
//in which case we'll just add the 'assumed' scope, or allow filtering at any level.
//We also want to be consistent with the XmlDriver in which all filters are predicates only.
string varfilter = "//Variation[{0}]";
if (xpath != null)
{
xpath = xpath.Trim();
if (xpath.Length > 0)
{
//Add the Variation Scope, if no scope was specified
if (xpath[0] != '/')
xpath = string.Format(varfilter, xpath);
}
}
return xpath;
}
public CTestCase CurTestCase
{
//Return the current test case:
//Note: We do this so that within global functions (i.e.: at the module level) the user can
//have know which test case/variation were in, without having to pass this state from
//execute around
get { return _curtestcase; }
set { _curtestcase = value; }
}
public override tagVARIATION_STATUS Execute()
{
List<object> children = Children;
if (children != null && children.Count > 0)
{
// this is not a leaf node, just invoke all the children's execute
foreach (object child in children)
{
CTestCase tc = child as CTestCase;
if (tc != null)
{
if (CModInfo.IsTestCaseSelected(tc.Name))
{
Console.WriteLine("TestCase:{0} - {1}", tc.Attribute.Name, tc.Attribute.Desc);
tc.Init();
tc.Execute();
}
}
}
}
Console.WriteLine("Pass:{0}, Fail:{1}, Skip:{2}", PassCount, FailCount, SkipCount);
return tagVARIATION_STATUS.eVariationStatusPassed;
}
public override IEnumerable<XunitTestCase> TestCases()
{
List<object> children = Children;
if (children != null && children.Count > 0)
{
foreach (object child in children)
{
CTestCase tc = child as CTestCase;
if (tc != null)
{
if (CModInfo.IsTestCaseSelected(tc.Name))
{
tc.Init();
foreach (XunitTestCase testCase in tc.TestCases())
{
yield return testCase;
}
}
}
}
}
}
}
}
| |
using Discord.API;
using Discord.Rest;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
namespace Discord.WebSocket
{
public partial class DiscordShardedClient : BaseSocketClient, IDiscordClient
{
private readonly DiscordSocketConfig _baseConfig;
private readonly Dictionary<int, int> _shardIdsToIndex;
private readonly bool _automaticShards;
private int[] _shardIds;
private DiscordSocketClient[] _shards;
private int _totalShards;
private SemaphoreSlim[] _identifySemaphores;
private object _semaphoreResetLock;
private Task _semaphoreResetTask;
private bool _isDisposed;
/// <inheritdoc />
public override int Latency { get => GetLatency(); protected set { } }
/// <inheritdoc />
public override UserStatus Status { get => _shards[0].Status; protected set { } }
/// <inheritdoc />
public override IActivity Activity { get => _shards[0].Activity; protected set { } }
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
/// <inheritdoc />
public override IReadOnlyCollection<SocketGuild> Guilds => GetGuilds().ToReadOnlyCollection(GetGuildCount);
/// <inheritdoc />
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => GetPrivateChannels().ToReadOnlyCollection(GetPrivateChannelCount);
public IReadOnlyCollection<DiscordSocketClient> Shards => _shards;
/// <inheritdoc />
[Obsolete("This property is obsolete, use the GetVoiceRegionsAsync method instead.")]
public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _shards[0].VoiceRegions;
/// <summary>
/// Provides access to a REST-only client with a shared state from this client.
/// </summary>
public override DiscordSocketRestClient Rest => _shards[0].Rest;
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
public DiscordShardedClient() : this(null, new DiscordSocketConfig()) { }
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
#pragma warning disable IDISP004
public DiscordShardedClient(DiscordSocketConfig config) : this(null, config, CreateApiClient(config)) { }
#pragma warning restore IDISP004
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
public DiscordShardedClient(int[] ids) : this(ids, new DiscordSocketConfig()) { }
/// <summary> Creates a new REST/WebSocket Discord client. </summary>
#pragma warning disable IDISP004
public DiscordShardedClient(int[] ids, DiscordSocketConfig config) : this(ids, config, CreateApiClient(config)) { }
#pragma warning restore IDISP004
private DiscordShardedClient(int[] ids, DiscordSocketConfig config, API.DiscordSocketApiClient client)
: base(config, client)
{
if (config.ShardId != null)
throw new ArgumentException($"{nameof(config.ShardId)} must not be set.");
if (ids != null && config.TotalShards == null)
throw new ArgumentException($"Custom ids are not supported when {nameof(config.TotalShards)} is not specified.");
_semaphoreResetLock = new object();
_shardIdsToIndex = new Dictionary<int, int>();
config.DisplayInitialLog = false;
_baseConfig = config;
if (config.TotalShards == null)
_automaticShards = true;
else
{
_totalShards = config.TotalShards.Value;
_shardIds = ids ?? Enumerable.Range(0, _totalShards).ToArray();
_shards = new DiscordSocketClient[_shardIds.Length];
_identifySemaphores = new SemaphoreSlim[config.IdentifyMaxConcurrency];
for (int i = 0; i < config.IdentifyMaxConcurrency; i++)
_identifySemaphores[i] = new SemaphoreSlim(1, 1);
for (int i = 0; i < _shardIds.Length; i++)
{
_shardIdsToIndex.Add(_shardIds[i], i);
var newConfig = config.Clone();
newConfig.ShardId = _shardIds[i];
_shards[i] = new DiscordSocketClient(newConfig, this, i != 0 ? _shards[0] : null);
RegisterEvents(_shards[i], i == 0);
}
}
}
private static API.DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config)
=> new API.DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent,
rateLimitPrecision: config.RateLimitPrecision);
internal async Task AcquireIdentifyLockAsync(int shardId, CancellationToken token)
{
int semaphoreIdx = shardId % _baseConfig.IdentifyMaxConcurrency;
await _identifySemaphores[semaphoreIdx].WaitAsync(token).ConfigureAwait(false);
}
internal void ReleaseIdentifyLock()
{
lock (_semaphoreResetLock)
{
if (_semaphoreResetTask == null)
_semaphoreResetTask = ResetSemaphoresAsync();
}
}
private async Task ResetSemaphoresAsync()
{
await Task.Delay(5000).ConfigureAwait(false);
lock (_semaphoreResetLock)
{
foreach (var semaphore in _identifySemaphores)
if (semaphore.CurrentCount == 0)
semaphore.Release();
_semaphoreResetTask = null;
}
}
internal override async Task OnLoginAsync(TokenType tokenType, string token)
{
if (_automaticShards)
{
var botGateway = await GetBotGatewayAsync().ConfigureAwait(false);
_shardIds = Enumerable.Range(0, botGateway.Shards).ToArray();
_totalShards = _shardIds.Length;
_shards = new DiscordSocketClient[_shardIds.Length];
int maxConcurrency = botGateway.SessionStartLimit.MaxConcurrency;
_baseConfig.IdentifyMaxConcurrency = maxConcurrency;
_identifySemaphores = new SemaphoreSlim[maxConcurrency];
for (int i = 0; i < maxConcurrency; i++)
_identifySemaphores[i] = new SemaphoreSlim(1, 1);
for (int i = 0; i < _shardIds.Length; i++)
{
_shardIdsToIndex.Add(_shardIds[i], i);
var newConfig = _baseConfig.Clone();
newConfig.ShardId = _shardIds[i];
newConfig.TotalShards = _totalShards;
_shards[i] = new DiscordSocketClient(newConfig, this, i != 0 ? _shards[0] : null);
RegisterEvents(_shards[i], i == 0);
}
}
//Assume thread safe: already in a connection lock
for (int i = 0; i < _shards.Length; i++)
await _shards[i].LoginAsync(tokenType, token);
}
internal override async Task OnLogoutAsync()
{
//Assume thread safe: already in a connection lock
if (_shards != null)
{
for (int i = 0; i < _shards.Length; i++)
await _shards[i].LogoutAsync();
}
CurrentUser = null;
if (_automaticShards)
{
_shardIds = new int[0];
_shardIdsToIndex.Clear();
_totalShards = 0;
_shards = null;
}
}
/// <inheritdoc />
public override async Task StartAsync()
=> await Task.WhenAll(_shards.Select(x => x.StartAsync())).ConfigureAwait(false);
/// <inheritdoc />
public override async Task StopAsync()
=> await Task.WhenAll(_shards.Select(x => x.StopAsync())).ConfigureAwait(false);
public DiscordSocketClient GetShard(int id)
{
if (_shardIdsToIndex.TryGetValue(id, out id))
return _shards[id];
return null;
}
private int GetShardIdFor(ulong guildId)
=> (int)((guildId >> 22) % (uint)_totalShards);
public int GetShardIdFor(IGuild guild)
=> GetShardIdFor(guild?.Id ?? 0);
private DiscordSocketClient GetShardFor(ulong guildId)
=> GetShard(GetShardIdFor(guildId));
public DiscordSocketClient GetShardFor(IGuild guild)
=> GetShardFor(guild?.Id ?? 0);
/// <inheritdoc />
public override async Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
=> await _shards[0].GetApplicationInfoAsync(options).ConfigureAwait(false);
/// <inheritdoc />
public override SocketGuild GetGuild(ulong id)
=> GetShardFor(id).GetGuild(id);
/// <inheritdoc />
public override SocketChannel GetChannel(ulong id)
{
for (int i = 0; i < _shards.Length; i++)
{
var channel = _shards[i].GetChannel(id);
if (channel != null)
return channel;
}
return null;
}
private IEnumerable<ISocketPrivateChannel> GetPrivateChannels()
{
for (int i = 0; i < _shards.Length; i++)
{
foreach (var channel in _shards[i].PrivateChannels)
yield return channel;
}
}
private int GetPrivateChannelCount()
{
int result = 0;
for (int i = 0; i < _shards.Length; i++)
result += _shards[i].PrivateChannels.Count;
return result;
}
private IEnumerable<SocketGuild> GetGuilds()
{
for (int i = 0; i < _shards.Length; i++)
{
foreach (var guild in _shards[i].Guilds)
yield return guild;
}
}
private int GetGuildCount()
{
int result = 0;
for (int i = 0; i < _shards.Length; i++)
result += _shards[i].Guilds.Count;
return result;
}
/// <inheritdoc />
public override SocketUser GetUser(ulong id)
{
for (int i = 0; i < _shards.Length; i++)
{
var user = _shards[i].GetUser(id);
if (user != null)
return user;
}
return null;
}
/// <inheritdoc />
public override SocketUser GetUser(string username, string discriminator)
{
for (int i = 0; i < _shards.Length; i++)
{
var user = _shards[i].GetUser(username, discriminator);
if (user != null)
return user;
}
return null;
}
/// <inheritdoc />
[Obsolete("This method is obsolete, use GetVoiceRegionAsync instead.")]
public override RestVoiceRegion GetVoiceRegion(string id)
=> _shards[0].GetVoiceRegion(id);
/// <inheritdoc />
public override async ValueTask<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null)
{
return await _shards[0].GetVoiceRegionsAsync().ConfigureAwait(false);
}
/// <inheritdoc />
public override async ValueTask<RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null)
{
return await _shards[0].GetVoiceRegionAsync(id, options).ConfigureAwait(false);
}
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="guilds"/> is <see langword="null"/></exception>
public override async Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
{
if (guilds == null) throw new ArgumentNullException(nameof(guilds));
for (int i = 0; i < _shards.Length; i++)
{
int id = _shardIds[i];
var arr = guilds.Where(x => GetShardIdFor(x) == id).ToArray();
if (arr.Length > 0)
await _shards[i].DownloadUsersAsync(arr).ConfigureAwait(false);
}
}
private int GetLatency()
{
int total = 0;
for (int i = 0; i < _shards.Length; i++)
total += _shards[i].Latency;
return (int)Math.Round(total / (double)_shards.Length);
}
/// <inheritdoc />
public override async Task SetStatusAsync(UserStatus status)
{
for (int i = 0; i < _shards.Length; i++)
await _shards[i].SetStatusAsync(status).ConfigureAwait(false);
}
/// <inheritdoc />
public override async Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing)
{
IActivity activity = null;
if (!string.IsNullOrEmpty(streamUrl))
activity = new StreamingGame(name, streamUrl);
else if (!string.IsNullOrEmpty(name))
activity = new Game(name, type);
await SetActivityAsync(activity).ConfigureAwait(false);
}
/// <inheritdoc />
public override async Task SetActivityAsync(IActivity activity)
{
for (int i = 0; i < _shards.Length; i++)
await _shards[i].SetActivityAsync(activity).ConfigureAwait(false);
}
private void RegisterEvents(DiscordSocketClient client, bool isPrimary)
{
client.Log += (msg) => _logEvent.InvokeAsync(msg);
client.LoggedOut += () =>
{
var state = LoginState;
if (state == LoginState.LoggedIn || state == LoginState.LoggingIn)
{
//Should only happen if token is changed
var _ = LogoutAsync(); //Signal the logout, fire and forget
}
return Task.Delay(0);
};
if (isPrimary)
{
client.Ready += () =>
{
CurrentUser = client.CurrentUser;
return Task.Delay(0);
};
}
client.Connected += () => _shardConnectedEvent.InvokeAsync(client);
client.Disconnected += (exception) => _shardDisconnectedEvent.InvokeAsync(exception, client);
client.Ready += () => _shardReadyEvent.InvokeAsync(client);
client.LatencyUpdated += (oldLatency, newLatency) => _shardLatencyUpdatedEvent.InvokeAsync(oldLatency, newLatency, client);
client.ChannelCreated += (channel) => _channelCreatedEvent.InvokeAsync(channel);
client.ChannelDestroyed += (channel) => _channelDestroyedEvent.InvokeAsync(channel);
client.ChannelUpdated += (oldChannel, newChannel) => _channelUpdatedEvent.InvokeAsync(oldChannel, newChannel);
client.MessageReceived += (msg) => _messageReceivedEvent.InvokeAsync(msg);
client.MessageDeleted += (cache, channel) => _messageDeletedEvent.InvokeAsync(cache, channel);
client.MessagesBulkDeleted += (cache, channel) => _messagesBulkDeletedEvent.InvokeAsync(cache, channel);
client.MessageUpdated += (oldMsg, newMsg, channel) => _messageUpdatedEvent.InvokeAsync(oldMsg, newMsg, channel);
client.ReactionAdded += (cache, channel, reaction) => _reactionAddedEvent.InvokeAsync(cache, channel, reaction);
client.ReactionRemoved += (cache, channel, reaction) => _reactionRemovedEvent.InvokeAsync(cache, channel, reaction);
client.ReactionsCleared += (cache, channel) => _reactionsClearedEvent.InvokeAsync(cache, channel);
client.ReactionsRemovedForEmote += (cache, channel, emote) => _reactionsRemovedForEmoteEvent.InvokeAsync(cache, channel, emote);
client.RoleCreated += (role) => _roleCreatedEvent.InvokeAsync(role);
client.RoleDeleted += (role) => _roleDeletedEvent.InvokeAsync(role);
client.RoleUpdated += (oldRole, newRole) => _roleUpdatedEvent.InvokeAsync(oldRole, newRole);
client.JoinedGuild += (guild) => _joinedGuildEvent.InvokeAsync(guild);
client.LeftGuild += (guild) => _leftGuildEvent.InvokeAsync(guild);
client.GuildAvailable += (guild) => _guildAvailableEvent.InvokeAsync(guild);
client.GuildUnavailable += (guild) => _guildUnavailableEvent.InvokeAsync(guild);
client.GuildMembersDownloaded += (guild) => _guildMembersDownloadedEvent.InvokeAsync(guild);
client.GuildUpdated += (oldGuild, newGuild) => _guildUpdatedEvent.InvokeAsync(oldGuild, newGuild);
client.UserJoined += (user) => _userJoinedEvent.InvokeAsync(user);
client.UserLeft += (user) => _userLeftEvent.InvokeAsync(user);
client.UserBanned += (user, guild) => _userBannedEvent.InvokeAsync(user, guild);
client.UserUnbanned += (user, guild) => _userUnbannedEvent.InvokeAsync(user, guild);
client.UserUpdated += (oldUser, newUser) => _userUpdatedEvent.InvokeAsync(oldUser, newUser);
client.GuildMemberUpdated += (oldUser, newUser) => _guildMemberUpdatedEvent.InvokeAsync(oldUser, newUser);
client.UserVoiceStateUpdated += (user, oldVoiceState, newVoiceState) => _userVoiceStateUpdatedEvent.InvokeAsync(user, oldVoiceState, newVoiceState);
client.VoiceServerUpdated += (server) => _voiceServerUpdatedEvent.InvokeAsync(server);
client.CurrentUserUpdated += (oldUser, newUser) => _selfUpdatedEvent.InvokeAsync(oldUser, newUser);
client.UserIsTyping += (oldUser, newUser) => _userIsTypingEvent.InvokeAsync(oldUser, newUser);
client.RecipientAdded += (user) => _recipientAddedEvent.InvokeAsync(user);
client.RecipientRemoved += (user) => _recipientRemovedEvent.InvokeAsync(user);
client.InviteCreated += (invite) => _inviteCreatedEvent.InvokeAsync(invite);
client.InviteDeleted += (channel, invite) => _inviteDeletedEvent.InvokeAsync(channel, invite);
}
//IDiscordClient
/// <inheritdoc />
async Task<IApplication> IDiscordClient.GetApplicationInfoAsync(RequestOptions options)
=> await GetApplicationInfoAsync().ConfigureAwait(false);
/// <inheritdoc />
Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IChannel>(GetChannel(id));
/// <inheritdoc />
Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels);
/// <inheritdoc />
async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options)
=> await GetConnectionsAsync().ConfigureAwait(false);
/// <inheritdoc />
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
=> await GetInviteAsync(inviteId, options).ConfigureAwait(false);
/// <inheritdoc />
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuild>(GetGuild(id));
/// <inheritdoc />
Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds);
/// <inheritdoc />
async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options)
=> await CreateGuildAsync(name, region, jpegIcon).ConfigureAwait(false);
/// <inheritdoc />
Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(id));
/// <inheritdoc />
Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(username, discriminator));
/// <inheritdoc />
Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options)
=> Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions);
/// <inheritdoc />
Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options)
=> Task.FromResult<IVoiceRegion>(GetVoiceRegion(id));
internal override void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
if (_shards != null)
{
foreach (var client in _shards)
client?.Dispose();
}
}
_isDisposed = true;
}
base.Dispose(disposing);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace System.Data.SQLite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if !SQLITE_OMIT_ATTACH
/// <summary>
/// Resolve an expression that was part of an ATTACH or DETACH statement. This
/// is slightly different from resolving a normal SQL expression, because simple
/// identifiers are treated as strings, not possible column names or aliases.
///
/// i.e. if the parser sees:
///
/// ATTACH DATABASE abc AS def
///
/// it treats the two expressions as literal strings 'abc' and 'def' instead of
/// looking for columns of the same name.
///
/// This only applies to the root node of pExpr, so the statement:
///
/// ATTACH DATABASE abc||def AS 'db2'
///
/// will fail because neither abc or def can be resolved.
/// </summary>
static int resolveAttachExpr(NameContext pName, Expr pExpr)
{
int rc = SQLITE_OK;
if (pExpr != null)
{
if (pExpr.op != TK_ID)
{
rc = sqlite3ResolveExprNames(pName, ref pExpr);
if (rc == SQLITE_OK && sqlite3ExprIsConstant(pExpr) == 0)
{
sqlite3ErrorMsg(pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken);
return SQLITE_ERROR;
}
}
else
{
pExpr.op = TK_STRING;
}
}
return rc;
}
/// <summary>
/// An SQL user-function registered to do the work of an ATTACH statement. The
/// three arguments to the function come directly from an attach statement:
///
/// ATTACH DATABASE x AS y KEY z
///
/// SELECT sqlite_attach(x, y, z)
///
/// If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
/// third argument.
/// </summary>
static void attachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
int i;
int rc = 0;
sqlite3 db = sqlite3_context_db_handle(context);
string zName;
string zFile;
string zPath = "";
string zErr = "";
int flags;
Db aNew = null;
string zErrDyn = "";
sqlite3_vfs pVfs = null;
UNUSED_PARAMETER(NotUsed);
zFile = argv[0].z != null && (argv[0].z.Length > 0) && argv[0].flags != MEM_Null ? sqlite3_value_text(argv[0]) : "";
zName = argv[1].z != null && (argv[1].z.Length > 0) && argv[1].flags != MEM_Null ? sqlite3_value_text(argv[1]) : "";
//if( zFile==null ) zFile = "";
//if ( zName == null ) zName = "";
/* Check for the following errors:
**
** * Too many attached databases,
** * Transaction currently open
** * Specified database name already being used.
*/
if (db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2)
{
zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
db.aLimit[SQLITE_LIMIT_ATTACHED]
);
goto attach_error;
}
if (0 == db.autoCommit)
{
zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
goto attach_error;
}
for (i = 0; i < db.nDb; i++)
{
string z = db.aDb[i].zName;
Debug.Assert(z != null && zName != null);
if (z.Equals(zName, StringComparison.InvariantCultureIgnoreCase))
{
zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
goto attach_error;
}
}
/* Allocate the new entry in the db.aDb[] array and initialise the schema
** hash tables.
*/
//if( db.aDb==db.aDbStatic ){
// aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 );
// if( aNew==0 ) return;
// memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2);
//}else {
if (db.aDb.Length <= db.nDb)
Array.Resize(ref db.aDb, db.nDb + 1);//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) );
if (db.aDb == null)
return; // if( aNew==0 ) return;
//}
db.aDb[db.nDb] = new Db();//db.aDb = aNew;
aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew));
// memset(aNew, 0, sizeof(*aNew));
/* Open the database file. If the btree is successfully opened, use
** it to obtain the database schema. At this point the schema may
** or may not be initialised.
*/
flags = (int)db.openFlags;
rc = sqlite3ParseUri(db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr);
if (rc != SQLITE_OK)
{
//if ( rc == SQLITE_NOMEM )
//db.mallocFailed = 1;
sqlite3_result_error(context, zErr, -1);
//sqlite3_free( zErr );
return;
}
Debug.Assert(pVfs != null);
flags |= SQLITE_OPEN_MAIN_DB;
rc = sqlite3BtreeOpen(pVfs, zPath, db, ref aNew.pBt, 0, (int)flags);
//sqlite3_free( zPath );
db.nDb++;
if (rc == SQLITE_CONSTRAINT)
{
rc = SQLITE_ERROR;
zErrDyn = sqlite3MPrintf(db, "database is already attached");
}
else if (rc == SQLITE_OK)
{
Pager pPager;
aNew.pSchema = sqlite3SchemaGet(db, aNew.pBt);
//if ( aNew.pSchema == null )
//{
// rc = SQLITE_NOMEM;
//}
//else
if (aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC(db))
{
zErrDyn = sqlite3MPrintf(db,
"attached databases must use the same text encoding as main database");
rc = SQLITE_ERROR;
}
pPager = sqlite3BtreePager(aNew.pBt);
sqlite3PagerLockingMode(pPager, db.dfltLockMode);
sqlite3BtreeSecureDelete(aNew.pBt,
sqlite3BtreeSecureDelete(db.aDb[0].pBt, -1));
}
aNew.safety_level = 3;
aNew.zName = zName;//sqlite3DbStrDup(db, zName);
//if( rc==SQLITE_OK && aNew.zName==0 ){
// rc = SQLITE_NOMEM;
//}
#if SQLITE_HAS_CODEC
if ( rc == SQLITE_OK )
{
//extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
//extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
int nKey;
string zKey;
int t = sqlite3_value_type( argv[2] );
switch ( t )
{
case SQLITE_INTEGER:
case SQLITE_FLOAT:
zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" );
rc = SQLITE_ERROR;
break;
case SQLITE_TEXT:
case SQLITE_BLOB:
nKey = sqlite3_value_bytes( argv[2] );
zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]);
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
break;
case SQLITE_NULL:
/* No key specified. Use the key from the main database */
sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey);
if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 )
{
rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
}
break;
}
}
#endif
/* If the file was opened successfully, read the schema for the new database.
** If this fails, or if opening the file failed, then close the file and
** remove the entry from the db.aDb[] array. i.e. put everything back the way
** we found it.
*/
if (rc == SQLITE_OK)
{
sqlite3BtreeEnterAll(db);
rc = sqlite3Init(db, ref zErrDyn);
sqlite3BtreeLeaveAll(db);
}
if (rc != 0)
{
int iDb = db.nDb - 1;
Debug.Assert(iDb >= 2);
if (db.aDb[iDb].pBt != null)
{
sqlite3BtreeClose(ref db.aDb[iDb].pBt);
db.aDb[iDb].pBt = null;
db.aDb[iDb].pSchema = null;
}
sqlite3ResetInternalSchema(db, -1);
db.nDb = iDb;
if (rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM)
{
//// db.mallocFailed = 1;
sqlite3DbFree(db, ref zErrDyn);
zErrDyn = sqlite3MPrintf(db, "out of memory");
}
else if (zErrDyn == "")
{
zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
}
goto attach_error;
}
return;
attach_error:
/* Return an error if we get here */
if (zErrDyn != "")
{
sqlite3_result_error(context, zErrDyn, -1);
sqlite3DbFree(db, ref zErrDyn);
}
if (rc != 0)
sqlite3_result_error_code(context, rc);
}
/// <summary>
/// An SQL user-function registered to do the work of an DETACH statement. The
/// three arguments to the function come directly from a detach statement:
///
/// DETACH DATABASE x
///
/// SELECT sqlite_detach(x)
/// </summary>
static void detachFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
string zName = argv[0].z != null && (argv[0].z.Length > 0) ? sqlite3_value_text(argv[0]) : "";//(sqlite3_value_text(argv[0]);
sqlite3 db = sqlite3_context_db_handle(context);
int i;
Db pDb = null;
StringBuilder zErr = new StringBuilder(200);
UNUSED_PARAMETER(NotUsed);
if (zName == null)
zName = "";
for (i = 0; i < db.nDb; i++)
{
pDb = db.aDb[i];
if (pDb.pBt == null)
continue;
if (pDb.zName.Equals(zName, StringComparison.InvariantCultureIgnoreCase))
break;
}
if (i >= db.nDb)
{
sqlite3_snprintf(200, zErr, "no such database: %s", zName);
goto detach_error;
}
if (i < 2)
{
sqlite3_snprintf(200, zErr, "cannot detach database %s", zName);
goto detach_error;
}
if (0 == db.autoCommit)
{
sqlite3_snprintf(200, zErr,
"cannot DETACH database within transaction");
goto detach_error;
}
if (sqlite3BtreeIsInReadTrans(pDb.pBt) || sqlite3BtreeIsInBackup(pDb.pBt))
{
sqlite3_snprintf(200, zErr, "database %s is locked", zName);
goto detach_error;
}
sqlite3BtreeClose(ref pDb.pBt);
pDb.pBt = null;
pDb.pSchema = null;
sqlite3ResetInternalSchema(db, -1);
return;
detach_error:
sqlite3_result_error(context, zErr.ToString(), -1);
}
/// <summary>
/// This procedure generates VDBE code for a single invocation of either the
/// sqlite_detach() or sqlite_attach() SQL user functions.
/// </summary>
/// <param name='pParse'>
/// The parser context
/// </param>
/// <param name='type'>
/// Either SQLITE_ATTACH or SQLITE_DETACH
/// </param>
/// <param name='pFunc'>
/// FuncDef wrapper for detachFunc() or attachFunc()
/// </param>
/// <param name='pAuthArg'>
/// Expression to pass to authorization callback
/// </param>
/// <param name='pFilename'>
/// Name of database file
/// </param>
/// <param name='pDbname'>
/// Name of the database to use internally
/// </param>
/// <param name='pKey'>
/// Database key for encryption extension
/// </param>
static void codeAttach(
Parse pParse,
int type,
FuncDef pFunc,
Expr pAuthArg,
Expr pFilename,
Expr pDbname,
Expr pKey
)
{
NameContext sName;
Vdbe v;
sqlite3 db = pParse.db;
int regArgs;
sName = new NameContext();// memset( &sName, 0, sizeof(NameContext));
sName.pParse = pParse;
if (
SQLITE_OK != (resolveAttachExpr(sName, pFilename)) ||
SQLITE_OK != (resolveAttachExpr(sName, pDbname)) ||
SQLITE_OK != (resolveAttachExpr(sName, pKey))
)
{
pParse.nErr++;
goto attach_end;
}
#if !SQLITE_OMIT_AUTHORIZATION
if( pAuthArg ){
char *zAuthArg;
if( pAuthArg->op==TK_STRING ){
zAuthArg = pAuthArg->u.zToken;
}else{
zAuthArg = 0;
}
rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
if(rc!=SQLITE_OK ){
goto attach_end;
}
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
v = sqlite3GetVdbe(pParse);
regArgs = sqlite3GetTempRange(pParse, 4);
sqlite3ExprCode(pParse, pFilename, regArgs);
sqlite3ExprCode(pParse, pDbname, regArgs + 1);
sqlite3ExprCode(pParse, pKey, regArgs + 2);
Debug.Assert(v != null /*|| db.mallocFailed != 0 */ );
if (v != null)
{
sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3);
Debug.Assert(pFunc.nArg == -1 || (pFunc.nArg & 0xff) == pFunc.nArg);
sqlite3VdbeChangeP5(v, (u8)(pFunc.nArg));
sqlite3VdbeChangeP4(v, -1, pFunc, P4_FUNCDEF);
/* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
** statement only). For DETACH, set it to false (expire all existing
** statements).
*/
sqlite3VdbeAddOp1(v, OP_Expire, (type == SQLITE_ATTACH) ? 1 : 0);
}
attach_end:
sqlite3ExprDelete(db, ref pFilename);
sqlite3ExprDelete(db, ref pDbname);
sqlite3ExprDelete(db, ref pKey);
}
/// <summary>
/// Called by the parser to compile a DETACH statement.
///
/// DETACH pDbname
/// </summary>
static FuncDef detach_func = new FuncDef(
1, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
detachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_detach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Detach(Parse pParse, Expr pDbname)
{
codeAttach(pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname);
}
/// <summary>
/// Called by the parser to compile an ATTACH statement.
///
/// ATTACH p AS pDbname KEY pKey
/// </summary>
static FuncDef attach_func = new FuncDef(
3, /* nArg */
SQLITE_UTF8, /* iPrefEnc */
0, /* flags */
null, /* pUserData */
null, /* pNext */
attachFunc, /* xFunc */
null, /* xStep */
null, /* xFinalize */
"sqlite_attach", /* zName */
null, /* pHash */
null /* pDestructor */
);
static void sqlite3Attach(Parse pParse, Expr p, Expr pDbname, Expr pKey)
{
codeAttach(pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey);
}
#endif // * SQLITE_OMIT_ATTACH */
/// <summary>
/// Initialize a DbFixer structure. This routine must be called prior
/// to passing the structure to one of the sqliteFixAAAA() routines below.
///
/// The return value indicates whether or not fixation is required. TRUE
/// means we do need to fix the database references, FALSE means we do not.
/// </summary>
static int sqlite3FixInit(
DbFixer pFix, /* The fixer to be initialized */
Parse pParse, /* Error messages will be written here */
int iDb, /* This is the database that must be used */
string zType, /* "view", "trigger", or "index" */
Token pName /* Name of the view, trigger, or index */
)
{
sqlite3 db;
if (NEVER(iDb < 0) || iDb == 1)
return 0;
db = pParse.db;
Debug.Assert(db.nDb > iDb);
pFix.pParse = pParse;
pFix.zDb = db.aDb[iDb].zName;
pFix.zType = zType;
pFix.pName = pName;
return 1;
}
/// <summary>
/// The following set of routines walk through the parse tree and assign
/// a specific database to all table references where the database name
/// was left unspecified in the original SQL statement. The pFix structure
/// must have been initialized by a prior call to sqlite3FixInit().
///
/// These routines are used to make sure that an index, trigger, or
/// view in one database does not refer to objects in a different database.
/// (Exception: indices, triggers, and views in the TEMP database are
/// allowed to refer to anything.) If a reference is explicitly made
/// to an object in a different database, an error message is added to
/// pParse.zErrMsg and these routines return non-zero. If everything
/// checks out, these routines return 0.
/// </summary>
static int sqlite3FixSrcList(
DbFixer pFix, /* Context of the fixation */
SrcList pList /* The Source list to check and modify */
)
{
int i;
string zDb;
SrcList_item pItem;
if (NEVER(pList == null))
return 0;
zDb = pFix.zDb;
for (i = 0; i < pList.nSrc; i++)
{//, pItem++){
pItem = pList.a[i];
if (pItem.zDatabase == null)
{
pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb );
}
else if (!pItem.zDatabase.Equals(zDb, StringComparison.InvariantCultureIgnoreCase))
{
sqlite3ErrorMsg(pFix.pParse,
"%s %T cannot reference objects in database %s",
pFix.zType, pFix.pName, pItem.zDatabase);
return 1;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
if (sqlite3FixSelect(pFix, pItem.pSelect) != 0)
return 1;
if (sqlite3FixExpr(pFix, pItem.pOn) != 0)
return 1;
#endif
}
return 0;
}
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
static int sqlite3FixSelect(
DbFixer pFix, /* Context of the fixation */
Select pSelect /* The SELECT statement to be fixed to one database */
)
{
while (pSelect != null)
{
if (sqlite3FixExprList(pFix, pSelect.pEList) != 0)
{
return 1;
}
if (sqlite3FixSrcList(pFix, pSelect.pSrc) != 0)
{
return 1;
}
if (sqlite3FixExpr(pFix, pSelect.pWhere) != 0)
{
return 1;
}
if (sqlite3FixExpr(pFix, pSelect.pHaving) != 0)
{
return 1;
}
pSelect = pSelect.pPrior;
}
return 0;
}
static int sqlite3FixExpr(
DbFixer pFix, /* Context of the fixation */
Expr pExpr /* The expression to be fixed to one database */
)
{
while (pExpr != null)
{
if (ExprHasAnyProperty(pExpr, EP_TokenOnly))
break;
if (ExprHasProperty(pExpr, EP_xIsSelect))
{
if (sqlite3FixSelect(pFix, pExpr.x.pSelect) != 0)
return 1;
}
else
{
if (sqlite3FixExprList(pFix, pExpr.x.pList) != 0)
return 1;
}
if (sqlite3FixExpr(pFix, pExpr.pRight) != 0)
{
return 1;
}
pExpr = pExpr.pLeft;
}
return 0;
}
static int sqlite3FixExprList(
DbFixer pFix, /* Context of the fixation */
ExprList pList /* The expression to be fixed to one database */
)
{
int i;
ExprList_item pItem;
if (pList == null)
return 0;
for (i = 0; i < pList.nExpr; i++)//, pItem++ )
{
pItem = pList.a[i];
if (sqlite3FixExpr(pFix, pItem.pExpr) != 0)
{
return 1;
}
}
return 0;
}
#endif
#if !SQLITE_OMIT_TRIGGER
static int sqlite3FixTriggerStep(
DbFixer pFix, /* Context of the fixation */
TriggerStep pStep /* The trigger step be fixed to one database */
)
{
while (pStep != null)
{
if (sqlite3FixSelect(pFix, pStep.pSelect) != 0)
{
return 1;
}
if (sqlite3FixExpr(pFix, pStep.pWhere) != 0)
{
return 1;
}
if (sqlite3FixExprList(pFix, pStep.pExprList) != 0)
{
return 1;
}
pStep = pStep.pNext;
}
return 0;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[CLSCompliant(false)]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct UInt64 : IComparable, IConvertible, IFormattable, IComparable<UInt64>, IEquatable<UInt64>
{
private ulong m_value; // Do not rename (binary serialization)
public const ulong MaxValue = (ulong)0xffffffffffffffffL;
public const ulong MinValue = 0x0;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt64, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is UInt64)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
ulong i = (ulong)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeUInt64);
}
public int CompareTo(UInt64 value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is UInt64))
{
return false;
}
return m_value == ((UInt64)obj).m_value;
}
[NonVersionable]
public bool Equals(UInt64 obj)
{
return m_value == obj;
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode()
{
return ((int)m_value) ^ (int)(m_value >> 32);
}
public override String ToString()
{
return Number.FormatUInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
return Number.FormatUInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
return Number.FormatUInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
return Number.FormatUInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ulong Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ulong Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ulong Parse(string s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ulong Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ulong Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static Boolean TryParse(String s, out UInt64 result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
}
[CLSCompliant(false)]
public static Boolean TryParse(ReadOnlySpan<char> s, out UInt64 result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.UInt64;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return m_value;
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt64", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.EventSystems;
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Fungus
{
/// <summary>
/// Visual scripting controller for the Flowchart programming language.
/// Flowchart objects may be edited visually using the Flowchart editor window.
/// </summary>
[ExecuteInEditMode]
public class Flowchart : MonoBehaviour, ISubstitutionHandler
{
public const string SubstituteVariableRegexString = "{\\$.*?}";
[HideInInspector]
[SerializeField] protected int version = 0; // Default to 0 to always trigger an update for older versions of Fungus.
[HideInInspector]
[SerializeField] protected Vector2 scrollPos;
[HideInInspector]
[SerializeField] protected Vector2 variablesScrollPos;
[HideInInspector]
[SerializeField] protected bool variablesExpanded = true;
[HideInInspector]
[SerializeField] protected float blockViewHeight = 400;
[HideInInspector]
[SerializeField] protected float zoom = 1f;
[HideInInspector]
[SerializeField] protected Rect scrollViewRect;
[HideInInspector]
[SerializeField] protected List<Block> selectedBlocks = new List<Block>();
[HideInInspector]
[SerializeField] protected List<Command> selectedCommands = new List<Command>();
[HideInInspector]
[SerializeField] protected List<Variable> variables = new List<Variable>();
[TextArea(3, 5)]
[Tooltip("Description text displayed in the Flowchart editor window")]
[SerializeField] protected string description = "";
[Range(0f, 5f)]
[Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")]
[SerializeField] protected float stepPause = 0f;
[Tooltip("Use command color when displaying the command list in the Fungus Editor window")]
[SerializeField] protected bool colorCommands = true;
[Tooltip("Hides the Flowchart block and command components in the inspector. Deselect to inspect the block and command components that make up the Flowchart.")]
[SerializeField] protected bool hideComponents = true;
[Tooltip("Saves the selected block and commands when saving the scene. Helps avoid version control conflicts if you've only changed the active selection.")]
[SerializeField] protected bool saveSelection = true;
[Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")]
[SerializeField] protected string localizationId = "";
[Tooltip("Display line numbers in the command list in the Block inspector.")]
[SerializeField] protected bool showLineNumbers = false;
[Tooltip("List of commands to hide in the Add Command menu. Use this to restrict the set of commands available when editing a Flowchart.")]
[SerializeField] protected List<string> hideCommands = new List<string>();
[Tooltip("Lua Environment to be used by default for all Execute Lua commands in this Flowchart")]
[SerializeField] protected LuaEnvironment luaEnvironment;
[Tooltip("The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing.")]
[SerializeField] protected string luaBindingName = "flowchart";
protected static List<Flowchart> cachedFlowcharts = new List<Flowchart>();
protected static bool eventSystemPresent;
protected StringSubstituter stringSubstituer;
#if UNITY_EDITOR
public bool SelectedCommandsStale { get; set; }
#endif
#if UNITY_5_4_OR_NEWER
#else
protected virtual void OnLevelWasLoaded(int level)
{
LevelWasLoaded();
}
#endif
protected virtual void LevelWasLoaded()
{
// Reset the flag for checking for an event system as there may not be one in the newly loaded scene.
eventSystemPresent = false;
}
protected virtual void Start()
{
CheckEventSystem();
}
// There must be an Event System in the scene for Say and Menu input to work.
// This method will automatically instantiate one if none exists.
protected virtual void CheckEventSystem()
{
if (eventSystemPresent)
{
return;
}
EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>();
if (eventSystem == null)
{
// Auto spawn an Event System from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/EventSystem");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.name = "EventSystem";
}
}
eventSystemPresent = true;
}
private void SceneManager_activeSceneChanged(UnityEngine.SceneManagement.Scene arg0, UnityEngine.SceneManagement.Scene arg1)
{
LevelWasLoaded();
}
protected virtual void OnEnable()
{
if (!cachedFlowcharts.Contains(this))
{
cachedFlowcharts.Add(this);
//TODO these pairs could be replaced by something static that manages all active flowcharts
#if UNITY_5_4_OR_NEWER
UnityEngine.SceneManagement.SceneManager.activeSceneChanged += SceneManager_activeSceneChanged;
#endif
}
CheckItemIds();
CleanupComponents();
UpdateVersion();
StringSubstituter.RegisterHandler(this);
}
protected virtual void OnDisable()
{
cachedFlowcharts.Remove(this);
#if UNITY_5_4_OR_NEWER
UnityEngine.SceneManagement.SceneManager.activeSceneChanged -= SceneManager_activeSceneChanged;
#endif
StringSubstituter.UnregisterHandler(this);
}
protected virtual void UpdateVersion()
{
if (version == FungusConstants.CurrentVersion)
{
// No need to update
return;
}
// Tell all components that implement IUpdateable to update to the new version
var components = GetComponents<Component>();
for (int i = 0; i < components.Length; i++)
{
var component = components[i];
IUpdateable u = component as IUpdateable;
if (u != null)
{
u.UpdateToVersion(version, FungusConstants.CurrentVersion);
}
}
version = FungusConstants.CurrentVersion;
}
protected virtual void CheckItemIds()
{
// Make sure item ids are unique and monotonically increasing.
// This should always be the case, but some legacy Flowcharts may have issues.
List<int> usedIds = new List<int>();
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.ItemId == -1 || usedIds.Contains(block.ItemId))
{
block.ItemId = NextItemId();
}
usedIds.Add(block.ItemId);
}
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
if (command.ItemId == -1 || usedIds.Contains(command.ItemId))
{
command.ItemId = NextItemId();
}
usedIds.Add(command.ItemId);
}
}
protected virtual void CleanupComponents()
{
// Delete any unreferenced components which shouldn't exist any more
// Unreferenced components don't have any effect on the flowchart behavior, but
// they waste memory so should be cleared out periodically.
// Remove any null entries in the variables list
// It shouldn't happen but it seemed to occur for a user on the forum
variables.RemoveAll(item => item == null);
if (selectedBlocks == null) selectedBlocks = new List<Block>();
if (selectedCommands == null) selectedCommands = new List<Command>();
selectedBlocks.RemoveAll(item => item == null);
selectedCommands.RemoveAll(item => item == null);
var allVariables = GetComponents<Variable>();
for (int i = 0; i < allVariables.Length; i++)
{
var variable = allVariables[i];
if (!variables.Contains(variable))
{
DestroyImmediate(variable);
}
}
var blocks = GetComponents<Block>();
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
bool found = false;
for (int j = 0; j < blocks.Length; j++)
{
var block = blocks[j];
if (block.CommandList.Contains(command))
{
found = true;
break;
}
}
if (!found)
{
DestroyImmediate(command);
}
}
var eventHandlers = GetComponents<EventHandler>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
bool found = false;
for (int j = 0; j < blocks.Length; j++)
{
var block = blocks[j];
if (block._EventHandler == eventHandler)
{
found = true;
break;
}
}
if (!found)
{
DestroyImmediate(eventHandler);
}
}
}
protected virtual Block CreateBlockComponent(GameObject parent)
{
Block block = parent.AddComponent<Block>();
return block;
}
#region Public members
/// <summary>
/// Cached list of flowchart objects in the scene for fast lookup.
/// </summary>
public static List<Flowchart> CachedFlowcharts { get { return cachedFlowcharts; } }
/// <summary>
/// Sends a message to all Flowchart objects in the current scene.
/// Any block with a matching MessageReceived event handler will start executing.
/// </summary>
public static void BroadcastFungusMessage(string messageName)
{
var eventHandlers = UnityEngine.Object.FindObjectsOfType<MessageReceived>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
eventHandler.OnSendFungusMessage(messageName);
}
}
/// <summary>
/// Scroll position of Flowchart editor window.
/// </summary>
public virtual Vector2 ScrollPos { get { return scrollPos; } set { scrollPos = value; } }
/// <summary>
/// Scroll position of Flowchart variables window.
/// </summary>
public virtual Vector2 VariablesScrollPos { get { return variablesScrollPos; } set { variablesScrollPos = value; } }
/// <summary>
/// Show the variables pane.
/// </summary>
public virtual bool VariablesExpanded { get { return variablesExpanded; } set { variablesExpanded = value; } }
/// <summary>
/// Height of command block view in inspector.
/// </summary>
public virtual float BlockViewHeight { get { return blockViewHeight; } set { blockViewHeight = value; } }
/// <summary>
/// Zoom level of Flowchart editor window.
/// </summary>
public virtual float Zoom { get { return zoom; } set { zoom = value; } }
/// <summary>
/// Scrollable area for Flowchart editor window.
/// </summary>
public virtual Rect ScrollViewRect { get { return scrollViewRect; } set { scrollViewRect = value; } }
/// <summary>
/// Current actively selected block in the Flowchart editor.
/// </summary>
public virtual Block SelectedBlock
{
get
{
if (selectedBlocks == null || selectedBlocks.Count == 0)
return null;
return selectedBlocks[0];
}
set
{
ClearSelectedBlocks();
AddSelectedBlock(value);
}
}
public virtual List<Block> SelectedBlocks { get { return selectedBlocks; } set { selectedBlocks = value; } }
/// <summary>
/// Currently selected command in the Flowchart editor.
/// </summary>
public virtual List<Command> SelectedCommands { get { return selectedCommands; } }
/// <summary>
/// The list of variables that can be accessed by the Flowchart.
/// </summary>
public virtual List<Variable> Variables { get { return variables; } }
public virtual int VariableCount { get { return variables.Count; } }
/// <summary>
/// Description text displayed in the Flowchart editor window
/// </summary>
public virtual string Description { get { return description; } }
/// <summary>
/// Slow down execution in the editor to make it easier to visualise program flow.
/// </summary>
public virtual float StepPause { get { return stepPause; } }
/// <summary>
/// Use command color when displaying the command list in the inspector.
/// </summary>
public virtual bool ColorCommands { get { return colorCommands; } }
/// <summary>
/// Saves the selected block and commands when saving the scene. Helps avoid version control conflicts if you've only changed the active selection.
/// </summary>
public virtual bool SaveSelection { get { return saveSelection; } }
/// <summary>
/// Unique identifier for identifying this flowchart in localized string keys.
/// </summary>
public virtual string LocalizationId { get { return localizationId; } }
/// <summary>
/// Display line numbers in the command list in the Block inspector.
/// </summary>
public virtual bool ShowLineNumbers { get { return showLineNumbers; } }
/// <summary>
/// Lua Environment to be used by default for all Execute Lua commands in this Flowchart.
/// </summary>
public virtual LuaEnvironment LuaEnv { get { return luaEnvironment; } }
/// <summary>
/// The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing.
/// </summary>
public virtual string LuaBindingName { get { return luaBindingName; } }
/// <summary>
/// Position in the center of all blocks in the flowchart.
/// </summary>
public virtual Vector2 CenterPosition { set; get; }
/// <summary>
/// Variable to track flowchart's version so components can update to new versions.
/// </summary>
public int Version { set { version = value; } }
/// <summary>
/// Returns true if the Flowchart gameobject is active.
/// </summary>
public bool IsActive()
{
return gameObject.activeInHierarchy;
}
/// <summary>
/// Returns the Flowchart gameobject name.
/// </summary>
public string GetName()
{
return gameObject.name;
}
/// <summary>
/// Returns the next id to assign to a new flowchart item.
/// Item ids increase monotically so they are guaranteed to
/// be unique within a Flowchart.
/// </summary>
public int NextItemId()
{
int maxId = -1;
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
maxId = Math.Max(maxId, block.ItemId);
}
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
maxId = Math.Max(maxId, command.ItemId);
}
return maxId + 1;
}
/// <summary>
/// Create a new block node which you can then add commands to.
/// </summary>
public virtual Block CreateBlock(Vector2 position)
{
Block b = CreateBlockComponent(gameObject);
b._NodeRect = new Rect(position.x, position.y, 0, 0);
b.BlockName = GetUniqueBlockKey(b.BlockName, b);
b.ItemId = NextItemId();
return b;
}
/// <summary>
/// Returns the named Block in the flowchart, or null if not found.
/// </summary>
public virtual Block FindBlock(string blockName)
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.BlockName == blockName)
{
return block;
}
}
return null;
}
/// <summary>
/// Checks availability of the block in the Flowchart.
/// You can use this method in a UI event. e.g. to test availability block, before handle it.
public virtual bool HasBlock(string blockName)
{
var block = FindBlock(blockName);
return block != null;
}
/// <summary>
/// Executes the block if it is available in the Flowchart.
/// You can use this method in a UI event. e.g. to try executing block without confidence in its existence.
public virtual bool ExecuteIfHasBlock(string blockName)
{
if (HasBlock(blockName))
{
ExecuteBlock(blockName);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Execute a child block in the Flowchart.
/// You can use this method in a UI event. e.g. to handle a button click.
public virtual void ExecuteBlock(string blockName)
{
var block = FindBlock(blockName);
if (block == null)
{
Debug.LogError("Block " + blockName + " does not exist");
return;
}
if (!ExecuteBlock(block))
{
Debug.LogWarning("Block " + blockName + " failed to execute");
}
}
/// <summary>
/// Stops an executing Block in the Flowchart.
/// </summary>
public virtual void StopBlock(string blockName)
{
var block = FindBlock(blockName);
if (block == null)
{
Debug.LogError("Block " + blockName + " does not exist");
return;
}
if (block.IsExecuting())
{
block.Stop();
}
}
/// <summary>
/// Execute a child block in the flowchart.
/// The block must be in an idle state to be executed.
/// This version provides extra options to control how the block is executed.
/// Returns true if the Block started execution.
/// </summary>
public virtual bool ExecuteBlock(Block block, int commandIndex = 0, Action onComplete = null)
{
if (block == null)
{
Debug.LogError("Block must not be null");
return false;
}
if (((Block)block).gameObject != gameObject)
{
Debug.LogError("Block must belong to the same gameobject as this Flowchart");
return false;
}
// Can't restart a running block, have to wait until it's idle again
if (block.IsExecuting())
{
Debug.LogWarning(block.BlockName + " cannot be called/executed, it is already running.");
return false;
}
// Start executing the Block as a new coroutine
StartCoroutine(block.Execute(commandIndex, onComplete));
return true;
}
/// <summary>
/// Stop all executing Blocks in this Flowchart.
/// </summary>
public virtual void StopAllBlocks()
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.IsExecuting())
{
block.Stop();
}
}
}
/// <summary>
/// Sends a message to this Flowchart only.
/// Any block with a matching MessageReceived event handler will start executing.
/// </summary>
public virtual void SendFungusMessage(string messageName)
{
var eventHandlers = GetComponents<MessageReceived>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
eventHandler.OnSendFungusMessage(messageName);
}
}
/// <summary>
/// Returns a new variable key that is guaranteed not to clash with any existing variable in the list.
/// </summary>
public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null)
{
int suffix = 0;
string baseKey = originalKey;
// Only letters and digits allowed
char[] arr = baseKey.Where(c => (char.IsLetterOrDigit(c) || c == '_')).ToArray();
baseKey = new string(arr);
// No leading digits allowed
baseKey = baseKey.TrimStart('0','1','2','3','4','5','6','7','8','9');
// No empty keys allowed
if (baseKey.Length == 0)
{
baseKey = "Var";
}
string key = baseKey;
while (true)
{
bool collision = false;
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
if (variable == null || variable == ignoreVariable || variable.Key == null)
{
continue;
}
if (variable.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{
collision = true;
suffix++;
key = baseKey + suffix;
}
}
if (!collision)
{
return key;
}
}
}
/// <summary>
/// Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart.
/// </summary>
public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null)
{
int suffix = 0;
string baseKey = originalKey.Trim();
// No empty keys allowed
if (baseKey.Length == 0)
{
baseKey = FungusConstants.DefaultBlockName;
}
var blocks = GetComponents<Block>();
string key = baseKey;
while (true)
{
bool collision = false;
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block == ignoreBlock || block.BlockName == null)
{
continue;
}
if (block.BlockName.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{
collision = true;
suffix++;
key = baseKey + suffix;
}
}
if (!collision)
{
return key;
}
}
}
/// <summary>
/// Returns a new Label key that is guaranteed not to clash with any existing Label in the Block.
/// </summary>
public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel)
{
int suffix = 0;
string baseKey = originalKey.Trim();
// No empty keys allowed
if (baseKey.Length == 0)
{
baseKey = "New Label";
}
var block = ignoreLabel.ParentBlock;
string key = baseKey;
while (true)
{
bool collision = false;
var commandList = block.CommandList;
for (int i = 0; i < commandList.Count; i++)
{
var command = commandList[i];
Label label = command as Label;
if (label == null || label == ignoreLabel)
{
continue;
}
if (label.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{
collision = true;
suffix++;
key = baseKey + suffix;
}
}
if (!collision)
{
return key;
}
}
}
/// <summary>
/// Returns the variable with the specified key, or null if the key is not found.
/// You will need to cast the returned variable to the correct sub-type.
/// You can then access the variable's value using the Value property. e.g.
/// BooleanVariable boolVar = flowchart.GetVariable("MyBool") as BooleanVariable;
/// boolVar.Value = false;
/// </summary>
public Variable GetVariable(string key)
{
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
if (variable != null && variable.Key == key)
{
return variable;
}
}
return null;
}
/// <summary>
/// Returns the variable with the specified key, or null if the key is not found.
/// You can then access the variable's value using the Value property. e.g.
/// BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool");
/// boolVar.Value = false;
/// </summary>
public T GetVariable<T>(string key) where T : Variable
{
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
if (variable != null && variable.Key == key)
{
return variable as T;
}
}
Debug.LogWarning("Variable " + key + " not found.");
return null;
}
/// <summary>
/// Register a new variable with the Flowchart at runtime.
/// The variable should be added as a component on the Flowchart game object.
/// </summary>
public void SetVariable<T>(string key, T newvariable) where T : Variable
{
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null && v.Key == key)
{
T variable = v as T;
if (variable != null)
{
variable = newvariable;
return;
}
}
}
Debug.LogWarning("Variable " + key + " not found.");
}
/// <summary>
/// Checks if a given variable exists in the flowchart.
/// </summary>
public virtual bool HasVariable(string key)
{
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null && v.Key == key)
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the list of variable names in the Flowchart.
/// </summary>
public virtual string[] GetVariableNames()
{
var vList = new string[variables.Count];
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null)
{
vList[i] = v.Key;
}
}
return vList;
}
/// <summary>
/// Gets a list of all variables with public scope in this Flowchart.
/// </summary>
public virtual List<Variable> GetPublicVariables()
{
var publicVariables = new List<Variable>();
for (int i = 0; i < variables.Count; i++)
{
var v = variables[i];
if (v != null && v.Scope == VariableScope.Public)
{
publicVariables.Add(v);
}
}
return publicVariables;
}
/// <summary>
/// Gets the value of a boolean variable.
/// Returns false if the variable key does not exist.
/// </summary>
public virtual bool GetBooleanVariable(string key)
{
var variable = GetVariable<BooleanVariable>(key);
if(variable != null)
{
return GetVariable<BooleanVariable>(key).Value;
}
else
{
return false;
}
}
/// <summary>
/// Sets the value of a boolean variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetBooleanVariable(string key, bool value)
{
var variable = GetVariable<BooleanVariable>(key);
if(variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of an integer variable.
/// Returns 0 if the variable key does not exist.
/// </summary>
public virtual int GetIntegerVariable(string key)
{
var variable = GetVariable<IntegerVariable>(key);
if (variable != null)
{
return GetVariable<IntegerVariable>(key).Value;
}
else
{
return 0;
}
}
/// <summary>
/// Sets the value of an integer variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetIntegerVariable(string key, int value)
{
var variable = GetVariable<IntegerVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a float variable.
/// Returns 0 if the variable key does not exist.
/// </summary>
public virtual float GetFloatVariable(string key)
{
var variable = GetVariable<FloatVariable>(key);
if (variable != null)
{
return GetVariable<FloatVariable>(key).Value;
}
else
{
return 0f;
}
}
/// <summary>
/// Sets the value of a float variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetFloatVariable(string key, float value)
{
var variable = GetVariable<FloatVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a string variable.
/// Returns the empty string if the variable key does not exist.
/// </summary>
public virtual string GetStringVariable(string key)
{
var variable = GetVariable<StringVariable>(key);
if (variable != null)
{
return GetVariable<StringVariable>(key).Value;
}
else
{
return "";
}
}
/// <summary>
/// Sets the value of a string variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetStringVariable(string key, string value)
{
var variable = GetVariable<StringVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a GameObject variable.
/// Returns null if the variable key does not exist.
/// </summary>
public virtual GameObject GetGameObjectVariable(string key)
{
var variable = GetVariable<GameObjectVariable>(key);
if (variable != null)
{
return GetVariable<GameObjectVariable>(key).Value;
}
else
{
return null;
}
}
/// <summary>
/// Sets the value of a GameObject variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetGameObjectVariable(string key, GameObject value)
{
var variable = GetVariable<GameObjectVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Gets the value of a Transform variable.
/// Returns null if the variable key does not exist.
/// </summary>
public virtual Transform GetTransformVariable(string key)
{
var variable = GetVariable<TransformVariable>(key);
if (variable != null)
{
return GetVariable<TransformVariable>(key).Value;
}
else
{
return null;
}
}
/// <summary>
/// Sets the value of a Transform variable.
/// The variable must already be added to the list of variables for this Flowchart.
/// </summary>
public virtual void SetTransformVariable(string key, Transform value)
{
var variable = GetVariable<TransformVariable>(key);
if (variable != null)
{
variable.Value = value;
}
}
/// <summary>
/// Set the block objects to be hidden or visible depending on the hideComponents property.
/// </summary>
public virtual void UpdateHideFlags()
{
if (hideComponents)
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
block.hideFlags = HideFlags.HideInInspector;
if (block.gameObject != gameObject)
{
block.hideFlags = HideFlags.HideInHierarchy;
}
}
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
command.hideFlags = HideFlags.HideInInspector;
}
var eventHandlers = GetComponents<EventHandler>();
for (int i = 0; i < eventHandlers.Length; i++)
{
var eventHandler = eventHandlers[i];
eventHandler.hideFlags = HideFlags.HideInInspector;
}
}
else
{
var monoBehaviours = GetComponents<MonoBehaviour>();
for (int i = 0; i < monoBehaviours.Length; i++)
{
var monoBehaviour = monoBehaviours[i];
if (monoBehaviour == null)
{
continue;
}
monoBehaviour.hideFlags = HideFlags.None;
monoBehaviour.gameObject.hideFlags = HideFlags.None;
}
}
}
/// <summary>
/// Clears the list of selected commands.
/// </summary>
public virtual void ClearSelectedCommands()
{
selectedCommands.Clear();
#if UNITY_EDITOR
SelectedCommandsStale = true;
#endif
}
/// <summary>
/// Adds a command to the list of selected commands.
/// </summary>
public virtual void AddSelectedCommand(Command command)
{
if (!selectedCommands.Contains(command))
{
selectedCommands.Add(command);
#if UNITY_EDITOR
SelectedCommandsStale = true;
#endif
}
}
/// <summary>
/// Clears the list of selected blocks.
/// </summary>
public virtual void ClearSelectedBlocks()
{
if(selectedBlocks == null)
{
selectedBlocks = new List<Block>();
}
for (int i = 0; i < selectedBlocks.Count; i++)
{
var item = selectedBlocks[i];
if(item != null)
{
item.IsSelected = false;
}
}
selectedBlocks.Clear();
}
/// <summary>
/// Adds a block to the list of selected blocks.
/// </summary>
public virtual void AddSelectedBlock(Block block)
{
if (!selectedBlocks.Contains(block))
{
block.IsSelected = true;
selectedBlocks.Add(block);
}
}
public virtual bool DeselectBlock(Block block)
{
if (selectedBlocks.Contains(block))
{
DeselectBlockNoCheck(block);
return true;
}
return false;
}
public virtual void DeselectBlockNoCheck(Block b)
{
b.IsSelected = false;
selectedBlocks.Remove(b);
}
public void UpdateSelectedCache()
{
selectedBlocks.Clear();
var res = gameObject.GetComponents<Block>();
selectedBlocks = res.Where(x => x.IsSelected).ToList();
}
/// <summary>
/// Reset the commands and variables in the Flowchart.
/// </summary>
public virtual void Reset(bool resetCommands, bool resetVariables)
{
if (resetCommands)
{
var commands = GetComponents<Command>();
for (int i = 0; i < commands.Length; i++)
{
var command = commands[i];
command.OnReset();
}
}
if (resetVariables)
{
for (int i = 0; i < variables.Count; i++)
{
var variable = variables[i];
variable.OnReset();
}
}
}
/// <summary>
/// Override this in a Flowchart subclass to filter which commands are shown in the Add Command list.
/// </summary>
public virtual bool IsCommandSupported(CommandInfoAttribute commandInfo)
{
for (int i = 0; i < hideCommands.Count; i++)
{
// Match on category or command name (case insensitive)
var key = hideCommands[i];
if (String.Compare(commandInfo.Category, key, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(commandInfo.CommandName, key, StringComparison.OrdinalIgnoreCase) == 0)
{
return false;
}
}
return true;
}
/// <summary>
/// Returns true if there are any executing blocks in this Flowchart.
/// </summary>
public virtual bool HasExecutingBlocks()
{
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.IsExecuting())
{
return true;
}
}
return false;
}
/// <summary>
/// Returns a list of all executing blocks in this Flowchart.
/// </summary>
public virtual List<Block> GetExecutingBlocks()
{
var executingBlocks = new List<Block>();
var blocks = GetComponents<Block>();
for (int i = 0; i < blocks.Length; i++)
{
var block = blocks[i];
if (block.IsExecuting())
{
executingBlocks.Add(block);
}
}
return executingBlocks;
}
/// <summary>
/// Substitute variables in the input text with the format {$VarName}
/// This will first match with private variables in this Flowchart, and then
/// with public variables in all Flowcharts in the scene (and any component
/// in the scene that implements StringSubstituter.ISubstitutionHandler).
/// </summary>
public virtual string SubstituteVariables(string input)
{
if (stringSubstituer == null)
{
stringSubstituer = new StringSubstituter();
}
// Use the string builder from StringSubstituter for efficiency.
StringBuilder sb = stringSubstituer._StringBuilder;
sb.Length = 0;
sb.Append(input);
// Instantiate the regular expression object.
Regex r = new Regex(SubstituteVariableRegexString);
bool changed = false;
// Match the regular expression pattern against a text string.
var results = r.Matches(input);
for (int i = 0; i < results.Count; i++)
{
Match match = results[i];
string key = match.Value.Substring(2, match.Value.Length - 3);
// Look for any matching private variables in this Flowchart first
for (int j = 0; j < variables.Count; j++)
{
var variable = variables[j];
if (variable == null)
continue;
if (variable.Scope == VariableScope.Private && variable.Key == key)
{
string value = variable.ToString();
sb.Replace(match.Value, value);
changed = true;
}
}
}
// Now do all other substitutions in the scene
changed |= stringSubstituer.SubstituteStrings(sb);
if (changed)
{
return sb.ToString();
}
else
{
return input;
}
}
public virtual void DetermineSubstituteVariables(string str, List<Variable> vars)
{
Regex r = new Regex(Flowchart.SubstituteVariableRegexString);
// Match the regular expression pattern against a text string.
var results = r.Matches(str);
for (int i = 0; i < results.Count; i++)
{
var match = results[i];
var v = GetVariable(match.Value.Substring(2, match.Value.Length - 3));
if (v != null)
{
vars.Add(v);
}
}
}
#endregion
#region IStringSubstituter implementation
/// <summary>
/// Implementation of StringSubstituter.ISubstitutionHandler which matches any public variable in the Flowchart.
/// To perform full variable substitution with all substitution handlers in the scene, you should
/// use the SubstituteVariables() method instead.
/// </summary>
[MoonSharp.Interpreter.MoonSharpHidden]
public virtual bool SubstituteStrings(StringBuilder input)
{
// Instantiate the regular expression object.
Regex r = new Regex(SubstituteVariableRegexString);
bool modified = false;
// Match the regular expression pattern against a text string.
var results = r.Matches(input.ToString());
for (int i = 0; i < results.Count; i++)
{
Match match = results[i];
string key = match.Value.Substring(2, match.Value.Length - 3);
// Look for any matching public variables in this Flowchart
for (int j = 0; j < variables.Count; j++)
{
var variable = variables[j];
if (variable == null)
{
continue;
}
if (variable.Scope == VariableScope.Public && variable.Key == key)
{
string value = variable.ToString();
input.Replace(match.Value, value);
modified = true;
}
}
}
return modified;
}
#endregion
}
}
| |
// Copyright 2019 Esri
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Threading.Tasks;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Core.Geoprocessing;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Framework.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using Version = ArcGIS.Core.Data.Version;
namespace DeleteFeaturesBasedOnSubtypeVersioned
{
/// <summary>
/// Represents the ComboBox which will list the subtypes for the FeatureClass.
/// Also encapsulates the logic for deleting the features corresponding to the selected subtype
/// </summary>
internal class SubtypesComboBox : ComboBox
{
private Random random;
/// <summary>
/// Combo Box contructor
/// </summary>
public SubtypesComboBox()
{
random = new Random();
}
/// <summary>
/// On Opening the Subtype Combobox, the subtypes in the selected FeatureClass are populated in the ComboBox
/// </summary>
protected override void OnDropDownOpened()
{
if (MapView.Active.GetSelectedLayers().Count == 1)
{
Clear();
QueuedTask.Run(() =>
{
var layer = MapView.Active.GetSelectedLayers()[0];
if (layer is FeatureLayer)
{
var featureLayer = layer as FeatureLayer;
if (featureLayer.GetTable().GetDatastore() is UnknownDatastore)
return;
using (var table = featureLayer.GetTable())
{
var readOnlyList = table.GetDefinition().GetSubtypes();
foreach (var subtype in readOnlyList)
{
Add(new ComboBoxItem(subtype.GetName()));
}
}
}
});
}
}
/// <summary>
/// This method will
/// 1. Make sure if a Feature Layer is selected.
/// 2. The Workspace is not null
/// 3. Make sure that the workspace is an Enterprise SQL Server Geodatabase Workspace
///
/// and then create a new version (In a Queued Task)
/// and Connect to the newly created version and delete all the features for the selected subtype (In a separate QueuedTask)
/// </summary>
/// <param name="item">The newly selected combo box item</param>
protected override async void OnSelectionChange(ComboBoxItem item)
{
if (item == null)
return;
if (string.IsNullOrEmpty(item.Text))
return;
Layer layer = MapView.Active.GetSelectedLayers()[0];
FeatureLayer featureLayer = null;
if (layer is FeatureLayer)
{
featureLayer = layer as FeatureLayer;
Geodatabase geodatabase = null;
await QueuedTask.Run(() => geodatabase = (featureLayer.GetTable().GetDatastore() as Geodatabase));
using (geodatabase)
{
if (geodatabase == null)
return;
}
}
else return;
EnterpriseDatabaseType enterpriseDatabaseType = EnterpriseDatabaseType.Unknown;
await QueuedTask.Run(() =>
{
using (Table table = (MapView.Active.GetSelectedLayers()[0] as FeatureLayer).GetTable())
{
try
{
var geodatabase = table.GetDatastore() as Geodatabase;
enterpriseDatabaseType = (geodatabase.GetConnector() as DatabaseConnectionProperties).DBMS;
}
catch (InvalidOperationException)
{
}
}
});
if (enterpriseDatabaseType != EnterpriseDatabaseType.SQLServer)
{
Enabled = false;
return;
}
string versionName = String.Empty;
await QueuedTask.Run(async () =>
{
using (Table table = featureLayer.GetTable())
{
versionName = await CreateVersion(table);
}
});
if (versionName == null)
return;
await QueuedTask.Run(() =>
{
using (Table table = featureLayer.GetTable())
{
if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned))
return;
}
});
await QueuedTask.Run(async () =>
{
using (Table table = featureLayer.GetTable())
{
string subtypeField = table.GetDefinition().GetSubtypeField();
int code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode();
QueryFilter queryFilter = new QueryFilter{WhereClause = string.Format("{0} = {1}", subtypeField, code)};
try
{
VersionManager versionManager = (table.GetDatastore() as Geodatabase).GetVersionManager();
Version newVersion = versionManager.GetVersions().First(version => version.GetName().Contains(versionName));
Geodatabase newVersionGeodatabase = newVersion.Connect();
using (Table newVersionTable = newVersionGeodatabase.OpenDataset<Table>(table.GetName()))
{
using (var rowCursor = newVersionTable.Search(queryFilter, false))
{
EditOperation editOperation = new EditOperation
{
EditOperationType = EditOperationType.Long,
Name = "Delete Based On Subtype"
};
editOperation.Callback(context =>
{
while (rowCursor.MoveNext())
{
using (Row row = rowCursor.Current)
{
context.Invalidate(row);
row.Delete();
}
}
}, newVersionTable);
bool result = await editOperation.ExecuteAsync();
if (!result)
MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}",
item.Text, editOperation.ErrorMessage));
await Project.Current.SaveEditsAsync();
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
});
}
/// <summary>
/// This method calls Geoprocessing to create a new version for the Workspace corresponding to the table
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
private async Task<string> CreateVersion(Table table)
{
try
{
Version defaultVersion = (table.GetDatastore() as Geodatabase).GetVersionManager().GetVersions().FirstOrDefault(version =>
{
string name = version.GetName();
return name.ToLowerInvariant().Equals("dbo.default") || name.ToLowerInvariant().Equals("sde.default");
});
if(defaultVersion == null)
return null;
using (defaultVersion)
{
IReadOnlyList<string> valueArray = Geoprocessing.MakeValueArray(new object[]{table, defaultVersion.GetName(), string.Format("NewVersion{0}", random.Next()), "private"});
List<string> values = new List<String>
{
valueArray[0].Remove(valueArray[0].LastIndexOf("\\", StringComparison.Ordinal)),
valueArray[1],
valueArray[2],
valueArray[3]
};
await Geoprocessing.ExecuteToolAsync("management.CreateVersion", values);
return valueArray[2];
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>
/// A <code>Stream</code> used to wrap a Windows Runtime stream to expose it as a managed steam.
/// </summary>
internal class WinRtToNetFxStreamAdapter : Stream, IDisposable
{
#region Construction
internal static WinRtToNetFxStreamAdapter Create(object windowsRuntimeStream)
{
if (windowsRuntimeStream == null)
throw new ArgumentNullException(nameof(windowsRuntimeStream));
bool canRead = windowsRuntimeStream is IInputStream;
bool canWrite = windowsRuntimeStream is IOutputStream;
bool canSeek = windowsRuntimeStream is IRandomAccessStream;
if (!canRead && !canWrite && !canSeek)
throw new ArgumentException(SR.Argument_ObjectMustBeWinRtStreamToConvertToNetFxStream);
// Proactively guard against a non-conforming curstomer implementations:
if (canSeek)
{
IRandomAccessStream iras = (IRandomAccessStream)windowsRuntimeStream;
if (!canRead && iras.CanRead)
throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanReadMustImplementIIS);
if (!canWrite && iras.CanWrite)
throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanWriteMustImplementIOS);
if (!iras.CanRead)
canRead = false;
if (!iras.CanWrite)
canWrite = false;
}
if (!canRead && !canWrite)
throw new ArgumentException(SR.Argument_WinRtStreamCannotReadOrWrite);
return new WinRtToNetFxStreamAdapter(windowsRuntimeStream, canRead, canWrite, canSeek);
}
private WinRtToNetFxStreamAdapter(object winRtStream, bool canRead, bool canWrite, bool canSeek)
{
Debug.Assert(winRtStream != null);
Debug.Assert(winRtStream is IInputStream || winRtStream is IOutputStream || winRtStream is IRandomAccessStream);
Debug.Assert((canSeek && (winRtStream is IRandomAccessStream)) || (!canSeek && !(winRtStream is IRandomAccessStream)));
Debug.Assert((canRead && (winRtStream is IInputStream))
||
(!canRead && (
!(winRtStream is IInputStream)
||
(winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanRead)
))
);
Debug.Assert((canWrite && (winRtStream is IOutputStream))
||
(!canWrite && (
!(winRtStream is IOutputStream)
||
(winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanWrite)
))
);
_winRtStream = winRtStream;
_canRead = canRead;
_canWrite = canWrite;
_canSeek = canSeek;
}
#endregion Construction
#region Instance variables
private byte[] _oneByteBuffer = null;
private bool _leaveUnderlyingStreamOpen = true;
private object _winRtStream;
private readonly bool _canRead;
private readonly bool _canWrite;
private readonly bool _canSeek;
#endregion Instance variables
#region Tools and Helpers
/// <summary>
/// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream.
/// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered
/// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are
/// finalized, the do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to
/// dispose the underlying stream.
/// </summary>
internal void SetWonInitializationRace()
{
_leaveUnderlyingStreamOpen = false;
}
public TWinRtStream GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class
{
object wrtStr = _winRtStream;
if (wrtStr == null)
return null;
Debug.Assert(wrtStr is TWinRtStream,
$"Attempted to get the underlying WinRT stream typed as \"{typeof(TWinRtStream)}\", " +
$"but the underlying WinRT stream cannot be cast to that type. Its actual type is \"{wrtStr.GetType()}\".");
return wrtStr as TWinRtStream;
}
private byte[] OneByteBuffer
{
get
{
byte[] obb = _oneByteBuffer;
if (obb == null) // benign race for multiple init
_oneByteBuffer = obb = new byte[1];
return obb;
}
}
#if DEBUG
private static void AssertValidStream(object winRtStream)
{
Debug.Assert(winRtStream != null,
"This to-NetFx Stream adapter must not be disposed and the underlying WinRT stream must be of compatible type for this operation");
}
#endif // DEBUG
private TWinRtStream EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class
{
object wrtStr = _winRtStream;
if (wrtStr == null)
throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
return (wrtStr as TWinRtStream);
}
private void EnsureNotDisposed()
{
if (_winRtStream == null)
throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
}
private void EnsureCanRead()
{
if (!_canRead)
throw new NotSupportedException(SR.NotSupported_CannotReadFromStream);
}
private void EnsureCanWrite()
{
if (!_canWrite)
throw new NotSupportedException(SR.NotSupported_CannotWriteToStream);
}
#endregion Tools and Helpers
#region Simple overrides
protected override void Dispose(bool disposing)
{
// WinRT streams should implement IDisposable (IClosable in WinRT), but let's be defensive:
if (disposing && _winRtStream != null && !_leaveUnderlyingStreamOpen)
{
IDisposable disposableWinRtStream = _winRtStream as IDisposable; // benign race on winRtStream
if (disposableWinRtStream != null)
disposableWinRtStream.Dispose();
}
_winRtStream = null;
base.Dispose(disposing);
}
public override bool CanRead
{
[Pure]
get
{ return (_canRead && _winRtStream != null); }
}
public override bool CanWrite
{
[Pure]
get
{ return (_canWrite && _winRtStream != null); }
}
public override bool CanSeek
{
[Pure]
get
{ return (_canSeek && _winRtStream != null); }
}
#endregion Simple overrides
#region Length and Position functions
public override long Length
{
get
{
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUseLength_StreamNotSeekable);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
ulong size = wrtStr.Size;
// These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive:
if (size > (ulong)long.MaxValue)
throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition);
return unchecked((long)size);
}
}
public override long Position
{
get
{
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
ulong pos = wrtStr.Position;
// These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive:
if (pos > (ulong)long.MaxValue)
throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition);
return unchecked((long)pos);
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("Position", SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
wrtStr.Seek(unchecked((ulong)value));
}
}
public override long Seek(long offset, SeekOrigin origin)
{
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
switch (origin)
{
case SeekOrigin.Begin:
{
Position = offset;
return offset;
}
case SeekOrigin.Current:
{
long curPos = Position;
if (long.MaxValue - curPos < offset)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
long newPos = curPos + offset;
if (newPos < 0)
throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
Position = newPos;
return newPos;
}
case SeekOrigin.End:
{
ulong size = wrtStr.Size;
long newPos;
if (size > (ulong)long.MaxValue)
{
if (offset >= 0)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
Debug.Assert(offset < 0);
ulong absOffset = (offset == long.MinValue) ? ((ulong)long.MaxValue) + 1 : (ulong)(-offset);
Debug.Assert(absOffset <= size);
ulong np = size - absOffset;
if (np > (ulong)long.MaxValue)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
newPos = (long)np;
}
else
{
Debug.Assert(size <= (ulong)long.MaxValue);
long s = unchecked((long)size);
if (long.MaxValue - s < offset)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
newPos = s + offset;
if (newPos < 0)
throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
}
Position = newPos;
return newPos;
}
default:
{
throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin));
}
}
}
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative);
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
EnsureCanWrite();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
wrtStr.Size = unchecked((ulong)value);
// If the length is set to a value < that the current position, then we need to set the position to that value
// Because we can't directly set the position, we are going to seek to it.
if (wrtStr.Size < wrtStr.Position)
wrtStr.Seek(unchecked((ulong)value));
}
#endregion Length and Position functions
#region Reading
private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
{
// This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult).
// It would be OK for cases where BeginRead is invoked directly by the public user.
// However, in cases where it is invoked by Read to achieve a blocking (synchronous) IO operation, the ReadAsync-approach may deadlock:
//
// The sync-over-async IO operation will be doing a blocking wait on the completion of the async IO operation assuming that
// a wait handle would be signalled by the completion handler. Recall that the IAsyncInfo representing the IO operation may
// not be free-threaded and not "free-marshalled"; it may also belong to an ASTA compartment because the underlying WinRT
// stream lives in an ASTA compartment. The completion handler is invoked on a pool thread, i.e. in MTA.
// That handler needs to fetch the results from the async IO operation, which requires a cross-compartment call from MTA into ASTA.
// But because the ASTA thread is busy waiting this call will deadlock.
// (Recall that although WaitOne pumps COM, ASTA specifically schedules calls on the outermost ?idle? pump only.)
//
// The solution is to make sure that:
// - In cases where main thread is waiting for the async IO to complete:
// Fetch results on the main thread after it has been signalled by the completion callback.
// - In cases where main thread is not waiting for the async IO to complete:
// Fetch results in the completion callback.
//
// But the Task-plumbing around IAsyncInfo.AsTask *always* fetches results in the completion handler because it has
// no way of knowing whether or not someone is waiting. So, instead of using ReadAsync here we implement our own IAsyncResult
// and our own completion handler which can behave differently according to whether it is being used by a blocking IO
// operation wrapping a BeginRead/EndRead pair, or by an actual async operation based on the old Begin/End pattern.
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
EnsureCanRead();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
IBuffer userBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer,
unchecked((uint)count),
InputStreamOptions.Partial);
StreamReadAsyncResult asyncResult = new StreamReadAsyncResult(asyncReadOperation, userBuffer, callback, state,
processCompletedOperationInCallback: !usedByBlockingWrapper);
// The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation.
// This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to
// asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW
// will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer is the only
// item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped.
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
EnsureNotDisposed();
EnsureCanRead();
StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
if (streamAsyncResult == null)
throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
streamAsyncResult.Wait();
try
{
// If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors,
// cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations.
// See the big comment in BeginRead for details.
if (!streamAsyncResult.ProcessCompletedOperationInCallback)
streamAsyncResult.ProcessCompletedOperation();
// Rethrow errors caught in the completion callback, if any:
if (streamAsyncResult.HasError)
{
streamAsyncResult.CloseStreamOperation();
streamAsyncResult.ThrowCachedError();
}
// Done:
long bytesCompleted = streamAsyncResult.BytesCompleted;
Debug.Assert(bytesCompleted <= unchecked((long)int.MaxValue));
return (int)bytesCompleted;
}
finally
{
// Closing multiple times is Ok.
streamAsyncResult.CloseStreamOperation();
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
EnsureNotDisposed();
EnsureCanRead();
// If already cancelled, bail early:
cancellationToken.ThrowIfCancellationRequested();
// State is Ok. Do the actual read:
return ReadAsyncInternal(buffer, offset, count, cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
// Arguments validation and not-disposed validation are done in BeginRead.
IAsyncResult asyncResult = BeginRead(buffer, offset, count, null, null, usedByBlockingWrapper: true);
int bytesRead = EndRead(asyncResult);
return bytesRead;
}
public override int ReadByte()
{
// EnsureNotDisposed will be called in Read->BeginRead.
byte[] oneByteArray = OneByteBuffer;
if (0 == Read(oneByteArray, 0, 1))
return -1;
int value = oneByteArray[0];
return value;
}
#endregion Reading
#region Writing
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return BeginWrite(buffer, offset, count, callback, state, usedByBlockingWrapper: false);
}
private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
{
// See the large comment in BeginRead about why we are not using this.WriteAsync,
// and instead using a custom implementation of IAsyncResult.
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<uint, uint> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer);
StreamWriteAsyncResult asyncResult = new StreamWriteAsyncResult(asyncWriteOperation, callback, state,
processCompletedOperationInCallback: !usedByBlockingWrapper);
// The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation.
// This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to
// asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW
// will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer if the only
// item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped.
return asyncResult;
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
EnsureNotDisposed();
EnsureCanWrite();
StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
if (streamAsyncResult == null)
throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
streamAsyncResult.Wait();
try
{
// If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors,
// cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations.
// See the big comment in BeginWrite for details.
if (!streamAsyncResult.ProcessCompletedOperationInCallback)
streamAsyncResult.ProcessCompletedOperation();
// Rethrow errors caught in the completion callback, if any:
if (streamAsyncResult.HasError)
{
streamAsyncResult.CloseStreamOperation();
streamAsyncResult.ThrowCachedError();
}
}
finally
{
// Closing multiple times is Ok.
streamAsyncResult.CloseStreamOperation();
}
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
// If already cancelled, bail early:
cancellationToken.ThrowIfCancellationRequested();
IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<uint, uint> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer);
Task asyncWriteTask = asyncWriteOperation.AsTask(cancellationToken);
// The underlying IBuffer is the only object to which we expose a direct pointer to native,
// and that is properly pinned using a mechanism similar to Overlapped.
return asyncWriteTask;
}
public override void Write(byte[] buffer, int offset, int count)
{
// Arguments validation and not-disposed validation are done in BeginWrite.
IAsyncResult asyncResult = BeginWrite(buffer, offset, count, null, null, usedByBlockingWrapper: true);
EndWrite(asyncResult);
}
public override void WriteByte(byte value)
{
// EnsureNotDisposed will be called in Write->BeginWrite.
byte[] oneByteArray = OneByteBuffer;
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
#endregion Writing
#region Flushing
public override void Flush()
{
// See the large comment in BeginRead about why we are not using this.FlushAsync,
// and instead using a custom implementation of IAsyncResult.
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
// Calling Flush in a non-writable stream is a no-op, not an error:
if (!_canWrite)
return;
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync();
StreamFlushAsyncResult asyncResult = new StreamFlushAsyncResult(asyncFlushOperation, processCompletedOperationInCallback: false);
asyncResult.Wait();
try
{
// We got signaled, so process the async Flush operation back on this thread:
// (This is to allow blocking-over-async IO operations. See the big comment in BeginRead for details.)
asyncResult.ProcessCompletedOperation();
// Rethrow errors cached by the async result, if any:
if (asyncResult.HasError)
{
asyncResult.CloseStreamOperation();
asyncResult.ThrowCachedError();
}
}
finally
{
// Closing multiple times is Ok.
asyncResult.CloseStreamOperation();
}
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
// Calling Flush in a non-writable stream is a no-op, not an error:
if (!_canWrite)
return Task.CompletedTask;
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
cancellationToken.ThrowIfCancellationRequested();
IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync();
Task asyncFlushTask = asyncFlushOperation.AsTask(cancellationToken);
return asyncFlushTask;
}
#endregion Flushing
#region ReadAsyncInternal implementation
// Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense.
// Should move this code into the Reading regios once using Dev11 VS becomes the norm.
private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - offset >= count);
Debug.Assert(_canRead);
IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
try
{
IBuffer userBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer,
unchecked((uint)count),
InputStreamOptions.Partial);
IBuffer resultBuffer = await asyncReadOperation.AsTask(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
// If cancellationToken was cancelled until now, then we are currently propagating the corresponding cancellation exception.
// (It will be correctly rethrown by the catch block below and overall we will return a cancelled task.)
// But if the underlying operation managed to complete before it was cancelled, we want
// the entire task to complete as well. This is ok as the continuation is very lightweight:
if (resultBuffer == null)
return 0;
WinRtIOHelper.EnsureResultsInUserBuffer(userBuffer, resultBuffer);
Debug.Assert(resultBuffer.Length <= unchecked((uint)int.MaxValue));
return (int)resultBuffer.Length;
}
catch (Exception ex)
{
// If the interop layer gave us an Exception, we assume that it hit a general/unknown case and wrap it into
// an IOException as this is what Stream users expect.
WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
return 0;
}
}
#endregion ReadAsyncInternal implementation
} // class WinRtToNetFxStreamAdapter
} // namespace
// WinRtToNetFxStreamAdapter.cs
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
namespace System.Abstract
{
/// <summary>
/// AbstractExtensions
/// </summary>
static partial class AbstractExtensions
{
/// <summary>
/// Sends the specified service bus.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="serviceBus">The service bus.</param>
/// <param name="messageBuilder">The message builder.</param>
/// <returns>IServiceBusCallback.</returns>
public static IServiceBusCallback Send<TMessage>(this IServiceBus serviceBus, Action<TMessage> messageBuilder)
where TMessage : class =>
serviceBus.Send(null, serviceBus.CreateMessage(messageBuilder));
/// <summary>
/// Sends the specified service bus.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="serviceBus">The service bus.</param>
/// <param name="destination">The destination.</param>
/// <param name="messageBuilder">The message builder.</param>
/// <returns>IServiceBusCallback.</returns>
public static IServiceBusCallback Send<TMessage>(this IServiceBus serviceBus, string destination, Action<TMessage> messageBuilder)
where TMessage : class =>
serviceBus.Send(new LiteralServiceBusEndpoint(destination), serviceBus.CreateMessage(messageBuilder));
/// <summary>
/// Sends the specified service bus.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="serviceBus">The service bus.</param>
/// <param name="destination">The destination.</param>
/// <param name="messageBuilder">The message builder.</param>
/// <returns>IServiceBusCallback.</returns>
public static IServiceBusCallback Send<TMessage>(this IServiceBus serviceBus, IServiceBusEndpoint destination, Action<TMessage> messageBuilder)
where TMessage : class =>
serviceBus.Send(destination, serviceBus.CreateMessage(messageBuilder));
/// <summary>
/// Sends the specified service bus.
/// </summary>
/// <param name="serviceBus">The service bus.</param>
/// <param name="messages">The messages.</param>
/// <returns>IServiceBusCallback.</returns>
public static IServiceBusCallback Send(this IServiceBus serviceBus, params object[] messages) =>
serviceBus.Send(null, messages);
/// <summary>
/// Sends the specified service bus.
/// </summary>
/// <param name="serviceBus">The service bus.</param>
/// <param name="destination">The destination.</param>
/// <param name="messages">The messages.</param>
/// <returns>IServiceBusCallback.</returns>
public static IServiceBusCallback Send(this IServiceBus serviceBus, string destination, params object[] messages) =>
serviceBus.Send(new LiteralServiceBusEndpoint(destination), messages);
/// <summary>
/// Replies the specified service bus.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="serviceBus">The service bus.</param>
/// <param name="messageBuilder">The message builder.</param>
public static void Reply<TMessage>(this IServiceBus serviceBus, Action<TMessage> messageBuilder)
where TMessage : class =>
serviceBus.Reply(serviceBus.CreateMessage(messageBuilder));
// publishing
/// <summary>
/// Publishes the specified service bus.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="serviceBus">The service bus.</param>
/// <param name="messageBuilder">The message builder.</param>
public static void Publish<TMessage>(this IPublishingServiceBus serviceBus, Action<TMessage> messageBuilder)
where TMessage : class =>
serviceBus.Publish(serviceBus.CreateMessage(messageBuilder));
/// <summary>
/// Subscribes the specified service bus.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="serviceBus">The service bus.</param>
/// <param name="condition">The condition.</param>
public static void Subscribe<TMessage>(this IPublishingServiceBus serviceBus, Predicate<TMessage> condition = null)
where TMessage : class =>
serviceBus.Subscribe(typeof(TMessage), condition == null ? null : new Predicate<object>(m => m is TMessage ? condition((TMessage)m) : true));
/// <summary>
/// Subscribes the specified service bus.
/// </summary>
/// <param name="serviceBus">The service bus.</param>
/// <param name="messageType">Type of the message.</param>
public static void Subscribe(this IPublishingServiceBus serviceBus, Type messageType) =>
serviceBus.Subscribe(messageType);
/// <summary>
/// Unsubscribes the specified service bus.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="serviceBus">The service bus.</param>
public static void Unsubscribe<TMessage>(this IPublishingServiceBus serviceBus)
where TMessage : class =>
serviceBus.Unsubscribe(typeof(TMessage));
#region BehaveAs
/// <summary>
/// Behaves as.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <returns>T.</returns>
public static T BehaveAs<T>(this IServiceBus service)
where T : class, IServiceBus
{
IServiceWrapper<IServiceBus> serviceWrapper;
do
{
serviceWrapper = (service as IServiceWrapper<IServiceBus>);
if (serviceWrapper != null)
service = serviceWrapper.Base;
} while (serviceWrapper != null);
return service as T;
}
#endregion
#region Lazy Setup
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="name">The name.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> RegisterWithServiceLocator<T>(this Lazy<IServiceBus> service, string name = null)
where T : class, IServiceBus
{ ServiceBusManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, name, ServiceLocatorManager.Lazy); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> RegisterWithServiceLocator<T>(this Lazy<IServiceBus> service, IServiceLocator locator, string name = null)
where T : class, IServiceBus
{ ServiceBusManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, name, locator); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> RegisterWithServiceLocator<T>(this Lazy<IServiceBus> service, Lazy<IServiceLocator> locator, string name = null)
where T : class, IServiceBus
{ ServiceBusManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, name, locator); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> RegisterWithServiceLocator(this Lazy<IServiceBus> service, Type serviceType, string name = null)
{ ServiceBusManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, serviceType, name, ServiceLocatorManager.Lazy); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="serviceType">Type of the service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> RegisterWithServiceLocator(this Lazy<IServiceBus> service, Type serviceType, IServiceLocator locator, string name = null)
{ ServiceBusManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, serviceType, name, locator); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="serviceType">Type of the service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> RegisterWithServiceLocator(this Lazy<IServiceBus> service, Type serviceType, Lazy<IServiceLocator> locator, string name = null)
{ ServiceBusManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, serviceType, name, locator); return service; }
/// <summary>
/// Adds the endpoint.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="endpoint">The endpoint.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> AddEndpoint(this Lazy<IServiceBus> service, string endpoint) =>
service;
/// <summary>
/// Adds the message handlers by scan.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> AddMessageHandlersByScan(this Lazy<IServiceBus> service, params Assembly[] assemblies)
{ ServiceBusManager.GetSetupDescriptor(service).Do(s => AddMessageHandlersByScan(s, null, assemblies)); return service; }
/// <summary>
/// Adds the message handlers by scan.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="predicate">The predicate.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> AddMessageHandlersByScan(this Lazy<IServiceBus> service, Predicate<Type> predicate, params Assembly[] assemblies)
{ ServiceBusManager.GetSetupDescriptor(service).Do(s => AddMessageHandlersByScan(s, predicate, assemblies)); return service; }
/// <summary>
/// Adds the message handler.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="handlerType">Type of the handler.</param>
/// <returns>Lazy<IServiceBus>.</returns>
public static Lazy<IServiceBus> AddMessageHandler(this Lazy<IServiceBus> service, Type handlerType)
{ ServiceBusManager.GetSetupDescriptor(service).Do(s => AddMessageHandler(s, handlerType)); return service; }
#endregion
/// <summary>
/// Adds the message handlers by scan.
/// </summary>
/// <typeparam name="TMessageHandler">The type of the message handler.</typeparam>
/// <param name="bus">The bus.</param>
public static void AddMessageHandlersByScan<TMessageHandler>(IServiceBus bus)
where TMessageHandler : class =>
AddMessageHandlersByScan(bus, typeof(TMessageHandler));
/// <summary>
/// Adds the message handlers by scan.
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="handlerType">Type of the handler.</param>
/// <exception cref="InvalidOperationException">Unable find a message handler</exception>
public static void AddMessageHandlersByScan(IServiceBus bus, Type handlerType)
{ var messageType = GetMessageTypeFromHandler(handlerType) ?? throw new InvalidOperationException("Unable find a message handler"); }
//IEnumerable<Type> GetTypesOfMessageHandlers(Type messageType)
//{
// return Items.Where(x => x.MessageType == messageType)
// .Select(x => x.MessageHandlerType);
//}
static IEnumerable<Type> GetMessageTypeFromHandler(Type messageHandlerType)
{
//var serviceMessageType = typeof(IServiceMessage);
//return messageHandlerType.GetInterfaces()
// .Where(h => h.IsGenericType && (h.FullName.StartsWith("System.Abstract.IServiceMessageHandler`1") || h.FullName.StartsWith("Contoso.Abstract.IApplicationServiceMessageHandler`1")))
// .Select(h => h.GetGenericArguments()[0])
// .Where(m => m.GetInterfaces().Any(x => x == serviceMessageType || x == applicationServiceMessageType));
return null;
}
/// <summary>
/// Adds the message handlers by scan.
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="predicate">The predicate.</param>
/// <param name="assemblies">The assemblies.</param>
public static void AddMessageHandlersByScan(IServiceBus bus, Predicate<Type> predicate, params Assembly[] assemblies)
{
if (assemblies.Count() == 0)
return;
//var types = assemblies.SelectMany(a => a.GetTypes())
// .Where(t => typeof(basedOnType.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract && (predicate == null || predicate(t)));
//foreach (var type in types)
// action(basedOnType, type, Guid.NewGuid().ToString());
}
/// <summary>
/// Adds the message handler.
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="handlerType">Type of the handler.</param>
public static void AddMessageHandler(IServiceBus bus, Type handlerType) { }
//public static string ToString(this IServiceBusLocation location, Func<IServiceBusLocation, object, string> builder, object arg)
//{
// if (location == null)
// throw new ArgumentNullException("location");
// if (builder == null)
// throw new ArgumentNullException("builder");
// if (location == ServiceBus.Self)
// return null;
// var literal = (location as LiteralServiceBusLocation);
// if (literal != null)
// return literal.Value;
// return builder(location, arg);
//}
}
}
| |
/*
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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web.Mvc;
using Adxstudio.Xrm.Cms.Security;
using Adxstudio.Xrm.Web.Mvc.Html;
using Adxstudio.Xrm.Web.Mvc.Liquid;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Newtonsoft.Json.Linq;
namespace Adxstudio.Xrm.Web.Mvc.Controllers
{
/// <summary>
/// Provides services for metadata and preview rendering for CMS (Liquid) templates.
/// </summary>
[PortalView]
public class CmsTemplateController : Controller
{
[HttpGet]
public ActionResult GetAll(string entityLogicalName, Guid id, string currentSiteMapNodeUrl, string context = null)
{
if (!Authorized(entityLogicalName, id, context))
{
return new JContainerResult(new JArray());
}
var templates = GetTemplateFileSystem()
.GetTemplateFiles()
.OrderBy(template => template.Name)
.Select(template => new JObject {
{ "name", template.Name },
{ "title", template.Title },
{ "description", template.Description },
{ "include", string.IsNullOrEmpty(template.DefaultArguments)
? "{{% include '{0}' %}}".FormatWith(template.Name)
: "{{% include '{0}' {1} %}}".FormatWith(template.Name, template.DefaultArguments)
},
{ "url", Url.RouteUrl("CmsTemplate_Get", new
{
encodedName = EncodeTemplateName(template.Name),
context
}) },
{ "preview_url", Url.RouteUrl("CmsTemplate_GetPreview", new
{
encodedName = EncodeTemplateName(template.Name),
__currentSiteMapNodeUrl__ = currentSiteMapNodeUrl,
context
}) },
{ "live_preview_url", Url.RouteUrl("CmsTemplate_GetLivePreview", new
{
__currentSiteMapNodeUrl__ = currentSiteMapNodeUrl,
context
}) }
});
return new JContainerResult(new JArray(templates));
}
[HttpGet]
public ActionResult Get(string entityLogicalName, Guid id, string encodedName, string context = null)
{
if (!Authorized(entityLogicalName, id, context))
{
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
var name = DecodeTemplateName(encodedName);
var fileSystem = GetTemplateFileSystem();
string template;
return fileSystem.TryReadTemplateFile(name, out template)
? TemplateContent(template)
: HttpNotFound();
}
[HttpGet]
[OutputCache(CacheProfile = "User")]
public ActionResult GetPreview(string entityLogicalName, Guid id, string encodedName, string context = null)
{
if (!Authorized(entityLogicalName, id, context))
{
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
var name = DecodeTemplateName(encodedName);
var fileSystem = GetTemplateFileSystem();
string template;
return fileSystem.TryReadTemplateFile(name, out template)
? TemplatePreviewContent(template)
: HttpNotFound();
}
[HttpPost]
[AjaxValidateAntiForgeryToken, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "Handled with the custom attribute AjaxValidateAntiForgeryToken")]
public ActionResult GetLivePreview(string entityLogicalName, Guid id, string source, string context = null)
{
if (!Authorized(entityLogicalName, id, context))
{
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
return TemplatePreviewContent(source ?? string.Empty);
}
private bool Authorized(string entityLogicalName, Guid id, string context = null)
{
var portalViewContext = ViewData[PortalExtensions.PortalViewContextKey] as IPortalViewContext;
if (portalViewContext == null)
{
return false;
}
using (var serviceContext = portalViewContext.CreateServiceContext())
{
var response = (RetrieveResponse)serviceContext.Execute(new RetrieveRequest
{
ColumnSet = new ColumnSet(true),
Target = new EntityReference(entityLogicalName, id)
});
if (response.Entity == null)
{
return false;
}
var entity = serviceContext.MergeClone(response.Entity);
if (entity.ToEntityReference().Equals(portalViewContext.Website.EntityReference) && context != null)
{
if (string.Equals(context, "adx_contentsnippet", StringComparison.OrdinalIgnoreCase))
{
return portalViewContext.WebsiteAccessPermissionProvider.TryAssert(serviceContext, WebsiteRight.ManageContentSnippets);
}
if (string.Equals(context, "adx_sitemarker", StringComparison.OrdinalIgnoreCase))
{
return portalViewContext.WebsiteAccessPermissionProvider.TryAssert(serviceContext, WebsiteRight.ManageSiteMarkers);
}
if (string.Equals(context, "adx_weblinkset", StringComparison.OrdinalIgnoreCase)
|| string.Equals(context, "adx_weblink", StringComparison.OrdinalIgnoreCase))
{
return portalViewContext.WebsiteAccessPermissionProvider.TryAssert(serviceContext, WebsiteRight.ManageWebLinkSets);
}
}
var securityProvider = portalViewContext.CreateCrmEntitySecurityProvider();
return securityProvider.TryAssert(serviceContext, entity, CrmEntityRight.Change);
}
}
private IComposableFileSystem GetTemplateFileSystem()
{
var portalViewContext = ViewData[PortalExtensions.PortalViewContextKey] as IPortalViewContext;
if (portalViewContext == null)
{
throw new InvalidOperationException("Unable to retrieve the portal view context.");
}
return new CompositeFileSystem(
new EntityFileSystem(portalViewContext, "adx_webtemplate", "adx_name", "adx_source"),
new EmbeddedResourceFileSystem(Assembly.GetExecutingAssembly(), "Adxstudio.Xrm.Liquid"));
}
private ActionResult TemplateContent(string template)
{
return Content(template, "text/plain");
}
private ActionResult TemplatePreviewContent(string template)
{
return View(new TemplatePreviewView(template));
}
private static string DecodeTemplateName(string name)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(name));
}
private static string EncodeTemplateName(string name)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(name));
}
private class TemplatePreviewView : IView
{
private readonly string _template;
public TemplatePreviewView(string template)
{
if (template == null) throw new ArgumentNullException("template");
_template = template;
}
public void Render(ViewContext viewContext, TextWriter writer)
{
viewContext.HttpContext.Response.ContentType = "text/plain";
var html = new HtmlHelper(viewContext, new ViewPage());
html.RenderLiquid(_template, writer, new
{
preview = true
});
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Xunit.Abstractions;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text.RegularExpressions;
namespace System.Xml.Tests
{
public class LineInfo
{
public int LineNumber { get; private set; }
public int LinePosition { get; private set; }
public string FilePath { get; private set; }
public LineInfo(int lineNum, int linePos)
{
LineNumber = lineNum;
LinePosition = linePos;
FilePath = string.Empty;
}
public LineInfo(int lineNum, int linePos, string filePath)
{
LineNumber = lineNum;
LinePosition = linePos;
FilePath = filePath;
}
}
[Flags]
public enum ExceptionVerificationFlags
{
None = 0,
IgnoreMultipleDots = 1,
IgnoreLineInfo = 2,
}
public class ExceptionVerifier
{
private readonly Assembly _asm;
private Assembly _locAsm;
private readonly Hashtable _resources;
private string _actualMessage;
private string _expectedMessage;
private Exception _ex;
private ExceptionVerificationFlags _verificationFlags = ExceptionVerificationFlags.None;
private ITestOutputHelper _output;
public bool IgnoreMultipleDots
{
get
{
return (_verificationFlags & ExceptionVerificationFlags.IgnoreMultipleDots) != 0;
}
set
{
if (value)
_verificationFlags = _verificationFlags | ExceptionVerificationFlags.IgnoreMultipleDots;
else
_verificationFlags = _verificationFlags & (~ExceptionVerificationFlags.IgnoreMultipleDots);
}
}
public bool IgnoreLineInfo
{
get
{
return (_verificationFlags & ExceptionVerificationFlags.IgnoreLineInfo) != 0;
}
set
{
if (value)
_verificationFlags = _verificationFlags | ExceptionVerificationFlags.IgnoreLineInfo;
else
_verificationFlags = _verificationFlags & (~ExceptionVerificationFlags.IgnoreLineInfo);
}
}
private const string ESCAPE_ANY = "~%anything%~";
private const string ESCAPE_NUMBER = "~%number%~";
public ExceptionVerifier(string assemblyName, ExceptionVerificationFlags flags, ITestOutputHelper output)
{
_output = output;
if (assemblyName == null)
throw new VerifyException("Assembly name cannot be null");
_verificationFlags = flags;
try
{
switch (assemblyName.ToUpper())
{
case "SYSTEM.XML":
{
var dom = new XmlDocument();
_asm = dom.GetType().Assembly;
}
break;
default:
_asm = Assembly.LoadFrom(Path.Combine(GetRuntimeInstallDir(), assemblyName + ".dll"));
break;
}
if (_asm == null)
throw new VerifyException("Can not load assembly " + assemblyName);
// let's determine if this is a loc run, if it is then we need to load satellite assembly
_locAsm = null;
if (!CultureInfo.CurrentCulture.Equals(new CultureInfo("en-US")) && !CultureInfo.CurrentCulture.Equals(new CultureInfo("en")))
{
try
{
// load satellite assembly
_locAsm = _asm.GetSatelliteAssembly(new CultureInfo(CultureInfo.CurrentCulture.Parent.IetfLanguageTag));
}
catch (FileNotFoundException e1)
{
_output.WriteLine(e1.ToString());
}
catch (FileLoadException e2)
{
_output.WriteLine(e2.ToString());
}
}
}
catch (Exception e)
{
_output.WriteLine("Exception: " + e.Message);
_output.WriteLine("Stack: " + e.StackTrace);
throw new VerifyException("Error while loading assembly");
}
string[] resArray;
Stream resStream = null;
var bFound = false;
// Check that assembly manifest has resources
if (null != _locAsm)
resArray = _locAsm.GetManifestResourceNames();
else
resArray = _asm.GetManifestResourceNames();
foreach (var s in resArray)
{
if (s.EndsWith(".resources"))
{
resStream = null != _locAsm ? _locAsm.GetManifestResourceStream(s) : _asm.GetManifestResourceStream(s);
bFound = true;
if (bFound && resStream != null)
{
// Populate hashtable from resources
var resReader = new ResourceReader(resStream);
if (_resources == null)
{
_resources = new Hashtable();
}
var ide = resReader.GetEnumerator();
while (ide.MoveNext())
{
if (!_resources.ContainsKey(ide.Key.ToString()))
_resources.Add(ide.Key.ToString(), ide.Value.ToString());
}
resReader.Dispose();
}
//break;
}
}
if (!bFound || resStream == null)
throw new VerifyException("GetManifestResourceStream() failed");
}
private static string GetRuntimeInstallDir()
{
// Get mscorlib path
var s = typeof(object).Module.FullyQualifiedName;
// Remove mscorlib.dll from the path
return Directory.GetParent(s).ToString();
}
public ExceptionVerifier(string assemblyName, ITestOutputHelper output)
: this(assemblyName, ExceptionVerificationFlags.None, output)
{ }
private void ExceptionInfoOutput()
{
// Use reflection to obtain "res" property value
var exceptionType = _ex.GetType();
var fInfo = exceptionType.GetField("res", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase) ??
exceptionType.BaseType.GetField("res", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (fInfo == null)
throw new VerifyException("Cannot obtain Resource ID from Exception.");
_output.WriteLine(
"\n===== Original Exception Message =====\n" + _ex.Message +
"\n===== Resource Id =====\n" + fInfo.GetValue(_ex) +
"\n===== HelpLink =====\n" + _ex.HelpLink +
"\n===== Source =====\n" + _ex.Source /*+
"\n===== TargetSite =====\n" + ex.TargetSite + "\n"*/);
_output.WriteLine(
"\n===== InnerException =====\n" + _ex.InnerException +
"\n===== StackTrace =====\n" + _ex.StackTrace);
}
public string[] ReturnAllMatchingResIds(string message)
{
var ide = _resources.GetEnumerator();
var list = new ArrayList();
_output.WriteLine("===== All mached ResIDs =====");
while (ide.MoveNext())
{
var resMessage = ide.Value.ToString();
resMessage = ESCAPE_ANY + Regex.Replace(resMessage, @"\{\d*\}", ESCAPE_ANY) + ESCAPE_ANY;
resMessage = MakeEscapes(resMessage).Replace(ESCAPE_ANY, ".*");
if (Regex.Match(message, resMessage, RegexOptions.Singleline).ToString() == message)
{
list.Add(ide.Key);
_output.WriteLine(" [" + ide.Key.ToString() + "] = \"" + ide.Value.ToString() + "\"");
}
}
return (string[])list.ToArray(typeof(string[]));
}
// Common helper methods used by different overloads of IsExceptionOk()
private static void CheckNull(Exception e)
{
if (e == null)
{
throw new VerifyException("NULL exception passed to IsExceptionOk()");
}
}
private void CompareMessages()
{
if (IgnoreMultipleDots && _expectedMessage.EndsWith("."))
_expectedMessage = _expectedMessage.TrimEnd(new char[] { '.' }) + ".";
_expectedMessage = Regex.Escape(_expectedMessage);
_expectedMessage = _expectedMessage.Replace(ESCAPE_ANY, ".*");
_expectedMessage = _expectedMessage.Replace(ESCAPE_NUMBER, @"\d*");
// ignore case
_expectedMessage = _expectedMessage.ToLowerInvariant();
_actualMessage = _actualMessage.ToLowerInvariant();
if (Regex.Match(_actualMessage, _expectedMessage, RegexOptions.Singleline).ToString() != _actualMessage)
{
// Unescape before printing the expected message string
_expectedMessage = Regex.Unescape(_expectedMessage);
_output.WriteLine("Mismatch in error message");
_output.WriteLine("===== Expected Message =====\n" + _expectedMessage);
_output.WriteLine("===== Expected Message Length =====\n" + _expectedMessage.Length);
_output.WriteLine("===== Actual Message =====\n" + _actualMessage);
_output.WriteLine("===== Actual Message Length =====\n" + _actualMessage.Length);
throw new VerifyException("Mismatch in error message");
}
}
public void IsExceptionOk(Exception e, string expectedResId)
{
CheckNull(e);
_ex = e;
if (expectedResId == null)
{
// Pint actual exception info and quit
// This can be used to dump exception properties, verify them and then plug them into our expected results
ExceptionInfoOutput();
throw new VerifyException("Did not pass resource ID to verify");
}
IsExceptionOk(e, new object[] { expectedResId });
}
public void IsExceptionOk(Exception e, string expectedResId, string[] paramValues)
{
var list = new ArrayList { expectedResId };
foreach (var param in paramValues)
list.Add(param);
IsExceptionOk(e, list.ToArray());
}
public void IsExceptionOk(Exception e, string expectedResId, string[] paramValues, LineInfo lineInfo)
{
var list = new ArrayList { expectedResId, lineInfo };
foreach (var param in paramValues)
list.Add(param);
IsExceptionOk(e, list.ToArray());
}
public void IsExceptionOk(Exception e, object[] IdsAndParams)
{
CheckNull(e);
_ex = e;
_actualMessage = e.Message;
_expectedMessage = ConstructExpectedMessage(IdsAndParams);
CompareMessages();
}
private static string MakeEscapes(string str)
{
return new[] { "\\", "$", "{", "[", "(", "|", ")", "*", "+", "?" }.Aggregate(str, (current, esc) => current.Replace(esc, "\\" + esc));
}
public string ConstructExpectedMessage(object[] IdsAndParams)
{
var lineInfoMessage = "";
var paramList = new ArrayList();
var paramsStartPosition = 1;
// Verify that input list contains at least one element - ResId
if (IdsAndParams.Length == 0 || !(IdsAndParams[0] is string))
throw new VerifyException("ResID at IDsAndParams[0] missing!");
string expectedResId = (IdsAndParams[0] as string);
// Verify that resource id exists in resources
if (!_resources.ContainsKey(expectedResId))
{
ExceptionInfoOutput();
throw new VerifyException("Resources in [" + _asm.GetName().Name + "] does not contain string resource: " + expectedResId);
}
// If LineInfo exist, construct LineInfo message
if (IdsAndParams.Length > 1 && (IdsAndParams[1] is LineInfo))
{
if (!IgnoreLineInfo)
{
var lineInfo = (IdsAndParams[1] as LineInfo);
// Xml_ErrorPosition = "Line {0}, position {1}."
lineInfoMessage = string.IsNullOrEmpty(lineInfo.FilePath) ? _resources["Xml_ErrorPosition"].ToString() : _resources["Xml_ErrorFilePosition"].ToString();
var lineNumber = lineInfo.LineNumber.ToString();
var linePosition = lineInfo.LinePosition.ToString();
lineInfoMessage = string.IsNullOrEmpty(lineInfo.FilePath) ? string.Format(lineInfoMessage, lineNumber, linePosition) : string.Format(lineInfoMessage, lineInfo.FilePath, lineNumber, linePosition);
}
else
lineInfoMessage = ESCAPE_ANY;
lineInfoMessage = " " + lineInfoMessage;
paramsStartPosition = 2;
}
string message = _resources[expectedResId].ToString();
for (var i = paramsStartPosition; i < IdsAndParams.Length; i++)
{
if (IdsAndParams[i] is object[])
paramList.Add(ConstructExpectedMessage(IdsAndParams[i] as object[]));
else
{
if (IdsAndParams[i] == null)
paramList.Add(ESCAPE_ANY);
else
paramList.Add(IdsAndParams[i] as string);
}
}
try
{
message = string.Format(message, paramList.ToArray());
}
catch (FormatException)
{
throw new VerifyException("Mismatch in number of parameters!");
}
return message + lineInfoMessage;
}
}
public class VerifyException : Exception
{
public VerifyException(string msg)
: base(msg)
{ }
}
}
| |
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 Appoints.Api.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;
}
}
}
| |
//
// Authors:
// Miguel de Icaza
//
// 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.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.CoreGraphics;
namespace MonoMac.ImageIO {
public class CGImageDestinationOptions {
static IntPtr kLossyCompressionQuality;
static IntPtr kBackgroundColor;
static void Init ()
{
if (kLossyCompressionQuality != IntPtr.Zero)
return;
IntPtr lib = Libraries.ImageIO.Handle;
kLossyCompressionQuality = Dlfcn.GetIntPtr (lib, "kCGImageDestinationLossyCompressionQuality");
kBackgroundColor = Dlfcn.GetIntPtr (lib, "kCGImageDestinationBackgroundColor");
}
public float? LossyCompressionQuality { get; set; }
public CGColor DestinationBackgroundColor { get; set; }
internal NSMutableDictionary ToDictionary ()
{
Init ();
var dict = new NSMutableDictionary ();
if (LossyCompressionQuality.HasValue)
dict.LowlevelSetObject (new NSNumber (LossyCompressionQuality.Value), kLossyCompressionQuality);
if (DestinationBackgroundColor != null)
dict.LowlevelSetObject (DestinationBackgroundColor.Handle, kBackgroundColor);
return dict;
}
}
public class CGImageDestination : INativeObject, IDisposable {
internal IntPtr handle;
// invoked by marshallers
internal CGImageDestination (IntPtr handle) : this (handle, false)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CGImageDestination (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
~CGImageDestination ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
[DllImport (Constants.ImageIOLibrary, EntryPoint="CGImageDestinationGetTypeID")]
public extern static int GetTypeID ();
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageDestinationCopyTypeIdentifiers ();
public static string [] TypeIdentifiers {
get {
return NSArray.StringArrayFromHandle (CGImageDestinationCopyTypeIdentifiers ());
}
}
// TODO: CGImageDestinationCreateWithDataConsumer
// Missing the CGDataConsumer API
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageDestinationCreateWithData (IntPtr data, IntPtr stringType, IntPtr count, IntPtr options);
public static CGImageDestination FromData (NSData data, string typeIdentifier, int imageCount)
{
return FromData (data, typeIdentifier, imageCount, null);
}
public static CGImageDestination FromData (NSData data, string typeIdentifier, int imageCount, CGImageDestinationOptions options)
{
if (data == null)
throw new ArgumentNullException ("data");
if (typeIdentifier == null)
throw new ArgumentNullException ("typeIdentifier");
var dict = options == null ? null : options.ToDictionary ();
var typeId = NSString.CreateNative (typeIdentifier);
IntPtr p = CGImageDestinationCreateWithData (data.Handle, typeId, (IntPtr) imageCount, dict == null ? IntPtr.Zero : dict.Handle);
NSString.ReleaseNative (typeId);
var ret = p == IntPtr.Zero ? null : new CGImageDestination (p, true);
if (dict != null)
dict.Dispose ();
return ret;
}
[DllImport (Constants.ImageIOLibrary)]
extern static IntPtr CGImageDestinationCreateWithURL (IntPtr url, IntPtr stringType, IntPtr count, IntPtr options);
public static CGImageDestination FromUrl (NSUrl url, string typeIdentifier, int imageCount)
{
return FromUrl (url, typeIdentifier, imageCount, null);
}
public static CGImageDestination FromUrl (NSUrl url, string typeIdentifier, int imageCount, CGImageDestinationOptions options)
{
if (url == null)
throw new ArgumentNullException ("url");
if (typeIdentifier == null)
throw new ArgumentNullException ("typeIdentifier");
var dict = options == null ? null : options.ToDictionary ();
var typeId = NSString.CreateNative (typeIdentifier);
IntPtr p = CGImageDestinationCreateWithURL (url.Handle, typeId, (IntPtr) imageCount, dict == null ? IntPtr.Zero : dict.Handle);
NSString.ReleaseNative (typeId);
var ret = p == IntPtr.Zero ? null : new CGImageDestination (p, true);
if (dict != null)
dict.Dispose ();
return ret;
}
[DllImport (Constants.ImageIOLibrary)]
extern static void CGImageDestinationSetProperties (IntPtr handle, IntPtr props);
public void SetProperties (NSDictionary properties)
{
if (properties == null)
throw new ArgumentNullException ("properties");
CGImageDestinationSetProperties (handle, properties.Handle);
}
[DllImport (Constants.ImageIOLibrary)]
extern static void CGImageDestinationAddImage (IntPtr handle, IntPtr image, IntPtr properties);
public void AddImage (CGImage image, NSDictionary properties)
{
if (image == null)
throw new ArgumentNullException ("image");
CGImageDestinationAddImage (handle, image.Handle, properties == null ? IntPtr.Zero : properties.Handle);
}
[DllImport (Constants.ImageIOLibrary)]
extern static void CGImageDestinationAddImageFromSource (IntPtr handle, IntPtr sourceHandle, IntPtr index, IntPtr properties);
public void AddImage (CGImageSource source, int index, NSDictionary properties)
{
if (source == null)
throw new ArgumentNullException ("source");
CGImageDestinationAddImageFromSource (handle, source.Handle, (IntPtr) index, properties == null ? IntPtr.Zero : properties.Handle);
}
[DllImport (Constants.ImageIOLibrary)]
extern static bool CGImageDestinationFinalize (IntPtr handle);
public bool Close ()
{
var success = CGImageDestinationFinalize (handle);
Dispose ();
return success;
}
}
}
| |
// Copyright (c) 2013 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using SharpYaml;
using SharpYaml.Events;
namespace SharpYaml.Serialization
{
/// <summary>
/// Represents an YAML document.
/// </summary>
public class YamlDocument
{
/// <summary>
/// Gets or sets the root node.
/// </summary>
/// <value>The root node.</value>
public YamlNode RootNode { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="YamlDocument"/> class.
/// </summary>
public YamlDocument(YamlNode rootNode)
{
RootNode = rootNode;
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlDocument"/> class with a single scalar node.
/// </summary>
public YamlDocument(string rootNode)
{
RootNode = new YamlScalarNode(rootNode);
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlDocument"/> class.
/// </summary>
/// <param name="events">The events.</param>
internal YamlDocument(EventReader events)
{
DocumentLoadingState state = new DocumentLoadingState();
events.Expect<DocumentStart>();
while (!events.Accept<DocumentEnd>())
{
Debug.Assert(RootNode == null);
RootNode = YamlNode.ParseNode(events, state);
if (RootNode is YamlAliasNode)
{
throw new YamlException();
}
}
state.ResolveAliases();
#if DEBUG
foreach (var node in AllNodes)
{
if (node is YamlAliasNode)
{
throw new InvalidOperationException("Error in alias resolution.");
}
}
#endif
events.Expect<DocumentEnd>();
}
/// <summary>
/// Visitor that assigns anchors to nodes that are referenced more than once but have no anchor.
/// </summary>
private class AnchorAssigningVisitor : YamlVisitor
{
private readonly HashSet<string> existingAnchors = new HashSet<string>();
private readonly Dictionary<YamlNode, bool> visitedNodes = new Dictionary<YamlNode, bool>(new YamlNodeIdentityEqualityComparer());
public void AssignAnchors(YamlDocument document)
{
existingAnchors.Clear();
visitedNodes.Clear();
document.Accept(this);
Random random = new Random();
foreach (var visitedNode in visitedNodes)
{
if (visitedNode.Value)
{
string anchor;
do
{
anchor = random.Next().ToString(CultureInfo.InvariantCulture);
} while (existingAnchors.Contains(anchor));
existingAnchors.Add(anchor);
visitedNode.Key.Anchor = anchor;
}
}
}
private void VisitNode(YamlNode node)
{
if (string.IsNullOrEmpty(node.Anchor))
{
bool isDuplicate;
if (visitedNodes.TryGetValue(node, out isDuplicate))
{
if (!isDuplicate)
{
visitedNodes[node] = true;
}
}
else
{
visitedNodes.Add(node, false);
}
}
else
{
existingAnchors.Add(node.Anchor);
}
}
protected override void Visit(YamlScalarNode scalar)
{
VisitNode(scalar);
}
protected override void Visit(YamlMappingNode mapping)
{
VisitNode(mapping);
}
protected override void Visit(YamlSequenceNode sequence)
{
VisitNode(sequence);
}
}
private void AssignAnchors()
{
AnchorAssigningVisitor visitor = new AnchorAssigningVisitor();
visitor.AssignAnchors(this);
}
internal void Save(IEmitter emitter)
{
AssignAnchors();
emitter.Emit(new DocumentStart());
RootNode.Save(emitter, new EmitterState());
emitter.Emit(new DocumentEnd(false));
}
/// <summary>
/// Accepts the specified visitor by calling the appropriate Visit method on it.
/// </summary>
/// <param name="visitor">
/// A <see cref="IYamlVisitor"/>.
/// </param>
public void Accept(IYamlVisitor visitor)
{
visitor.Visit(this);
}
/// <summary>
/// Gets all nodes from the document.
/// </summary>
public IEnumerable<YamlNode> AllNodes
{
get
{
return RootNode.AllNodes;
}
}
}
}
| |
using Foundation;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using UIKit;
using Xamarin.Forms;
using zsquared;
namespace vitaadmin
{
public partial class VC_Suggestions : UIViewController
{
C_Global Global;
List<C_Suggestion> Suggestions;
C_VitaUser LoggedInUser;
public VC_Suggestions (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
Global = myAppDelegate.Global;
LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId);
B_Back.TouchUpInside += (sender, e) =>
PerformSegue("Segue_SuggestionsToMain", this);
SC_State.ValueChanged += (sender, e) =>
{
int selectedSegment = (int)SC_State.SelectedSegment;
E_SuggestionStatus selssug = E_SuggestionStatus.Unknown;
foreach (E_SuggestionStatus ss in Enum.GetValues(typeof(E_SuggestionStatus)))
{
if ((int)ss == selectedSegment)
{
selssug = ss;
break;
}
}
Global.SelectedSuggestion.Status = selssug;
Task.Run(async () =>
{
//bool success = await Global.SelectedSuggestion.UpdateSuggestion(LoggedInUser.Token);
C_IOResult ior = await Global.UpdateSuggestion(Global.SelectedSuggestion, LoggedInUser.Token);
});
};
AI_Busy.StartAnimating();
EnableUI(false);
Task.Run(async () =>
{
Suggestions = await Global.FetchAllSuggestions(LoggedInUser.Token);
UIApplication.SharedApplication.InvokeOnMainThread(
new Action(() =>
{
AI_Busy.StopAnimating();
EnableUI(true);
Global.ViewCameFrom = E_ViewCameFrom.MySignUps;
C_SuggestionsTableSource ts = new C_SuggestionsTableSource(Global, Suggestions);
TV_Suggestions.Source = ts;
TV_Suggestions.Delegate = new C_SuggestionsTableDelegate(Global, this, ts);
TV_Suggestions.ReloadData();
}));
});
SC_State.RemoveAllSegments();
foreach (E_SuggestionStatus ss in Enum.GetValues(typeof(E_SuggestionStatus)))
SC_State.InsertSegment(ss.ToString(), (int)ss, true);
}
private void PopulateSuggestion()
{
C_Suggestion s = Global.SelectedSuggestion;
L_From.Text = s.FromPublic ? "--- public ---" : s.UserId.ToString();
L_Date.Text = s.CreateDate.ToString("mmm dd, yyyy");
SC_State.SelectedSegment = (int)s.Status;
L_Subject.Text = s.Subject;
L_UpdatedDate.Text = s.UpdateDate.ToString("mmm dd, yyyy");
string contentDirectoryPath = Path.Combine(NSBundle.MainBundle.BundlePath, "/");
WV_Message.LoadHtmlString(s.Text, new NSUrl(contentDirectoryPath, true));
if (!s.FromPublic)
{
Task.Run(async () =>
{
C_VitaUser u = await Global.FetchUserWithId(s.UserId);
UIApplication.SharedApplication.InvokeOnMainThread(
new Action(() =>
{
L_From.Text = u.Name;
}));
});
}
}
private void EnableUI(bool en)
{
TV_Suggestions.UserInteractionEnabled = en;
SC_State.Enabled = en;
B_Back.Enabled = en;
}
public class C_SuggestionsTableDelegate : UITableViewDelegate
{
readonly C_Global Global;
readonly VC_Suggestions OurVC;
readonly C_SuggestionsTableSource TableSource;
readonly string Token;
public C_SuggestionsTableDelegate(C_Global global, VC_Suggestions vc, C_SuggestionsTableSource tsource)
{
Global = global;
OurVC = vc;
TableSource = tsource;
C_VitaUser user = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId);
Token = user.Token;
}
public override UITableViewRowAction[] EditActionsForRow(UITableView tableView, NSIndexPath indexPath)
{
UITableViewRowAction hiButton = UITableViewRowAction.Create(UITableViewRowActionStyle.Default, "Remove",
async delegate
{
C_Suggestion suggestionToRemove = TableSource.OurSuggestions[indexPath.Row];
OurVC.AI_Busy.StartAnimating();
OurVC.EnableUI(false);
C_IOResult ior = await Global.RemoveSuggestion(suggestionToRemove, Token);
TableSource.OurSuggestions.Remove(suggestionToRemove);
OurVC.EnableUI(true);
OurVC.AI_Busy.StopAnimating();
OurVC.TV_Suggestions.ReloadData();
});
return new UITableViewRowAction[] { hiButton };
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
// identify the specific signup
Global.SelectedSuggestion = TableSource.OurSuggestions[indexPath.Row];
OurVC.PopulateSuggestion();
}
}
public class C_SuggestionsTableSource : UITableViewSource
{
const string CellIdentifier = "TableCell_SuggestionsTableSource";
public List<C_Suggestion> OurSuggestions;
readonly C_Global Global;
public C_SuggestionsTableSource(C_Global global, List<C_Suggestion> ourSuggestions)
{
Global = global;
OurSuggestions = ourSuggestions;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
int count = 0;
if (OurSuggestions != null)
count = OurSuggestions.Count;
return count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
//---- if there are no cells to reuse, create a new one
if (cell == null)
cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier);
C_Suggestion suggestion = OurSuggestions[indexPath.Row];
cell.TextLabel.Text = suggestion.Subject;
string subject = "";
if (suggestion.Subject != null)
subject = suggestion.Subject;
int maxLength = 100;
if (subject.Length < maxLength)
maxLength = subject.Length;
cell.DetailTextLabel.Text = subject.Substring(0, maxLength);
return cell;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using CodeEditor.Text.Data;
using CodeEditor.Text.UI.Completion;
using CodeEditor.Text.UI.Unity.Engine;
using UnityEditor;
using UnityEngine;
namespace CodeEditor.Text.UI.Unity.Editor.Implementation
{
internal class CodeEditorWindow : EditorWindow, ICompletionSessionProvider
{
[Serializable]
class BackupData
{
public int caretRow, caretColumn;
public Vector2 scrollOffset;
public Vector2 selectionAnchor; // argh: Unity cannot serialize Position since its a custom struct... so we store it as a Vector2
}
// Serialized fields (between assembly reloads but NOT between sessions)
// ---------------------
string _filePath;
string _fileNameWithExtension;
BackupData _backupData;
bool _showingSettings;
// Non serialized fields (reconstructed from serialized state above or recreated when needed)
// ---------------------
[NonSerialized]
CodeView _codeView;
[NonSerialized]
ITextView _textView;
[NonSerialized]
SettingsDialog _settingsDialog;
[NonSerialized]
int[] _fontSizes = null;
[NonSerialized]
string[] _fontSizesNames;
// Layout
// ---------------------
class Styles
{
public GUIContent saveText = new GUIContent ("Save");
public GUIContent optionsIcon = new GUIContent("",EditorGUIUtility.FindTexture("_Popup"));
}
static Styles s_Styles;
static public CodeEditorWindow OpenOrFocusExistingWindow()
{
var window = GetWindow<CodeEditorWindow>();
window.title = "Code Editor";
window.minSize = new Vector2(200, 200);
return window;
}
static public void OpenWindowFor(string file, Position? position = null)
{
var window = OpenOrFocusExistingWindow();
var actualPosition = position ?? new Position(0, 0);
window.OpenFile(file, actualPosition.Row, actualPosition.Column);
}
private CodeEditorWindow()
{
}
// Use of this section requires 4.2 UnityEditor.dll
/*
[UnityEditor.Callbacks.OnOpenAsset]
public static bool OnOpenAsset(int instanceID, int line)
{
string assetpath = AssetDatabase.GetAssetPath(instanceID);
UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(assetpath, typeof(UnityEngine.Object));
if(asset is TextAsset || asset is ComputeShader)
{
OpenWindowFor(assetpath);
return true;
}
return false;
}
*/
/// <returns>true if the file was open, false otherwise</returns>
bool OpenFile (string file)
{
_textView = null;
_codeView = null;
_filePath = file;
_fileNameWithExtension = "";
if (string.IsNullOrEmpty(_filePath))
return false;
_textView = TextViewFactory.ViewForFile(_filePath);
_codeView = new CodeView(this, _textView);
_fileNameWithExtension = Path.GetFileName(_filePath);
if (_textView != null)
_settingsDialog = new SettingsDialog(_textView);
return true;
}
public void OnInspectorUpdate()
{
if (_codeView == null)
return;
_codeView.Update();
}
static ITextViewFactory TextViewFactory
{
get { return UnityEditorCompositionContainer.GetExportedValue<ITextViewFactory>(); }
}
bool OpenFile(string file, int row, int column)
{
if (!OpenFile(file))
return false;
SetPosition(row, column);
return true;
}
void InitIfNeeded()
{
if (s_Styles == null)
s_Styles = new Styles ();
if (_backupData == null)
_backupData = new BackupData();
// Reconstruct state after domain reloading
if (_textView == null && !string.IsNullOrEmpty(_filePath))
{
OpenFile(_filePath, _backupData.caretRow, _backupData.caretColumn);
_textView.ScrollOffset = _backupData.scrollOffset;
_textView.SelectionAnchor = new Position((int)_backupData.selectionAnchor.y, (int)_backupData.selectionAnchor.x);
}
}
void SetPosition(int row, int column)
{
_textView.Document.Caret.SetPosition(row, column);
}
void OnGUI()
{
InitIfNeeded();
const float topAreaHeight = 30f;
Rect topAreaRect = new Rect (0,0, position.width, topAreaHeight);
Rect codeViewRect = new Rect(0, topAreaHeight, position.width, position.height - topAreaHeight);
BeginWindows();
if (_showingSettings)
_settingsDialog.OnGUI(codeViewRect);
TopArea(topAreaRect);
CodeViewArea(codeViewRect);
EndWindows();
BackupState ();
}
void CodeViewArea (Rect rect)
{
HandleZoomScrolling(rect);
if (_codeView != null)
_codeView.OnGUI(rect);
}
void TopArea(Rect rect)
{
if (_textView == null)
return;
if(_fontSizes == null)
{
_fontSizes = _textView.FontManager.GetCurrentFontSizes();
var names = new List<string>();
foreach(int size in _fontSizes)
names.Add(size.ToString());
_fontSizesNames = names.ToArray();
}
GUILayout.BeginArea(rect);
{
GUILayout.BeginVertical ();
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
{
GUILayout.Space(10f);
if (GUILayout.Button(s_Styles.saveText, EditorStyles.miniButton))
_textView.Document.Save();
GUILayout.FlexibleSpace();
GUILayout.Label(_fileNameWithExtension);
GUILayout.FlexibleSpace();
if (GUILayout.Button(s_Styles.optionsIcon, EditorStyles.label))
{
_showingSettings = !_showingSettings;
Repaint();
}
GUILayout.Space(10f);
} GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
GUILayout.EndVertical ();
} GUILayout.EndArea();
}
void BackupState ()
{
if (_textView != null)
{
_backupData.caretRow = _textView.Document.Caret.Row;
_backupData.caretColumn = _textView.Document.Caret.Column;
_backupData.scrollOffset = _textView.ScrollOffset;
_backupData.selectionAnchor = new Vector2(_textView.SelectionAnchor.Column, _textView.SelectionAnchor.Row);
}
}
public void StartCompletionSession(TextSpan completionSpan, ICompletionSet completions)
{
_codeView.StartCompletionSession(new CompletionSession(completionSpan, completions));
}
void HandleZoomScrolling(Rect rect)
{
if (EditorGUI.actionKey && Event.current.type == EventType.scrollWheel && rect.Contains(Event.current.mousePosition))
{
Event.current.Use();
int sign = Event.current.delta.y > 0 ? -1 : 1;
int orgSize = _textView.FontManager.CurrentFontSize;
int index = Array.IndexOf(_fontSizes, orgSize);
index = Mathf.Clamp(index + sign, 0, _fontSizes.Length-1);
int newSize = _fontSizes[index];
if (newSize != orgSize)
{
_textView.FontManager.CurrentFontSize = newSize;
GUI.changed = true;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.