context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
//
// Copyright (c) 2003-2006 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
public class LicenseHeader
{
static string mode = "check";
static StringCollection licenseText = new StringCollection();
public static int Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Usage: LicenseHeader <license_file> add|replace|check|missing filename1 .. filenameN");
return 1;
}
string licenseFile = args[0];
mode = args[1].ToLower();
using (StreamReader lic = File.OpenText(licenseFile))
{
string line;
while ((line = lic.ReadLine()) != null)
licenseText.Add(line);
}
for (int i = 2; i < args.Length; ++i)
{
switch (mode)
{
case "check":
CheckLicense(args[i]);
break;
case "remove":
RemoveLicense(args[i]);
break;
case "replace":
ReplaceLicense(args[i]);
break;
case "add":
AddLicense(args[i], false);
break;
}
}
return 0;
}
static void RemoveLicense(TextWriter output, string fileName)
{
using (StreamReader input = File.OpenText(fileName))
{
string line = input.ReadLine();
if (line.Trim() == "/*")
{
while ((line = input.ReadLine()) != null)
{
line = line.TrimStart();
if (line.StartsWith("*/"))
break;
}
while ((line = input.ReadLine()) != null)
{
if (line.TrimStart().Length != 0)
break;
}
}
else if (line.TrimStart().StartsWith("//"))
{
while ((line = input.ReadLine()) != null)
{
if (!line.TrimStart().StartsWith("//"))
break;
}
if (line.TrimStart().Length == 0)
{
while ((line = input.ReadLine()) != null)
{
if (line.TrimStart().Length != 0)
break;
}
}
}
output.WriteLine(line);
output.Write(input.ReadToEnd());
output.Flush();
}
}
static void RemoveLicense(string fileName)
{
string tmpFile = fileName + ".tmp";
string bakFile = Path.ChangeExtension(fileName, ".bak");
using (StreamWriter sw = File.CreateText(tmpFile))
{
RemoveLicense(sw, fileName);
}
if (File.Exists(bakFile))
File.Delete(bakFile);
if (FilesDiffer(fileName, tmpFile))
{
File.Move(fileName, bakFile);
File.Move(tmpFile, fileName);
Console.WriteLine("{1,20} {0}", fileName, "REMOVED");
}
else
{
File.Delete(tmpFile);
}
}
static void ReplaceLicense(string fileName)
{
string tmpFile = fileName + ".tmp";
string bakFile = Path.ChangeExtension(fileName, ".bak");
using (StreamWriter sw = File.CreateText(tmpFile))
{
RemoveLicense(sw, fileName);
}
AddLicense(tmpFile, true);
if (File.Exists(bakFile))
File.Delete(bakFile);
if (FilesDiffer(fileName, tmpFile))
{
File.Move(fileName, bakFile);
File.Move(tmpFile, fileName);
Console.WriteLine("{1,20} {0}", fileName, "REPLACED");
} else {
File.Delete(tmpFile);
}
}
static void CheckLicense(string fileName)
{
StringCollection foundLicenseText = new StringCollection();
using (StreamReader input = File.OpenText(fileName))
{
string line = input.ReadLine();
if (line.Trim() == "/*")
{
while ((line = input.ReadLine()) != null)
{
line = line.TrimStart();
if (line.StartsWith("*/"))
break;
foundLicenseText.Add(line);
}
}
else if (line.TrimStart().StartsWith("//"))
{
while ((line = input.ReadLine()) != null)
{
if (!line.TrimStart().StartsWith("//"))
break;
foundLicenseText.Add(line.TrimStart(' ', '/'));
}
}
}
Hashtable found = new Hashtable();
int lineCount = 0;
foreach (string s in licenseText)
{
string s2 = s.Trim();
if (s2 != "")
{
found.Add(s2, s2);
lineCount++;
}
}
foreach (string s in foundLicenseText)
{
string s2 = s.Trim();
if (s2 != "")
{
if (found.Contains(s2))
found.Remove(s2);
}
}
string status;
if (found.Count == 0)
status = "FOUND";
else if (lineCount > 8)
{
if (found.Count < lineCount / 2)
{
status = "FOUND_MODIFIED(" + found.Count + ")";
}
else
{
status = "NOT_FOUND";
}
} else {
status = "UNKNOWN";
}
Console.WriteLine("{1,20} {0}", fileName, status);
}
static void AddLicense(TextWriter output, string fileName)
{
foreach (string s in licenseText)
{
if (s.Length == 0)
output.WriteLine("//");
else
output.WriteLine("// {0}", s);
}
output.WriteLine();
using (StreamReader input = File.OpenText(fileName))
{
output.Write(input.ReadToEnd());
}
output.Flush();
}
static void AddLicense(string fileName, bool quiet)
{
string tmpFile = fileName + ".tmp";
string bakFile = Path.ChangeExtension(fileName, ".bak");
using (StreamWriter sw = File.CreateText(tmpFile))
{
AddLicense(sw, fileName);
}
if (File.Exists(bakFile))
File.Delete(bakFile);
if (FilesDiffer(fileName, tmpFile))
{
if (!quiet)
File.Move(fileName, bakFile);
else
File.Delete(fileName);
File.Move(tmpFile, fileName);
if (!quiet)
Console.WriteLine("{1,20} {0}", fileName, "ADDED");
} else {
File.Delete(tmpFile);
}
}
static bool FilesDiffer(string fn1, string fn2)
{
string contents1;
string contents2;
using (StreamReader sr = File.OpenText(fn1))
{
contents1 = sr.ReadToEnd();
}
using (StreamReader sr = File.OpenText(fn2))
{
contents2 = sr.ReadToEnd();
}
return contents1 != contents2;
}
}
| |
#region License
/*
* ChunkedRequestStream.cs
*
* This code is derived from ChunkedInputStream.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 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:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.IO;
namespace WebSocketSharp.Net
{
internal class ChunkedRequestStream : RequestStream
{
#region Private Fields
private const int _bufferLength = 8192;
private HttpListenerContext _context;
private ChunkStream _decoder;
private bool _disposed;
private bool _noMoreData;
#endregion
#region Internal Constructors
internal ChunkedRequestStream (
Stream stream, byte[] buffer, int offset, int count, HttpListenerContext context)
: base (stream, buffer, offset, count)
{
_context = context;
_decoder = new ChunkStream ((WebHeaderCollection) context.Request.Headers);
}
#endregion
#region Internal Properties
internal ChunkStream Decoder {
get {
return _decoder;
}
set {
_decoder = value;
}
}
#endregion
#region Private Methods
private void onRead (IAsyncResult asyncResult)
{
var rstate = (ReadBufferState) asyncResult.AsyncState;
var ares = rstate.AsyncResult;
try {
var nread = base.EndRead (asyncResult);
_decoder.Write (ares.Buffer, ares.Offset, nread);
nread = _decoder.Read (rstate.Buffer, rstate.Offset, rstate.Count);
rstate.Offset += nread;
rstate.Count -= nread;
if (rstate.Count == 0 || !_decoder.WantMore || nread == 0) {
_noMoreData = !_decoder.WantMore && nread == 0;
ares.Count = rstate.InitialCount - rstate.Count;
ares.Complete ();
return;
}
ares.Offset = 0;
ares.Count = Math.Min (_bufferLength, _decoder.ChunkLeft + 6);
base.BeginRead (ares.Buffer, ares.Offset, ares.Count, onRead, rstate);
}
catch (Exception ex) {
_context.Connection.SendError (ex.Message, 400);
ares.Complete (ex);
}
}
#endregion
#region Public Methods
public override IAsyncResult BeginRead (
byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException ("offset", "A negative value.");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "A negative value.");
var len = buffer.Length;
if (offset + count > len)
throw new ArgumentException (
"The sum of 'offset' and 'count' is greater than 'buffer' length.");
var ares = new HttpStreamAsyncResult (callback, state);
if (_noMoreData) {
ares.Complete ();
return ares;
}
var nread = _decoder.Read (buffer, offset, count);
offset += nread;
count -= nread;
if (count == 0) {
// Got all we wanted, no need to bother the decoder yet.
ares.Count = nread;
ares.Complete ();
return ares;
}
if (!_decoder.WantMore) {
_noMoreData = nread == 0;
ares.Count = nread;
ares.Complete ();
return ares;
}
ares.Buffer = new byte[_bufferLength];
ares.Offset = 0;
ares.Count = _bufferLength;
var rstate = new ReadBufferState (buffer, offset, count, ares);
rstate.InitialCount += nread;
base.BeginRead (ares.Buffer, ares.Offset, ares.Count, onRead, rstate);
return ares;
}
public override void Close ()
{
if (_disposed)
return;
_disposed = true;
base.Close ();
}
public override int EndRead (IAsyncResult asyncResult)
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
var ares = asyncResult as HttpStreamAsyncResult;
if (ares == null)
throw new ArgumentException ("A wrong IAsyncResult.", "asyncResult");
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
if (ares.HasException)
throw new HttpListenerException (400, "I/O operation aborted.");
return ares.Count;
}
public override int Read (byte[] buffer, int offset, int count)
{
var ares = BeginRead (buffer, offset, count, null, null);
return EndRead (ares);
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="OperationSignatures.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Provides types with operation signatures.
// </summary>
//
// @owner mruiz
//---------------------------------------------------------------------
namespace System.Data.Services.Parsing
{
using System;
/// <summary>This class provides inner types with operation signatures.</summary>
internal static class OperationSignatures
{
/// <summary>Signatures for logical operations.</summary>
internal interface ILogicalSignatures
{
/// <summary>Logical signatures for bool arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(bool x, bool y);
/// <summary>Logical signatures for bool? arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(bool? x, bool? y);
/// <summary>Logical signatures for object arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(object x, object y);
}
/// <summary>Signatures for arithmetic operations.</summary>
internal interface IArithmeticSignatures
{
/// <summary>Arithmetic signature for int arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(int x, int y);
/// <summary>Arithmetic signature for long arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(long x, long y);
/// <summary>Arithmetic signature for float arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(float x, float y);
/// <summary>Arithmetic signature for double arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(double x, double y);
/// <summary>Arithmetic signature for decimal arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(decimal x, decimal y);
/// <summary>Arithmetic signature for int? arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(int? x, int? y);
/// <summary>Arithmetic signature for long? arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(long? x, long? y);
/// <summary>Arithmetic signature for float? arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(float? x, float? y);
/// <summary>Arithmetic signature for double? arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(double? x, double? y);
/// <summary>Arithmetic signature for decimal? arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(decimal? x, decimal? y);
/// <summary>Arithmetic signature for object arguments.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(object x, object y);
}
/// <summary>Signatures for relational operations.</summary>
internal interface IRelationalSignatures : IArithmeticSignatures
{
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(string x, string y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(bool x, bool y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(bool? x, bool? y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(Guid x, Guid y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(Guid? x, Guid? y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(char x, char y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(DateTime x, DateTime y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(char? x, char? y);
/// <summary>Relational operation signature.</summary>
/// <param name="x">First argument.</param><param name="y">Second argument.</param>
void F(DateTime? x, DateTime? y);
}
/// <summary>Signatures for equality operations.</summary>
internal interface IEqualitySignatures : IRelationalSignatures
{
}
/// <summary>Signatures for addition operations.</summary>
internal interface IAddSignatures : IArithmeticSignatures
{
}
/// <summary>Signatures for subtraction operations.</summary>
internal interface ISubtractSignatures : IAddSignatures
{
}
/// <summary>Signatures for negation operations.</summary>
internal interface INegationSignatures
{
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(int x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(long x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(float x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(double x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(decimal x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(int? x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(long? x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(float? x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(double? x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(decimal? x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(object x);
}
/// <summary>Signatures for logical negation operations.</summary>
internal interface INotSignatures
{
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(bool x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(bool? x);
/// <summary>Negation operation signature.</summary>
/// <param name="x">Argument.</param>
void F(object x);
}
/// <summary>Signatures for enumerable operations.</summary>
internal interface IEnumerableSignatures
{
/// <summary>Enumerable operation signature.</summary>
/// <param name="predicate">Predicate.</param>
void Where(bool predicate);
/// <summary>Enumerable operation signature.</summary>
void Any();
/// <summary>Enumerable operation signature.</summary>
/// <param name="predicate">Predicate.</param>
void Any(bool predicate);
/// <summary>Enumerable operation signature.</summary>
/// <param name="predicate">Predicate.</param>
void All(bool predicate);
/// <summary>Enumerable operation signature.</summary>
void Count();
/// <summary>Enumerable operation signature.</summary>
/// <param name="predicate">Predicate.</param>
void Count(bool predicate);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Min(object selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Max(object selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(int selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(int? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(long selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(long? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(float selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(float? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(double selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(double? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(decimal selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Sum(decimal? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(int selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(int? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(long selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(long? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(float selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(float? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(double selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(double? selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(decimal selector);
/// <summary>Enumerable operation signature.</summary>
/// <param name="selector">Selector.</param>
void Average(decimal? selector);
}
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Q42.HueApi.Extensions;
using Newtonsoft.Json;
using Q42.HueApi.Models.Groups;
using System.Dynamic;
using Q42.HueApi.Models;
using Q42.HueApi.Interfaces;
using System.Collections.Concurrent;
namespace Q42.HueApi
{
/// <summary>
/// Partial HueClient, contains requests to the /lights/ url
/// </summary>
public partial class HueClient : IHueClient_Lights
{
/// <summary>
/// Asynchronously retrieves an individual light.
/// </summary>
/// <param name="id">The light's Id.</param>
/// <returns>The <see cref="Light"/> if found, <c>null</c> if not.</returns>
/// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="id"/> is empty or a blank string.</exception>
public async Task<Light?> GetLightAsync(string id)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if (id.Trim() == String.Empty)
throw new ArgumentException("id can not be empty or a blank string", nameof(id));
CheckInitialized();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}lights/{1}", ApiBase, id))).ConfigureAwait(false);
//#if DEBUG
// //Normal result example
// stringResult = "{ \"state\": { \"hue\": 50000, \"on\": true, \"effect\": \"none\", \"alert\": \"none\", \"bri\": 200, \"sat\": 200, \"ct\": 500, \"xy\": [0.5, 0.5], \"reachable\": true, \"colormode\": \"hs\" }, \"type\": \"Living Colors\", \"name\": \"LC 1\", \"modelid\": \"LC0015\", \"swversion\": \"1.0.3\", \"pointsymbol\": { \"1\": \"none\", \"2\": \"none\", \"3\": \"none\", \"4\": \"none\", \"5\": \"none\", \"6\": \"none\", \"7\": \"none\", \"8\": \"none\" }}";
// //Lux result
// stringResult = "{ \"state\": { \"on\": true, \"effect\": \"none\", \"alert\": \"none\", \"bri\": 200, \"reachable\": true, \"colormode\": \"hs\" }, \"type\": \"Living Colors\", \"name\": \"LC 1\", \"modelid\": \"LC0015\", \"swversion\": \"1.0.3\", \"pointsymbol\": { \"1\": \"none\", \"2\": \"none\", \"3\": \"none\", \"4\": \"none\", \"5\": \"none\", \"6\": \"none\", \"7\": \"none\", \"8\": \"none\" }}";
//#endif
JToken token = JToken.Parse(stringResult);
if (token.Type == JTokenType.Array)
{
// Hue gives back errors in an array for this request
var error = token.First?["error"];
if (error?["type"]?.Value<int>() == 3) // Light not found
return null;
throw new HueException(error?["description"]?.Value<string>());
}
var light = token.ToObject<Light>();
if (light != null)
light.Id = id;
return light;
}
/// <summary>
/// Sets the light name
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <returns></returns>
public async Task<HueResults> SetLightNameAsync(string id, string name)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if (id.Trim() == String.Empty)
throw new ArgumentException("id can not be empty or a blank string", nameof(id));
CheckInitialized();
string command = JsonConvert.SerializeObject(new { name = name });
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var result = await client.PutAsync(new Uri(String.Format("{0}lights/{1}", ApiBase, id)), new JsonContent(command)).ConfigureAwait(false);
var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
return DeserializeDefaultHueResult(jsonResult);
}
/// <summary>
/// Sets the light name
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <returns></returns>
public async Task<HueResults> LightConfigUpdate(string id, LightConfigUpdate config)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if (config == null)
throw new ArgumentNullException(nameof(config));
CheckInitialized();
string jsonCommand = JsonConvert.SerializeObject(config, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var result = await client.PutAsync(new Uri(String.Format("{0}lights/{1}/config", ApiBase, id)), new JsonContent(jsonCommand)).ConfigureAwait(false);
var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
return DeserializeDefaultHueResult(jsonResult);
}
/// <summary>
/// Asynchronously gets all lights registered with the bridge.
/// </summary>
/// <returns>An enumerable of <see cref="Light"/>s registered with the bridge.</returns>
public async Task<IEnumerable<Light>> GetLightsAsync()
{
CheckInitialized();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}lights", ApiBase))).ConfigureAwait(false);
List<Light> results = new List<Light>();
JToken token = JToken.Parse(stringResult);
if (token.Type == JTokenType.Object)
{
//Each property is a light
var jsonResult = (JObject)token;
foreach (var prop in jsonResult.Properties())
{
Light? newLight = JsonConvert.DeserializeObject<Light>(prop.Value.ToString());
if (newLight != null)
{
newLight.Id = prop.Name;
results.Add(newLight);
}
}
}
return results;
}
/// <summary>
/// Send a lightCommand to a list of lights
/// </summary>
/// <param name="command"></param>
/// <param name="lightList">if null, send command to all lights</param>
/// <returns></returns>
public Task<HueResults> SendCommandAsync(LightCommand command, IEnumerable<string>? lightList = null)
{
if (command == null)
throw new ArgumentNullException(nameof(command));
string jsonCommand = JsonConvert.SerializeObject(command, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
return SendCommandRawAsync(jsonCommand, lightList);
}
/// <summary>
/// Send a json command to a list of lights
/// </summary>
/// <param name="command"></param>
/// <param name="lightList">if null, send command to all lights</param>
/// <returns></returns>
public async Task<HueResults> SendCommandRawAsync(string command, IEnumerable<string>? lightList = null)
{
if (command == null)
throw new ArgumentNullException(nameof(command));
CheckInitialized();
if (lightList == null || !lightList.Any())
{
//Group 0 always contains all the lights
return await SendGroupCommandAsync(command).ConfigureAwait(false);
}
else
{
BlockingCollection<DefaultHueResult> results = new BlockingCollection<DefaultHueResult>();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
await lightList.ForEachAsync(_parallelRequests, async (lightId) =>
{
try
{
var result = await client.PutAsync(new Uri(ApiBase + $"lights/{lightId}/state"), new JsonContent(command)).ConfigureAwait(false);
string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
var hueResults = DeserializeDefaultHueResult(jsonResult);
foreach(var hueResult in hueResults)
{
results.Add(hueResult);
}
}
catch(Exception ex)
{
results.Add(new DefaultHueResult()
{
Error = new ErrorResult()
{
Address = $"lights/{lightId}/state",
Description = ex.ToString()
}
}); ;
}
}).ConfigureAwait(false);
HueResults hueResults = new HueResults();
hueResults.AddRange(results);
return hueResults;
}
}
/// <summary>
/// Start searching for new lights
/// </summary>
/// <param name="deviceIds">The maxiumum number of serial numbers in any request is 10.</param>
/// <returns></returns>
public async Task<HueResults> SearchNewLightsAsync(IEnumerable<string>? deviceIds = null)
{
CheckInitialized();
StringContent? jsonStringContent = null;
if (deviceIds != null)
{
JObject jsonObj = new JObject();
jsonObj.Add("deviceid", JToken.FromObject(deviceIds.Take(10)));
string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
jsonStringContent = new JsonContent(jsonString);
}
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var response = await client.PostAsync(new Uri(String.Format("{0}lights", ApiBase)), jsonStringContent).ConfigureAwait(false);
var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return DeserializeDefaultHueResult(jsonResult);
}
/// <summary>
/// Gets a list of lights that were discovered the last time a search for new lights was performed. The list of new lights is always deleted when a new search is started.
/// </summary>
/// <returns></returns>
public async Task<IReadOnlyCollection<Light>> GetNewLightsAsync()
{
CheckInitialized();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}lights/new", ApiBase))).ConfigureAwait(false);
//#if DEBUG
// //stringResult = "{\"7\": {\"name\": \"Hue Lamp 7\"}, \"8\": {\"name\": \"Hue Lamp 8\"}, \"lastscan\": \"2012-10-29T12:00:00\"}";
//#endif
List<Light> results = new List<Light>();
JToken token = JToken.Parse(stringResult);
if (token.Type == JTokenType.Object)
{
//Each property is a light
var jsonResult = (JObject)token;
foreach (var prop in jsonResult.Properties())
{
if (prop.Name != "lastscan")
{
Light? newLight = JsonConvert.DeserializeObject<Light>(prop.Value.ToString());
if (newLight != null)
{
newLight.Id = prop.Name;
results.Add(newLight);
}
}
}
}
return results;
}
/// <summary>
/// Deletes a single light
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
public async Task<IReadOnlyCollection<DeleteDefaultHueResult>> DeleteLightAsync(string id)
{
CheckInitialized();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
//Delete light
var result = await client.DeleteAsync(new Uri(ApiBase + string.Format("lights/{0}", id))).ConfigureAwait(false);
string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
//#if DEBUG
// jsonResult = "[{\"success\":\"/lights/" + id + " deleted\"}]";
//#endif
return DeserializeDefaultHueResult<DeleteDefaultHueResult>(jsonResult);
}
}
}
| |
using NUnit.Framework;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Zu.AsyncWebDriver;
using Zu.WebBrowser.BasicTypes;
namespace Zu.AsyncChromeDriver.Tests
{
[TestFixture]
public class ChildrenFindingTest : DriverTestFixture
{
[Test]
public async Task FindElementByXPath()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
IWebElement child = await element.FindElement(By.XPath("select"));
Assert.AreEqual(await child.GetAttribute("id"), "2");
}
[Test]
public async Task FindingElementsOnElementByXPathShouldFindTopLevelElements()
{
await driver.GoToUrl(simpleTestPage);
IWebElement parent = await driver.FindElement(By.Id("multiline"));
ReadOnlyCollection<IWebElement> allParaElements = await driver.FindElements(By.XPath("//p"));
ReadOnlyCollection<IWebElement> children = await parent.FindElements(By.XPath("//p"));
Assert.AreEqual(allParaElements.Count, children.Count);
}
[Test]
public async Task FindingDotSlashElementsOnElementByXPathShouldFindNotTopLevelElements()
{
await driver.GoToUrl(simpleTestPage);
IWebElement parent = await driver.FindElement(By.Id("multiline"));
ReadOnlyCollection<IWebElement> children = await parent.FindElements(By.XPath("./p"));
Assert.AreEqual(1, children.Count);
Assert.AreEqual("A div containing", await children[0].Text());
}
[Test]
public async Task FindElementByXPathWhenNoMatch()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
//Assert.That(async () => await element.FindElement(By.XPath("select/x")), Throws.InstanceOf<NoSuchElementException>());
await AssertEx.ThrowsAsync<WebBrowserException>(async () => await element.FindElement(By.XPath("select/x")),
exception => Assert.AreEqual(exception.Error, "no such element"));
}
[Test]
public async Task FindElementsByXPath()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
ReadOnlyCollection<IWebElement> children = await element.FindElements(By.XPath("select/option"));
Assert.AreEqual(children.Count, 8);
Assert.AreEqual(await children[0].Text(), "One");
Assert.AreEqual(await children[1].Text(), "Two");
}
[Test]
public async Task FindElementsByXPathWhenNoMatch()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
ReadOnlyCollection<IWebElement> children = await element.FindElements(By.XPath("select/x"));
Assert.AreEqual(0, children.Count);
}
[Test]
public async Task FindElementByName()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
IWebElement child = await element.FindElement(By.Name("selectomatic"));
Assert.AreEqual(await child.GetAttribute("id"), "2");
}
[Test]
public async Task FindElementsByName()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
ReadOnlyCollection<IWebElement> children = await element.FindElements(By.Name("selectomatic"));
Assert.AreEqual(children.Count, 2);
}
[Test]
public async Task FindElementById()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
IWebElement child = await element.FindElement(By.Id("2"));
Assert.AreEqual(await child.GetAttribute("name"), "selectomatic");
}
[Test]
public async Task FindElementByIdWhenMultipleMatchesExist()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Id("test_id_div"));
IWebElement child = await element.FindElement(By.Id("test_id"));
Assert.AreEqual(await child.Text(), "inside");
}
[Test]
public async Task FindElementByIdWhenIdContainsNonAlphanumericCharacters()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Id("test_special_chars"));
IWebElement childWithSpaces = await element.FindElement(By.Id("white space"));
Assert.That(await childWithSpaces.Text().Contains("space"));
IWebElement childWithCssChars = await element.FindElement(By.Id("css#.chars"));
Assert.That(await childWithCssChars.Text(), Is.EqualTo("css escapes"));
}
[Test]
public async Task FindElementByIdWhenNoMatchInContext()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Id("test_id_div"));
await AssertEx.ThrowsAsync<WebBrowserException>(async () => await element.FindElement(By.Id("test_id_out")),
exception => Assert.AreEqual(exception.Error, "no such element"));
}
[Test]
public async Task FindElementsById()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("form2"));
ReadOnlyCollection<IWebElement> children = await element.FindElements(By.Id("2"));
Assert.AreEqual(children.Count, 2);
}
[Test]
public async Task FindElementsByIdWithNonAlphanumericCharacters()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Id("test_special_chars"));
ReadOnlyCollection<IWebElement> children = await element.FindElements(By.Id("white space"));
Assert.That(children.Count, Is.EqualTo(1));
ReadOnlyCollection<IWebElement> children2 = await element.FindElements(By.Id("css#.chars"));
Assert.That(children2.Count, Is.EqualTo(1));
}
[Test]
public async Task FindElementByLinkText()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("div1"));
IWebElement child = await element.FindElement(By.LinkText("hello world"));
Assert.AreEqual(await child.GetAttribute("name"), "link1");
}
[Test]
public async Task FindElementsByLinkText()
{
await driver.GoToUrl(nestedPage);
IWebElement element = await driver.FindElement(By.Name("div1"));
ReadOnlyCollection<IWebElement> elements = await element.FindElements(By.LinkText("hello world"));
Assert.AreEqual(2, elements.Count);
Assert.AreEqual(await elements[0].GetAttribute("name"), "link1");
Assert.AreEqual(await elements[1].GetAttribute("name"), "link2");
}
[Test]
public async Task ShouldFindChildElementsById()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Id("test_id_div"));
IWebElement element = await parent.FindElement(By.Id("test_id"));
Assert.AreEqual("inside", await element.Text());
}
[Test]
public async Task ShouldFindChildElementsByClassName()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Name("classes"));
IWebElement element = await parent.FindElement(By.ClassName("one"));
Assert.AreEqual("Find me", await element.Text());
}
[Test]
public async Task ShouldFindChildrenByClassName()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Name("classes"));
ReadOnlyCollection<IWebElement> elements = await parent.FindElements(By.ClassName("one"));
Assert.AreEqual(2, elements.Count);
}
[Test]
public async Task ShouldFindChildElementsByTagName()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Name("div1"));
IWebElement element = await parent.FindElement(By.TagName("a"));
Assert.AreEqual("link1", await element.GetAttribute("name"));
}
[Test]
public async Task ShouldFindChildrenByTagName()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Name("div1"));
ReadOnlyCollection<IWebElement> elements = await parent.FindElements(By.TagName("a"));
Assert.AreEqual(2, elements.Count);
}
[Test]
public async Task ShouldBeAbleToFindAnElementByCssSelector()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Name("form2"));
IWebElement element = await parent.FindElement(By.CssSelector("*[name=\"selectomatic\"]"));
Assert.AreEqual("2", await element.GetAttribute("id"));
}
[Test]
public async Task ShouldBeAbleToFindAnElementByCss3Selector()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Name("form2"));
IWebElement element = await parent.FindElement(By.CssSelector("*[name^=\"selecto\"]"));
Assert.AreEqual("2", await element.GetAttribute("id"));
}
[Test]
public async Task ShouldBeAbleToFindElementsByCssSelector()
{
await driver.GoToUrl(nestedPage);
IWebElement parent = await driver.FindElement(By.Name("form2"));
ReadOnlyCollection<IWebElement> elements = await parent.FindElements(By.CssSelector("*[name=\"selectomatic\"]"));
Assert.AreEqual(2, elements.Count);
}
[Test]
public async Task ShouldBeAbleToFindChildrenOfANode()
{
await driver.GoToUrl(selectableItemsPage);
ReadOnlyCollection<IWebElement> elements = await driver.FindElements(By.XPath("/html/head"));
IWebElement head = elements[0];
ReadOnlyCollection<IWebElement> importedScripts = await head.FindElements(By.TagName("script"));
Assert.That(importedScripts.Count, Is.EqualTo(3));
}
[Test]
public async Task ReturnAnEmptyListWhenThereAreNoChildrenOfANode()
{
await driver.GoToUrl(xhtmlTestPage);
IWebElement table = await driver.FindElement(By.Id("table"));
ReadOnlyCollection<IWebElement> rows = await table.FindElements(By.TagName("tr"));
Assert.That(rows.Count, Is.EqualTo(0));
}
[Test]
public async Task ShouldFindGrandChildren()
{
await driver.GoToUrl(formsPage);
IWebElement form = await driver.FindElement(By.Id("nested_form"));
await form.FindElement(By.Name("x"));
}
[Test]
public async Task ShouldNotFindElementOutSideTree()
{
await driver.GoToUrl(formsPage);
IWebElement element = await driver.FindElement(By.Name("login"));
//Assert.That(async () => await element.FindElement(By.Name("x")), Throws.InstanceOf<NoSuchElementException>());
await AssertEx.ThrowsAsync<WebBrowserException>(async () => await element.FindElement(By.Name("x")),
exception => Assert.AreEqual(exception.Error, "no such element"));
}
[Test]
public async Task FindingByTagNameShouldNotIncludeParentElementIfSameTagType()
{
await driver.GoToUrl(xhtmlTestPage);
IWebElement parent = await driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, await parent.FindElements(By.TagName("div")).Count());
Assert.AreEqual(2, await parent.FindElements(By.TagName("span")).Count());
}
[Test]
public async Task FindingByCssShouldNotIncludeParentElementIfSameTagType()
{
await driver.GoToUrl(xhtmlTestPage);
IWebElement parent = await driver.FindElement(By.CssSelector("div#parent"));
IWebElement child = await parent.FindElement(By.CssSelector("div"));
Assert.AreEqual("child", await child.GetAttribute("id"));
}
[Test]
public async Task FindMultipleElements()
{
await driver.GoToUrl(simpleTestPage);
IWebElement elem = await driver.FindElement(By.Id("links"));
ReadOnlyCollection<IWebElement> elements = await elem.FindElements(By.PartialLinkText("link"));
Assert.That(elements, Is.Not.Null);
Assert.AreEqual(6, elements.Count);
}
[Test]
public async Task LinkWithLeadingSpaces()
{
await driver.GoToUrl(simpleTestPage);
IWebElement elem = await driver.FindElement(By.Id("links"));
IWebElement res = await elem.FindElement(By.PartialLinkText("link with leading space"));
Assert.AreEqual("link with leading space", await res.Text());
}
[Test]
public async Task LinkWithTrailingSpace()
{
await driver.GoToUrl(simpleTestPage);
IWebElement elem = await driver.FindElement(By.Id("links"));
IWebElement res = await elem.FindElement(By.PartialLinkText("link with trailing space"));
Assert.AreEqual("link with trailing space", await res.Text());
}
[Test]
public async Task ElementCanGetLinkByLinkTestIgnoringTrailingWhitespace()
{
await driver.GoToUrl(simpleTestPage);
IWebElement elem = await driver.FindElement(By.Id("links"));
IWebElement link = await elem.FindElement(By.LinkText("link with trailing space"));
Assert.AreEqual("linkWithTrailingSpace", await link.GetAttribute("id"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public sealed class SocketsHttpHandler : HttpMessageHandler
{
private readonly HttpConnectionSettings _settings = new HttpConnectionSettings();
private HttpMessageHandler _handler;
private bool _disposed;
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(SocketsHttpHandler));
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_handler != null)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
public bool UseCookies
{
get => _settings._useCookies;
set
{
CheckDisposedOrStarted();
_settings._useCookies = value;
}
}
public CookieContainer CookieContainer
{
get => _settings._cookieContainer ?? (_settings._cookieContainer = new CookieContainer());
set
{
CheckDisposedOrStarted();
_settings._cookieContainer = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get => _settings._automaticDecompression;
set
{
CheckDisposedOrStarted();
_settings._automaticDecompression = value;
}
}
public bool UseProxy
{
get => _settings._useProxy;
set
{
CheckDisposedOrStarted();
_settings._useProxy = value;
}
}
public IWebProxy Proxy
{
get => _settings._proxy;
set
{
CheckDisposedOrStarted();
_settings._proxy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get => _settings._defaultProxyCredentials;
set
{
CheckDisposedOrStarted();
_settings._defaultProxyCredentials = value;
}
}
public bool PreAuthenticate
{
get => _settings._preAuthenticate;
set
{
CheckDisposedOrStarted();
_settings._preAuthenticate = value;
}
}
public ICredentials Credentials
{
get => _settings._credentials;
set
{
CheckDisposedOrStarted();
_settings._credentials = value;
}
}
public bool AllowAutoRedirect
{
get => _settings._allowAutoRedirect;
set
{
CheckDisposedOrStarted();
_settings._allowAutoRedirect = value;
}
}
public int MaxAutomaticRedirections
{
get => _settings._maxAutomaticRedirections;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxAutomaticRedirections = value;
}
}
public int MaxConnectionsPerServer
{
get => _settings._maxConnectionsPerServer;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxConnectionsPerServer = value;
}
}
public int MaxResponseDrainSize
{
get => _settings._maxResponseDrainSize;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegativeNum);
}
CheckDisposedOrStarted();
_settings._maxResponseDrainSize = value;
}
}
public TimeSpan ResponseDrainTimeout
{
get => _settings._maxResponseDrainTime;
set
{
if ((value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._maxResponseDrainTime = value;
}
}
public int MaxResponseHeadersLength
{
get => _settings._maxResponseHeadersLength;
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxResponseHeadersLength = value;
}
}
public SslClientAuthenticationOptions SslOptions
{
get => _settings._sslOptions ?? (_settings._sslOptions = new SslClientAuthenticationOptions());
set
{
CheckDisposedOrStarted();
_settings._sslOptions = value;
}
}
public TimeSpan PooledConnectionLifetime
{
get => _settings._pooledConnectionLifetime;
set
{
if (value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._pooledConnectionLifetime = value;
}
}
public TimeSpan PooledConnectionIdleTimeout
{
get => _settings._pooledConnectionIdleTimeout;
set
{
if (value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._pooledConnectionIdleTimeout = value;
}
}
public TimeSpan ConnectTimeout
{
get => _settings._connectTimeout;
set
{
if ((value <= TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._connectTimeout = value;
}
}
public TimeSpan Expect100ContinueTimeout
{
get => _settings._expect100ContinueTimeout;
set
{
if ((value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._expect100ContinueTimeout = value;
}
}
public IDictionary<string, object> Properties =>
_settings._properties ?? (_settings._properties = new Dictionary<string, object>());
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
_handler?.Dispose();
}
base.Dispose(disposing);
}
private HttpMessageHandler SetupHandlerChain()
{
// Clone the settings to get a relatively consistent view that won't change after this point.
// (This isn't entirely complete, as some of the collections it contains aren't currently deeply cloned.)
HttpConnectionSettings settings = _settings.CloneAndNormalize();
HttpConnectionPoolManager poolManager = new HttpConnectionPoolManager(settings);
HttpMessageHandler handler;
if (settings._credentials == null)
{
handler = new HttpConnectionHandler(poolManager);
}
else
{
handler = new HttpAuthenticatedConnectionHandler(poolManager);
}
if (settings._allowAutoRedirect)
{
// Just as with WinHttpHandler and CurlHandler, for security reasons, we do not support authentication on redirects
// if the credential is anything other than a CredentialCache.
// We allow credentials in a CredentialCache since they are specifically tied to URIs.
HttpMessageHandler redirectHandler =
(settings._credentials == null || settings._credentials is CredentialCache) ?
handler :
new HttpConnectionHandler(poolManager); // will not authenticate
handler = new RedirectHandler(settings._maxAutomaticRedirections, handler, redirectHandler);
}
if (settings._automaticDecompression != DecompressionMethods.None)
{
handler = new DecompressionHandler(settings._automaticDecompression, handler);
}
// Ensure a single handler is used for all requests.
if (Interlocked.CompareExchange(ref _handler, handler, null) != null)
{
handler.Dispose();
}
return _handler;
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
CheckDisposed();
HttpMessageHandler handler = _handler ?? SetupHandlerChain();
Exception error = ValidateAndNormalizeRequest(request);
if (error != null)
{
return Task.FromException<HttpResponseMessage>(error);
}
return handler.SendAsync(request, cancellationToken);
}
private Exception ValidateAndNormalizeRequest(HttpRequestMessage request)
{
if (request.Version.Major == 0)
{
return new NotSupportedException(SR.net_http_unsupported_version);
}
// Add headers to define content transfer, if not present
if (request.HasHeaders && request.Headers.TransferEncodingChunked.GetValueOrDefault())
{
if (request.Content == null)
{
return new HttpRequestException(SR.net_http_client_execution_error,
new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content));
}
// Since the user explicitly set TransferEncodingChunked to true, we need to remove
// the Content-Length header if present, as sending both is invalid.
request.Content.Headers.ContentLength = null;
}
else if (request.Content != null && request.Content.Headers.ContentLength == null)
{
// We have content, but neither Transfer-Encoding nor Content-Length is set.
request.Headers.TransferEncodingChunked = true;
}
if (request.Version.Minor == 0 && request.Version.Major == 1 && request.HasHeaders)
{
// HTTP 1.0 does not support chunking
if (request.Headers.TransferEncodingChunked == true)
{
return new NotSupportedException(SR.net_http_unsupported_chunking);
}
// HTTP 1.0 does not support Expect: 100-continue; just disable it.
if (request.Headers.ExpectContinue == true)
{
request.Headers.ExpectContinue = false;
}
}
return null;
}
}
}
| |
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.Remoting.Messaging;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
#endregion Using directives
namespace System.Workflow.Activities
{
internal static class StateMachineHelpers
{
internal static bool IsStateMachine(StateActivity state)
{
if (state == null)
throw new ArgumentNullException("state");
return (state is StateMachineWorkflowActivity);
}
internal static bool IsRootState(StateActivity state)
{
if (state == null)
throw new ArgumentNullException("state");
StateActivity parent = state.Parent as StateActivity;
return parent == null;
}
internal static bool IsLeafState(StateActivity state)
{
if (state == null)
throw new ArgumentNullException("state");
if (IsRootState(state))
return false;
foreach (Activity child in state.EnabledActivities)
{
if (child is StateActivity)
return false;
}
return true;
}
internal static bool IsRootExecutionContext(ActivityExecutionContext context)
{
return (context.Activity.Parent == null);
}
/// <summary>
/// Finds the enclosing state for this activity
/// </summary>
/// <param name="activity"></param>
/// <returns></returns>
internal static StateActivity FindEnclosingState(Activity activity)
{
Debug.Assert(activity != null);
Debug.Assert(activity.Parent != activity);
StateActivity state = activity as StateActivity;
if (state != null)
return state;
if (activity.Parent == null)
return null;
return FindEnclosingState(activity.Parent);
}
/// <summary>
/// Returns the root State activity
/// </summary>
/// <param name="state"></param>
/// <returns></returns>
internal static StateActivity GetRootState(StateActivity state)
{
Debug.Assert(state != null);
Debug.Assert(state.Parent != state);
if (state.Parent == null)
return state;
// this handles the case when the StateMachineWorkflow
// is called using an Invoke activity
if (!(state.Parent is StateActivity))
return state;
return GetRootState((StateActivity)state.Parent);
}
internal static bool IsInitialState(StateActivity state)
{
Debug.Assert(state != null);
string initialStateName = GetInitialStateName(state);
if (initialStateName == null)
return false;
return state.QualifiedName.Equals(initialStateName);
}
internal static bool IsCompletedState(StateActivity state)
{
Debug.Assert(state != null);
string completedStateName = GetCompletedStateName(state);
if (completedStateName == null)
return false;
return state.QualifiedName.Equals(completedStateName);
}
internal static string GetInitialStateName(StateActivity state)
{
StateActivity rootState = GetRootState(state);
return (string)rootState.GetValue(StateMachineWorkflowActivity.InitialStateNameProperty);
}
internal static string GetCompletedStateName(StateActivity state)
{
Debug.Assert(state != null);
StateActivity rootState = GetRootState(state);
return (string)rootState.GetValue(StateMachineWorkflowActivity.CompletedStateNameProperty);
}
/*
internal static bool IsInInitialStatePath(StateActivity state)
{
StateActivity rootState = GetRootState(state);
string initialStateName = GetInitialStateName(rootState);
StateActivity initialState = FindStateByName(rootState, initialStateName);
CompositeActivity current = initialState;
while (current != null)
{
if (current.QualifiedName == state.QualifiedName)
return true;
current = current.Parent;
}
return false;
}
*/
/// <summary>
/// Returns the State activity that is currently executing
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
static internal StateActivity GetCurrentState(ActivityExecutionContext context)
{
StateActivity state = context.Activity as StateActivity;
if (state == null)
state = FindEnclosingState(context.Activity);
Debug.Assert(state != null, "StateMachineHelpers.GetCurrentState: only valid to call this method from a State executor or a contained EventDriven");
StateActivity rootState = GetRootState(state);
StateMachineExecutionState executionState = StateMachineExecutionState.Get(rootState);
string currentStateName = executionState.CurrentStateName;
if (currentStateName == null)
return null;
StateActivity currentState = FindDynamicStateByName(rootState, currentStateName);
Debug.Assert(currentState == null || IsLeafState(currentState));
return currentState;
}
static internal StateActivity FindDynamicStateByName(StateActivity state, string stateQualifiedName)
{
while (!state.QualifiedName.Equals(stateQualifiedName) && ContainsState(state, stateQualifiedName))
{
foreach (Activity activity in state.EnabledActivities)
{
StateActivity childState = activity as StateActivity;
if (childState == null)
continue;
if (ContainsState(childState, stateQualifiedName))
{
StateActivity dynamicChildState = (StateActivity)state.GetDynamicActivity(childState.QualifiedName);
if (dynamicChildState == null)
return null;
state = dynamicChildState;
break;
}
}
}
if (state.QualifiedName.Equals(stateQualifiedName))
return state;
else
return null;
}
static internal StateActivity FindStateByName(StateActivity state, string qualifiedName)
{
Debug.Assert(state != null);
Debug.Assert(qualifiedName != null);
StateActivity found = FindActivityByName(state, qualifiedName) as StateActivity;
return found;
}
static internal Activity FindActivityByName(CompositeActivity parentActivity, string qualifiedName)
{
return parentActivity.GetActivityByName(qualifiedName, true);
}
static internal bool ContainsEventActivity(CompositeActivity compositeActivity)
{
Debug.Assert(compositeActivity != null);
Queue<Activity> activities = new Queue<Activity>();
activities.Enqueue(compositeActivity);
while (activities.Count > 0)
{
Activity activity = activities.Dequeue();
if (activity is IEventActivity)
return true;
compositeActivity = activity as CompositeActivity;
if (compositeActivity != null)
{
foreach (Activity child in compositeActivity.Activities)
{
if (child.Enabled)
activities.Enqueue(child);
}
}
}
return false;
}
static internal IEventActivity GetEventActivity(EventDrivenActivity eventDriven)
{
CompositeActivity sequenceActivity = eventDriven as CompositeActivity;
Debug.Assert(eventDriven.EnabledActivities.Count > 0);
IEventActivity eventActivity = sequenceActivity.EnabledActivities[0] as IEventActivity;
Debug.Assert(eventActivity != null);
return eventActivity;
}
static internal EventDrivenActivity GetParentEventDriven(IEventActivity eventActivity)
{
Activity activity = ((Activity)eventActivity).Parent;
while (activity != null)
{
EventDrivenActivity eventDriven = activity as EventDrivenActivity;
if (eventDriven != null)
return eventDriven;
activity = activity.Parent;
}
return null;
}
static internal bool ContainsState(StateActivity state, string stateName)
{
if (state == null)
throw new ArgumentNullException("state");
if (String.IsNullOrEmpty(stateName))
throw new ArgumentNullException("stateName");
Queue<StateActivity> states = new Queue<StateActivity>();
states.Enqueue(state);
while (states.Count > 0)
{
state = states.Dequeue();
if (state.QualifiedName.Equals(stateName))
return true;
foreach (Activity childActivity in state.EnabledActivities)
{
StateActivity childState = childActivity as StateActivity;
if (childState != null)
{
states.Enqueue(childState);
}
}
}
return false;
}
}
#region StateMachineMessages
#if DEBUG
/*
* this is only used for testing the State Machine related resource messages
*
internal class StateMachineMessages
{
internal static void PrintMessages()
{
Console.WriteLine("GetInvalidUserDataInStateChangeTrackingRecord: {0}\n", SR.GetInvalidUserDataInStateChangeTrackingRecord());
Console.WriteLine("GetError_EventDrivenInvalidFirstActivity: {0}\n", SR.GetError_EventDrivenInvalidFirstActivity());
Console.WriteLine("GetError_InvalidLeafStateChild: {0}\n", SR.GetError_InvalidLeafStateChild());
Console.WriteLine("GetError_InvalidCompositeStateChild: {0}\n", SR.GetError_InvalidCompositeStateChild());
Console.WriteLine("GetError_SetStateOnlyWorksOnStateMachineWorkflow: {0}\n", SR.GetError_SetStateOnlyWorksOnStateMachineWorkflow());
Console.WriteLine("GetError_SetStateMustPointToAState: {0}\n", SR.GetError_SetStateMustPointToAState());
Console.WriteLine("GetError_InitialStateMustPointToAState: {0}\n", SR.GetError_InitialStateMustPointToAState());
Console.WriteLine("GetError_CompletedStateMustPointToAState: {0}\n", SR.GetError_CompletedStateMustPointToAState());
Console.WriteLine("GetError_SetStateMustPointToALeafNodeState: {0}\n", SR.GetError_SetStateMustPointToALeafNodeState());
Console.WriteLine("GetError_InitialStateMustPointToALeafNodeState: {0}\n", SR.GetError_InitialStateMustPointToALeafNodeState());
Console.WriteLine("GetError_CompletedStateMustPointToALeafNodeState: {0}\n", SR.GetError_CompletedStateMustPointToALeafNodeState());
Console.WriteLine("GetError_StateInitializationParentNotState: {0}\n", SR.GetError_StateInitializationParentNotState());
Console.WriteLine("GetError_StateFinalizationParentNotState: {0}\n", SR.GetError_StateFinalizationParentNotState());
Console.WriteLine("GetError_EventActivityNotValidInStateInitialization: {0}\n", SR.GetError_EventActivityNotValidInStateInitialization());
Console.WriteLine("GetError_EventActivityNotValidInStateFinalization: {0}\n", SR.GetError_EventActivityNotValidInStateFinalization());
Console.WriteLine("GetError_MultipleStateInitializationActivities: {0}\n", SR.GetError_MultipleStateInitializationActivities());
Console.WriteLine("GetError_MultipleStateFinalizationActivities: {0}\n", SR.GetError_MultipleStateFinalizationActivities());
Console.WriteLine("GetError_InvalidTargetStateInStateInitialization: {0}\n", SR.GetError_InvalidTargetStateInStateInitialization());
Console.WriteLine("GetError_CantRemoveState: {0}\n", SR.GetError_CantRemoveState());
Console.WriteLine("GetSqlTrackingServiceRequired: {0}\n", SR.GetSqlTrackingServiceRequired());
Console.WriteLine("GetStateMachineWorkflowMustHaveACurrentState: {0}\n", SR.GetStateMachineWorkflowMustHaveACurrentState());
Console.WriteLine("GetInvalidActivityStatus: {0}\n", SR.GetInvalidActivityStatus(new Activity("Hello")));
Console.WriteLine("GetStateMachineWorkflowRequired: {0}\n", SR.GetStateMachineWorkflowRequired());
Console.WriteLine("GetError_EventDrivenParentNotListen: {0}\n", SR.GetError_EventDrivenParentNotListen());
Console.WriteLine("GetGetUnableToTransitionToState: {0}\n", SR.GetUnableToTransitionToState("StateName"));
Console.WriteLine("GetInvalidStateTransitionPath: {0}\n", SR.GetInvalidStateTransitionPath());
Console.WriteLine("GetInvalidSetStateInStateInitialization: {0}\n", SR.GetInvalidSetStateInStateInitialization());
Console.WriteLine("GetStateAlreadySubscribesToThisEvent: {0}\n", SR.GetStateAlreadySubscribesToThisEvent("StateName", "QueueName"));
}
}
*/
#endif
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using System.Linq;
// -----===== autogenerated code =====-----
// ReSharper disable All
// generator: BasicUnitValuesGenerator, UnitJsonConverterGenerator, UnitExtensionsGenerator
namespace iSukces.UnitedValues
{
[Serializable]
[JsonConverter(typeof(DeltaKelvinTemperatureJsonConverter))]
public partial struct DeltaKelvinTemperature : IUnitedValue<KelvinTemperatureUnit>, IEquatable<DeltaKelvinTemperature>, IComparable<DeltaKelvinTemperature>, IFormattable
{
/// <summary>
/// creates instance of DeltaKelvinTemperature
/// </summary>
/// <param name="value">value</param>
/// <param name="unit">unit</param>
public DeltaKelvinTemperature(decimal value, KelvinTemperatureUnit unit)
{
Value = value;
if (unit is null)
throw new NullReferenceException(nameof(unit));
Unit = unit;
}
public int CompareTo(DeltaKelvinTemperature other)
{
return UnitedValuesUtils.Compare<DeltaKelvinTemperature, KelvinTemperatureUnit>(this, other);
}
public DeltaKelvinTemperature ConvertTo(KelvinTemperatureUnit newUnit)
{
// generator : BasicUnitValuesGenerator.Add_ConvertTo
if (Unit.Equals(newUnit))
return this;
var basic = GetBaseUnitValue();
var factor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
return new DeltaKelvinTemperature(basic / factor, newUnit);
}
public bool Equals(DeltaKelvinTemperature other)
{
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public bool Equals(IUnitedValue<KelvinTemperatureUnit> other)
{
if (other is null)
return false;
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public override bool Equals(object other)
{
return other is IUnitedValue<KelvinTemperatureUnit> unitedValue ? Equals(unitedValue) : false;
}
public decimal GetBaseUnitValue()
{
// generator : BasicUnitValuesGenerator.Add_GetBaseUnitValue
if (Unit.Equals(BaseUnit))
return Value;
var factor = GlobalUnitRegistry.Factors.Get(Unit);
if (!(factor is null))
return Value * factor.Value;
throw new Exception("Unable to find multiplication for unit " + Unit);
}
public override int GetHashCode()
{
unchecked
{
return (Value.GetHashCode() * 397) ^ Unit?.GetHashCode() ?? 0;
}
}
public DeltaKelvinTemperature Round(int decimalPlaces)
{
return new DeltaKelvinTemperature(Math.Round(Value, decimalPlaces), Unit);
}
/// <summary>
/// Returns unit name
/// </summary>
public override string ToString()
{
return Value.ToString(CultureInfo.InvariantCulture) + Unit.UnitName;
}
/// <summary>
/// Returns unit name
/// </summary>
/// <param name="format"></param>
/// <param name="provider"></param>
public string ToString(string format, IFormatProvider provider = null)
{
return this.ToStringFormat(format, provider);
}
/// <summary>
/// implements - operator
/// </summary>
/// <param name="value"></param>
public static DeltaKelvinTemperature operator -(DeltaKelvinTemperature value)
{
return new DeltaKelvinTemperature(-value.Value, value.Unit);
}
public static DeltaKelvinTemperature operator -(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
// generator : BasicUnitValuesGenerator.Add_Algebra_PlusMinus
if (left.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(left.Unit?.UnitName))
return -right;
if (right.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(right.Unit?.UnitName))
return left;
right = right.ConvertTo(left.Unit);
return new DeltaKelvinTemperature(left.Value - right.Value, left.Unit);
}
public static bool operator !=(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
return left.CompareTo(right) != 0;
}
/// <summary>
/// implements * operator
/// </summary>
/// <param name="value"></param>
/// <param name="number"></param>
public static DeltaKelvinTemperature operator *(DeltaKelvinTemperature value, decimal number)
{
return new DeltaKelvinTemperature(value.Value * number, value.Unit);
}
/// <summary>
/// implements * operator
/// </summary>
/// <param name="number"></param>
/// <param name="value"></param>
public static DeltaKelvinTemperature operator *(decimal number, DeltaKelvinTemperature value)
{
return new DeltaKelvinTemperature(value.Value * number, value.Unit);
}
/// <summary>
/// implements / operator
/// </summary>
/// <param name="value"></param>
/// <param name="number"></param>
public static DeltaKelvinTemperature operator /(DeltaKelvinTemperature value, decimal number)
{
return new DeltaKelvinTemperature(value.Value / number, value.Unit);
}
public static decimal operator /(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
// generator : BasicUnitValuesGenerator.Add_Algebra_MulDiv
right = right.ConvertTo(left.Unit);
return left.Value / right.Value;
}
/// <summary>
/// implements / operator
/// </summary>
/// <param name="number"></param>
/// <param name="value"></param>
public static InversedDeltaKelvinTemperature operator /(decimal number, DeltaKelvinTemperature value)
{
return new InversedDeltaKelvinTemperature(number / value.Value, InversedKelvinTemperatureUnits.GetInversedKelvinTemperatureUnit(value.Unit));
}
public static DeltaKelvinTemperature operator +(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
// generator : BasicUnitValuesGenerator.Add_Algebra_PlusMinus
if (left.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(left.Unit?.UnitName))
return right;
if (right.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(right.Unit?.UnitName))
return left;
right = right.ConvertTo(left.Unit);
return new DeltaKelvinTemperature(left.Value + right.Value, left.Unit);
}
public static bool operator <(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator ==(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
return left.CompareTo(right) == 0;
}
public static bool operator >(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >=(DeltaKelvinTemperature left, DeltaKelvinTemperature right)
{
return left.CompareTo(right) >= 0;
}
/// <summary>
/// creates deltaKelvinTemperature from value in ----
/// </summary>
/// <param name="value">DeltaKelvinTemperature value in ----</param>
public static DeltaKelvinTemperature FromDegree(decimal value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new DeltaKelvinTemperature(value, KelvinTemperatureUnits.Degree);
}
/// <summary>
/// creates deltaKelvinTemperature from value in ----
/// </summary>
/// <param name="value">DeltaKelvinTemperature value in ----</param>
public static DeltaKelvinTemperature FromDegree(double value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new DeltaKelvinTemperature((decimal)value, KelvinTemperatureUnits.Degree);
}
/// <summary>
/// creates deltaKelvinTemperature from value in ----
/// </summary>
/// <param name="value">DeltaKelvinTemperature value in ----</param>
public static DeltaKelvinTemperature FromDegree(int value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new DeltaKelvinTemperature(value, KelvinTemperatureUnits.Degree);
}
/// <summary>
/// creates deltaKelvinTemperature from value in ----
/// </summary>
/// <param name="value">DeltaKelvinTemperature value in ----</param>
public static DeltaKelvinTemperature FromDegree(long value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new DeltaKelvinTemperature(value, KelvinTemperatureUnits.Degree);
}
public static DeltaKelvinTemperature Parse(string value)
{
// generator : BasicUnitValuesGenerator.Add_Parse
var parseResult = CommonParse.Parse(value, typeof(DeltaKelvinTemperature));
return new DeltaKelvinTemperature(parseResult.Value, new KelvinTemperatureUnit(parseResult.UnitName));
}
/// <summary>
/// value
/// </summary>
public decimal Value { get; }
/// <summary>
/// unit
/// </summary>
public KelvinTemperatureUnit Unit { get; }
public static readonly KelvinTemperatureUnit BaseUnit = KelvinTemperatureUnits.Degree;
public static readonly DeltaKelvinTemperature Zero = new DeltaKelvinTemperature(0, BaseUnit);
}
public static partial class DeltaKelvinTemperatureExtensions
{
public static DeltaKelvinTemperature Sum(this IEnumerable<DeltaKelvinTemperature> items)
{
if (items is null)
return DeltaKelvinTemperature.Zero;
var c = items.ToArray();
if (c.Length == 0)
return DeltaKelvinTemperature.Zero;
if (c.Length == 1)
return c[0];
var unit = c[0].Unit;
var value = c.Aggregate(0m, (x, y) => x + y.ConvertTo(unit).Value);
return new DeltaKelvinTemperature(value, unit);
}
public static DeltaKelvinTemperature Sum(this IEnumerable<DeltaKelvinTemperature?> items)
{
if (items is null)
return DeltaKelvinTemperature.Zero;
return items.Where(a => a != null).Select(a => a.Value).Sum();
}
public static DeltaKelvinTemperature Sum<T>(this IEnumerable<T> items, Func<T, DeltaKelvinTemperature> map)
{
if (items is null)
return DeltaKelvinTemperature.Zero;
return items.Select(map).Sum();
}
}
public partial class DeltaKelvinTemperatureJsonConverter : AbstractUnitJsonConverter<DeltaKelvinTemperature, KelvinTemperatureUnit>
{
protected override DeltaKelvinTemperature Make(decimal value, string unit)
{
unit = unit?.Trim();
return new DeltaKelvinTemperature(value, string.IsNullOrEmpty(unit) ? DeltaKelvinTemperature.BaseUnit : new KelvinTemperatureUnit(unit));
}
protected override DeltaKelvinTemperature Parse(string txt)
{
return DeltaKelvinTemperature.Parse(txt);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
////////////////////////////////////////////////////////////////////////////
//
// Class: StringInfo
//
// Purpose: This class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
// Date: March 31, 1999
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
[System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
{
private String m_str;
private int[] m_indexes;
// Legacy constructor
public StringInfo() : this("") { }
// Primary, useful constructor
public StringInfo(String value)
{
this.String = value;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
return (this.m_str.Equals(that.m_str));
}
return (false);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return this.m_str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
private int[] Indexes
{
get
{
if ((null == this.m_indexes) && (0 < this.String.Length))
{
this.m_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
return (this.m_indexes);
}
}
public String String
{
get
{
return (this.m_str);
}
set
{
if (null == value)
{
throw new ArgumentNullException("String",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
this.m_str = value;
this.m_indexes = null;
}
}
public int LengthInTextElements
{
get
{
if (null == this.Indexes)
{
// Indexes not initialized, so assume length zero
return (0);
}
return (this.Indexes.Length);
}
}
public static String GetNextTextElement(String str)
{
return (GetNextTextElement(str, 0));
}
////////////////////////////////////////////////////////////////////////
//
// Get the code point count of the current text element.
//
// A combining class is defined as:
// A character/surrogate that has the following Unicode category:
// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
//
// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
//
// 1. If a character/surrogate is in the following category, it is a text element.
// It can NOT further combine with characters in the combinging class to form a text element.
// * one of the Unicode category in the combinging class
// * UnicodeCategory.Format
// * UnicodeCateogry.Control
// * UnicodeCategory.OtherNotAssigned
// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
//
// Return:
// The length of the current text element
//
// Parameters:
// String str
// index The starting index
// len The total length of str (to define the upper boundary)
// ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return (currentCharCount);
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return (index - startIndex);
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return (ret);
}
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
public static String GetNextTextElement(String str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return (String.Empty);
}
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
public static TextElementEnumerator GetTextElementEnumerator(String str)
{
return (GetTextElementEnumerator(str, 0));
}
public static TextElementEnumerator GetTextElementEnumerator(String str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
return (new TextElementEnumerator(str, index, len));
}
/*
* Returns the indices of each base character or properly formed surrogate pair
* within the str. It recognizes a base character plus one or more combining
* characters or a properly formed surrogate pair as a text element and returns
* the index of the base character or high surrogate. Each index is the
* beginning of a text element within a str. The length of each element is
* easily computed as the difference between successive indices. The length of
* the array will always be less than or equal to the length of the str. For
* example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
* return the indices: 0, 2, 4.
*/
public static int[] ParseCombiningCharacters(String str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, returnArray, resultCount);
return (returnArray);
}
return (result);
}
}
}
| |
/*
* 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 OpenSim 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.Drawing;
using System.IO;
using System.Net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
{
public class LoadImageURLModule : IRegionModule, IDynamicTextureRender
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "LoadImageURL";
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
private string m_proxyurl = String.Empty;
private string m_proxyexcepts = String.Empty;
#region IDynamicTextureRender Members
public string GetName()
{
return m_name;
}
public string GetContentType()
{
return ("image");
}
public bool SupportsAsynchronous()
{
return true;
}
public byte[] ConvertUrl(string url, string extraParams)
{
return null;
}
public byte[] ConvertStream(Stream data, string extraParams)
{
return null;
}
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
MakeHttpRequest(url, id);
return true;
}
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
{
return false;
}
public void GetDrawStringSize(string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
}
#endregion
#region IRegionModule Members
public void Initialize(Scene scene, IConfigSource config)
{
if (m_scene == null)
{
m_scene = scene;
}
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
}
public void PostInitialize()
{
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null)
{
m_textureManager.RegisterRender(GetContentType(), this);
}
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
private void MakeHttpRequest(string url, UUID requestID)
{
WebRequest request = HttpWebRequest.Create(url);
if (!String.IsNullOrEmpty(m_proxyurl))
{
if (!String.IsNullOrEmpty(m_proxyexcepts))
{
string[] elist = m_proxyexcepts.Split(';');
request.Proxy = new WebProxy(m_proxyurl, true, elist);
}
else
{
request.Proxy = new WebProxy(m_proxyurl, true);
}
}
RequestState state = new RequestState((HttpWebRequest) request, requestID);
// IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
state.TimeOfRequest = (int) t.TotalSeconds;
}
private void HttpRequestReturn(IAsyncResult result)
{
RequestState state = (RequestState) result.AsyncState;
WebRequest request = (WebRequest) state.Request;
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
if (response.StatusCode == HttpStatusCode.OK)
{
Bitmap image = new Bitmap(response.GetResponseStream());
Size newsize;
// TODO: make this a bit less hard coded
if ((image.Height < 64) && (image.Width < 64))
{
newsize = new Size(32, 32);
}
else if ((image.Height < 128) && (image.Width < 128))
{
newsize = new Size(64, 64);
}
else if ((image.Height < 256) && (image.Width < 256))
{
newsize = new Size(128, 128);
}
else if ((image.Height < 512 && image.Width < 512))
{
newsize = new Size(256, 256);
}
else if ((image.Height < 1024 && image.Width < 1024))
{
newsize = new Size(512, 512);
}
else
{
newsize = new Size(1024, 1024);
}
Bitmap resize = new Bitmap(image, newsize);
byte[] imageJ2000 = new byte[0];
try
{
imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
}
catch (Exception)
{
m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Encode Failed. Empty byte data returned!");
}
m_textureManager.ReturnData(state.RequestID, imageJ2000);
}
}
catch (WebException)
{
}
}
#region Nested type: RequestState
public class RequestState
{
public HttpWebRequest Request = null;
public UUID RequestID = UUID.Zero;
public int TimeOfRequest = 0;
public RequestState(HttpWebRequest request, UUID requestID)
{
Request = request;
RequestID = requestID;
}
}
#endregion
}
}
| |
/*
* Copyright (C) 2016-2020. Autumn Beauchesne. All rights reserved.
* Author: Autumn Beauchesne
* Date: 7 Nov 2018
*
* File: BasePanel.cs
* Purpose: Abstract two-state UI panel.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace BeauRoutine.Extensions
{
/// <summary>
/// Base class for panels. Can be shown or hidden.
/// </summary>
public abstract class BasePanel : MonoBehaviour
{
/// <summary>
/// Animation type.
/// </summary>
public enum TransitionType : byte
{
Animated,
Instant
}
/// <summary>
/// Event for transitions.
/// </summary>
public class TransitionEvent : UnityEvent<TransitionType> { }
protected enum InputAnimationBehavior
{
AlwaysOn = 0,
DisableInteract = 1,
DisableRaycasts = 2
}
/// <summary>
/// Interface for performing transition animations.
/// </summary>
public interface IAnimator
{
/// <summary>
/// Performs an instant transition to the given state.
/// </summary>
void InstantTransitionTo(bool inbOn);
/// <summary>
/// Returns an IEnumerator for transitioning to the given state.
/// </summary>
IEnumerator TransitionTo(bool inbOn);
}
#region Inspector
[Header("Components")]
[SerializeField] protected RectTransform m_RootTransform = null;
[SerializeField] protected CanvasGroup m_RootGroup = null;
[SerializeField] private BasePanelAnimator[] m_PanelAnimators = null;
[Header("Behavior")]
[SerializeField] private InputAnimationBehavior m_InputBehavior = InputAnimationBehavior.DisableInteract;
[SerializeField] private bool m_HideOnStart = true;
[Header("Events")]
[SerializeField] private TransitionEvent m_OnShowEvent = new TransitionEvent();
[SerializeField] private TransitionEvent m_OnShowCompleteEvent = new TransitionEvent();
[SerializeField] private TransitionEvent m_OnHideEvent = new TransitionEvent();
[SerializeField] private TransitionEvent m_OnHideCompleteEvent = new TransitionEvent();
#endregion // Inspector
[NonSerialized] private Routine m_ShowHideAnim;
[NonSerialized] private bool m_Showing;
[NonSerialized] private bool m_StateInitialized;
[NonSerialized] private bool m_LastState;
public RectTransform Root { get { return m_RootTransform; } }
public CanvasGroup CanvasGroup { get { return m_RootGroup; } }
public TransitionEvent OnShowEvent { get { return m_OnShowEvent; } }
public TransitionEvent OnShowCompleteEvent { get { return m_OnShowCompleteEvent; } }
public TransitionEvent OnHideEvent { get { return m_OnHideEvent; } }
public TransitionEvent OnHideCompleteEvent { get { return m_OnHideCompleteEvent; } }
#region Unity Events
protected virtual void Awake() { }
protected virtual void Start()
{
if (m_StateInitialized)
return;
if (m_HideOnStart)
{
InstantHide();
}
else
{
InstantShow();
}
}
protected virtual void OnEnable() { }
protected virtual void OnDisable()
{
InstantHide();
}
#endregion // Unity Events
#region Show/Hide
/// <summary>
/// Returns the current showing state.
/// </summary>
public bool IsShowing()
{
return m_Showing;
}
/// <summary>
/// Returns if a show/hide animation is currently playing.
/// </summary>
public bool IsTransitioning()
{
return m_ShowHideAnim;
}
/// <summary>
/// Returns the previous showing state.
/// </summary>
public bool WasShowing()
{
return m_LastState;
}
public IEnumerator Show(float inDelay = 0)
{
if (!m_StateInitialized)
{
InstantShow();
return null;
}
if (!m_Showing)
{
m_LastState = m_Showing;
m_Showing = true;
m_ShowHideAnim.Replace(this, ShowImpl(inDelay)).ExecuteWhileDisabled().TryManuallyUpdate(0);
}
return m_ShowHideAnim.Wait();
}
public void InstantShow()
{
m_ShowHideAnim.Stop();
m_LastState = m_Showing;
m_Showing = true;
m_StateInitialized = true;
InvokeOnShow(TransitionType.Instant);
SubAnimatorInstantTransition(true);
InstantTransitionToShow();
SetInputState(true);
InvokeOnShowComplete(TransitionType.Instant);
}
public IEnumerator Hide(float inDelay = 0)
{
if (!m_StateInitialized)
{
InstantHide();
return null;
}
if (m_Showing)
{
m_LastState = m_Showing;
m_Showing = false;
SetInputState(false);
m_ShowHideAnim.Replace(this, HideImpl(inDelay)).ExecuteWhileDisabled().TryManuallyUpdate(0);
}
return m_ShowHideAnim.Wait();
}
public void InstantHide()
{
m_ShowHideAnim.Stop();
m_LastState = m_Showing;
m_Showing = false;
m_StateInitialized = true;
InvokeOnHide(TransitionType.Instant);
SubAnimatorInstantTransition(false);
InstantTransitionToHide();
SetInputState(false);
if (m_RootTransform)
m_RootTransform.gameObject.SetActive(false);
InvokeOnHideComplete(TransitionType.Instant);
}
#endregion // Show/Hide
#region Animations
private IEnumerator ShowImpl(float inDelay)
{
SetInputState(false);
if (inDelay > 0)
yield return inDelay;
InvokeOnShow(TransitionType.Animated);
yield return Routine.Inline(Routine.Combine(
TransitionToShow(),
SubAnimatorTransition(true)
));
SetInputState(true);
InvokeOnShowComplete(TransitionType.Animated);
}
private IEnumerator HideImpl(float inDelay)
{
SetInputState(false);
if (inDelay > 0)
yield return inDelay;
InvokeOnHide(TransitionType.Animated);
yield return Routine.Inline(Routine.Combine(
TransitionToHide(),
SubAnimatorTransition(false)
));
if (m_RootTransform)
m_RootTransform.gameObject.SetActive(false);
InvokeOnHideComplete(TransitionType.Animated);
}
protected virtual void SetInputState(bool inbEnabled)
{
if (!m_RootGroup || m_InputBehavior == InputAnimationBehavior.AlwaysOn)
return;
switch (m_InputBehavior)
{
case InputAnimationBehavior.DisableInteract:
m_RootGroup.interactable = inbEnabled;
break;
case InputAnimationBehavior.DisableRaycasts:
m_RootGroup.blocksRaycasts = inbEnabled;
break;
}
}
private IEnumerator SubAnimatorTransition(bool inbOn)
{
if (m_PanelAnimators == null || m_PanelAnimators.Length == 0)
return null;
if (m_PanelAnimators.Length == 1)
return m_PanelAnimators[0].TransitionTo(inbOn);
IEnumerator[] children = new IEnumerator[m_PanelAnimators.Length];
for (int i = 0; i < m_PanelAnimators.Length; ++i)
{
children[i] = Routine.Inline(m_PanelAnimators[i].TransitionTo(inbOn));
}
return Routine.Inline(Routine.Combine(children));
}
private void SubAnimatorInstantTransition(bool inbOn)
{
if (m_PanelAnimators != null)
{
for (int i = 0; i < m_PanelAnimators.Length; ++i)
{
m_PanelAnimators[i].InstantTransitionTo(inbOn);
}
}
}
private void InvokeOnShow(TransitionType inType)
{
m_OnShowEvent.Invoke(inType);
OnShow(inType == TransitionType.Instant);
}
private void InvokeOnShowComplete(TransitionType inType)
{
m_OnShowCompleteEvent.Invoke(inType);
OnShowComplete(inType == TransitionType.Instant);
}
private void InvokeOnHide(TransitionType inType)
{
m_OnHideEvent.Invoke(inType);
OnHide(inType == TransitionType.Instant);
}
private void InvokeOnHideComplete(TransitionType inType)
{
m_OnHideCompleteEvent.Invoke(inType);
OnHideComplete(inType == TransitionType.Instant);
}
#endregion // Animations
#region Abstract
protected virtual void OnShow(bool inbInstant) { }
protected virtual void OnShowComplete(bool inbInstant) { }
protected virtual IEnumerator TransitionToShow()
{
InstantTransitionToShow();
return null;
}
protected virtual void InstantTransitionToShow()
{
if (m_RootTransform)
m_RootTransform.gameObject.SetActive(true);
}
protected virtual void OnHide(bool inbInstant) { }
protected virtual void OnHideComplete(bool inbInstant) { }
protected virtual IEnumerator TransitionToHide()
{
InstantTransitionToHide();
return null;
}
protected virtual void InstantTransitionToHide()
{
if (m_RootTransform)
m_RootTransform.gameObject.SetActive(false);
}
#endregion // Abstract
#region Debug
#if UNITY_EDITOR
[ContextMenu("Show Panel")]
private void ShowDebug()
{
if (UnityEditor.EditorApplication.isPlaying)
{
Show();
}
else
{
UnityEditor.Undo.RegisterFullObjectHierarchyUndo(this, "Showing Panel");
InstantTransitionToShow();
}
}
[ContextMenu("Hide Panel")]
private void HideDebug()
{
if (UnityEditor.EditorApplication.isPlaying)
{
Hide();
}
else
{
UnityEditor.Undo.RegisterFullObjectHierarchyUndo(this, "Hiding Panel");
InstantTransitionToHide();
}
}
#endif // UNITY_EDITOR
#endregion // Debug
}
}
| |
namespace android.content.res
{
[global::MonoJavaBridge.JavaClass()]
public partial class TypedArray : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static TypedArray()
{
InitJNI();
}
protected TypedArray(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _toString2341;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._toString2341)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._toString2341)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getBoolean2342;
public virtual bool getBoolean(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.res.TypedArray._getBoolean2342, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getBoolean2342, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getInt2343;
public virtual int getInt(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getInt2343, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getInt2343, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getFloat2344;
public virtual float getFloat(int arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.content.res.TypedArray._getFloat2344, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getFloat2344, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _length2345;
public virtual int length()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._length2345);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._length2345);
}
internal static global::MonoJavaBridge.MethodId _getValue2346;
public virtual bool getValue(int arg0, android.util.TypedValue arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.res.TypedArray._getValue2346, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getValue2346, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getResources2347;
public virtual global::android.content.res.Resources getResources()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getResources2347)) as android.content.res.Resources;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getResources2347)) as android.content.res.Resources;
}
internal static global::MonoJavaBridge.MethodId _getInteger2348;
public virtual int getInteger(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getInteger2348, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getInteger2348, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getString2349;
public virtual global::java.lang.String getString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getString2349, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getString2349, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getIndex2350;
public virtual int getIndex(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getIndex2350, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getIndex2350, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getText2351;
public virtual global::java.lang.CharSequence getText(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getText2351, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getText2351, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _recycle2352;
public virtual void recycle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.res.TypedArray._recycle2352);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._recycle2352);
}
internal static global::MonoJavaBridge.MethodId _getTextArray2353;
public virtual global::java.lang.CharSequence[] getTextArray(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getTextArray2353, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getTextArray2353, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence[];
}
internal static global::MonoJavaBridge.MethodId _getDimension2354;
public virtual float getDimension(int arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.content.res.TypedArray._getDimension2354, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getDimension2354, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getDimensionPixelOffset2355;
public virtual int getDimensionPixelOffset(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getDimensionPixelOffset2355, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getDimensionPixelOffset2355, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getDimensionPixelSize2356;
public virtual int getDimensionPixelSize(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getDimensionPixelSize2356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getDimensionPixelSize2356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getFraction2357;
public virtual float getFraction(int arg0, int arg1, int arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.content.res.TypedArray._getFraction2357, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getFraction2357, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _getDrawable2358;
public virtual global::android.graphics.drawable.Drawable getDrawable(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getDrawable2358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getDrawable2358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _getColor2359;
public virtual int getColor(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getColor2359, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getColor2359, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getColorStateList2360;
public virtual global::android.content.res.ColorStateList getColorStateList(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getColorStateList2360, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.ColorStateList;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getColorStateList2360, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.ColorStateList;
}
internal static global::MonoJavaBridge.MethodId _getPositionDescription2361;
public virtual global::java.lang.String getPositionDescription()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getPositionDescription2361)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getPositionDescription2361)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getIndexCount2362;
public virtual int getIndexCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getIndexCount2362);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getIndexCount2362);
}
internal static global::MonoJavaBridge.MethodId _getNonResourceString2363;
public virtual global::java.lang.String getNonResourceString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._getNonResourceString2363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getNonResourceString2363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getLayoutDimension2364;
public virtual int getLayoutDimension(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getLayoutDimension2364, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getLayoutDimension2364, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getLayoutDimension2365;
public virtual int getLayoutDimension(int arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getLayoutDimension2365, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getLayoutDimension2365, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getResourceId2366;
public virtual int getResourceId(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.TypedArray._getResourceId2366, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._getResourceId2366, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _hasValue2367;
public virtual bool hasValue(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.res.TypedArray._hasValue2367, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._hasValue2367, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _peekValue2368;
public virtual global::android.util.TypedValue peekValue(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.TypedArray._peekValue2368, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.util.TypedValue;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.TypedArray.staticClass, global::android.content.res.TypedArray._peekValue2368, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.util.TypedValue;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.res.TypedArray.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/res/TypedArray"));
global::android.content.res.TypedArray._toString2341 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "toString", "()Ljava/lang/String;");
global::android.content.res.TypedArray._getBoolean2342 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getBoolean", "(IZ)Z");
global::android.content.res.TypedArray._getInt2343 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getInt", "(II)I");
global::android.content.res.TypedArray._getFloat2344 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getFloat", "(IF)F");
global::android.content.res.TypedArray._length2345 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "length", "()I");
global::android.content.res.TypedArray._getValue2346 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getValue", "(ILandroid/util/TypedValue;)Z");
global::android.content.res.TypedArray._getResources2347 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getResources", "()Landroid/content/res/Resources;");
global::android.content.res.TypedArray._getInteger2348 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getInteger", "(II)I");
global::android.content.res.TypedArray._getString2349 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getString", "(I)Ljava/lang/String;");
global::android.content.res.TypedArray._getIndex2350 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getIndex", "(I)I");
global::android.content.res.TypedArray._getText2351 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getText", "(I)Ljava/lang/CharSequence;");
global::android.content.res.TypedArray._recycle2352 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "recycle", "()V");
global::android.content.res.TypedArray._getTextArray2353 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getTextArray", "(I)[Ljava/lang/CharSequence;");
global::android.content.res.TypedArray._getDimension2354 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getDimension", "(IF)F");
global::android.content.res.TypedArray._getDimensionPixelOffset2355 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getDimensionPixelOffset", "(II)I");
global::android.content.res.TypedArray._getDimensionPixelSize2356 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getDimensionPixelSize", "(II)I");
global::android.content.res.TypedArray._getFraction2357 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getFraction", "(IIIF)F");
global::android.content.res.TypedArray._getDrawable2358 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getDrawable", "(I)Landroid/graphics/drawable/Drawable;");
global::android.content.res.TypedArray._getColor2359 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getColor", "(II)I");
global::android.content.res.TypedArray._getColorStateList2360 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getColorStateList", "(I)Landroid/content/res/ColorStateList;");
global::android.content.res.TypedArray._getPositionDescription2361 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getPositionDescription", "()Ljava/lang/String;");
global::android.content.res.TypedArray._getIndexCount2362 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getIndexCount", "()I");
global::android.content.res.TypedArray._getNonResourceString2363 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getNonResourceString", "(I)Ljava/lang/String;");
global::android.content.res.TypedArray._getLayoutDimension2364 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getLayoutDimension", "(II)I");
global::android.content.res.TypedArray._getLayoutDimension2365 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getLayoutDimension", "(ILjava/lang/String;)I");
global::android.content.res.TypedArray._getResourceId2366 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "getResourceId", "(II)I");
global::android.content.res.TypedArray._hasValue2367 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "hasValue", "(I)Z");
global::android.content.res.TypedArray._peekValue2368 = @__env.GetMethodIDNoThrow(global::android.content.res.TypedArray.staticClass, "peekValue", "(I)Landroid/util/TypedValue;");
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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.Text;
using System.Collections;
using Alachisoft.NCache.Common.Threading;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Caching.Statistics;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Util;
using System.Threading;
using Alachisoft.NCache.Caching.Exceptions;
using Runtime = Alachisoft.NCache.Runtime;
namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
#region / --- StateTransferTask --- /
/// <summary>
/// Asynchronous state tranfer job.
/// </summary>
internal class StateTransferTask
{
/// <summary> The partition base class </summary>
internal ClusterCacheBase _parent = null;
/// <summary> A promise object to wait on. </summary>
protected Promise _promise = null;
/// <summary> 10K is the threshold data size. Above this threshold value, data will be state
/// transfered in chunks. </summary>
//muds: temporarily we are disabling the bulk transfer of sparsed buckets.
//in future we may need it back.
protected long _threshold = 0; //10 * 1000;
/// <summary>
/// All the buckets that has less than threshold data size are sparsed.
/// This is the list of sparsed bucket ids.
/// </summary>
protected ArrayList _sparsedBuckets = new ArrayList();
/// <summary>
/// All the buckets that has more than threshold data size are filled.
/// This is the list of the filled buckted ids.
/// </summary>
protected ArrayList _filledBuckets = new ArrayList();
protected bool _isInStateTxfr = false;
protected System.Threading.Thread _worker;
protected bool _isRunning;
protected object _stateTxfrMutex = new object();
protected Address _localAddress;
protected int _bktTxfrRetryCount = 3;
protected ArrayList _correspondingNodes = new ArrayList();
/// <summary>Flag which determines that if sparsed buckets are to be transferred in bulk or not.</summary>
protected bool _allowBulkInSparsedBuckets = true;
protected byte _trasferType = StateTransferType.MOVE_DATA;
protected bool _logStateTransferEvent;
protected bool _stateTransferEventLogged;
/// <summary>
/// State Transfer Size is used to control the rate of data transfer during State Tranfer i.e per second tranfer rate in MB
/// </summary>
private static long MB = 1024 * 1024;
protected long stateTxfrDataSizePerSecond = MB;
TimeSpan _interval = new TimeSpan(0, 0, 1);
private ThrottlingManager _throttlingManager;
private bool _enableGc;
private long _gcThreshhold = 1024 * MB * 2;//default is 2 Gb
private long _dataTransferred;
/// <summary>
/// Gets or sets a value indicating whether this task is for Balancing Data Load or State Transfer.
/// </summary>
protected bool _isBalanceDataLoad = false;
/// <summary>
/// Keep List of Failed keys on main node during state txfr
/// </summary>
///
ArrayList failedKeysList = null;
private int updateCount;
string _cacheserver = "NCache";
private object _updateIdMutex = new object();
protected StringBuilder _sb = new StringBuilder();
/// <summary>
/// Constructor
/// </summary>
protected StateTransferTask()
{
_promise = new Promise();
}
protected virtual string Name
{
get { return "(" + _localAddress.ToString() + ")StateTransferTask"; }
}
protected virtual bool IsSyncReplica
{
get { return false; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="parent"></param>
public StateTransferTask(ClusterCacheBase parent, Address localAdd)
{
_parent = parent;
_promise = new Promise();
_localAddress = localAdd;
if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.StateTransferDataSizePerSecond"]))
{
try
{
float result = 0;
float.TryParse(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.StateTransferDataSizePerSecond"], out result);
if (result > 0)
stateTxfrDataSizePerSecond = (long)(result * MB);
}
catch (Exception e)
{
_parent.NCacheLog.Error(this.Name, "Invalid value specified for NCacheServer.StateTransferDataSizePerSecond." + System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.StateTransferDataSizePerSecond"]);
}
}
if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EnableGCDuringStateTransfer"]))
{
try
{
bool enabled = false;
if (bool.TryParse(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EnableGCDuringStateTransfer"], out enabled))
_enableGc = enabled;
}
catch (Exception e)
{
_parent.NCacheLog.Error(this.Name, "Invalid value specified for NCacheServer.EnableGCDuringStateTransfer." + System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EnableGCDuringStateTransfer"]);
}
}
if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.GCThreshold"]))
{
try
{
long threshold = _gcThreshhold;
if (long.TryParse(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.GCThreshold"], out threshold))
_gcThreshhold = threshold * MB;
}
catch (Exception e)
{
_parent.NCacheLog.Error(this.Name, "Invalid value specified for NCacheServer.GCThreshold." + System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.GCThreshold"]);
}
}
if (_parent != null && _parent.NCacheLog.IsErrorEnabled)
_parent.NCacheLog.CriticalInfo(Name, " explicit-gc-enabled =" + _enableGc + " threshold = " + _gcThreshhold);
}
public void Start()
{
string instanceName = this.ToString();
_throttlingManager = new ThrottlingManager(stateTxfrDataSizePerSecond);
_throttlingManager.Start();
_worker = new System.Threading.Thread(new System.Threading.ThreadStart(Process));
_worker.IsBackground = true;
_worker.Start();
}
public void Stop()
{
if (_worker != null)
{
_parent.Context.NCacheLog.Flush();
_worker.Abort();
_worker = null;
}
_sparsedBuckets.Clear();
_filledBuckets.Clear();
}
public void DoStateTransfer(ArrayList buckets, bool transferQueue)
{
int updateId = 0;
lock (_updateIdMutex)
{
updateId = ++updateCount;
}
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(UpdateAsync), new object[] { buckets, transferQueue, updateId });
}
public void UpdateAsync(object state)
{
try
{
object[] obj = state as object[];
ArrayList buckets = obj[0] as ArrayList;
bool transferQueue = (bool)obj[1];
int updateId = (int)obj[2];
_parent.DetermineClusterStatus();
if (!UpdateStateTransfer(buckets, updateId))
{
return;
}
if (_parent.HasDisposed)
return;
if (!_isRunning)
{
_logStateTransferEvent = _stateTransferEventLogged = false;
Start();
}
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error(Name + ".UpdateAsync", e.ToString());
}
}
/// <summary>
/// Gets or sets a value indicating whether this StateTransfer task is initiated for Data balancing purposes or not.
/// </summary>
public bool IsBalanceDataLoad
{
get { return _isBalanceDataLoad; }
set { _isBalanceDataLoad = value; }
}
public bool IsRunning
{
get { lock (_stateTxfrMutex) { return _isRunning; } }
set { lock (_stateTxfrMutex) { _isRunning = value; } }
}
/// <summary>
/// Do the state transfer now.
/// </summary>
protected virtual void Process()
{
//muds:
//fetch the latest stats from every node.
_isRunning = true;
object result = null;
try
{
_parent.Cluster.MarkClusterInStateTransfer();
_parent.DetermineClusterStatus();
_parent.Context.NCacheLog.CriticalInfo(Name + ".Process", " State transfer has started");
BucketTxfrInfo info;
while (true)
{
lock (_stateTxfrMutex)
{
info = GetBucketsForTxfr();
//muds:
//if no more data to transfer then stop.
if (info.end)
{
_isRunning = false;
break;
}
}
ArrayList bucketIds = info.bucketIds;
Address owner = info.owner;
bool isSparsed = info.isSparsed;
if (bucketIds != null && bucketIds.Count > 0)
{
if (!_correspondingNodes.Contains(owner))
_correspondingNodes.Add(owner);
TransferData(bucketIds, owner, isSparsed);
}
}
result = _parent.Local_Count();
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error(Name + ".Process", e.ToString());
result = e;
}
finally
{
//Mark state transfer completed.
_parent.Cluster.MarkClusterStateTransferCompleted();
try
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".Process", " Ending state transfer with result : " + result.ToString());
_parent.EndStateTransfer(result);
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".Process", " Total Corresponding Nodes: " + _correspondingNodes.Count);
foreach (Address corNode in _correspondingNodes)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".Process", " Corresponding Node: " + corNode.ToString());
_parent.SignalEndOfStateTxfr(corNode);
}
_isInStateTxfr = false;
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".Process", " Finalizing state transfer");
FinalizeStateTransfer();
_parent.Context.NCacheLog.CriticalInfo(Name + ".Process", " State transfer has ended");
if (_logStateTransferEvent)
{
AppUtil.LogEvent(_cacheserver, "\"" + _parent.Context.SerializationContext + "(" + _parent.Cluster.LocalAddress.ToString() + ")\"" + " has ended state transfer.", System.Diagnostics.EventLogEntryType.Information, EventCategories.Information, EventID.StateTransferStop);
}
}
catch (Exception ex)
{
_parent.Context.NCacheLog.Error(Name + ".Process", ex.ToString());
}
}
}
protected virtual void FinalizeStateTransfer() { }
private void TransferData(int bucketId, Address owner, bool sparsedBucket)
{
ArrayList tmp = new ArrayList(1);
tmp.Add(bucketId);
TransferData(tmp, owner, sparsedBucket);
}
protected virtual void TransferData(ArrayList bucketIds, Address owner, bool sparsedBuckets)
{
ArrayList ownershipChanged = null;
ArrayList lockAcquired = null;
ArrayList alreayLocked = null;
//muds:
//ask coordinator node to lock this/these bucket(s) during the state transfer.
Hashtable lockResults = AcquireLockOnBuckets(bucketIds);
if (lockResults != null)
{
ownershipChanged = (ArrayList)lockResults[BucketLockResult.OwnerChanged];
if (ownershipChanged != null && ownershipChanged.Count > 0)
{
//muds:
//remove from local buckets. remove from sparsedBuckets. remove from filledBuckets.
//these are no more my property.
IEnumerator ie = ownershipChanged.GetEnumerator();
while (ie.MoveNext())
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".TransferData", " " + ie.Current.ToString() + " ownership changed");
if (_parent.InternalCache.Statistics.LocalBuckets.Contains(ie.Current))
{
lock (_parent.InternalCache.Statistics.LocalBuckets.SyncRoot)
{
_parent.InternalCache.Statistics.LocalBuckets.Remove(ie.Current);
}
}
}
}
lockAcquired = (ArrayList)lockResults[BucketLockResult.LockAcquired];
if (lockAcquired != null && lockAcquired.Count > 0)
{
failedKeysList = new ArrayList();
AnnounceStateTransfer(lockAcquired);
bool bktsTxfrd = TransferBuckets(lockAcquired, ref owner, sparsedBuckets);
ReleaseBuckets(lockAcquired);
RemoveFailedKeysOnReplica();
}
}
else
if (_parent.Context.NCacheLog.IsErrorEnabled) _parent.Context.NCacheLog.Error(Name + ".TransferData", " Lock acquisition failure");
}
protected virtual void PrepareBucketsForStateTxfr(ArrayList buckets) { }
protected virtual void EndBucketsStateTxfr(ArrayList buckets) { }
protected virtual void AnnounceStateTransfer(ArrayList buckets)
{
_parent.AnnounceStateTransfer(buckets);
}
protected virtual void ReleaseBuckets(ArrayList lockedBuckets)
{
if (_parent != null) _parent.ReleaseBuckets(lockedBuckets);
}
/// <summary>
/// Transfers the buckets from a its owner. We may receive data in chunks.
/// It is a pull model, a node wanting state transfer a bucket makes request
/// to its owner.
/// </summary>
/// <param name="buckets"></param>
/// <param name="owner"></param>
/// <returns></returns>
private bool TransferBuckets(ArrayList buckets, ref Address owner, bool sparsedBuckets)
{
bool transferEnd;
bool successfullyTxfrd = false;
int expectedTxfrId = 1;
bool resync = false;
try
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".TransferBuckets", " Starting transfer. Owner : " + owner.ToString() + " , Bucket : " + ((int)buckets[0]).ToString());
PrepareBucketsForStateTxfr(buckets);
long dataRecieved = 0;
long currentIternationData = 0;
while (true)
{
if (_enableGc && _dataTransferred >= _gcThreshhold)
{
_dataTransferred = 0;
DateTime start = DateTime.Now;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
DateTime end = DateTime.Now;
TimeSpan diff = end - start;
if (_parent.NCacheLog.IsErrorEnabled) _parent.NCacheLog.CriticalInfo(this.Name + ".TransferBucket", "explicit GC called. time taken(ms) :" + diff.TotalMilliseconds + " gcThreshold :" + _gcThreshhold);
}
else
_dataTransferred += currentIternationData;
Boolean sleep = false;
resync = false;
transferEnd = true;
StateTxfrInfo info = null;
try
{
currentIternationData = 0;
info = SafeTransferBucket(buckets, owner, sparsedBuckets, expectedTxfrId);
if (info != null)
{
currentIternationData = info.DataSize;
dataRecieved += info.DataSize;
}
}
catch (Runtime.Exceptions.SuspectedException)
{
resync = true;
}
catch (Runtime.Exceptions.TimeoutException)
{
}
if (resync)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".TransferBuckets", owner + " is suspected");
Address changedOwner = GetChangedOwner((int)buckets[0], owner);
if (changedOwner != null)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".TransferBuckets", changedOwner + " is new owner");
if (changedOwner.Equals(owner))
{
continue;
}
else
{
owner = changedOwner;
expectedTxfrId = 1;
continue;
}
}
else
{
_parent.Context.NCacheLog.Error(Name + ".TransferBuckets", " Could not get new owner");
info = new StateTxfrInfo(true);
}
}
if (info != null)
{
successfullyTxfrd = true;
transferEnd = info.transferCompleted;
Hashtable tbl = info.data;
CacheEntry entry = null;
expectedTxfrId++;
//muds:
//add data to local cache.
if (tbl != null && tbl.Count > 0)
{
IDictionaryEnumerator ide = tbl.GetEnumerator();
while (ide.MoveNext())
{
if (!_stateTransferEventLogged)
{
AppUtil.LogEvent(_cacheserver, "\"" + _parent.Context.SerializationContext + "(" + _parent.Cluster.LocalAddress.ToString() + ")\"" + " has started state transfer.", System.Diagnostics.EventLogEntryType.Information, EventCategories.Information, EventID.StateTransferStart);
_stateTransferEventLogged = _logStateTransferEvent = true;
}
try
{
OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
if (ide.Value != null)
{
entry = ide.Value as CacheEntry;
CacheInsResultWithEntry result = _parent.InternalCache.Insert(ide.Key, entry, false, false, null, LockAccessType.DEFAULT, operationContext);
if (result != null && result.Result == CacheInsResult.NeedsEviction)
{
failedKeysList.Add(ide.Key);
}
}
else
{
_parent.InternalCache.Remove(ide.Key, ItemRemoveReason.Removed, false, false, null, LockAccessType.IGNORE_LOCK, operationContext);
}
}
catch (StateTransferException se)
{
_parent.Context.NCacheLog.Error(Name + ".TransferBuckets", " Can not add/remove key = " + ide.Key + " : value is " + ((ide.Value == null) ? "null" : " not null") + " : " + se.Message);
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error(Name + ".TransferBuckets", " Can not add/remove key = " + ide.Key + " : value is " + ((ide.Value == null) ? "null" : " not null") + " : " + e.Message);
}
}
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".TransferBuckets", " BalanceDataLoad = " + _isBalanceDataLoad.ToString());
if (_isBalanceDataLoad)
_parent.Context.PerfStatsColl.IncrementDataBalPerSecStatsBy(tbl.Count);
else
_parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(tbl.Count);
}
}
else
successfullyTxfrd = false;
if (transferEnd)
{
BucketsTransfered(owner, buckets);
EndBucketsStateTxfr(buckets);
//muds:
//send ack for the state transfer over.
//Ask every node to release lock on this/these bucket(s)
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".TransferBuckets", "Acknowledging transfer. Owner : " + owner.ToString() + " , Bucket : " + ((int)buckets[0]).ToString());
AcknowledgeStateTransferCompleted(owner, buckets);
break;
}
if (info != null)
_throttlingManager.Throttle(info.DataSize);
}
}
catch (System.Threading.ThreadAbortException)
{
EndBucketsStateTxfr(buckets);
throw;
}
return successfullyTxfrd;
}
private void RemoveFailedKeysOnReplica()
{
try
{
if (IsSyncReplica && failedKeysList != null && failedKeysList.Count > 0)
{
OperationContext operationContext = new OperationContext(OperationContextFieldName.RemoveOnReplica, true);
operationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
IEnumerator ieFailedKeys = failedKeysList.GetEnumerator();
while (ieFailedKeys.MoveNext())
{
string key = (string)ieFailedKeys.Current;
try
{
_parent.Context.CacheImpl.Remove(key, ItemRemoveReason.Removed, false, null, LockAccessType.IGNORE_LOCK, operationContext);
}
catch (Exception ex)
{
}
}
}
}
finally
{
failedKeysList = null;
}
}
public virtual void AcknowledgeStateTransferCompleted(Address owner, ArrayList buckets)
{
if (owner != null)
{
_parent.AckStateTxfrCompleted(owner, buckets);
}
}
/// <summary>
/// Safely transfer a buckets from its owner. In case timeout occurs we
/// retry once again.
/// </summary>
/// <param name="buckets"></param>
/// <param name="owner"></param>
/// <returns></returns>
private StateTxfrInfo SafeTransferBucket(ArrayList buckets, Address owner, bool sparsedBuckets, int expectedTxfrId)
{
StateTxfrInfo info = null;
int retryCount = _bktTxfrRetryCount;
while (retryCount > 0)
{
try
{
info = _parent.TransferBucket(buckets, owner, _trasferType, sparsedBuckets, expectedTxfrId, _isBalanceDataLoad);
return info;
}
catch (Runtime.Exceptions.SuspectedException)
{
//Member with which we were doing state txfer has left.
_parent.Context.NCacheLog.Error(Name + ".SafeTransterBucket", " " + owner + " is suspected during state txfr");
foreach (int bucket in buckets)
{
try
{
_parent.EmptyBucket(bucket);
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error(Name + ".SafeTransterBucket", e.ToString());
}
}
throw;
}
catch (Runtime.Exceptions.TimeoutException tout_e)
{
_parent.Context.NCacheLog.Error(Name + ".SafeTransterBucket", " State transfer request timed out from " + owner);
retryCount--;
if (retryCount <= 0)
throw;
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error(Name + ".SafeTransterBucket", " An error occured during state Txfr " + e.ToString());
break;
}
}
return info;
}
/// <summary>
/// Acquire locks on the buckets.
/// </summary>
/// <param name="buckets"></param>
/// <returns></returns>
protected virtual Hashtable AcquireLockOnBuckets(ArrayList buckets)
{
int maxTries = 3;
while (maxTries > 0)
{
try
{
Hashtable lockResults = _parent.LockBuckets(buckets);
return lockResults;
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error(Name + ".AcquireLockOnBuckets", "could not acquire lock on buckets. error: " + e.ToString());
maxTries--;
}
}
return null;
}
public virtual BucketTxfrInfo GetBucketsForTxfr()
{
ArrayList bucketIds = null;
Address owner = null;
int bucketId;
ArrayList filledBucketIds = null;
lock (_stateTxfrMutex)
{
if (_sparsedBuckets != null && _sparsedBuckets.Count > 0)
{
lock (_sparsedBuckets.SyncRoot)
{
BucketsPack bPack = _sparsedBuckets[0] as BucketsPack;
owner = bPack.Owner;
bucketIds = bPack.BucketIds;
if (_allowBulkInSparsedBuckets)
{
return new BucketTxfrInfo(bucketIds, true, owner);
}
else
{
ArrayList list = new ArrayList();
list.Add(bucketIds[0]);
//Although it is from the sparsed bucket but we intentionally set flag as non-sparsed.
return new BucketTxfrInfo(list, false, owner);
}
}
}
else if (_filledBuckets != null && _filledBuckets.Count > 0)
{
lock (_filledBuckets.SyncRoot)
{
BucketsPack bPack = _filledBuckets[0] as BucketsPack;
owner = bPack.Owner;
filledBucketIds = bPack.BucketIds;
if (filledBucketIds != null && filledBucketIds.Count > 0)
{
bucketId = (int)filledBucketIds[0];
bucketIds = new ArrayList(1);
bucketIds.Add(bucketId);
}
}
return new BucketTxfrInfo(bucketIds, false, owner);
}
else
return new BucketTxfrInfo(true);
}
}
/// <summary>
/// Removes the buckets from the list of transferable buckets after we have
/// transferred them.
/// </summary>
/// <param name="owner"></param>
/// <param name="buckets"></param>
/// <param name="sparsed"></param>
protected void BucketsTransfered(Address owner, ArrayList buckets)
{
BucketsPack bPack = null;
lock (_stateTxfrMutex)
{
if (_sparsedBuckets != null)
{
BucketsPack dummy = new BucketsPack(null, owner);
int index = _sparsedBuckets.IndexOf(dummy);
if (index != -1)
{
bPack = _sparsedBuckets[index] as BucketsPack;
foreach (int bucket in buckets)
{
bPack.BucketIds.Remove(bucket);
}
if (bPack.BucketIds.Count == 0)
_sparsedBuckets.RemoveAt(index);
}
}
if (_filledBuckets != null)
{
BucketsPack dummy = new BucketsPack(null, owner);
int index = _filledBuckets.IndexOf(dummy);
if (index != -1)
{
bPack = _filledBuckets[index] as BucketsPack;
foreach (int bucket in buckets)
{
bPack.BucketIds.Remove(bucket);
}
if (bPack.BucketIds.Count == 0)
_filledBuckets.RemoveAt(index);
}
}
}
}
private BucketStatistics GetBucketStats(int bucketId, Address owner)
{
ArrayList nodeInfos = _parent._stats.Nodes.Clone() as ArrayList;
if (nodeInfos != null)
{
IEnumerator ie = nodeInfos.GetEnumerator();
if (ie != null)
{
while (ie.MoveNext())
{
NodeInfo tmp = ie.Current as NodeInfo;
if (tmp.Address.CompareTo(owner) == 0 && tmp.Statistics != null)
{
if (tmp.Statistics.LocalBuckets != null)
{
object obj = tmp.Statistics.LocalBuckets[bucketId];
if (obj != null)
return obj as BucketStatistics;
}
return new BucketStatistics();
}
}
}
}
return null;
}
/// <summary>
/// Updates the state transfer task in synchronus way. It adds/remove buckets
/// to be transferred by the state transfer task.
/// </summary>
/// <param name="myBuckets"></param>
public bool UpdateStateTransfer(ArrayList myBuckets, int updateId)
{
if (_parent.HasDisposed)
return false;
StringBuilder sb = new StringBuilder();
lock (_updateIdMutex)
{
if (updateId != updateCount)
{
if (_parent.NCacheLog.IsErrorEnabled) _parent.Context.NCacheLog.CriticalInfo(this.Name + "UpdateStateTxfr", " Do not need to update the task as update id does not match; provided id :" + updateId + " currentId :" + updateCount);
return false;
}
}
lock (_stateTxfrMutex)
{
try
{
if (myBuckets != null)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".UpdateStateTxfr", " my buckets " + myBuckets.Count);
//we work on the copy of the map.
ArrayList buckets = myBuckets.Clone() as ArrayList;
ArrayList leavingNodes = new ArrayList();
if (_sparsedBuckets != null && _sparsedBuckets.Count > 0)
{
IEnumerator e = _sparsedBuckets.GetEnumerator();
lock (_sparsedBuckets.SyncRoot)
{
while (e.MoveNext())
{
BucketsPack bPack = (BucketsPack)e.Current;
ArrayList bucketIds = bPack.BucketIds.Clone() as ArrayList;
foreach (int bucketId in bucketIds)
{
HashMapBucket current = new HashMapBucket(null, bucketId);
if (!buckets.Contains(current))
{
((BucketsPack)e.Current).BucketIds.Remove(bucketId);
}
else
{
HashMapBucket bucket = buckets[buckets.IndexOf(current)] as HashMapBucket;
if (!bPack.Owner.Equals(bucket.PermanentAddress))
{
//either i have become owner of the bucket or
//some one else for e.g a replica node
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".UpdateStateTxfer", bucket.BucketId + "bucket owner changed old :" + bPack.Owner + " new :" + bucket.PermanentAddress);
bPack.BucketIds.Remove(bucketId);
}
}
}
if (bPack.BucketIds.Count == 0)
{
//This owner has left.
leavingNodes.Add(bPack.Owner);
}
}
foreach (Address leavigNode in leavingNodes)
{
BucketsPack bPack = new BucketsPack(null, leavigNode);
_sparsedBuckets.Remove(bPack);
}
leavingNodes.Clear();
}
}
if (_filledBuckets != null && _filledBuckets.Count > 0)
{
IEnumerator e = _filledBuckets.GetEnumerator();
lock (_filledBuckets.SyncRoot)
{
while (e.MoveNext())
{
BucketsPack bPack = (BucketsPack)e.Current;
ArrayList bucketIds = bPack.BucketIds.Clone() as ArrayList;
foreach (int bucketId in bucketIds)
{
HashMapBucket current = new HashMapBucket(null, bucketId);
if (!buckets.Contains(current))
{
((BucketsPack)e.Current).BucketIds.Remove(bucketId);
}
else
{
HashMapBucket bucket = buckets[buckets.IndexOf(current)] as HashMapBucket;
if (!bPack.Owner.Equals(bucket.PermanentAddress))
{
//either i have become owner of the bucket or
//some one else for e.g a replica node
bPack.BucketIds.Remove(bucketId);
}
}
}
if (bPack.BucketIds.Count == 0)
{
//This owner has left.
leavingNodes.Add(bPack.Owner);
}
}
foreach (Address leavigNode in leavingNodes)
{
BucketsPack bPack = new BucketsPack(null, leavigNode);
_filledBuckets.Remove(bPack);
}
leavingNodes.Clear();
}
}
//Now we add those buckets which we have to be state transferred
//and are not currently in our list
IEnumerator ie = buckets.GetEnumerator();
while (ie.MoveNext())
{
HashMapBucket bucket = ie.Current as HashMapBucket;
if (_localAddress.Equals(bucket.TempAddress) && !_localAddress.Equals(bucket.PermanentAddress))
{
BucketsPack bPack = new BucketsPack(null, bucket.PermanentAddress);
if (IsSparsedBucket(bucket.BucketId, bucket.PermanentAddress))
{
int index = _sparsedBuckets.IndexOf(bPack);
if (index != -1)
{
bPack = _sparsedBuckets[index] as BucketsPack;
}
else
_sparsedBuckets.Add(bPack);
if (!bPack.BucketIds.Contains(bucket.BucketId))
{
bPack.BucketIds.Add(bucket.BucketId);
}
}
else
{
int index = _filledBuckets.IndexOf(bPack);
if (index != -1)
{
bPack = _filledBuckets[index] as BucketsPack;
}
else
{
_filledBuckets.Add(bPack);
}
if (!bPack.BucketIds.Contains(bucket.BucketId))
{
bPack.BucketIds.Add(bucket.BucketId);
}
}
}
}
}
}
catch (NullReferenceException ex)
{
_parent.Context.NCacheLog.Error(Name + ".UpdateStateTxfr", ex.ToString());
}
catch (Exception e)
{
_parent.Context.NCacheLog.Error(Name + ".UpdateStateTxfr", e.ToString());
}
finally
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".UpdateStateTxfr", " Pulsing waiting thread");
System.Threading.Monitor.PulseAll(_stateTxfrMutex);
}
}
return true;
}
protected Address GetChangedOwner(int bucket, Address currentOwner)
{
Address newOwner = null;
lock (_stateTxfrMutex)
{
while (true)
{
newOwner = GetOwnerOfBucket(bucket);
if (newOwner == null) return null;
if (newOwner.Equals(currentOwner))
{
System.Threading.Monitor.Wait(_stateTxfrMutex);
}
else
return newOwner;
}
}
}
protected Address GetOwnerOfBucket(int bucket)
{
lock (_stateTxfrMutex)
{
if (_sparsedBuckets != null)
{
foreach (BucketsPack bPack in _sparsedBuckets)
{
if (bPack.BucketIds.Contains(bucket))
return bPack.Owner;
}
}
if (_filledBuckets != null)
{
foreach (BucketsPack bPack in _filledBuckets)
{
if (bPack.BucketIds.Contains(bucket))
return bPack.Owner;
}
}
}
return null;
}
/// <summary>
/// Determines whether a given bucket is sparsed one or not. A bucket is
/// considered sparsed if its size is less than the threshhold value.
/// </summary>
/// <param name="bucketId"></param>
/// <param name="owner"></param>
/// <returns>True, if bucket is sparsed.</returns>
public bool IsSparsedBucket(int bucketId, Address owner)
{
bool isSparsed = false;
BucketStatistics stats = GetBucketStats((int)bucketId, owner);
isSparsed = stats != null ? stats.DataSize < _threshold : false;
return isSparsed;
}
public void UpdateBuckets()
{
lock (_parent._internalCache.Statistics.LocalBuckets.SyncRoot)
{
IDictionaryEnumerator ide = _parent._internalCache.Statistics.LocalBuckets.GetEnumerator();
while (ide.MoveNext())
{
if (_isInStateTxfr)
{
if (_sparsedBuckets != null && _sparsedBuckets.Count > 0)
{
ArrayList tmp = _sparsedBuckets.Clone() as ArrayList;
IEnumerator e = tmp.GetEnumerator();
lock (_sparsedBuckets.SyncRoot)
{
while (e.MoveNext())
{
ArrayList bucketIds = ((BucketsPack)e.Current).BucketIds.Clone() as ArrayList;
foreach (int bucketId in bucketIds)
{
if (!_parent._internalCache.Statistics.LocalBuckets.Contains(bucketId))
{
if (((HashMapBucket)_parent.HashMap[bucketId]).Status != BucketStatus.UnderStateTxfr)
((BucketsPack)e.Current).BucketIds.Remove(bucketId);
}
}
}
}
}
if (_filledBuckets != null && _filledBuckets.Count > 0)
{
ArrayList tmp = _filledBuckets.Clone() as ArrayList;
IEnumerator e = tmp.GetEnumerator();
lock (_filledBuckets.SyncRoot)
{
while (e.MoveNext())
{
ArrayList bucketIds = ((BucketsPack)e.Current).BucketIds.Clone() as ArrayList;
foreach (int bucketId in bucketIds)
{
if (!_parent._internalCache.Statistics.LocalBuckets.Contains(bucketId))
{
if (((HashMapBucket)_parent.HashMap[bucketId]).Status != BucketStatus.UnderStateTxfr)
((BucketsPack)e.Current).BucketIds.Remove(bucketId);
}
}
}
}
}
}
else
{
Address owner = ((HashMapBucket)_parent.HashMap[(int)ide.Key]).PermanentAddress;
BucketsPack bPack = new BucketsPack(null, owner);
BucketStatistics bucketStats = GetBucketStats((int)ide.Key, owner);
if (bucketStats.Count > 0)
{
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info(Name + ".UpdateBuckets()", " Bucket : " + ide.Key + " has " + bucketStats.Count + " items");
}
if (bucketStats.DataSize < _threshold)
{
int index = _sparsedBuckets.IndexOf(bPack);
if (index != -1)
{
bPack = _sparsedBuckets[index] as BucketsPack;
}
bPack.BucketIds.Add(ide.Key);
if (!_sparsedBuckets.Contains(bPack))
{
_sparsedBuckets.Add(bPack);
}
}
else
{
int index = _filledBuckets.IndexOf(bPack);
if (index != -1)
{
bPack = _filledBuckets[index] as BucketsPack;
}
bPack.BucketIds.Add(ide.Key);
if (!_filledBuckets.Contains(owner))
{
_filledBuckets.Add(bPack);
}
}
}
}
}
}
}
#endregion
}
| |
using DeviceMotion.Plugin.Abstractions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Windows.Devices.Sensors;
namespace DeviceMotion.Plugin
{
/// <summary>
/// Implementation for DeviceMotion
/// </summary>
public class DeviceMotionImplementation : IDeviceMotion
{
private Accelerometer accelerometer;
private Gyrometer gyrometer;
private Compass compass;
#if WINDOWS_PHONE_APP
private Magnetometer magnetometer;
#endif
private double ms = 1000.0;
private Dictionary<MotionSensorType, bool> sensorStatus;
/// <summary>
/// Initializes a new instance of the DeviceMotionImplementation class.
/// </summary>
public DeviceMotionImplementation()
{
accelerometer = Accelerometer.GetDefault();
gyrometer = Gyrometer.GetDefault();
compass = Compass.GetDefault();
#if WINDOWS_PHONE_APP
magnetometer = Magnetometer.GetDefault();
#endif
sensorStatus = new Dictionary<MotionSensorType, bool>()
{
{ MotionSensorType.Accelerometer, false},
{ MotionSensorType.Gyroscope, false},
{ MotionSensorType.Magnetometer, false},
{ MotionSensorType.Compass, false}
};
}
/// <summary>
/// Occurs when sensor value changed.
/// </summary>
public event SensorValueChangedEventHandler SensorValueChanged;
/// <summary>
/// Start the specified sensorType and interval.
/// </summary>
/// <param name="sensorType">Sensor type.</param>
/// <param name="interval">Interval.</param>
public void Start(MotionSensorType sensorType, MotionSensorDelay interval = MotionSensorDelay.Default)
{
uint delay = (uint)((double)Convert.ToInt32(interval) / ms);
switch (sensorType)
{
case MotionSensorType.Accelerometer:
if (accelerometer != null)
{
accelerometer.ReportInterval = delay;
accelerometer.ReadingChanged += AccelerometerReadingChanged;
}
else
{
Debug.WriteLine("Accelerometer not available");
}
break;
case MotionSensorType.Gyroscope:
if (gyrometer != null)
{
gyrometer.ReportInterval = delay;
gyrometer.ReadingChanged += GyrometerReadingChanged;
}
else
{
Debug.WriteLine("Gyrometer not available");
}
break;
case MotionSensorType.Magnetometer:
#if WINDOWS_PHONE_APP
if(magnetometer != null)
{
magnetometer.ReportInterval = delay;
magnetometer.ReadingChanged += MagnetometerReadingChanged;
}
else
{
Debug.WriteLine("Magnetometer not available");
}
#else
Debug.WriteLine("Magnetometer not supported");
#endif
break;
case MotionSensorType.Compass:
if(compass != null)
{
compass.ReportInterval = delay;
compass.ReadingChanged += CompassReadingChanged;
}
else
{
Debug.WriteLine("Compass not available");
}
break;
}
sensorStatus[sensorType] = true;
}
#if WINDOWS_PHONE_APP
void MagnetometerReadingChanged(Magnetometer sender, MagnetometerReadingChangedEventArgs args)
{
if(SensorValueChanged != null)
SensorValueChanged(this, new SensorValueChangedEventArgs { ValueType = MotionSensorValueType.Vector, SensorType = MotionSensorType.Magnetometer, Value = new MotionVector() { X = args.Reading.MagneticFieldX, Y = args.Reading.MagneticFieldY, Z = args.Reading.MagneticFieldZ } });
}
#endif
void CompassReadingChanged(Compass sender, CompassReadingChangedEventArgs args)
{
if (args.Reading.HeadingTrueNorth!=null &&SensorValueChanged!=null)
SensorValueChanged(this, new SensorValueChangedEventArgs { ValueType = MotionSensorValueType.Single, SensorType = MotionSensorType.Compass, Value = new MotionValue() { Value = args.Reading.HeadingTrueNorth} });
}
void GyrometerReadingChanged(Gyrometer sender, GyrometerReadingChangedEventArgs args)
{
if (SensorValueChanged != null)
SensorValueChanged(this, new SensorValueChangedEventArgs { ValueType= MotionSensorValueType.Vector, SensorType = MotionSensorType.Gyroscope, Value = new MotionVector() { X = args.Reading.AngularVelocityX, Y = args.Reading.AngularVelocityY, Z = args.Reading.AngularVelocityZ } });
}
void AccelerometerReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
{
if (SensorValueChanged != null)
SensorValueChanged(this, new SensorValueChangedEventArgs { ValueType = MotionSensorValueType.Vector, SensorType = MotionSensorType.Accelerometer, Value = new MotionVector() { X = args.Reading.AccelerationX, Y = args.Reading.AccelerationY, Z = args.Reading.AccelerationZ } });
}
/// <summary>
/// Stop the specified sensorType.
/// </summary>
/// <param name="sensorType">Sensor type.</param>
public void Stop(MotionSensorType sensorType)
{
switch (sensorType)
{
case MotionSensorType.Accelerometer:
if(accelerometer!=null)
{
accelerometer.ReadingChanged -= AccelerometerReadingChanged;
}
else
{
Debug.WriteLine("Accelerometer not available");
}
break;
case MotionSensorType.Gyroscope:
if (gyrometer != null)
{
gyrometer.ReadingChanged -= GyrometerReadingChanged;
}
else
{
Debug.WriteLine("Gyrometer not available");
}
break;
case MotionSensorType.Magnetometer:
#if WINDOWS_PHONE_APP
if(magnetometer!=null)
{
magnetometer.ReadingChanged -= MagnetometerReadingChanged;
}
else
{
Debug.WriteLine("Magnetometer not available");
}
#else
Debug.WriteLine("Magnetometer not supported");
#endif
break;
case MotionSensorType.Compass:
if (compass != null)
{
compass.ReadingChanged -= CompassReadingChanged;
}
else
{
Debug.WriteLine("Compass not available");
}
break;
}
sensorStatus[sensorType] = false;
}
/// <summary>
/// Determines whether this instance is active the specified sensorType.
/// </summary>
/// <returns><c>true</c> if this instance is active the specified sensorType; otherwise, <c>false</c>.</returns>
/// <param name="sensorType">Sensor type.</param>
public bool IsActive(MotionSensorType sensorType)
{
return sensorStatus[sensorType];
}
#region IDisposable implementation
/// <summary>
/// Dispose of class and parent classes
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose up
/// </summary>
~DeviceMotionImplementation()
{
Dispose(false);
}
private bool disposed = false;
/// <summary>
/// Dispose method
/// </summary>
/// <param name="disposing"></param>
public virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
//dispose only
}
disposed = true;
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2010, www.wojilu.com. All rights reserved.
*/
using System;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Web.Context;
using wojilu.Apps.Forum.Domain;
using wojilu.Members.Users.Domain;
namespace wojilu.Web.Controller.Forum.Utils {
public class ForumValidator {
public static ForumBoard ValidateBoard( MvcContext ctx ) {
return ValidateBoard( null, ctx );
}
public static ForumBoard ValidateBoard( ForumBoard board, MvcContext ctx ) {
if (board == null) board = new ForumBoard();
String name = ctx.Post( "Name" );
if (strUtil.IsNullOrEmpty( name )) {
ctx.errors.Add( lang.get( "exName" ) );
}
String description = ctx.Post( "Description" );
int parentId = ctx.PostInt( "ParentId" );
String notice = ctx.PostHtml( "Notice" );
board.ParentId = parentId;
board.Name = name;
board.Description = description;
board.Notice = notice;
board.AppId = ctx.app.Id;
board.Creator = (User)ctx.viewer.obj;
board.CreatorUrl = ctx.viewer.obj.Url;
board.OwnerId = ctx.owner.Id;
board.OwnerUrl = ctx.owner.obj.Url;
board.OwnerType = ctx.owner.obj.GetType().FullName;
board.Ip = ctx.Ip;
board.IsCategory = ctx.PostInt( "IsCategory" );
board.ViewId = ctx.PostInt( "ViewId" );
return board;
}
public static ForumCategory ValidateCategory( MvcContext ctx ) {
return ValidateCategory( null, ctx );
}
public static ForumCategory ValidateCategory( ForumCategory category, MvcContext ctx ) {
if (category == null) category = new ForumCategory();
String name = ctx.Post( "Name" );
if (strUtil.IsNullOrEmpty( name ))
ctx.errors.Add( lang.get( "exName" ) );
String nameColor = ctx.Post( "NameColor" );
if (strUtil.HasText( nameColor )) {
String errorInfo = alang( ctx, "exColorFormat" );
if (nameColor.Length != 7) ctx.errors.Add( errorInfo );
if (nameColor.StartsWith( "#" ) == false) ctx.errors.Add( errorInfo );
}
int boardId = ctx.PostInt( "BoardId" );
category.Name = name;
category.NameColor = nameColor;
category.BoardId = boardId;
category.OwnerId = ctx.owner.Id;
category.OwnerType = ctx.owner.obj.GetType().FullName;
category.Creator = (User)ctx.viewer.obj;
return category;
}
public static ForumLink ValidateLink( MvcContext ctx ) {
return ValidateLink( null, ctx );
}
public static ForumLink ValidateLink( ForumLink link, MvcContext ctx ) {
if (link == null) link = new ForumLink();
String name = ctx.Post( "Name" );
String description = ctx.Post( "Description" );
String url = ctx.Post( "Url" );
String logo = ctx.Post( "Logo" );
if (strUtil.IsNullOrEmpty( name )) ctx.errors.Add( lang.get( "exName" ) );
if (strUtil.IsNullOrEmpty( url ))
ctx.errors.Add( lang.get( "exUrl" ) );
else if (!url.ToLower().StartsWith( "http://" ))
url = "http://" + url;
if (strUtil.IsNullOrEmpty( logo ))
ctx.errors.Add( alang( ctx, "exLogo" ) );
else if (!logo.ToLower().StartsWith( "http://" ))
logo = "http://" + logo;
link.Name = name;
link.Description = description;
link.Url = url;
link.Logo = logo;
link.AppId = ctx.app.Id;
link.OwnerId = ctx.owner.Id;
link.OwnerType = ctx.owner.obj.GetType().FullName;
return link;
}
public static ForumPost ValidatePost( MvcContext ctx ) {
ForumPost post = new ForumPost();
int boardId = ctx.PostInt( "forumId" );
int topicId = ctx.PostInt( "topicId" );
int parentId = ctx.PostInt( "parentId" );
String title = ctx.Post( "Title" );
String content = ctx.PostHtml( "Content" );
if (boardId <= 0) {
ctx.errors.Add( alang( ctx, "exBoardSet" ) );
}
else {
post.ForumBoardId = boardId;
}
if (topicId <= 0) {
ctx.errors.Add( ctx.controller.alang( "exTopicNotFound" ) );
}
else {
ForumTopic topic = ForumTopic.findById( topicId );
if (topic == null) {
ctx.errors.Add( ctx.controller.alang( "exTopicNotFound" ) );
}
else {
post.Topic = topic;
}
}
if (strUtil.IsNullOrEmpty( title )) ctx.errors.Add( lang.get( "exTitle" ) );
if (strUtil.IsNullOrEmpty( content )) ctx.errors.Add( lang.get( "exContent" ) );
post.ForumBoardId = boardId;
post.TopicId = topicId;
post.ParentId = parentId;
post.Title = title;
post.Content = content;
post.Ip = ctx.Ip;
return post;
}
public static ForumPost ValidatePostEdit( ForumPost post, MvcContext ctx ) {
String title = ctx.Post( "Title" );
String content = ctx.PostHtml( "Content" );
if (strUtil.IsNullOrEmpty( title )) ctx.errors.Add( lang.get( "exTitle" ) );
if (strUtil.IsNullOrEmpty( content )) ctx.errors.Add( lang.get( "exContent" ) );
post.Title = title;
post.Content = content;
return post;
}
public static ForumTopic ValidateTopic( MvcContext ctx ) {
return ValidateTopic( null, ctx );
}
public static ForumTopic ValidateTopic( ForumTopic topic, MvcContext ctx ) {
if (topic == null) topic = new ForumTopic();
String title = ctx.Post( "Title" );
String content = ctx.PostHtml( "Content" );
if (strUtil.IsNullOrEmpty( title )) ctx.errors.Add( lang.get( "exTitle" ) );
if (strUtil.IsNullOrEmpty( content )) ctx.errors.Add( lang.get( "exContent" ) );
topic.Title = title;
topic.Content = content;
topic.Category = new ForumCategory( ctx.PostInt( "CategoryId" ) );
topic.Reward = ctx.PostInt( "Reward" );
topic.RewardAvailable = topic.Reward;
topic.ReadPermission = ctx.PostInt( "ReadPermission" );
topic.Price = ctx.PostInt( "Price" );
topic.TagRawString = ctx.Post( "TagList" );
topic.IsAttachmentLogin = ctx.PostIsCheck( "IsAttachmentLogin" );
return topic;
}
public static ForumTopic ValidateTopicEdit( ForumTopic topic, MvcContext ctx ) {
if (topic == null) topic = new ForumTopic();
String title = ctx.Post( "Title" );
String content = ctx.PostHtml( "Content" );
if (strUtil.IsNullOrEmpty( title )) ctx.errors.Add( lang.get( "exTitle" ) );
if (strUtil.IsNullOrEmpty( content )) ctx.errors.Add( lang.get( "exContent" ) );
topic.Title = title;
topic.Content = content;
topic.Category = new ForumCategory( ctx.PostInt( "CategoryId" ) );
topic.TagRawString = ctx.Post( "TagList" );
return topic;
}
private static String alang( MvcContext ctx, String key ) {
return ctx.controller.alang( key );
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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 Multiverse.Tools.WorldEditor
{
partial class WorldEditor
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WorldEditor));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newWorldToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadWorldToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openWorldRootToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveWorldToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveWorldAsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.packageWorldAssetsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.recentFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.treeViewSearchMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.preferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.controlMappingEditorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.wireFrameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayOceanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayTerrainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayFogEffectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayLightEffectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showCollisionVolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayShadowsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayPathToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayParticleEffectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayBoundaryMarkersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayRoadMarkersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayMarkerPointsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayPointLightMarkersViewMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayPointLightAttenuationCirclesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.disableAllMarkersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayTerrainDecalsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lockCameraToSelectedObjectToolStipMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.renderLeavesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cameraFollowsTerrainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cameraAboveTerrainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setCameraNearDistanceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setMaximumFramesPerSecondToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.releaseNotesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutWorldEditorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutWorldEditorToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.loadWorldButton = new System.Windows.Forms.ToolStripButton();
this.saveWorldButton = new System.Windows.Forms.ToolStripButton();
this.newWorldButton = new System.Windows.Forms.ToolStripButton();
this.designateAssetRepositoryButton = new System.Windows.Forms.ToolStripButton();
this.undoButton = new System.Windows.Forms.ToolStripButton();
this.redoButton = new System.Windows.Forms.ToolStripButton();
this.cameraSpeedAccelDropDownButton = new System.Windows.Forms.ToolStripDropDownButton();
this.accelDropDownPreset1MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.accelDropDownPreset2MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.accelDropDownPreset3MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.accelDropDownPreset4MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cameraSpeedDropDownPreset1MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cameraSpeedDropDownPreset2MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cameraSpeedDropDownPreset3MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cameraSpeedDropDownPreset4MenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mouseWheelMultiplierDropDownButton = new System.Windows.Forms.ToolStripDropDownButton();
this.mWMMenuItemPreset1 = new System.Windows.Forms.ToolStripMenuItem();
this.mWMMenuItemPreset2 = new System.Windows.Forms.ToolStripMenuItem();
this.mWMMenuItemPreset3 = new System.Windows.Forms.ToolStripMenuItem();
this.mWMMenuItemPreset4 = new System.Windows.Forms.ToolStripMenuItem();
this.nodePropertyGrid = new System.Windows.Forms.PropertyGrid();
this.propertyTabControl = new System.Windows.Forms.TabControl();
this.propertiesTabPage = new System.Windows.Forms.TabPage();
this.positionTabPage = new System.Windows.Forms.TabPage();
this.positionPanel = new System.Windows.Forms.Panel();
this.movementScaleLabel = new System.Windows.Forms.Label();
this.oneMRadioButton = new System.Windows.Forms.RadioButton();
this.tenCMRadioButton = new System.Windows.Forms.RadioButton();
this.oneCMRadioButton = new System.Windows.Forms.RadioButton();
this.oneMMRadioButton = new System.Windows.Forms.RadioButton();
this.yLabel = new System.Windows.Forms.Label();
this.yDownButton = new System.Windows.Forms.Button();
this.yUpButton = new System.Windows.Forms.Button();
this.xzLabel = new System.Windows.Forms.Label();
this.zDownButton = new System.Windows.Forms.Button();
this.zUpButton = new System.Windows.Forms.Button();
this.xUpButton = new System.Windows.Forms.Button();
this.xDownButton = new System.Windows.Forms.Button();
this.positionXTextBox = new System.Windows.Forms.TextBox();
this.positionZTextBox = new System.Windows.Forms.TextBox();
this.PositionXLabel = new System.Windows.Forms.Label();
this.positionYTextBox = new System.Windows.Forms.TextBox();
this.positionYLabel = new System.Windows.Forms.Label();
this.positionZLabel = new System.Windows.Forms.Label();
this.scaleTabPage = new System.Windows.Forms.TabPage();
this.scalePanel = new System.Windows.Forms.Panel();
this.oneHundredPercentScaleRadioButton = new System.Windows.Forms.RadioButton();
this.tenPercentScaleRadioButton = new System.Windows.Forms.RadioButton();
this.onePercentScaleRadioButton = new System.Windows.Forms.RadioButton();
this.scalePercentageLabel = new System.Windows.Forms.Label();
this.scaleDownButton = new System.Windows.Forms.Button();
this.scaleUpButton = new System.Windows.Forms.Button();
this.scaleTextBox = new System.Windows.Forms.TextBox();
this.scaleLabel = new System.Windows.Forms.Label();
this.rotationTabPage = new System.Windows.Forms.TabPage();
this.rotationPanel = new System.Windows.Forms.Panel();
this.rotationTrackBar = new System.Windows.Forms.TrackBar();
this.rotationTextBox = new System.Windows.Forms.TextBox();
this.rotationLabel = new System.Windows.Forms.Label();
this.orientationPage = new System.Windows.Forms.TabPage();
this.orientationPanel = new System.Windows.Forms.Panel();
this.orientationRotationTrackBar = new System.Windows.Forms.TrackBar();
this.inclinationTextBox = new System.Windows.Forms.TextBox();
this.inclinationLabel = new System.Windows.Forms.Label();
this.inclinationTrackbar = new System.Windows.Forms.TrackBar();
this.orientationRotationLabel = new System.Windows.Forms.Label();
this.orientationRotationTextBox = new System.Windows.Forms.TextBox();
this.rightSplitContainer = new System.Windows.Forms.SplitContainer();
this.worldTreeView = new Multiverse.ToolBox.MultiSelectTreeView();
this.mainSplitContainer = new System.Windows.Forms.SplitContainer();
this.designateRepositoryDialog = new System.Windows.Forms.FolderBrowserDialog();
this.designateAssetRepository = new System.Windows.Forms.ToolStripButton();
this.btnDebugWorld = new System.Windows.Forms.ToolStripButton();
this.menuStrip1.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.propertyTabControl.SuspendLayout();
this.propertiesTabPage.SuspendLayout();
this.positionTabPage.SuspendLayout();
this.positionPanel.SuspendLayout();
this.scaleTabPage.SuspendLayout();
this.scalePanel.SuspendLayout();
this.rotationTabPage.SuspendLayout();
this.rotationPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rotationTrackBar)).BeginInit();
this.orientationPage.SuspendLayout();
this.orientationPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.orientationRotationTrackBar)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.inclinationTrackbar)).BeginInit();
this.rightSplitContainer.Panel1.SuspendLayout();
this.rightSplitContainer.Panel2.SuspendLayout();
this.rightSplitContainer.SuspendLayout();
this.mainSplitContainer.Panel2.SuspendLayout();
this.mainSplitContainer.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.viewToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1016, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newWorldToolStripMenuItem,
this.loadWorldToolStripMenuItem,
this.openWorldRootToolStripMenuItem,
this.saveWorldToolStripMenuItem,
this.saveWorldAsMenuItem,
this.packageWorldAssetsMenuItem,
this.recentFilesToolStripMenuItem,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
this.fileToolStripMenuItem.DropDownOpening += new System.EventHandler(this.fileToolStripMenuItem_DropDownOpening);
//
// newWorldToolStripMenuItem
//
this.newWorldToolStripMenuItem.Name = "newWorldToolStripMenuItem";
this.newWorldToolStripMenuItem.Size = new System.Drawing.Size(198, 22);
this.newWorldToolStripMenuItem.Text = "&New World";
this.newWorldToolStripMenuItem.ToolTipText = "Clear the current world and create a new world";
this.newWorldToolStripMenuItem.Click += new System.EventHandler(this.newWorldToolStripMenuItem_Click);
//
// loadWorldToolStripMenuItem
//
this.loadWorldToolStripMenuItem.Name = "loadWorldToolStripMenuItem";
this.loadWorldToolStripMenuItem.Size = new System.Drawing.Size(198, 22);
this.loadWorldToolStripMenuItem.Text = "&Open World";
this.loadWorldToolStripMenuItem.ToolTipText = "Select world file to open";
this.loadWorldToolStripMenuItem.Click += new System.EventHandler(this.loadWorldToolStripMenuItem_Click);
//
// openWorldRootToolStripMenuItem
//
this.openWorldRootToolStripMenuItem.Name = "openWorldRootToolStripMenuItem";
this.openWorldRootToolStripMenuItem.Size = new System.Drawing.Size(198, 22);
this.openWorldRootToolStripMenuItem.Text = "Open World Root";
this.openWorldRootToolStripMenuItem.Click += new System.EventHandler(this.loadWorldRootToolStripMenuItem_Click);
//
// saveWorldToolStripMenuItem
//
this.saveWorldToolStripMenuItem.Enabled = false;
this.saveWorldToolStripMenuItem.Name = "saveWorldToolStripMenuItem";
this.saveWorldToolStripMenuItem.Size = new System.Drawing.Size(198, 22);
this.saveWorldToolStripMenuItem.Text = "&Save World";
this.saveWorldToolStripMenuItem.ToolTipText = "Save the world with the current filename";
this.saveWorldToolStripMenuItem.Click += new System.EventHandler(this.saveWorldToolStripMenuItem_Click);
//
// saveWorldAsMenuItem
//
this.saveWorldAsMenuItem.Enabled = false;
this.saveWorldAsMenuItem.Name = "saveWorldAsMenuItem";
this.saveWorldAsMenuItem.Size = new System.Drawing.Size(198, 22);
this.saveWorldAsMenuItem.Text = "Save World As";
this.saveWorldAsMenuItem.ToolTipText = "Save the World with a new filename";
this.saveWorldAsMenuItem.Click += new System.EventHandler(this.saveAsWorldToolStripMenuItem_Click);
//
// packageWorldAssetsMenuItem
//
this.packageWorldAssetsMenuItem.Name = "packageWorldAssetsMenuItem";
this.packageWorldAssetsMenuItem.Size = new System.Drawing.Size(198, 22);
this.packageWorldAssetsMenuItem.Text = "Package World Assets...";
this.packageWorldAssetsMenuItem.Click += new System.EventHandler(this.packageWorldAssetsMenuItem_Click);
//
// recentFilesToolStripMenuItem
//
this.recentFilesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aToolStripMenuItem});
this.recentFilesToolStripMenuItem.Name = "recentFilesToolStripMenuItem";
this.recentFilesToolStripMenuItem.Size = new System.Drawing.Size(198, 22);
this.recentFilesToolStripMenuItem.Text = "Recent Files";
this.recentFilesToolStripMenuItem.MouseEnter += new System.EventHandler(this.recentFilesToolStripMenuItem_MouseEnter);
//
// aToolStripMenuItem
//
this.aToolStripMenuItem.Name = "aToolStripMenuItem";
this.aToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.aToolStripMenuItem.Text = "a";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(198, 22);
this.exitToolStripMenuItem.Text = "&Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.deleteToolStripMenuItem,
this.treeViewSearchMenuItem,
this.preferencesToolStripMenuItem,
this.controlMappingEditorToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
this.editToolStripMenuItem.DropDownOpening += new System.EventHandler(this.editToolStripMenuItem_DropDownOpening);
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.undoToolStripMenuItem.Text = "&Undo";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.redoToolStripMenuItem.Text = "&Redo";
this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItemClicked_Clicked);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.copyToolStripMenuItem.Text = "&Copy";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Clicked);
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Clicked);
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
this.deleteToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.deleteToolStripMenuItem.Text = "&Delete";
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Clicked);
//
// treeViewSearchMenuItem
//
this.treeViewSearchMenuItem.Name = "treeViewSearchMenuItem";
this.treeViewSearchMenuItem.Size = new System.Drawing.Size(199, 22);
this.treeViewSearchMenuItem.Text = "&Find in Tree View";
this.treeViewSearchMenuItem.Click += new System.EventHandler(this.editMenuTreeViewSearchItem_clicked);
//
// preferencesToolStripMenuItem
//
this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem";
this.preferencesToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.preferencesToolStripMenuItem.Text = "P&references";
this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.editMenuPreferencesItem_clicked);
//
// controlMappingEditorToolStripMenuItem
//
this.controlMappingEditorToolStripMenuItem.Name = "controlMappingEditorToolStripMenuItem";
this.controlMappingEditorToolStripMenuItem.Size = new System.Drawing.Size(199, 22);
this.controlMappingEditorToolStripMenuItem.Text = "C&ontrol Mapping Editor";
this.controlMappingEditorToolStripMenuItem.Click += new System.EventHandler(this.editMenuControlMappingEditorItem_clicked);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.wireFrameToolStripMenuItem,
this.displayOceanToolStripMenuItem,
this.displayTerrainToolStripMenuItem,
this.displayFogEffectsToolStripMenuItem,
this.displayLightEffectsToolStripMenuItem,
this.showCollisionVolToolStripMenuItem,
this.displayShadowsMenuItem,
this.displayPathToolStripMenuItem,
this.displayParticleEffectsToolStripMenuItem,
this.displayBoundaryMarkersToolStripMenuItem,
this.displayRoadMarkersToolStripMenuItem,
this.displayMarkerPointsToolStripMenuItem,
this.displayPointLightMarkersViewMenuItem,
this.displayPointLightAttenuationCirclesMenuItem,
this.disableAllMarkersToolStripMenuItem,
this.displayTerrainDecalsToolStripMenuItem,
this.lockCameraToSelectedObjectToolStipMenuItem,
this.renderLeavesToolStripMenuItem,
this.cameraFollowsTerrainToolStripMenuItem,
this.cameraAboveTerrainToolStripMenuItem,
this.setCameraNearDistanceToolStripMenuItem,
this.setMaximumFramesPerSecondToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.viewToolStripMenuItem.Text = "&View";
this.viewToolStripMenuItem.DropDownOpening += new System.EventHandler(this.viewToolStripMenu_DropDownOpening);
//
// wireFrameToolStripMenuItem
//
this.wireFrameToolStripMenuItem.Name = "wireFrameToolStripMenuItem";
this.wireFrameToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.wireFrameToolStripMenuItem.Text = "&Wire Frame";
this.wireFrameToolStripMenuItem.Click += new System.EventHandler(this.wireFrameToolStripMenuItem_Click);
//
// displayOceanToolStripMenuItem
//
this.displayOceanToolStripMenuItem.Name = "displayOceanToolStripMenuItem";
this.displayOceanToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayOceanToolStripMenuItem.Text = "Display &Ocean";
this.displayOceanToolStripMenuItem.Click += new System.EventHandler(this.displayOceanToolStripMenuItem_Click);
//
// displayTerrainToolStripMenuItem
//
this.displayTerrainToolStripMenuItem.Name = "displayTerrainToolStripMenuItem";
this.displayTerrainToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayTerrainToolStripMenuItem.Text = "Display &Terrain";
this.displayTerrainToolStripMenuItem.Click += new System.EventHandler(this.displayTerrainToolStripMenuItem_Click);
//
// displayFogEffectsToolStripMenuItem
//
this.displayFogEffectsToolStripMenuItem.Name = "displayFogEffectsToolStripMenuItem";
this.displayFogEffectsToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayFogEffectsToolStripMenuItem.Text = "Display &Fog Effects";
this.displayFogEffectsToolStripMenuItem.Click += new System.EventHandler(this.displayFogEffectsToolStripMenuItem_Click);
//
// displayLightEffectsToolStripMenuItem
//
this.displayLightEffectsToolStripMenuItem.Name = "displayLightEffectsToolStripMenuItem";
this.displayLightEffectsToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayLightEffectsToolStripMenuItem.Text = "Display &Light Effects";
this.displayLightEffectsToolStripMenuItem.Click += new System.EventHandler(this.displayLightEffectsToolStripMenuItem_Click);
//
// showCollisionVolToolStripMenuItem
//
this.showCollisionVolToolStripMenuItem.CheckOnClick = true;
this.showCollisionVolToolStripMenuItem.Name = "showCollisionVolToolStripMenuItem";
this.showCollisionVolToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.showCollisionVolToolStripMenuItem.Text = "Display &Collision Volumes";
this.showCollisionVolToolStripMenuItem.Click += new System.EventHandler(this.showCollisionVolToolStripMenuItem_Click);
//
// displayShadowsMenuItem
//
this.displayShadowsMenuItem.CheckOnClick = true;
this.displayShadowsMenuItem.Name = "displayShadowsMenuItem";
this.displayShadowsMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayShadowsMenuItem.Text = "Display S&hadows";
this.displayShadowsMenuItem.Click += new System.EventHandler(this.displayShadowsMenuItem_Clicked);
//
// displayPathToolStripMenuItem
//
this.displayPathToolStripMenuItem.Name = "displayPathToolStripMenuItem";
this.displayPathToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayPathToolStripMenuItem.Text = "Display P&ath";
this.displayPathToolStripMenuItem.Visible = false;
this.displayPathToolStripMenuItem.Click += new System.EventHandler(this.displayPathToolStripMenuItem_Click);
//
// displayParticleEffectsToolStripMenuItem
//
this.displayParticleEffectsToolStripMenuItem.Name = "displayParticleEffectsToolStripMenuItem";
this.displayParticleEffectsToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayParticleEffectsToolStripMenuItem.Text = "Display &Particle Effects";
this.displayParticleEffectsToolStripMenuItem.Click += new System.EventHandler(this.displayParticleEffectsToolStripMenuItem_Click);
//
// displayBoundaryMarkersToolStripMenuItem
//
this.displayBoundaryMarkersToolStripMenuItem.Name = "displayBoundaryMarkersToolStripMenuItem";
this.displayBoundaryMarkersToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayBoundaryMarkersToolStripMenuItem.Text = "Display &Region Markers";
this.displayBoundaryMarkersToolStripMenuItem.Click += new System.EventHandler(this.displayBoundaryMarkersToolStripMenuItem_Click);
//
// displayRoadMarkersToolStripMenuItem
//
this.displayRoadMarkersToolStripMenuItem.Name = "displayRoadMarkersToolStripMenuItem";
this.displayRoadMarkersToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayRoadMarkersToolStripMenuItem.Text = "Display Roa&d Markers";
this.displayRoadMarkersToolStripMenuItem.Click += new System.EventHandler(this.displayRoadMarkersToolStripMenuItem_Click);
//
// displayMarkerPointsToolStripMenuItem
//
this.displayMarkerPointsToolStripMenuItem.Name = "displayMarkerPointsToolStripMenuItem";
this.displayMarkerPointsToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayMarkerPointsToolStripMenuItem.Text = "Display &Marker Points";
this.displayMarkerPointsToolStripMenuItem.Click += new System.EventHandler(this.displayMarkerPointsToolStripMenuItem_Click);
//
// displayPointLightMarkersViewMenuItem
//
this.displayPointLightMarkersViewMenuItem.Name = "displayPointLightMarkersViewMenuItem";
this.displayPointLightMarkersViewMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayPointLightMarkersViewMenuItem.Text = "Display Point Light Markers";
this.displayPointLightMarkersViewMenuItem.Click += new System.EventHandler(this.displayPointLightMarkerMenuItem_Click);
//
// displayPointLightAttenuationCirclesMenuItem
//
this.displayPointLightAttenuationCirclesMenuItem.Name = "displayPointLightAttenuationCirclesMenuItem";
this.displayPointLightAttenuationCirclesMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayPointLightAttenuationCirclesMenuItem.Text = "Display Point Light Attenuation Circles";
this.displayPointLightAttenuationCirclesMenuItem.Click += new System.EventHandler(this.displayPointLightAttenuationCirclesMenuItem_Click);
//
// disableAllMarkersToolStripMenuItem
//
this.disableAllMarkersToolStripMenuItem.Name = "disableAllMarkersToolStripMenuItem";
this.disableAllMarkersToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.disableAllMarkersToolStripMenuItem.Text = "&Disable All Markers";
this.disableAllMarkersToolStripMenuItem.Click += new System.EventHandler(this.disableAllMarkersToolStripMenuItem_Click);
//
// displayTerrainDecalsToolStripMenuItem
//
this.displayTerrainDecalsToolStripMenuItem.CheckOnClick = true;
this.displayTerrainDecalsToolStripMenuItem.Name = "displayTerrainDecalsToolStripMenuItem";
this.displayTerrainDecalsToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.displayTerrainDecalsToolStripMenuItem.Text = "Display T&errain Decals";
this.displayTerrainDecalsToolStripMenuItem.Click += new System.EventHandler(this.displayDisplayTerrainDecalToolStripMenuItem_Click);
//
// lockCameraToSelectedObjectToolStipMenuItem
//
this.lockCameraToSelectedObjectToolStipMenuItem.Name = "lockCameraToSelectedObjectToolStipMenuItem";
this.lockCameraToSelectedObjectToolStipMenuItem.Size = new System.Drawing.Size(277, 22);
this.lockCameraToSelectedObjectToolStipMenuItem.Text = "Lock Camera to Selected Object";
this.lockCameraToSelectedObjectToolStipMenuItem.Click += new System.EventHandler(this.lockCameraToSelectedObjectToolStipMenuItem_Click);
//
// renderLeavesToolStripMenuItem
//
this.renderLeavesToolStripMenuItem.Name = "renderLeavesToolStripMenuItem";
this.renderLeavesToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.renderLeavesToolStripMenuItem.Text = "Render &Leaves";
this.renderLeavesToolStripMenuItem.Click += new System.EventHandler(this.renderLeavesToolStripMenuItem_Click);
//
// cameraFollowsTerrainToolStripMenuItem
//
this.cameraFollowsTerrainToolStripMenuItem.CheckOnClick = true;
this.cameraFollowsTerrainToolStripMenuItem.Name = "cameraFollowsTerrainToolStripMenuItem";
this.cameraFollowsTerrainToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.cameraFollowsTerrainToolStripMenuItem.Text = "Camera Follo&ws Terrain";
this.cameraFollowsTerrainToolStripMenuItem.Click += new System.EventHandler(this.cameraFollowsTerrainToolStripMenuItem_clicked);
//
// cameraAboveTerrainToolStripMenuItem
//
this.cameraAboveTerrainToolStripMenuItem.Name = "cameraAboveTerrainToolStripMenuItem";
this.cameraAboveTerrainToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.cameraAboveTerrainToolStripMenuItem.Text = "Camera Stays A&bove Terrain";
this.cameraAboveTerrainToolStripMenuItem.Click += new System.EventHandler(this.cameraAboveTerrainToolStripMenuItem_Click);
//
// setCameraNearDistanceToolStripMenuItem
//
this.setCameraNearDistanceToolStripMenuItem.Name = "setCameraNearDistanceToolStripMenuItem";
this.setCameraNearDistanceToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.setCameraNearDistanceToolStripMenuItem.Text = "Set Camera &Near Distance";
this.setCameraNearDistanceToolStripMenuItem.Click += new System.EventHandler(this.setCameraNearDistanceToolStripMenuItem_Click);
//
// setMaximumFramesPerSecondToolStripMenuItem
//
this.setMaximumFramesPerSecondToolStripMenuItem.Name = "setMaximumFramesPerSecondToolStripMenuItem";
this.setMaximumFramesPerSecondToolStripMenuItem.Size = new System.Drawing.Size(277, 22);
this.setMaximumFramesPerSecondToolStripMenuItem.Text = "Set Ma&ximum Frames Per Second";
this.setMaximumFramesPerSecondToolStripMenuItem.Click += new System.EventHandler(this.setMaximumFramesPerSecondToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.helpToolStripMenuItem1,
this.releaseNotesToolStripMenuItem,
this.aboutWorldEditorToolStripMenuItem,
this.aboutWorldEditorToolStripMenuItem1});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// helpToolStripMenuItem1
//
this.helpToolStripMenuItem1.Name = "helpToolStripMenuItem1";
this.helpToolStripMenuItem1.Size = new System.Drawing.Size(212, 22);
this.helpToolStripMenuItem1.Text = "&Launch Online Help";
this.helpToolStripMenuItem1.Click += new System.EventHandler(this.helpToolStripMenuItem_clicked);
//
// releaseNotesToolStripMenuItem
//
this.releaseNotesToolStripMenuItem.Name = "releaseNotesToolStripMenuItem";
this.releaseNotesToolStripMenuItem.Size = new System.Drawing.Size(212, 22);
this.releaseNotesToolStripMenuItem.Text = "&Release Notes";
this.releaseNotesToolStripMenuItem.Click += new System.EventHandler(this.releaseNotesToolStripMenuItem_click);
//
// aboutWorldEditorToolStripMenuItem
//
this.aboutWorldEditorToolStripMenuItem.Name = "aboutWorldEditorToolStripMenuItem";
this.aboutWorldEditorToolStripMenuItem.Size = new System.Drawing.Size(212, 22);
this.aboutWorldEditorToolStripMenuItem.Text = "&Submit Feedback or a Bug";
this.aboutWorldEditorToolStripMenuItem.Click += new System.EventHandler(this.feedbackMenuItem_clicked);
//
// aboutWorldEditorToolStripMenuItem1
//
this.aboutWorldEditorToolStripMenuItem1.Name = "aboutWorldEditorToolStripMenuItem1";
this.aboutWorldEditorToolStripMenuItem1.Size = new System.Drawing.Size(212, 22);
this.aboutWorldEditorToolStripMenuItem1.Text = "&About World Editor";
this.aboutWorldEditorToolStripMenuItem1.Click += new System.EventHandler(this.AboutMenuItem_clicked);
//
// statusStrip1
//
this.statusStrip1.Location = new System.Drawing.Point(0, 719);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(1016, 22);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// toolStrip1
//
this.toolStrip1.ImageScalingSize = new System.Drawing.Size(32, 32);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadWorldButton,
this.saveWorldButton,
this.newWorldButton,
this.designateAssetRepositoryButton,
this.undoButton,
this.redoButton,
this.cameraSpeedAccelDropDownButton,
this.mouseWheelMultiplierDropDownButton,
this.btnDebugWorld});
this.toolStrip1.Location = new System.Drawing.Point(0, 24);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(1016, 39);
this.toolStrip1.TabIndex = 3;
this.toolStrip1.Text = "toolStrip1";
//
// loadWorldButton
//
this.loadWorldButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.loadWorldButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.load_world;
this.loadWorldButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.loadWorldButton.Name = "loadWorldButton";
this.loadWorldButton.Size = new System.Drawing.Size(36, 36);
this.loadWorldButton.ToolTipText = "Open World";
this.loadWorldButton.Click += new System.EventHandler(this.loadWorldToolStripMenuItem_Click);
//
// saveWorldButton
//
this.saveWorldButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveWorldButton.Enabled = false;
this.saveWorldButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.save_world;
this.saveWorldButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveWorldButton.Name = "saveWorldButton";
this.saveWorldButton.Size = new System.Drawing.Size(36, 36);
this.saveWorldButton.ToolTipText = "Save World";
this.saveWorldButton.Click += new System.EventHandler(this.saveWorldToolStripMenuItem_Click);
//
// newWorldButton
//
this.newWorldButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.newWorldButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.new_world;
this.newWorldButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newWorldButton.Name = "newWorldButton";
this.newWorldButton.Size = new System.Drawing.Size(36, 36);
this.newWorldButton.ToolTipText = "New World";
this.newWorldButton.Click += new System.EventHandler(this.newWorldToolStripMenuItem_Click);
//
// designateAssetRepositoryButton
//
this.designateAssetRepositoryButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.designateAssetRepositoryButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.designate_asset_repository;
this.designateAssetRepositoryButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.designateAssetRepositoryButton.Name = "designateAssetRepositoryButton";
this.designateAssetRepositoryButton.Size = new System.Drawing.Size(36, 36);
this.designateAssetRepositoryButton.ToolTipText = "Designate Asset Repository";
this.designateAssetRepositoryButton.Click += new System.EventHandler(this.designateAssetRepositoryMenuItem_Click);
//
// undoButton
//
this.undoButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.undoButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.undo;
this.undoButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.undoButton.Name = "undoButton";
this.undoButton.Size = new System.Drawing.Size(36, 36);
this.undoButton.ToolTipText = "Undo";
this.undoButton.Click += new System.EventHandler(this.undoButton_Clicked);
//
// redoButton
//
this.redoButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.redoButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.redo;
this.redoButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.redoButton.Name = "redoButton";
this.redoButton.Size = new System.Drawing.Size(36, 36);
this.redoButton.ToolTipText = "Redo";
this.redoButton.Click += new System.EventHandler(this.redoButton_Clicked);
//
// cameraSpeedAccelDropDownButton
//
this.cameraSpeedAccelDropDownButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cameraSpeedAccelDropDownButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.accelDropDownPreset1MenuItem,
this.accelDropDownPreset2MenuItem,
this.accelDropDownPreset3MenuItem,
this.accelDropDownPreset4MenuItem,
this.cameraSpeedDropDownPreset1MenuItem,
this.cameraSpeedDropDownPreset2MenuItem,
this.cameraSpeedDropDownPreset3MenuItem,
this.cameraSpeedDropDownPreset4MenuItem});
this.cameraSpeedAccelDropDownButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.help;
this.cameraSpeedAccelDropDownButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cameraSpeedAccelDropDownButton.Name = "cameraSpeedAccelDropDownButton";
this.cameraSpeedAccelDropDownButton.Size = new System.Drawing.Size(45, 36);
this.cameraSpeedAccelDropDownButton.MouseEnter += new System.EventHandler(this.cameraSpeedAccelDropDownButtonEnter);
//
// accelDropDownPreset1MenuItem
//
this.accelDropDownPreset1MenuItem.AutoSize = false;
this.accelDropDownPreset1MenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.accelDropDownPreset1MenuItem.Name = "accelDropDownPreset1MenuItem";
this.accelDropDownPreset1MenuItem.Size = new System.Drawing.Size(152, 25);
this.accelDropDownPreset1MenuItem.Visible = false;
this.accelDropDownPreset1MenuItem.Click += new System.EventHandler(this.axiomSetAccelPreset1);
//
// accelDropDownPreset2MenuItem
//
this.accelDropDownPreset2MenuItem.AutoSize = false;
this.accelDropDownPreset2MenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.accelDropDownPreset2MenuItem.Name = "accelDropDownPreset2MenuItem";
this.accelDropDownPreset2MenuItem.Size = new System.Drawing.Size(152, 25);
this.accelDropDownPreset2MenuItem.Visible = false;
this.accelDropDownPreset2MenuItem.Click += new System.EventHandler(this.axiomSetAccelPreset2);
//
// accelDropDownPreset3MenuItem
//
this.accelDropDownPreset3MenuItem.AutoSize = false;
this.accelDropDownPreset3MenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.accelDropDownPreset3MenuItem.Name = "accelDropDownPreset3MenuItem";
this.accelDropDownPreset3MenuItem.Size = new System.Drawing.Size(152, 25);
this.accelDropDownPreset3MenuItem.Visible = false;
this.accelDropDownPreset3MenuItem.Click += new System.EventHandler(this.axiomSetAccelPreset3);
//
// accelDropDownPreset4MenuItem
//
this.accelDropDownPreset4MenuItem.AutoSize = false;
this.accelDropDownPreset4MenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.accelDropDownPreset4MenuItem.Name = "accelDropDownPreset4MenuItem";
this.accelDropDownPreset4MenuItem.Size = new System.Drawing.Size(152, 25);
this.accelDropDownPreset4MenuItem.Visible = false;
this.accelDropDownPreset4MenuItem.Click += new System.EventHandler(this.axiomSetAccelPreset4);
//
// cameraSpeedDropDownPreset1MenuItem
//
this.cameraSpeedDropDownPreset1MenuItem.AutoSize = false;
this.cameraSpeedDropDownPreset1MenuItem.Name = "cameraSpeedDropDownPreset1MenuItem";
this.cameraSpeedDropDownPreset1MenuItem.Size = new System.Drawing.Size(152, 22);
this.cameraSpeedDropDownPreset1MenuItem.Visible = false;
this.cameraSpeedDropDownPreset1MenuItem.Click += new System.EventHandler(this.axiomSetSpeedPreset1);
//
// cameraSpeedDropDownPreset2MenuItem
//
this.cameraSpeedDropDownPreset2MenuItem.AutoSize = false;
this.cameraSpeedDropDownPreset2MenuItem.Name = "cameraSpeedDropDownPreset2MenuItem";
this.cameraSpeedDropDownPreset2MenuItem.Size = new System.Drawing.Size(152, 22);
this.cameraSpeedDropDownPreset2MenuItem.Visible = false;
this.cameraSpeedDropDownPreset2MenuItem.Click += new System.EventHandler(this.axiomSetSpeedPreset2);
//
// cameraSpeedDropDownPreset3MenuItem
//
this.cameraSpeedDropDownPreset3MenuItem.AutoSize = false;
this.cameraSpeedDropDownPreset3MenuItem.Name = "cameraSpeedDropDownPreset3MenuItem";
this.cameraSpeedDropDownPreset3MenuItem.Size = new System.Drawing.Size(152, 22);
this.cameraSpeedDropDownPreset3MenuItem.Visible = false;
this.cameraSpeedDropDownPreset3MenuItem.Click += new System.EventHandler(this.axiomSetSpeedPreset3);
//
// cameraSpeedDropDownPreset4MenuItem
//
this.cameraSpeedDropDownPreset4MenuItem.AutoSize = false;
this.cameraSpeedDropDownPreset4MenuItem.Name = "cameraSpeedDropDownPreset4MenuItem";
this.cameraSpeedDropDownPreset4MenuItem.Size = new System.Drawing.Size(152, 22);
this.cameraSpeedDropDownPreset4MenuItem.Visible = false;
this.cameraSpeedDropDownPreset4MenuItem.Click += new System.EventHandler(this.axiomSetSpeedPreset4);
//
// mouseWheelMultiplierDropDownButton
//
this.mouseWheelMultiplierDropDownButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.mouseWheelMultiplierDropDownButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mWMMenuItemPreset1,
this.mWMMenuItemPreset2,
this.mWMMenuItemPreset3,
this.mWMMenuItemPreset4});
this.mouseWheelMultiplierDropDownButton.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.mouseSensitivity_icon;
this.mouseWheelMultiplierDropDownButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mouseWheelMultiplierDropDownButton.Name = "mouseWheelMultiplierDropDownButton";
this.mouseWheelMultiplierDropDownButton.Size = new System.Drawing.Size(45, 36);
this.mouseWheelMultiplierDropDownButton.Text = "Mouse Wheel Multiplier";
this.mouseWheelMultiplierDropDownButton.ToolTipText = "Preset Mouse Wheel Multiplier Drop Down";
this.mouseWheelMultiplierDropDownButton.MouseEnter += new System.EventHandler(this.mouseWheelMultiplierMouseEnter);
//
// mWMMenuItemPreset1
//
this.mWMMenuItemPreset1.AutoSize = false;
this.mWMMenuItemPreset1.Name = "mWMMenuItemPreset1";
this.mWMMenuItemPreset1.Size = new System.Drawing.Size(152, 22);
this.mWMMenuItemPreset1.Click += new System.EventHandler(this.axiomSetPresetMWM1);
//
// mWMMenuItemPreset2
//
this.mWMMenuItemPreset2.AutoSize = false;
this.mWMMenuItemPreset2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.mWMMenuItemPreset2.Name = "mWMMenuItemPreset2";
this.mWMMenuItemPreset2.Size = new System.Drawing.Size(152, 22);
this.mWMMenuItemPreset2.Click += new System.EventHandler(this.axiomSetPresetMWM2);
//
// mWMMenuItemPreset3
//
this.mWMMenuItemPreset3.AutoSize = false;
this.mWMMenuItemPreset3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.mWMMenuItemPreset3.Name = "mWMMenuItemPreset3";
this.mWMMenuItemPreset3.Size = new System.Drawing.Size(152, 22);
this.mWMMenuItemPreset3.Click += new System.EventHandler(this.axiomSetPresetMWM3);
//
// mWMMenuItemPreset4
//
this.mWMMenuItemPreset4.AutoSize = false;
this.mWMMenuItemPreset4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.mWMMenuItemPreset4.Name = "mWMMenuItemPreset4";
this.mWMMenuItemPreset4.Size = new System.Drawing.Size(152, 22);
this.mWMMenuItemPreset4.Click += new System.EventHandler(this.axiomSetPresetMWM4);
//
// nodePropertyGrid
//
this.nodePropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.nodePropertyGrid.Location = new System.Drawing.Point(3, 3);
this.nodePropertyGrid.Name = "nodePropertyGrid";
this.nodePropertyGrid.Size = new System.Drawing.Size(264, 270);
this.nodePropertyGrid.TabIndex = 5;
this.nodePropertyGrid.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.nodePropertyGrid_PropertyValueChanged);
//
// propertyTabControl
//
this.propertyTabControl.Controls.Add(this.propertiesTabPage);
this.propertyTabControl.Controls.Add(this.positionTabPage);
this.propertyTabControl.Controls.Add(this.scaleTabPage);
this.propertyTabControl.Controls.Add(this.rotationTabPage);
this.propertyTabControl.Controls.Add(this.orientationPage);
this.propertyTabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.propertyTabControl.Location = new System.Drawing.Point(0, 0);
this.propertyTabControl.Name = "propertyTabControl";
this.propertyTabControl.SelectedIndex = 0;
this.propertyTabControl.Size = new System.Drawing.Size(278, 302);
this.propertyTabControl.TabIndex = 6;
//
// propertiesTabPage
//
this.propertiesTabPage.Controls.Add(this.nodePropertyGrid);
this.propertiesTabPage.Location = new System.Drawing.Point(4, 22);
this.propertiesTabPage.Name = "propertiesTabPage";
this.propertiesTabPage.Padding = new System.Windows.Forms.Padding(3);
this.propertiesTabPage.Size = new System.Drawing.Size(270, 276);
this.propertiesTabPage.TabIndex = 0;
this.propertiesTabPage.Text = "Properties";
this.propertiesTabPage.UseVisualStyleBackColor = true;
//
// positionTabPage
//
this.positionTabPage.Controls.Add(this.positionPanel);
this.positionTabPage.Location = new System.Drawing.Point(4, 22);
this.positionTabPage.Name = "positionTabPage";
this.positionTabPage.Padding = new System.Windows.Forms.Padding(3);
this.positionTabPage.Size = new System.Drawing.Size(270, 276);
this.positionTabPage.TabIndex = 1;
this.positionTabPage.Text = "Position";
this.positionTabPage.UseVisualStyleBackColor = true;
//
// positionPanel
//
this.positionPanel.Controls.Add(this.movementScaleLabel);
this.positionPanel.Controls.Add(this.oneMRadioButton);
this.positionPanel.Controls.Add(this.tenCMRadioButton);
this.positionPanel.Controls.Add(this.oneCMRadioButton);
this.positionPanel.Controls.Add(this.oneMMRadioButton);
this.positionPanel.Controls.Add(this.yLabel);
this.positionPanel.Controls.Add(this.yDownButton);
this.positionPanel.Controls.Add(this.yUpButton);
this.positionPanel.Controls.Add(this.xzLabel);
this.positionPanel.Controls.Add(this.zDownButton);
this.positionPanel.Controls.Add(this.zUpButton);
this.positionPanel.Controls.Add(this.xUpButton);
this.positionPanel.Controls.Add(this.xDownButton);
this.positionPanel.Controls.Add(this.positionXTextBox);
this.positionPanel.Controls.Add(this.positionZTextBox);
this.positionPanel.Controls.Add(this.PositionXLabel);
this.positionPanel.Controls.Add(this.positionYTextBox);
this.positionPanel.Controls.Add(this.positionYLabel);
this.positionPanel.Controls.Add(this.positionZLabel);
this.positionPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.positionPanel.Enabled = false;
this.positionPanel.Location = new System.Drawing.Point(3, 3);
this.positionPanel.Name = "positionPanel";
this.positionPanel.Size = new System.Drawing.Size(264, 270);
this.positionPanel.TabIndex = 6;
//
// movementScaleLabel
//
this.movementScaleLabel.AutoSize = true;
this.movementScaleLabel.Location = new System.Drawing.Point(24, 158);
this.movementScaleLabel.Name = "movementScaleLabel";
this.movementScaleLabel.Size = new System.Drawing.Size(90, 13);
this.movementScaleLabel.TabIndex = 18;
this.movementScaleLabel.Text = "Movement Scale:";
//
// oneMRadioButton
//
this.oneMRadioButton.AutoSize = true;
this.oneMRadioButton.Location = new System.Drawing.Point(197, 192);
this.oneMRadioButton.Name = "oneMRadioButton";
this.oneMRadioButton.Size = new System.Drawing.Size(42, 17);
this.oneMRadioButton.TabIndex = 17;
this.oneMRadioButton.Text = "1 m";
this.oneMRadioButton.UseVisualStyleBackColor = true;
this.oneMRadioButton.CheckedChanged += new System.EventHandler(this.oneMRadioButton_CheckedChanged);
//
// tenCMRadioButton
//
this.tenCMRadioButton.AutoSize = true;
this.tenCMRadioButton.Checked = true;
this.tenCMRadioButton.Location = new System.Drawing.Point(137, 192);
this.tenCMRadioButton.Name = "tenCMRadioButton";
this.tenCMRadioButton.Size = new System.Drawing.Size(54, 17);
this.tenCMRadioButton.TabIndex = 16;
this.tenCMRadioButton.TabStop = true;
this.tenCMRadioButton.Text = "10 cm";
this.tenCMRadioButton.UseVisualStyleBackColor = true;
this.tenCMRadioButton.CheckedChanged += new System.EventHandler(this.tenCMRadioButton_CheckedChanged);
//
// oneCMRadioButton
//
this.oneCMRadioButton.AutoSize = true;
this.oneCMRadioButton.Location = new System.Drawing.Point(86, 192);
this.oneCMRadioButton.Name = "oneCMRadioButton";
this.oneCMRadioButton.Size = new System.Drawing.Size(48, 17);
this.oneCMRadioButton.TabIndex = 15;
this.oneCMRadioButton.Text = "1 cm";
this.oneCMRadioButton.UseVisualStyleBackColor = true;
this.oneCMRadioButton.CheckedChanged += new System.EventHandler(this.oneCMRadioButton_CheckedChanged);
//
// oneMMRadioButton
//
this.oneMMRadioButton.AutoSize = true;
this.oneMMRadioButton.Location = new System.Drawing.Point(30, 192);
this.oneMMRadioButton.Name = "oneMMRadioButton";
this.oneMMRadioButton.Size = new System.Drawing.Size(50, 17);
this.oneMMRadioButton.TabIndex = 14;
this.oneMMRadioButton.Text = "1 mm";
this.oneMMRadioButton.UseVisualStyleBackColor = true;
this.oneMMRadioButton.CheckedChanged += new System.EventHandler(this.oneMMRadioButton_CheckedChanged);
//
// yLabel
//
this.yLabel.AutoSize = true;
this.yLabel.Location = new System.Drawing.Point(178, 92);
this.yLabel.Name = "yLabel";
this.yLabel.Size = new System.Drawing.Size(17, 13);
this.yLabel.TabIndex = 13;
this.yLabel.Text = "Y:";
//
// yDownButton
//
this.yDownButton.Image = ((System.Drawing.Image)(resources.GetObject("yDownButton.Image")));
this.yDownButton.Location = new System.Drawing.Point(201, 100);
this.yDownButton.Name = "yDownButton";
this.yDownButton.Size = new System.Drawing.Size(30, 30);
this.yDownButton.TabIndex = 12;
this.yDownButton.UseVisualStyleBackColor = true;
this.yDownButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.yDownButton_mouseDown);
this.yDownButton.MouseUp += new System.Windows.Forms.MouseEventHandler(this.positionPanelButton_mouseUp);
//
// yUpButton
//
this.yUpButton.Image = ((System.Drawing.Image)(resources.GetObject("yUpButton.Image")));
this.yUpButton.Location = new System.Drawing.Point(201, 64);
this.yUpButton.Name = "yUpButton";
this.yUpButton.Size = new System.Drawing.Size(30, 30);
this.yUpButton.TabIndex = 11;
this.yUpButton.UseVisualStyleBackColor = true;
this.yUpButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.yUpButton_mouseDown);
this.yUpButton.MouseUp += new System.Windows.Forms.MouseEventHandler(this.positionPanelButton_mouseUp);
//
// xzLabel
//
this.xzLabel.AutoSize = true;
this.xzLabel.Location = new System.Drawing.Point(24, 92);
this.xzLabel.Name = "xzLabel";
this.xzLabel.Size = new System.Drawing.Size(29, 13);
this.xzLabel.TabIndex = 10;
this.xzLabel.Text = "X/Z:";
//
// zDownButton
//
this.zDownButton.Image = ((System.Drawing.Image)(resources.GetObject("zDownButton.Image")));
this.zDownButton.Location = new System.Drawing.Point(95, 100);
this.zDownButton.Name = "zDownButton";
this.zDownButton.Size = new System.Drawing.Size(30, 30);
this.zDownButton.TabIndex = 9;
this.zDownButton.UseVisualStyleBackColor = true;
this.zDownButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.zDownButton_mouseDown);
this.zDownButton.MouseUp += new System.Windows.Forms.MouseEventHandler(this.positionPanelButton_mouseUp);
//
// zUpButton
//
this.zUpButton.Image = ((System.Drawing.Image)(resources.GetObject("zUpButton.Image")));
this.zUpButton.Location = new System.Drawing.Point(95, 64);
this.zUpButton.Name = "zUpButton";
this.zUpButton.Size = new System.Drawing.Size(30, 30);
this.zUpButton.TabIndex = 8;
this.zUpButton.UseVisualStyleBackColor = true;
this.zUpButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.zUpButton_mouseDown);
this.zUpButton.MouseUp += new System.Windows.Forms.MouseEventHandler(this.positionPanelButton_mouseUp);
//
// xUpButton
//
this.xUpButton.Image = ((System.Drawing.Image)(resources.GetObject("xUpButton.Image")));
this.xUpButton.Location = new System.Drawing.Point(131, 83);
this.xUpButton.Name = "xUpButton";
this.xUpButton.Size = new System.Drawing.Size(30, 30);
this.xUpButton.TabIndex = 7;
this.xUpButton.UseVisualStyleBackColor = true;
this.xUpButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.xUpButton_mouseDown);
this.xUpButton.MouseUp += new System.Windows.Forms.MouseEventHandler(this.positionPanelButton_mouseUp);
//
// xDownButton
//
this.xDownButton.Image = ((System.Drawing.Image)(resources.GetObject("xDownButton.Image")));
this.xDownButton.Location = new System.Drawing.Point(59, 83);
this.xDownButton.Name = "xDownButton";
this.xDownButton.Size = new System.Drawing.Size(30, 30);
this.xDownButton.TabIndex = 6;
this.xDownButton.UseVisualStyleBackColor = true;
this.xDownButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.xDownButton_mouseDown);
this.xDownButton.MouseUp += new System.Windows.Forms.MouseEventHandler(this.positionPanelButton_mouseUp);
//
// positionXTextBox
//
this.positionXTextBox.Location = new System.Drawing.Point(27, 14);
this.positionXTextBox.Name = "positionXTextBox";
this.positionXTextBox.Size = new System.Drawing.Size(58, 20);
this.positionXTextBox.TabIndex = 3;
this.positionXTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.positionXTextBox_KeyPress);
this.positionXTextBox.Leave += new System.EventHandler(this.positionXTextBox_Leave);
//
// positionZTextBox
//
this.positionZTextBox.Location = new System.Drawing.Point(201, 14);
this.positionZTextBox.Name = "positionZTextBox";
this.positionZTextBox.Size = new System.Drawing.Size(58, 20);
this.positionZTextBox.TabIndex = 5;
this.positionZTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.positionZTextBox_KeyPress);
this.positionZTextBox.Leave += new System.EventHandler(this.positionZTextBox_Leave);
//
// PositionXLabel
//
this.PositionXLabel.AutoSize = true;
this.PositionXLabel.Location = new System.Drawing.Point(4, 17);
this.PositionXLabel.Name = "PositionXLabel";
this.PositionXLabel.Size = new System.Drawing.Size(17, 13);
this.PositionXLabel.TabIndex = 0;
this.PositionXLabel.Text = "X:";
//
// positionYTextBox
//
this.positionYTextBox.Location = new System.Drawing.Point(114, 14);
this.positionYTextBox.Name = "positionYTextBox";
this.positionYTextBox.Size = new System.Drawing.Size(58, 20);
this.positionYTextBox.TabIndex = 4;
this.positionYTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.positionYTextBox_KeyPress);
this.positionYTextBox.Leave += new System.EventHandler(this.positionYTextBox_Leave);
//
// positionYLabel
//
this.positionYLabel.AutoSize = true;
this.positionYLabel.Location = new System.Drawing.Point(92, 17);
this.positionYLabel.Name = "positionYLabel";
this.positionYLabel.Size = new System.Drawing.Size(17, 13);
this.positionYLabel.TabIndex = 1;
this.positionYLabel.Text = "Y:";
//
// positionZLabel
//
this.positionZLabel.AutoSize = true;
this.positionZLabel.Location = new System.Drawing.Point(178, 17);
this.positionZLabel.Name = "positionZLabel";
this.positionZLabel.Size = new System.Drawing.Size(17, 13);
this.positionZLabel.TabIndex = 2;
this.positionZLabel.Text = "Z:";
//
// scaleTabPage
//
this.scaleTabPage.Controls.Add(this.scalePanel);
this.scaleTabPage.Location = new System.Drawing.Point(4, 22);
this.scaleTabPage.Name = "scaleTabPage";
this.scaleTabPage.Size = new System.Drawing.Size(270, 276);
this.scaleTabPage.TabIndex = 2;
this.scaleTabPage.Text = "Scale";
this.scaleTabPage.UseVisualStyleBackColor = true;
//
// scalePanel
//
this.scalePanel.Controls.Add(this.oneHundredPercentScaleRadioButton);
this.scalePanel.Controls.Add(this.tenPercentScaleRadioButton);
this.scalePanel.Controls.Add(this.onePercentScaleRadioButton);
this.scalePanel.Controls.Add(this.scalePercentageLabel);
this.scalePanel.Controls.Add(this.scaleDownButton);
this.scalePanel.Controls.Add(this.scaleUpButton);
this.scalePanel.Controls.Add(this.scaleTextBox);
this.scalePanel.Controls.Add(this.scaleLabel);
this.scalePanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.scalePanel.Enabled = false;
this.scalePanel.Location = new System.Drawing.Point(0, 0);
this.scalePanel.Name = "scalePanel";
this.scalePanel.Size = new System.Drawing.Size(270, 276);
this.scalePanel.TabIndex = 0;
//
// oneHundredPercentScaleRadioButton
//
this.oneHundredPercentScaleRadioButton.AutoSize = true;
this.oneHundredPercentScaleRadioButton.Location = new System.Drawing.Point(179, 155);
this.oneHundredPercentScaleRadioButton.Name = "oneHundredPercentScaleRadioButton";
this.oneHundredPercentScaleRadioButton.Size = new System.Drawing.Size(51, 17);
this.oneHundredPercentScaleRadioButton.TabIndex = 7;
this.oneHundredPercentScaleRadioButton.TabStop = true;
this.oneHundredPercentScaleRadioButton.Text = "100%";
this.oneHundredPercentScaleRadioButton.UseVisualStyleBackColor = true;
this.oneHundredPercentScaleRadioButton.CheckedChanged += new System.EventHandler(this.oneHundredPercentScaleRadioButton_CheckedChanged);
//
// tenPercentScaleRadioButton
//
this.tenPercentScaleRadioButton.AutoSize = true;
this.tenPercentScaleRadioButton.Checked = true;
this.tenPercentScaleRadioButton.Location = new System.Drawing.Point(108, 155);
this.tenPercentScaleRadioButton.Name = "tenPercentScaleRadioButton";
this.tenPercentScaleRadioButton.Size = new System.Drawing.Size(48, 17);
this.tenPercentScaleRadioButton.TabIndex = 6;
this.tenPercentScaleRadioButton.TabStop = true;
this.tenPercentScaleRadioButton.Text = "10 %";
this.tenPercentScaleRadioButton.UseVisualStyleBackColor = true;
this.tenPercentScaleRadioButton.CheckedChanged += new System.EventHandler(this.tenPercentScaleRadioButton_CheckedChanged);
//
// onePercentScaleRadioButton
//
this.onePercentScaleRadioButton.AutoSize = true;
this.onePercentScaleRadioButton.Location = new System.Drawing.Point(42, 155);
this.onePercentScaleRadioButton.Name = "onePercentScaleRadioButton";
this.onePercentScaleRadioButton.Size = new System.Drawing.Size(42, 17);
this.onePercentScaleRadioButton.TabIndex = 5;
this.onePercentScaleRadioButton.TabStop = true;
this.onePercentScaleRadioButton.Text = "1 %";
this.onePercentScaleRadioButton.UseVisualStyleBackColor = true;
this.onePercentScaleRadioButton.CheckedChanged += new System.EventHandler(this.onePercentScaleRadioButton_CheckedChanged);
//
// scalePercentageLabel
//
this.scalePercentageLabel.AutoSize = true;
this.scalePercentageLabel.Location = new System.Drawing.Point(20, 123);
this.scalePercentageLabel.Name = "scalePercentageLabel";
this.scalePercentageLabel.Size = new System.Drawing.Size(95, 13);
this.scalePercentageLabel.TabIndex = 4;
this.scalePercentageLabel.Text = "Scale Percentage:";
//
// scaleDownButton
//
this.scaleDownButton.Image = ((System.Drawing.Image)(resources.GetObject("scaleDownButton.Image")));
this.scaleDownButton.Location = new System.Drawing.Point(179, 58);
this.scaleDownButton.Name = "scaleDownButton";
this.scaleDownButton.Size = new System.Drawing.Size(30, 30);
this.scaleDownButton.TabIndex = 3;
this.scaleDownButton.UseVisualStyleBackColor = true;
this.scaleDownButton.Click += new System.EventHandler(this.scaleDownButton_Click);
//
// scaleUpButton
//
this.scaleUpButton.Image = ((System.Drawing.Image)(resources.GetObject("scaleUpButton.Image")));
this.scaleUpButton.Location = new System.Drawing.Point(179, 22);
this.scaleUpButton.Name = "scaleUpButton";
this.scaleUpButton.Size = new System.Drawing.Size(30, 30);
this.scaleUpButton.TabIndex = 2;
this.scaleUpButton.UseVisualStyleBackColor = true;
this.scaleUpButton.Click += new System.EventHandler(this.scaleUpButton_Click);
//
// scaleTextBox
//
this.scaleTextBox.Location = new System.Drawing.Point(63, 46);
this.scaleTextBox.Name = "scaleTextBox";
this.scaleTextBox.Size = new System.Drawing.Size(84, 20);
this.scaleTextBox.TabIndex = 1;
this.scaleTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.scaleTextBox_KeyPress);
this.scaleTextBox.Leave += new System.EventHandler(this.scaleTextBox_Leave);
//
// scaleLabel
//
this.scaleLabel.AutoSize = true;
this.scaleLabel.Location = new System.Drawing.Point(20, 49);
this.scaleLabel.Name = "scaleLabel";
this.scaleLabel.Size = new System.Drawing.Size(37, 13);
this.scaleLabel.TabIndex = 0;
this.scaleLabel.Text = "Scale:";
//
// rotationTabPage
//
this.rotationTabPage.Controls.Add(this.rotationPanel);
this.rotationTabPage.Location = new System.Drawing.Point(4, 22);
this.rotationTabPage.Name = "rotationTabPage";
this.rotationTabPage.Size = new System.Drawing.Size(270, 276);
this.rotationTabPage.TabIndex = 3;
this.rotationTabPage.Text = "Rotation";
this.rotationTabPage.UseVisualStyleBackColor = true;
//
// rotationPanel
//
this.rotationPanel.Controls.Add(this.rotationTrackBar);
this.rotationPanel.Controls.Add(this.rotationTextBox);
this.rotationPanel.Controls.Add(this.rotationLabel);
this.rotationPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.rotationPanel.Enabled = false;
this.rotationPanel.Location = new System.Drawing.Point(0, 0);
this.rotationPanel.Name = "rotationPanel";
this.rotationPanel.Size = new System.Drawing.Size(270, 276);
this.rotationPanel.TabIndex = 0;
//
// rotationTrackBar
//
this.rotationTrackBar.Location = new System.Drawing.Point(20, 85);
this.rotationTrackBar.Maximum = 180;
this.rotationTrackBar.Minimum = -180;
this.rotationTrackBar.Name = "rotationTrackBar";
this.rotationTrackBar.Size = new System.Drawing.Size(197, 45);
this.rotationTrackBar.TabIndex = 2;
this.rotationTrackBar.TickStyle = System.Windows.Forms.TickStyle.None;
this.rotationTrackBar.Scroll += new System.EventHandler(this.rotationTrackBar_Scroll);
this.rotationTrackBar.MouseUp += new System.Windows.Forms.MouseEventHandler(this.rotationTrackBar_MouseUp);
//
// rotationTextBox
//
this.rotationTextBox.Location = new System.Drawing.Point(81, 35);
this.rotationTextBox.Name = "rotationTextBox";
this.rotationTextBox.Size = new System.Drawing.Size(83, 20);
this.rotationTextBox.TabIndex = 1;
this.rotationTextBox.Text = "0";
this.rotationTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.rotationTextBox_KeyPress);
this.rotationTextBox.Leave += new System.EventHandler(this.rotationTextBox_Leave);
//
// rotationLabel
//
this.rotationLabel.AutoSize = true;
this.rotationLabel.Location = new System.Drawing.Point(17, 38);
this.rotationLabel.Name = "rotationLabel";
this.rotationLabel.Size = new System.Drawing.Size(50, 13);
this.rotationLabel.TabIndex = 0;
this.rotationLabel.Text = "Rotation:";
//
// orientationPage
//
this.orientationPage.Controls.Add(this.orientationPanel);
this.orientationPage.Location = new System.Drawing.Point(4, 22);
this.orientationPage.Name = "orientationPage";
this.orientationPage.Padding = new System.Windows.Forms.Padding(3);
this.orientationPage.Size = new System.Drawing.Size(270, 276);
this.orientationPage.TabIndex = 4;
this.orientationPage.Text = "Orientation";
this.orientationPage.UseVisualStyleBackColor = true;
//
// orientationPanel
//
this.orientationPanel.Controls.Add(this.orientationRotationTrackBar);
this.orientationPanel.Controls.Add(this.inclinationTextBox);
this.orientationPanel.Controls.Add(this.inclinationLabel);
this.orientationPanel.Controls.Add(this.inclinationTrackbar);
this.orientationPanel.Controls.Add(this.orientationRotationLabel);
this.orientationPanel.Controls.Add(this.orientationRotationTextBox);
this.orientationPanel.Enabled = false;
this.orientationPanel.Location = new System.Drawing.Point(0, 0);
this.orientationPanel.Name = "orientationPanel";
this.orientationPanel.Size = new System.Drawing.Size(274, 279);
this.orientationPanel.TabIndex = 0;
//
// orientationRotationTrackBar
//
this.orientationRotationTrackBar.Location = new System.Drawing.Point(27, 55);
this.orientationRotationTrackBar.Maximum = 180;
this.orientationRotationTrackBar.Minimum = -180;
this.orientationRotationTrackBar.Name = "orientationRotationTrackBar";
this.orientationRotationTrackBar.Size = new System.Drawing.Size(197, 45);
this.orientationRotationTrackBar.TabIndex = 14;
this.orientationRotationTrackBar.TickStyle = System.Windows.Forms.TickStyle.None;
this.orientationRotationTrackBar.Scroll += new System.EventHandler(this.orientationRotationTrackBar_Scroll);
this.orientationRotationTrackBar.MouseUp += new System.Windows.Forms.MouseEventHandler(this.orientationRotationTrackBar_MouseUp);
//
// inclinationTextBox
//
this.inclinationTextBox.Location = new System.Drawing.Point(88, 125);
this.inclinationTextBox.Name = "inclinationTextBox";
this.inclinationTextBox.Size = new System.Drawing.Size(83, 20);
this.inclinationTextBox.TabIndex = 17;
this.inclinationTextBox.Text = "0";
this.inclinationTextBox.TextChanged += new System.EventHandler(this.UpdateOrientationFromTextboxes);
//
// inclinationLabel
//
this.inclinationLabel.AutoSize = true;
this.inclinationLabel.Location = new System.Drawing.Point(24, 128);
this.inclinationLabel.Name = "inclinationLabel";
this.inclinationLabel.Size = new System.Drawing.Size(58, 13);
this.inclinationLabel.TabIndex = 16;
this.inclinationLabel.Text = "Inclination:";
//
// inclinationTrackbar
//
this.inclinationTrackbar.Location = new System.Drawing.Point(27, 160);
this.inclinationTrackbar.Maximum = 90;
this.inclinationTrackbar.Minimum = -90;
this.inclinationTrackbar.Name = "inclinationTrackbar";
this.inclinationTrackbar.Size = new System.Drawing.Size(197, 45);
this.inclinationTrackbar.TabIndex = 15;
this.inclinationTrackbar.TickStyle = System.Windows.Forms.TickStyle.None;
this.inclinationTrackbar.Scroll += new System.EventHandler(this.inclincationTrackbar_Scroll);
this.inclinationTrackbar.MouseUp += new System.Windows.Forms.MouseEventHandler(this.inclinationTrackbar_MouseUp);
//
// orientationRotationLabel
//
this.orientationRotationLabel.AutoSize = true;
this.orientationRotationLabel.Location = new System.Drawing.Point(24, 22);
this.orientationRotationLabel.Name = "orientationRotationLabel";
this.orientationRotationLabel.Size = new System.Drawing.Size(50, 13);
this.orientationRotationLabel.TabIndex = 12;
this.orientationRotationLabel.Text = "Rotation:";
//
// orientationRotationTextBox
//
this.orientationRotationTextBox.Location = new System.Drawing.Point(88, 19);
this.orientationRotationTextBox.Name = "orientationRotationTextBox";
this.orientationRotationTextBox.Size = new System.Drawing.Size(83, 20);
this.orientationRotationTextBox.TabIndex = 13;
this.orientationRotationTextBox.Text = "0";
this.orientationRotationTextBox.TextChanged += new System.EventHandler(this.UpdateOrientationFromTextboxes);
//
// rightSplitContainer
//
this.rightSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.rightSplitContainer.Location = new System.Drawing.Point(0, 0);
this.rightSplitContainer.Name = "rightSplitContainer";
this.rightSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// rightSplitContainer.Panel1
//
this.rightSplitContainer.Panel1.Controls.Add(this.worldTreeView);
//
// rightSplitContainer.Panel2
//
this.rightSplitContainer.Panel2.Controls.Add(this.propertyTabControl);
this.rightSplitContainer.Size = new System.Drawing.Size(278, 656);
this.rightSplitContainer.SplitterDistance = 350;
this.rightSplitContainer.TabIndex = 7;
//
// worldTreeView
//
this.worldTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.worldTreeView.DrawMode = System.Windows.Forms.TreeViewDrawMode.OwnerDrawText;
this.worldTreeView.HideSelection = false;
this.worldTreeView.Location = new System.Drawing.Point(0, 0);
this.worldTreeView.Name = "worldTreeView";
this.worldTreeView.SelectedNodes = ((System.Collections.Generic.List<Multiverse.ToolBox.MultiSelectTreeNode>)(resources.GetObject("worldTreeView.SelectedNodes")));
this.worldTreeView.Size = new System.Drawing.Size(278, 350);
this.worldTreeView.TabIndex = 4;
this.worldTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.worldTreeView_AfterSelect);
this.worldTreeView.DoubleClick += new System.EventHandler(this.worldTreeView_DoubleClick);
this.worldTreeView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeView_KeyDown);
//
// mainSplitContainer
//
this.mainSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.mainSplitContainer.Location = new System.Drawing.Point(0, 63);
this.mainSplitContainer.Name = "mainSplitContainer";
//
// mainSplitContainer.Panel1
//
this.mainSplitContainer.Panel1.BackColor = System.Drawing.SystemColors.Control;
this.mainSplitContainer.Panel1.Padding = new System.Windows.Forms.Padding(2);
//
// mainSplitContainer.Panel2
//
this.mainSplitContainer.Panel2.Controls.Add(this.rightSplitContainer);
this.mainSplitContainer.Size = new System.Drawing.Size(1016, 656);
this.mainSplitContainer.SplitterDistance = 734;
this.mainSplitContainer.TabIndex = 8;
//
// designateRepositoryDialog
//
this.designateRepositoryDialog.Description = "Designate Asset Repository Directory";
//
// designateAssetRepository
//
this.designateAssetRepository.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.designateAssetRepository.Image = global::Multiverse.Tools.WorldEditor.Properties.Resources.designate_asset_repository;
this.designateAssetRepository.ImageTransparentColor = System.Drawing.Color.Magenta;
this.designateAssetRepository.Name = "designateAssetRepository";
this.designateAssetRepository.Size = new System.Drawing.Size(36, 36);
this.designateAssetRepository.Text = "Designate Asset Repository";
//
// btnDebugWorld
//
this.btnDebugWorld.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnDebugWorld.Image = ((System.Drawing.Image)(resources.GetObject("btnDebugWorld.Image")));
this.btnDebugWorld.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnDebugWorld.Name = "btnDebugWorld";
this.btnDebugWorld.Size = new System.Drawing.Size(36, 36);
this.btnDebugWorld.Text = "Debug World";
this.btnDebugWorld.Click += new System.EventHandler(this.btnDebugWorld_Click);
//
// WorldEditor
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1016, 741);
this.Controls.Add(this.mainSplitContainer);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MainMenuStrip = this.menuStrip1;
this.Name = "WorldEditor";
this.Activated += new System.EventHandler(this.worldEditor_activated);
this.Deactivate += new System.EventHandler(this.worldEditor_deactivated);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.WorldEditor_FormClosing);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.worldEditor_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.worldEditor_DragEnter);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.WorldEditor_KeyDown);
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.WorldEditor_KeyUp);
this.Resize += new System.EventHandler(this.WorldEditor_Resize);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.propertyTabControl.ResumeLayout(false);
this.propertiesTabPage.ResumeLayout(false);
this.positionTabPage.ResumeLayout(false);
this.positionPanel.ResumeLayout(false);
this.positionPanel.PerformLayout();
this.scaleTabPage.ResumeLayout(false);
this.scalePanel.ResumeLayout(false);
this.scalePanel.PerformLayout();
this.rotationTabPage.ResumeLayout(false);
this.rotationPanel.ResumeLayout(false);
this.rotationPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.rotationTrackBar)).EndInit();
this.orientationPage.ResumeLayout(false);
this.orientationPanel.ResumeLayout(false);
this.orientationPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.orientationRotationTrackBar)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.inclinationTrackbar)).EndInit();
this.rightSplitContainer.Panel1.ResumeLayout(false);
this.rightSplitContainer.Panel2.ResumeLayout(false);
this.rightSplitContainer.ResumeLayout(false);
this.mainSplitContainer.Panel2.ResumeLayout(false);
this.mainSplitContainer.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem wireFrameToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayOceanToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripMenuItem displayTerrainToolStripMenuItem;
private Multiverse.ToolBox.MultiSelectTreeView worldTreeView;
private System.Windows.Forms.PropertyGrid nodePropertyGrid;
private System.Windows.Forms.ToolStripMenuItem newWorldToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveWorldToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadWorldToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.TabControl propertyTabControl;
private System.Windows.Forms.TabPage propertiesTabPage;
private System.Windows.Forms.TabPage positionTabPage;
private System.Windows.Forms.SplitContainer rightSplitContainer;
private System.Windows.Forms.SplitContainer mainSplitContainer;
private System.Windows.Forms.Label PositionXLabel;
private System.Windows.Forms.Label positionZLabel;
private System.Windows.Forms.Label positionYLabel;
private System.Windows.Forms.TextBox positionZTextBox;
private System.Windows.Forms.TextBox positionYTextBox;
private System.Windows.Forms.TextBox positionXTextBox;
private System.Windows.Forms.Panel positionPanel;
private System.Windows.Forms.Button zUpButton;
private System.Windows.Forms.Button xUpButton;
private System.Windows.Forms.Button xDownButton;
private System.Windows.Forms.Label yLabel;
private System.Windows.Forms.Button yDownButton;
private System.Windows.Forms.Button yUpButton;
private System.Windows.Forms.Label xzLabel;
private System.Windows.Forms.Button zDownButton;
private System.Windows.Forms.Label movementScaleLabel;
private System.Windows.Forms.RadioButton oneMRadioButton;
private System.Windows.Forms.RadioButton tenCMRadioButton;
private System.Windows.Forms.RadioButton oneCMRadioButton;
private System.Windows.Forms.RadioButton oneMMRadioButton;
private System.Windows.Forms.TabPage scaleTabPage;
private System.Windows.Forms.TabPage rotationTabPage;
private System.Windows.Forms.Panel scalePanel;
private System.Windows.Forms.Button scaleUpButton;
private System.Windows.Forms.TextBox scaleTextBox;
private System.Windows.Forms.Label scaleLabel;
private System.Windows.Forms.RadioButton oneHundredPercentScaleRadioButton;
private System.Windows.Forms.RadioButton tenPercentScaleRadioButton;
private System.Windows.Forms.RadioButton onePercentScaleRadioButton;
private System.Windows.Forms.Label scalePercentageLabel;
private System.Windows.Forms.Button scaleDownButton;
private System.Windows.Forms.Panel rotationPanel;
private System.Windows.Forms.TextBox rotationTextBox;
private System.Windows.Forms.Label rotationLabel;
private System.Windows.Forms.TrackBar rotationTrackBar;
private System.Windows.Forms.ToolStripMenuItem renderLeavesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem aboutWorldEditorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutWorldEditorToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem releaseNotesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cameraFollowsTerrainToolStripMenuItem;
private System.Windows.Forms.TabPage orientationPage;
private System.Windows.Forms.Panel orientationPanel;
private System.Windows.Forms.TrackBar orientationRotationTrackBar;
private System.Windows.Forms.TextBox inclinationTextBox;
private System.Windows.Forms.Label inclinationLabel;
private System.Windows.Forms.TrackBar inclinationTrackbar;
private System.Windows.Forms.Label orientationRotationLabel;
private System.Windows.Forms.TextBox orientationRotationTextBox;
private System.Windows.Forms.FolderBrowserDialog designateRepositoryDialog;
private System.Windows.Forms.ToolStripMenuItem displayFogEffectsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayLightEffectsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showCollisionVolToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem setCameraNearDistanceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveWorldAsMenuItem;
private System.Windows.Forms.ToolStripMenuItem packageWorldAssetsMenuItem;
private System.Windows.Forms.ToolStripMenuItem setMaximumFramesPerSecondToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayPathToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayShadowsMenuItem;
private System.Windows.Forms.ToolStripButton loadWorldButton;
private System.Windows.Forms.ToolStripButton saveWorldButton;
private System.Windows.Forms.ToolStripButton newWorldButton;
private System.Windows.Forms.ToolStripButton designateAssetRepositoryButton;
private System.Windows.Forms.ToolStripButton designateAssetRepository;
private System.Windows.Forms.ToolStripButton undoButton;
private System.Windows.Forms.ToolStripButton redoButton;
private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem controlMappingEditorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem treeViewSearchMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayBoundaryMarkersToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayRoadMarkersToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayMarkerPointsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem disableAllMarkersToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayParticleEffectsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cameraAboveTerrainToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayTerrainDecalsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayPointLightMarkersViewMenuItem;
private System.Windows.Forms.ToolStripMenuItem lockCameraToSelectedObjectToolStipMenuItem;
private System.Windows.Forms.ToolStripMenuItem openWorldRootToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem recentFilesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aToolStripMenuItem;
private System.Windows.Forms.ToolStripDropDownButton cameraSpeedAccelDropDownButton;
private System.Windows.Forms.ToolStripDropDownButton mouseWheelMultiplierDropDownButton;
private System.Windows.Forms.ToolStripMenuItem accelDropDownPreset1MenuItem;
private System.Windows.Forms.ToolStripMenuItem accelDropDownPreset2MenuItem;
private System.Windows.Forms.ToolStripMenuItem accelDropDownPreset3MenuItem;
private System.Windows.Forms.ToolStripMenuItem accelDropDownPreset4MenuItem;
private System.Windows.Forms.ToolStripMenuItem cameraSpeedDropDownPreset1MenuItem;
private System.Windows.Forms.ToolStripMenuItem cameraSpeedDropDownPreset2MenuItem;
private System.Windows.Forms.ToolStripMenuItem cameraSpeedDropDownPreset3MenuItem;
private System.Windows.Forms.ToolStripMenuItem cameraSpeedDropDownPreset4MenuItem;
private System.Windows.Forms.ToolStripMenuItem mWMMenuItemPreset1;
private System.Windows.Forms.ToolStripMenuItem mWMMenuItemPreset2;
private System.Windows.Forms.ToolStripMenuItem mWMMenuItemPreset3;
private System.Windows.Forms.ToolStripMenuItem mWMMenuItemPreset4;
private System.Windows.Forms.ToolStripMenuItem displayPointLightAttenuationCirclesMenuItem;
private System.Windows.Forms.ToolStripButton btnDebugWorld;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ErrorLogger;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes
{
public class CodeFixServiceTests
{
[Fact]
public void TestGetFirstDiagnosticWithFixAsync()
{
var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());
var fixers = CreateFixers();
var code = @"
a
";
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code))
{
var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetService<IErrorLoggerService>()));
var fixService = new CodeFixService(
diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>());
var incrementalAnalzyer = (IIncrementalAnalyzerProvider)diagnosticService;
// register diagnostic engine to solution crawler
var analyzer = incrementalAnalzyer.CreateIncrementalAnalyzer(workspace);
var reference = new MockAnalyzerReference();
var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
var document = project.Documents.Single();
var unused = fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None).Result;
var fixer1 = fixers.Single().Value as MockFixer;
var fixer2 = reference.Fixer as MockFixer;
// check to make sure both of them are called.
Assert.True(fixer1.Called);
Assert.True(fixer2.Called);
}
}
[Fact]
public void TestGetCodeFixWithExceptionInRegisterMethod()
{
GetFirstDiagnosticWithFix(new ErrorCases.ExceptionInRegisterMethod());
GetAddedFixes(new ErrorCases.ExceptionInRegisterMethod());
}
[Fact]
public void TestGetCodeFixWithExceptionInRegisterMethodAsync()
{
GetFirstDiagnosticWithFix(new ErrorCases.ExceptionInRegisterMethodAsync());
GetAddedFixes(new ErrorCases.ExceptionInRegisterMethodAsync());
}
[Fact]
public void TestGetCodeFixWithExceptionInFixableDiagnosticIds()
{
GetDefaultFixes(new ErrorCases.ExceptionInFixableDiagnosticIds());
GetAddedFixes(new ErrorCases.ExceptionInFixableDiagnosticIds());
}
[Fact]
public void TestGetCodeFixWithExceptionInGetFixAllProvider()
{
GetAddedFixes(new ErrorCases.ExceptionInGetFixAllProvider());
}
public void GetDefaultFixes(CodeFixProvider codefix)
{
TestDiagnosticAnalyzerService diagnosticService;
CodeFixService fixService;
IErrorLoggerService errorLogger;
using (var workspace = ServiceSetup(codefix, out diagnosticService, out fixService, out errorLogger))
{
Document document;
EditorLayerExtensionManager.ExtensionManager extensionManager;
GetDocumentAndExtensionManager(diagnosticService, workspace, out document, out extensionManager);
var fixes = fixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None).Result;
Assert.True(((TestErrorLogger)errorLogger).Messages.Count == 1);
string message;
Assert.True(((TestErrorLogger)errorLogger).Messages.TryGetValue(codefix.GetType().Name, out message));
}
}
public void GetAddedFixes(CodeFixProvider codefix)
{
TestDiagnosticAnalyzerService diagnosticService;
CodeFixService fixService;
IErrorLoggerService errorLogger;
using (var workspace = ServiceSetup(codefix, out diagnosticService, out fixService, out errorLogger))
{
Document document;
EditorLayerExtensionManager.ExtensionManager extensionManager;
GetDocumentAndExtensionManager(diagnosticService, workspace, out document, out extensionManager);
var incrementalAnalzyer = (IIncrementalAnalyzerProvider)diagnosticService;
var analyzer = incrementalAnalzyer.CreateIncrementalAnalyzer(workspace);
var reference = new MockAnalyzerReference(codefix);
var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
document = project.Documents.Single();
var fixes = fixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None).Result;
Assert.True(extensionManager.IsDisabled(codefix));
Assert.False(extensionManager.IsIgnored(codefix));
}
}
public void GetFirstDiagnosticWithFix(CodeFixProvider codefix)
{
TestDiagnosticAnalyzerService diagnosticService;
CodeFixService fixService;
IErrorLoggerService errorLogger;
using (var workspace = ServiceSetup(codefix, out diagnosticService, out fixService, out errorLogger))
{
Document document;
EditorLayerExtensionManager.ExtensionManager extensionManager;
GetDocumentAndExtensionManager(diagnosticService, workspace, out document, out extensionManager);
var unused = fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None).Result;
Assert.True(extensionManager.IsDisabled(codefix));
Assert.False(extensionManager.IsIgnored(codefix));
}
}
private static TestWorkspace ServiceSetup(CodeFixProvider codefix, out TestDiagnosticAnalyzerService diagnosticService, out CodeFixService fixService, out IErrorLoggerService errorLogger)
{
diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());
var fixers = SpecializedCollections.SingletonEnumerable(
new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(
() => codefix,
new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));
var code = @"class Program { }";
var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code);
var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => new TestErrorLogger()));
errorLogger = logger.First().Value;
fixService = new CodeFixService(
diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>());
return workspace;
}
private static void GetDocumentAndExtensionManager(TestDiagnosticAnalyzerService diagnosticService, TestWorkspace workspace, out Document document, out EditorLayerExtensionManager.ExtensionManager extensionManager)
{
var incrementalAnalzyer = (IIncrementalAnalyzerProvider)diagnosticService;
// register diagnostic engine to solution crawler
var analyzer = incrementalAnalzyer.CreateIncrementalAnalyzer(workspace);
var reference = new MockAnalyzerReference();
var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
document = project.Documents.Single();
extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager;
}
private IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> CreateFixers()
{
return SpecializedCollections.SingletonEnumerable(
new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => new MockFixer(), new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));
}
internal class MockFixer : CodeFixProvider
{
public const string Id = "MyDiagnostic";
public bool Called = false;
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(Id); }
}
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
Called = true;
return SpecializedTasks.EmptyTask;
}
}
private class MockAnalyzerReference : AnalyzerReference, ICodeFixProviderFactory
{
public readonly CodeFixProvider Fixer;
public readonly MockDiagnosticAnalyzer Analyzer = new MockDiagnosticAnalyzer();
public MockAnalyzerReference()
{
Fixer = new MockFixer();
}
public MockAnalyzerReference(CodeFixProvider codeFix)
{
Fixer = codeFix;
}
public override string Display
{
get
{
return "MockAnalyzerReference";
}
}
public override string FullPath
{
get
{
return string.Empty;
}
}
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language)
{
return ImmutableArray.Create<DiagnosticAnalyzer>(Analyzer);
}
public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages()
{
return ImmutableArray<DiagnosticAnalyzer>.Empty;
}
public ImmutableArray<CodeFixProvider> GetFixers()
{
return ImmutableArray.Create<CodeFixProvider>(Fixer);
}
public class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
private DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(MockFixer.Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(_descriptor);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction(c =>
{
c.ReportDiagnostic(Diagnostic.Create(_descriptor, c.Tree.GetLocation(TextSpan.FromBounds(0, 0))));
});
}
}
}
internal class TestErrorLogger : IErrorLoggerService
{
public Dictionary<string, string> Messages = new Dictionary<string, string>();
public void LogError(string source, string message)
{
Messages.Add(source, message);
}
public bool TryLogError(string source, string message)
{
try
{
Messages.Add(source, message);
return true;
}
catch (Exception)
{
return false;
}
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using DocuSign.eSign.Client;
using DocuSign.eSign.Model;
namespace DocuSign.eSign.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ITrustServiceProvidersApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns></returns>
CompleteSignHashResponse CompleteSignHash (CompleteSignRequest completeSignRequest = null);
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns>ApiResponse of </returns>
ApiResponse<CompleteSignHashResponse> CompleteSignHashWithHttpInfo (CompleteSignRequest completeSignRequest = null);
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns></returns>
UserInfoResponse GetUserInfo ();
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of </returns>
ApiResponse<UserInfoResponse> GetUserInfoWithHttpInfo ();
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns></returns>
void HealthCheck (TspHealthCheckRequest tspHealthCheckRequest = null);
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> HealthCheckWithHttpInfo (TspHealthCheckRequest tspHealthCheckRequest = null);
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns></returns>
SignHashSessionInfoResponse SignHashSessionInfo (SignSessionInfoRequest signSessionInfoRequest = null);
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns>ApiResponse of </returns>
ApiResponse<SignHashSessionInfoResponse> SignHashSessionInfoWithHttpInfo (SignSessionInfoRequest signSessionInfoRequest = null);
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns></returns>
UpdateTransactionResponse UpdateTransaction (UpdateTransactionRequest updateTransactionRequest = null);
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns>ApiResponse of </returns>
ApiResponse<UpdateTransactionResponse> UpdateTransactionWithHttpInfo (UpdateTransactionRequest updateTransactionRequest = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns>Task of CompleteSignHashResponse</returns>
System.Threading.Tasks.Task<CompleteSignHashResponse> CompleteSignHashAsync (CompleteSignRequest completeSignRequest = null);
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns>Task of ApiResponse (CompleteSignHashResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<CompleteSignHashResponse>> CompleteSignHashAsyncWithHttpInfo (CompleteSignRequest completeSignRequest = null);
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of UserInfoResponse</returns>
System.Threading.Tasks.Task<UserInfoResponse> GetUserInfoAsync ();
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of ApiResponse (UserInfoResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<UserInfoResponse>> GetUserInfoAsyncWithHttpInfo ();
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task HealthCheckAsync (TspHealthCheckRequest tspHealthCheckRequest = null);
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> HealthCheckAsyncWithHttpInfo (TspHealthCheckRequest tspHealthCheckRequest = null);
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns>Task of SignHashSessionInfoResponse</returns>
System.Threading.Tasks.Task<SignHashSessionInfoResponse> SignHashSessionInfoAsync (SignSessionInfoRequest signSessionInfoRequest = null);
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns>Task of ApiResponse (SignHashSessionInfoResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<SignHashSessionInfoResponse>> SignHashSessionInfoAsyncWithHttpInfo (SignSessionInfoRequest signSessionInfoRequest = null);
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns>Task of UpdateTransactionResponse</returns>
System.Threading.Tasks.Task<UpdateTransactionResponse> UpdateTransactionAsync (UpdateTransactionRequest updateTransactionRequest = null);
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns>Task of ApiResponse (UpdateTransactionResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<UpdateTransactionResponse>> UpdateTransactionAsyncWithHttpInfo (UpdateTransactionRequest updateTransactionRequest = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class TrustServiceProvidersApi : ITrustServiceProvidersApi
{
private DocuSign.eSign.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="TrustServiceProvidersApi"/> class.
/// </summary>
/// <returns></returns>
public TrustServiceProvidersApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = DocuSign.eSign.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="TrustServiceProvidersApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public TrustServiceProvidersApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = DocuSign.eSign.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public DocuSign.eSign.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns>CompleteSignHashResponse</returns>
public CompleteSignHashResponse CompleteSignHash (CompleteSignRequest completeSignRequest = null)
{
ApiResponse<CompleteSignHashResponse> localVarResponse = CompleteSignHashWithHttpInfo(completeSignRequest);
return localVarResponse.Data;
}
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns>ApiResponse of CompleteSignHashResponse</returns>
public ApiResponse< CompleteSignHashResponse > CompleteSignHashWithHttpInfo (CompleteSignRequest completeSignRequest = null)
{
var localVarPath = "/v2/signature/completesignhash";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (completeSignRequest != null && completeSignRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(completeSignRequest); // http body (model) parameter
}
else
{
localVarPostBody = completeSignRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("CompleteSignHash", localVarResponse);
if (exception != null) throw exception;
}
// DocuSign: Handle for PDF return types
if (localVarResponse.ContentType != null && !localVarResponse.ContentType.ToLower().Contains("json"))
{
return new ApiResponse<CompleteSignHashResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (CompleteSignHashResponse) Configuration.ApiClient.Deserialize(localVarResponse.RawBytes, typeof(CompleteSignHashResponse)));
}
else
{
return new ApiResponse<CompleteSignHashResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (CompleteSignHashResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CompleteSignHashResponse)));
}
}
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns>Task of CompleteSignHashResponse</returns>
public async System.Threading.Tasks.Task<CompleteSignHashResponse> CompleteSignHashAsync (CompleteSignRequest completeSignRequest = null)
{
ApiResponse<CompleteSignHashResponse> localVarResponse = await CompleteSignHashAsyncWithHttpInfo(completeSignRequest);
return localVarResponse.Data;
}
/// <summary>
/// Complete Sign Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="completeSignRequest"> (optional)</param>
/// <returns>Task of ApiResponse (CompleteSignHashResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<CompleteSignHashResponse>> CompleteSignHashAsyncWithHttpInfo (CompleteSignRequest completeSignRequest = null)
{
var localVarPath = "/v2/signature/completesignhash";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (completeSignRequest != null && completeSignRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(completeSignRequest); // http body (model) parameter
}
else
{
localVarPostBody = completeSignRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("CompleteSignHash", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<CompleteSignHashResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(CompleteSignHashResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CompleteSignHashResponse)));
}
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>UserInfoResponse</returns>
public UserInfoResponse GetUserInfo ()
{
ApiResponse<UserInfoResponse> localVarResponse = GetUserInfoWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of UserInfoResponse</returns>
public ApiResponse< UserInfoResponse > GetUserInfoWithHttpInfo ()
{
var localVarPath = "/v2/signature/userInfo";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetUserInfo", localVarResponse);
if (exception != null) throw exception;
}
// DocuSign: Handle for PDF return types
if (localVarResponse.ContentType != null && !localVarResponse.ContentType.ToLower().Contains("json"))
{
return new ApiResponse<UserInfoResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (UserInfoResponse) Configuration.ApiClient.Deserialize(localVarResponse.RawBytes, typeof(UserInfoResponse)));
}
else
{
return new ApiResponse<UserInfoResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (UserInfoResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(UserInfoResponse)));
}
}
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of UserInfoResponse</returns>
public async System.Threading.Tasks.Task<UserInfoResponse> GetUserInfoAsync ()
{
ApiResponse<UserInfoResponse> localVarResponse = await GetUserInfoAsyncWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// Get User Info To Sign Document
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of ApiResponse (UserInfoResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<UserInfoResponse>> GetUserInfoAsyncWithHttpInfo ()
{
var localVarPath = "/v2/signature/userInfo";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetUserInfo", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<UserInfoResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(UserInfoResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(UserInfoResponse)));
}
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns></returns>
public void HealthCheck (TspHealthCheckRequest tspHealthCheckRequest = null)
{
HealthCheckWithHttpInfo(tspHealthCheckRequest);
}
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> HealthCheckWithHttpInfo (TspHealthCheckRequest tspHealthCheckRequest = null)
{
var localVarPath = "/v2/signature/healthcheck";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (tspHealthCheckRequest != null && tspHealthCheckRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(tspHealthCheckRequest); // http body (model) parameter
}
else
{
localVarPostBody = tspHealthCheckRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("HealthCheck", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task HealthCheckAsync (TspHealthCheckRequest tspHealthCheckRequest = null)
{
await HealthCheckAsyncWithHttpInfo(tspHealthCheckRequest);
}
/// <summary>
/// Report status from the TSP to DocuSign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="tspHealthCheckRequest"> (optional)</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> HealthCheckAsyncWithHttpInfo (TspHealthCheckRequest tspHealthCheckRequest = null)
{
var localVarPath = "/v2/signature/healthcheck";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (tspHealthCheckRequest != null && tspHealthCheckRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(tspHealthCheckRequest); // http body (model) parameter
}
else
{
localVarPostBody = tspHealthCheckRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("HealthCheck", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns>SignHashSessionInfoResponse</returns>
public SignHashSessionInfoResponse SignHashSessionInfo (SignSessionInfoRequest signSessionInfoRequest = null)
{
ApiResponse<SignHashSessionInfoResponse> localVarResponse = SignHashSessionInfoWithHttpInfo(signSessionInfoRequest);
return localVarResponse.Data;
}
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns>ApiResponse of SignHashSessionInfoResponse</returns>
public ApiResponse< SignHashSessionInfoResponse > SignHashSessionInfoWithHttpInfo (SignSessionInfoRequest signSessionInfoRequest = null)
{
var localVarPath = "/v2/signature/signhashsessioninfo";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (signSessionInfoRequest != null && signSessionInfoRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(signSessionInfoRequest); // http body (model) parameter
}
else
{
localVarPostBody = signSessionInfoRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("SignHashSessionInfo", localVarResponse);
if (exception != null) throw exception;
}
// DocuSign: Handle for PDF return types
if (localVarResponse.ContentType != null && !localVarResponse.ContentType.ToLower().Contains("json"))
{
return new ApiResponse<SignHashSessionInfoResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (SignHashSessionInfoResponse) Configuration.ApiClient.Deserialize(localVarResponse.RawBytes, typeof(SignHashSessionInfoResponse)));
}
else
{
return new ApiResponse<SignHashSessionInfoResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (SignHashSessionInfoResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(SignHashSessionInfoResponse)));
}
}
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns>Task of SignHashSessionInfoResponse</returns>
public async System.Threading.Tasks.Task<SignHashSessionInfoResponse> SignHashSessionInfoAsync (SignSessionInfoRequest signSessionInfoRequest = null)
{
ApiResponse<SignHashSessionInfoResponse> localVarResponse = await SignHashSessionInfoAsyncWithHttpInfo(signSessionInfoRequest);
return localVarResponse.Data;
}
/// <summary>
/// Get Signature Session Info To Sign Document Hash
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="signSessionInfoRequest"> (optional)</param>
/// <returns>Task of ApiResponse (SignHashSessionInfoResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<SignHashSessionInfoResponse>> SignHashSessionInfoAsyncWithHttpInfo (SignSessionInfoRequest signSessionInfoRequest = null)
{
var localVarPath = "/v2/signature/signhashsessioninfo";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (signSessionInfoRequest != null && signSessionInfoRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(signSessionInfoRequest); // http body (model) parameter
}
else
{
localVarPostBody = signSessionInfoRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("SignHashSessionInfo", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<SignHashSessionInfoResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(SignHashSessionInfoResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(SignHashSessionInfoResponse)));
}
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns>UpdateTransactionResponse</returns>
public UpdateTransactionResponse UpdateTransaction (UpdateTransactionRequest updateTransactionRequest = null)
{
ApiResponse<UpdateTransactionResponse> localVarResponse = UpdateTransactionWithHttpInfo(updateTransactionRequest);
return localVarResponse.Data;
}
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns>ApiResponse of UpdateTransactionResponse</returns>
public ApiResponse< UpdateTransactionResponse > UpdateTransactionWithHttpInfo (UpdateTransactionRequest updateTransactionRequest = null)
{
var localVarPath = "/v2/signature/updatetransaction";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (updateTransactionRequest != null && updateTransactionRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(updateTransactionRequest); // http body (model) parameter
}
else
{
localVarPostBody = updateTransactionRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateTransaction", localVarResponse);
if (exception != null) throw exception;
}
// DocuSign: Handle for PDF return types
if (localVarResponse.ContentType != null && !localVarResponse.ContentType.ToLower().Contains("json"))
{
return new ApiResponse<UpdateTransactionResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (UpdateTransactionResponse) Configuration.ApiClient.Deserialize(localVarResponse.RawBytes, typeof(UpdateTransactionResponse)));
}
else
{
return new ApiResponse<UpdateTransactionResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (UpdateTransactionResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(UpdateTransactionResponse)));
}
}
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns>Task of UpdateTransactionResponse</returns>
public async System.Threading.Tasks.Task<UpdateTransactionResponse> UpdateTransactionAsync (UpdateTransactionRequest updateTransactionRequest = null)
{
ApiResponse<UpdateTransactionResponse> localVarResponse = await UpdateTransactionAsyncWithHttpInfo(updateTransactionRequest);
return localVarResponse.Data;
}
/// <summary>
/// Report an error from the tsp to docusign
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="updateTransactionRequest"> (optional)</param>
/// <returns>Task of ApiResponse (UpdateTransactionResponse)</returns>
public async System.Threading.Tasks.Task<ApiResponse<UpdateTransactionResponse>> UpdateTransactionAsyncWithHttpInfo (UpdateTransactionRequest updateTransactionRequest = null)
{
var localVarPath = "/v2/signature/updatetransaction";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (updateTransactionRequest != null && updateTransactionRequest.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(updateTransactionRequest); // http body (model) parameter
}
else
{
localVarPostBody = updateTransactionRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateTransaction", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<UpdateTransactionResponse>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(UpdateTransactionResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(UpdateTransactionResponse)));
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Statistics.Algo
File: IOrderStatisticParameter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Statistics
{
using System;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.BusinessEntities;
using StockSharp.Localization;
/// <summary>
/// The interface, describing statistic parameter, calculated based on orders.
/// </summary>
public interface IOrderStatisticParameter
{
/// <summary>
/// To add to the parameter an information on new order.
/// </summary>
/// <param name="order">New order.</param>
void New(Order order);
/// <summary>
/// To add to the parameter an information on changed order.
/// </summary>
/// <param name="order">The changed order.</param>
void Changed(Order order);
/// <summary>
/// To add to the parameter an information on error of order registration.
/// </summary>
/// <param name="fail">Error registering order.</param>
void RegisterFailed(OrderFail fail);
/// <summary>
/// To add to the parameter an information on error of order cancelling.
/// </summary>
/// <param name="fail">Error cancelling order.</param>
void CancelFailed(OrderFail fail);
}
/// <summary>
/// The base statistic parameter, calculated based on orders.
/// </summary>
/// <typeparam name="TValue">The type of the parameter value.</typeparam>
public abstract class BaseOrderStatisticParameter<TValue> : BaseStatisticParameter<TValue>, IOrderStatisticParameter
where TValue : IComparable<TValue>
{
/// <summary>
/// Initialize <see cref="BaseOrderStatisticParameter{T}"/>.
/// </summary>
protected BaseOrderStatisticParameter()
{
}
/// <inheritdoc />
public virtual void New(Order order)
{
}
/// <inheritdoc />
public virtual void Changed(Order order)
{
}
/// <inheritdoc />
public virtual void RegisterFailed(OrderFail fail)
{
}
/// <inheritdoc />
public virtual void CancelFailed(OrderFail fail)
{
}
}
/// <summary>
/// The maximal value of the order registration delay.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str947Key)]
[DescriptionLoc(LocalizedStrings.Str948Key)]
[CategoryLoc(LocalizedStrings.OrdersKey)]
public class MaxLatencyRegistrationParameter : BaseOrderStatisticParameter<TimeSpan>
{
/// <inheritdoc />
public override void New(Order order)
{
if (order.LatencyRegistration != null)
Value = Value.Max(order.LatencyRegistration.Value);
}
}
/// <summary>
/// The maximal value of the order cancelling delay.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str950Key)]
[DescriptionLoc(LocalizedStrings.Str951Key)]
[CategoryLoc(LocalizedStrings.OrdersKey)]
public class MaxLatencyCancellationParameter : BaseOrderStatisticParameter<TimeSpan>
{
/// <inheritdoc />
public override void Changed(Order order)
{
if (order.LatencyCancellation != null)
Value = Value.Max(order.LatencyCancellation.Value);
}
}
/// <summary>
/// The minimal value of order registration delay.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str952Key)]
[DescriptionLoc(LocalizedStrings.Str953Key)]
[CategoryLoc(LocalizedStrings.OrdersKey)]
public class MinLatencyRegistrationParameter : BaseOrderStatisticParameter<TimeSpan>
{
private bool _initialized;
/// <inheritdoc />
public override void Reset()
{
_initialized = false;
base.Reset();
}
/// <inheritdoc />
public override void New(Order order)
{
if (order.LatencyRegistration == null)
return;
if (!_initialized)
{
Value = order.LatencyRegistration.Value;
_initialized = true;
}
else
Value = Value.Min(order.LatencyRegistration.Value);
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
_initialized = storage.GetValue<bool>("Initialized");
base.Load(storage);
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
storage.SetValue("Initialized", _initialized);
base.Save(storage);
}
}
/// <summary>
/// The minimal value of order cancelling delay.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str954Key)]
[DescriptionLoc(LocalizedStrings.Str955Key)]
[CategoryLoc(LocalizedStrings.OrdersKey)]
public class MinLatencyCancellationParameter : BaseOrderStatisticParameter<TimeSpan>
{
private bool _initialized;
/// <inheritdoc />
public override void Reset()
{
_initialized = false;
base.Reset();
}
/// <inheritdoc />
public override void Changed(Order order)
{
if (order.LatencyCancellation == null)
return;
if (!_initialized)
{
Value = order.LatencyCancellation.Value;
_initialized = true;
}
else
Value = Value.Min(order.LatencyCancellation.Value);
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
_initialized = storage.GetValue<bool>("Initialized");
base.Load(storage);
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
storage.SetValue("Initialized", _initialized);
base.Save(storage);
}
}
/// <summary>
/// Total number of orders.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str956Key)]
[DescriptionLoc(LocalizedStrings.Str957Key)]
[CategoryLoc(LocalizedStrings.OrdersKey)]
public class OrderCountParameter : BaseOrderStatisticParameter<int>
{
/// <inheritdoc />
public override void New(Order order)
{
Value++;
}
}
}
| |
using System;
using System.Collections.Generic;
using QuickGraph.Algorithms.Services;
using System.Diagnostics.Contracts;
namespace QuickGraph.Algorithms.Search
{
/// <summary>
/// A edge depth first search algorithm for implicit directed graphs
/// </summary>
/// <remarks>
/// This is a variant of the classic DFS where the edges are color
/// marked.
/// </remarks>
/// <reference-ref
/// idref="gross98graphtheory"
/// chapter="4.2"
/// />
#if !SILVERLIGHT
[Serializable]
#endif
public sealed class ImplicitEdgeDepthFirstSearchAlgorithm<TVertex, TEdge> :
RootedAlgorithmBase<TVertex,IIncidenceGraph<TVertex,TEdge>>,
ITreeBuilderAlgorithm<TVertex,TEdge>
where TEdge : IEdge<TVertex>
{
private int maxDepth = int.MaxValue;
private IDictionary<TEdge,GraphColor> edgeColors = new Dictionary<TEdge,GraphColor>();
public ImplicitEdgeDepthFirstSearchAlgorithm(IIncidenceGraph<TVertex, TEdge> visitedGraph)
: this(null, visitedGraph)
{ }
public ImplicitEdgeDepthFirstSearchAlgorithm(
IAlgorithmComponent host,
IIncidenceGraph<TVertex,TEdge> visitedGraph
)
:base(host, visitedGraph)
{}
/// <summary>
/// Gets the vertex color map
/// </summary>
/// <value>
/// Vertex color (<see cref="GraphColor"/>) dictionary
/// </value>
public IDictionary<TEdge, GraphColor> EdgeColors
{
get
{
return this.edgeColors;
}
}
/// <summary>
/// Gets or sets the maximum exploration depth, from
/// the start vertex.
/// </summary>
/// <remarks>
/// Defaulted at <c>int.MaxValue</c>.
/// </remarks>
/// <value>
/// Maximum exploration depth.
/// </value>
public int MaxDepth
{
get
{
return this.maxDepth;
}
set
{
this.maxDepth = value;
}
}
/// <summary>
/// Invoked on the source vertex once before the start of the search.
/// </summary>
public event VertexAction<TVertex> StartVertex;
/// <summary>
/// Triggers the StartVertex event.
/// </summary>
/// <param name="v"></param>
private void OnStartVertex(TVertex v)
{
var eh = StartVertex;
if (eh != null)
eh(v);
}
/// <summary>
/// Invoked on the first edge of a test case
/// </summary>
public event EdgeAction<TVertex,TEdge> StartEdge;
/// <summary>
/// Triggers the StartEdge event.
/// </summary>
/// <param name="e"></param>
private void OnStartEdge(TEdge e)
{
var eh = StartEdge;
if (eh != null)
eh(e);
}
/// <summary>
///
/// </summary>
public event EdgeEdgeAction<TVertex, TEdge> DiscoverTreeEdge;
/// <summary>
/// Triggers DiscoverEdge event
/// </summary>
/// <param name="se"></param>
/// <param name="e"></param>
private void OnDiscoverTreeEdge(TEdge se, TEdge e)
{
var eh = this.DiscoverTreeEdge;
if (eh != null)
eh(se, e);
}
/// <summary>
/// Invoked on each edge as it becomes a member of the edges that form
/// the search tree. If you wish to record predecessors, do so at this
/// event point.
/// </summary>
public event EdgeAction<TVertex, TEdge> TreeEdge;
/// <summary>
/// Triggers the TreeEdge event.
/// </summary>
/// <param name="e"></param>
private void OnTreeEdge(TEdge e)
{
var eh = this.TreeEdge;
if (eh != null)
eh(e);
}
/// <summary>
/// Invoked on the back edges in the graph.
/// </summary>
public event EdgeAction<TVertex, TEdge> BackEdge;
/// <summary>
/// Triggers the BackEdge event.
/// </summary>
/// <param name="e"></param>
private void OnBackEdge(TEdge e)
{
var eh = this.BackEdge;
if (eh != null)
eh(e);
}
/// <summary>
/// Invoked on forward or cross edges in the graph.
/// (In an undirected graph this method is never called.)
/// </summary>
public event EdgeAction<TVertex, TEdge> ForwardOrCrossEdge;
/// <summary>
/// Triggers the ForwardOrCrossEdge event.
/// </summary>
/// <param name="e"></param>
private void OnForwardOrCrossEdge(TEdge e)
{
var eh = ForwardOrCrossEdge;
if (eh != null)
eh(e);
}
/// <summary>
/// Invoked on a edge after all of its out edges have been added to
/// the search tree and all of the adjacent vertices have been
/// discovered (but before their out-edges have been examined).
/// </summary>
public event EdgeAction<TVertex, TEdge> FinishEdge;
/// <summary>
/// Triggers the ForwardOrCrossEdge event.
/// </summary>
/// <param name="e"></param>
private void OnFinishEdge(TEdge e)
{
var eh = FinishEdge;
if (eh != null)
eh(e);
}
protected override void InternalCompute()
{
TVertex rootVertex;
if (!this.TryGetRootVertex(out rootVertex))
throw new InvalidOperationException("root vertex not set");
// initialize algorithm
this.Initialize();
// start whith him:
OnStartVertex(rootVertex);
var cancelManager = this.Services.CancelManager;
// process each out edge of v
foreach (var e in this.VisitedGraph.OutEdges(rootVertex))
{
if (cancelManager.IsCancelling) return;
if (!this.EdgeColors.ContainsKey(e))
{
OnStartEdge(e);
Visit(e, 0);
}
}
}
/// <summary>
/// Does a depth first search on the vertex u
/// </summary>
/// <param name="se">edge to explore</param>
/// <param name="depth">current exploration depth</param>
/// <exception cref="ArgumentNullException">se cannot be null</exception>
private void Visit(TEdge se, int depth)
{
Contract.Requires(se != null);
Contract.Requires(depth >= 0);
if (depth > this.maxDepth)
return;
// mark edge as gray
this.EdgeColors[se] = GraphColor.Gray;
// add edge to the search tree
OnTreeEdge(se);
var cancelManager = this.Services.CancelManager;
// iterate over out-edges
foreach (var e in this.VisitedGraph.OutEdges(se.Target))
{
if (cancelManager.IsCancelling) return;
// check edge is not explored yet,
// if not, explore it.
GraphColor c;
if (!this.EdgeColors.TryGetValue(e, out c))
{
OnDiscoverTreeEdge(se, e);
Visit(e, depth + 1);
}
else
{
if (c == GraphColor.Gray)
OnBackEdge(e);
else
OnForwardOrCrossEdge(e);
}
}
// all out-edges have been explored
this.EdgeColors[se] = GraphColor.Black;
OnFinishEdge(se);
}
/// <summary>
/// Initializes the algorithm before computation.
/// </summary>
protected override void Initialize()
{
base.Initialize();
this.EdgeColors.Clear();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Components
{
public class ComponentFactoryTest
{
[Fact]
public void InstantiateComponent_CreatesInstance()
{
// Arrange
var componentType = typeof(EmptyComponent);
var factory = new ComponentFactory(new DefaultComponentActivator());
// Act
var instance = factory.InstantiateComponent(GetServiceProvider(), componentType);
// Assert
Assert.NotNull(instance);
Assert.IsType<EmptyComponent>(instance);
}
[Fact]
public void InstantiateComponent_CreatesInstance_NonComponent()
{
// Arrange
var componentType = typeof(List<string>);
var factory = new ComponentFactory(new DefaultComponentActivator());
// Assert
var ex = Assert.Throws<ArgumentException>(() => factory.InstantiateComponent(GetServiceProvider(), componentType));
Assert.StartsWith($"The type {componentType.FullName} does not implement {nameof(IComponent)}.", ex.Message);
}
[Fact]
public void InstantiateComponent_CreatesInstance_WithCustomActivator()
{
// Arrange
var componentType = typeof(EmptyComponent);
var factory = new ComponentFactory(new CustomComponentActivator<ComponentWithInjectProperties>());
// Act
var instance = factory.InstantiateComponent(GetServiceProvider(), componentType);
// Assert
Assert.NotNull(instance);
var component = Assert.IsType<ComponentWithInjectProperties>(instance); // Custom activator returns a different type
// Public, and non-public properties, and properties with non-public setters should get assigned
Assert.NotNull(component.Property1);
Assert.NotNull(component.GetProperty2());
Assert.NotNull(component.Property3);
Assert.NotNull(component.Property4);
}
[Fact]
public void InstantiateComponent_ThrowsForNullInstance()
{
// Arrange
var componentType = typeof(EmptyComponent);
var factory = new ComponentFactory(new NullResultComponentActivator());
// Act
var ex = Assert.Throws<InvalidOperationException>(() => factory.InstantiateComponent(GetServiceProvider(), componentType));
Assert.Equal($"The component activator returned a null value for a component of type {componentType.FullName}.", ex.Message);
}
[Fact]
public void InstantiateComponent_AssignsPropertiesWithInjectAttributeOnBaseType()
{
// Arrange
var componentType = typeof(DerivedComponent);
var factory = new ComponentFactory(new CustomComponentActivator<DerivedComponent>());
// Act
var instance = factory.InstantiateComponent(GetServiceProvider(), componentType);
// Assert
Assert.NotNull(instance);
var component = Assert.IsType<DerivedComponent>(instance);
Assert.NotNull(component.Property1);
Assert.NotNull(component.GetProperty2());
Assert.NotNull(component.Property3);
// Property on derived type without [Inject] should not be assigned
Assert.Null(component.Property4);
// Property on the base type with the [Inject] attribute should
Assert.NotNull(((ComponentWithInjectProperties)component).Property4);
}
[Fact]
public void InstantiateComponent_IgnoresPropertiesWithoutInjectAttribute()
{
// Arrange
var componentType = typeof(ComponentWithNonInjectableProperties);
var factory = new ComponentFactory(new DefaultComponentActivator());
// Act
var instance = factory.InstantiateComponent(GetServiceProvider(), componentType);
// Assert
Assert.NotNull(instance);
var component = Assert.IsType<ComponentWithNonInjectableProperties>(instance);
// Public, and non-public properties, and properties with non-public setters should get assigned
Assert.NotNull(component.Property1);
Assert.Null(component.Property2);
}
private static IServiceProvider GetServiceProvider()
{
return new ServiceCollection()
.AddTransient<TestService1>()
.AddTransient<TestService2>()
.BuildServiceProvider();
}
private class EmptyComponent : IComponent
{
public void Attach(RenderHandle renderHandle)
{
throw new NotImplementedException();
}
public Task SetParametersAsync(ParameterView parameters)
{
throw new NotImplementedException();
}
}
private class ComponentWithInjectProperties : IComponent
{
[Inject]
public TestService1 Property1 { get; set; }
[Inject]
private TestService2 Property2 { get; set; }
[Inject]
public TestService1 Property3 { get; private set; }
[Inject]
public TestService1 Property4 { get; set; }
public TestService2 GetProperty2() => Property2;
public void Attach(RenderHandle renderHandle)
{
throw new NotImplementedException();
}
public Task SetParametersAsync(ParameterView parameters)
{
throw new NotImplementedException();
}
}
private class ComponentWithNonInjectableProperties : IComponent
{
[Inject]
public TestService1 Property1 { get; set; }
public TestService1 Property2 { get; set; }
public void Attach(RenderHandle renderHandle)
{
throw new NotImplementedException();
}
public Task SetParametersAsync(ParameterView parameters)
{
throw new NotImplementedException();
}
}
private class DerivedComponent : ComponentWithInjectProperties
{
public new TestService2 Property4 { get; set; }
[Inject]
public TestService2 Property5 { get; set; }
}
public class TestService1 { }
public class TestService2 { }
private class CustomComponentActivator<TResult> : IComponentActivator where TResult : IComponent, new()
{
public IComponent CreateInstance(Type componentType)
{
return new TResult();
}
}
private class NullResultComponentActivator : IComponentActivator
{
public IComponent CreateInstance(Type componentType)
{
return null;
}
}
}
}
| |
/*
* Vericred API
*
* Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
## Getting Started
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and another for our Sandbox (select the appropriate Plan when
you create the Application).
## SDKs
Our API follows standard REST conventions, so you can use any HTTP client
to integrate with us. You will likely find it easier to use one of our
[autogenerated SDKs](https://github.com/vericred/?query=vericred-),
which we make available for several common programming languages.
## Authentication
To authenticate, pass the API Key you created in the Developer Portal as
a `Vericred-Api-Key` header.
`curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Versioning
Vericred's API default to the latest version. However, if you need a specific
version, you can request it with an `Accept-Version` header.
The current version is `v3`. Previous versions are `v1` and `v2`.
`curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Pagination
Endpoints that accept `page` and `per_page` parameters are paginated. They expose
four additional fields that contain data about your position in the response,
namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988).
For example, to display 5 results per page and view the second page of a
`GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`.
## Sideloading
When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s
we sideload the associated data. In this example, we would provide an Array of
`State`s and a `state_id` for each provider. This is done primarily to reduce the
payload size since many of the `Provider`s will share a `State`
```
{
providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }],
states: [{ id: 1, code: 'NY' }]
}
```
If you need the second level of the object graph, you can just match the
corresponding id.
## Selecting specific data
All endpoints allow you to specify which fields you would like to return.
This allows you to limit the response to contain only the data you need.
For example, let's take a request that returns the following JSON by default
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890',
field_we_dont_care_about: 'value_we_dont_care_about'
},
states: [{
id: 1,
name: 'New York',
code: 'NY',
field_we_dont_care_about: 'value_we_dont_care_about'
}]
}
```
To limit our results to only return the fields we care about, we specify the
`select` query string parameter for the corresponding fields in the JSON
document.
In this case, we want to select `name` and `phone` from the `provider` key,
so we would add the parameters `select=provider.name,provider.phone`.
We also want the `name` and `code` from the `states` key, so we would
add the parameters `select=states.name,staes.code`. The id field of
each document is always returned whether or not it is requested.
Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code`
The response would be
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890'
},
states: [{
id: 1,
name: 'New York',
code: 'NY'
}]
}
```
## Benefits summary format
Benefit cost-share strings are formatted to capture:
* Network tiers
* Compound or conditional cost-share
* Limits on the cost-share
* Benefit-specific maximum out-of-pocket costs
**Example #1**
As an example, we would represent [this Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as:
* **Hospital stay facility fees**:
- Network Provider: `$400 copay/admit plus 20% coinsurance`
- Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance`
- Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible`
* **Rehabilitation services:**
- Network Provider: `20% coinsurance`
- Out-of-Network Provider: `50% coinsurance`
- Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.`
- Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period`
**Example #2**
In [this other Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies.
* **Specialty drugs:**
- Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply`
- Out-of-Network Provider `Not covered`
- Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%`
**BNF**
Here's a description of the benefits summary string, represented as a context-free grammar:
```
<cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit>
<tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:"
<opt-num-prefix> ::= "first" <num> <unit> | ""
<unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)"
<value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable"
<compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible>
<copay> ::= "$" <num>
<coinsurace> ::= <num> "%"
<ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited"
<opt-per-unit> ::= "per day" | "per visit" | "per stay" | ""
<deductible> ::= "before deductible" | "after deductible" | ""
<tier-limit> ::= ", " <limit> | ""
<benefit-limit> ::= <limit> | ""
```
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Vericred.Model
{
/// <summary>
/// FormularyDrugPackageResponse
/// </summary>
[DataContract]
public partial class FormularyDrugPackageResponse : IEquatable<FormularyDrugPackageResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="FormularyDrugPackageResponse" /> class.
/// </summary>
/// <param name="Coverage">DrugCoverage.</param>
/// <param name="DrugPackage">DrugPackage.</param>
/// <param name="Formulary">Formulary.</param>
public FormularyDrugPackageResponse(DrugCoverage Coverage = null, DrugPackage DrugPackage = null, Formulary Formulary = null)
{
this.Coverage = Coverage;
this.DrugPackage = DrugPackage;
this.Formulary = Formulary;
}
/// <summary>
/// DrugCoverage
/// </summary>
/// <value>DrugCoverage</value>
[DataMember(Name="coverage", EmitDefaultValue=false)]
public DrugCoverage Coverage { get; set; }
/// <summary>
/// DrugPackage
/// </summary>
/// <value>DrugPackage</value>
[DataMember(Name="drug_package", EmitDefaultValue=false)]
public DrugPackage DrugPackage { get; set; }
/// <summary>
/// Formulary
/// </summary>
/// <value>Formulary</value>
[DataMember(Name="formulary", EmitDefaultValue=false)]
public Formulary Formulary { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FormularyDrugPackageResponse {\n");
sb.Append(" Coverage: ").Append(Coverage).Append("\n");
sb.Append(" DrugPackage: ").Append(DrugPackage).Append("\n");
sb.Append(" Formulary: ").Append(Formulary).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as FormularyDrugPackageResponse);
}
/// <summary>
/// Returns true if FormularyDrugPackageResponse instances are equal
/// </summary>
/// <param name="other">Instance of FormularyDrugPackageResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FormularyDrugPackageResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Coverage == other.Coverage ||
this.Coverage != null &&
this.Coverage.Equals(other.Coverage)
) &&
(
this.DrugPackage == other.DrugPackage ||
this.DrugPackage != null &&
this.DrugPackage.Equals(other.DrugPackage)
) &&
(
this.Formulary == other.Formulary ||
this.Formulary != null &&
this.Formulary.Equals(other.Formulary)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Coverage != null)
hash = hash * 59 + this.Coverage.GetHashCode();
if (this.DrugPackage != null)
hash = hash * 59 + this.DrugPackage.GetHashCode();
if (this.Formulary != null)
hash = hash * 59 + this.Formulary.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace mapgenerator
{
class mapgenerator
{
static void WriteFieldMember(TextWriter writer, MapField field)
{
string type = String.Empty;
switch (field.Type)
{
case FieldType.BOOL:
type = "bool";
break;
case FieldType.F32:
type = "float";
break;
case FieldType.F64:
type = "double";
break;
case FieldType.IPPORT:
case FieldType.U16:
type = "ushort";
break;
case FieldType.IPADDR:
case FieldType.U32:
type = "uint";
break;
case FieldType.LLQuaternion:
type = "Quaternion";
break;
case FieldType.LLUUID:
type = "UUID";
break;
case FieldType.LLVector3:
type = "Vector3";
break;
case FieldType.LLVector3d:
type = "Vector3d";
break;
case FieldType.LLVector4:
type = "Vector4";
break;
case FieldType.S16:
type = "short";
break;
case FieldType.S32:
type = "int";
break;
case FieldType.S8:
type = "sbyte";
break;
case FieldType.U64:
type = "ulong";
break;
case FieldType.U8:
type = "byte";
break;
case FieldType.Fixed:
type = "byte[]";
break;
}
if (field.Type != FieldType.Variable)
{
//writer.WriteLine(" /// <summary>" + field.Name + " field</summary>");
writer.WriteLine(" public " + type + " " + field.Name + ";");
}
else
{
writer.WriteLine(" public byte[] " + field.Name + ";");
//writer.WriteLine(" private byte[] _" + field.Name.ToLower() + ";");
////writer.WriteLine(" /// <summary>" + field.Name + " field</summary>");
//writer.WriteLine(" public byte[] " + field.Name + Environment.NewLine + " {");
//writer.WriteLine(" get { return _" + field.Name.ToLower() + "; }");
//writer.WriteLine(" set" + Environment.NewLine + " {");
//writer.WriteLine(" if (value == null) { _" +
// field.Name.ToLower() + " = null; return; }");
//writer.WriteLine(" if (value.Length > " +
// ((field.Count == 1) ? "255" : "1100") + ") { throw new OverflowException(" +
// "\"Value exceeds " + ((field.Count == 1) ? "255" : "1100") + " characters\"); }");
//writer.WriteLine(" else { _" + field.Name.ToLower() +
// " = new byte[value.Length]; Buffer.BlockCopy(value, 0, _" +
// field.Name.ToLower() + ", 0, value.Length); }");
//writer.WriteLine(" }" + Environment.NewLine + " }");
}
}
static void WriteFieldFromBytes(TextWriter writer, MapField field)
{
switch (field.Type)
{
case FieldType.BOOL:
writer.WriteLine(" " +
field.Name + " = (bytes[i++] != 0) ? (bool)true : (bool)false;");
break;
case FieldType.F32:
writer.WriteLine(" " +
field.Name + " = Utils.BytesToFloat(bytes, i); i += 4;");
break;
case FieldType.F64:
writer.WriteLine(" " +
field.Name + " = Utils.BytesToDouble(bytes, i); i += 8;");
break;
case FieldType.Fixed:
writer.WriteLine(" " + field.Name + " = new byte[" + field.Count + "];");
writer.WriteLine(" Buffer.BlockCopy(bytes, i, " + field.Name +
", 0, " + field.Count + "); i += " + field.Count + ";");
break;
case FieldType.IPADDR:
case FieldType.U32:
writer.WriteLine(" " + field.Name +
" = (uint)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));");
break;
case FieldType.IPPORT:
// IPPORT is big endian while U16/S16 are little endian. Go figure
writer.WriteLine(" " + field.Name +
" = (ushort)((bytes[i++] << 8) + bytes[i++]);");
break;
case FieldType.U16:
writer.WriteLine(" " + field.Name +
" = (ushort)(bytes[i++] + (bytes[i++] << 8));");
break;
case FieldType.LLQuaternion:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i, true); i += 12;");
break;
case FieldType.LLUUID:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 16;");
break;
case FieldType.LLVector3:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 12;");
break;
case FieldType.LLVector3d:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 24;");
break;
case FieldType.LLVector4:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 16;");
break;
case FieldType.S16:
writer.WriteLine(" " + field.Name +
" = (short)(bytes[i++] + (bytes[i++] << 8));");
break;
case FieldType.S32:
writer.WriteLine(" " + field.Name +
" = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));");
break;
case FieldType.S8:
writer.WriteLine(" " + field.Name +
" = (sbyte)bytes[i++];");
break;
case FieldType.U64:
writer.WriteLine(" " + field.Name +
" = (ulong)((ulong)bytes[i++] + ((ulong)bytes[i++] << 8) + " +
"((ulong)bytes[i++] << 16) + ((ulong)bytes[i++] << 24) + " +
"((ulong)bytes[i++] << 32) + ((ulong)bytes[i++] << 40) + " +
"((ulong)bytes[i++] << 48) + ((ulong)bytes[i++] << 56));");
break;
case FieldType.U8:
writer.WriteLine(" " + field.Name +
" = (byte)bytes[i++];");
break;
case FieldType.Variable:
if (field.Count == 1)
{
writer.WriteLine(" length = bytes[i++];");
}
else
{
writer.WriteLine(" length = (bytes[i++] + (bytes[i++] << 8));");
}
writer.WriteLine(" " + field.Name + " = new byte[length];");
writer.WriteLine(" Buffer.BlockCopy(bytes, i, " + field.Name + ", 0, length); i += length;");
break;
default:
writer.WriteLine("!!! ERROR: Unhandled FieldType: " + field.Type.ToString() + " !!!");
break;
}
}
static void WriteFieldToBytes(TextWriter writer, MapField field)
{
writer.Write(" ");
switch (field.Type)
{
case FieldType.BOOL:
writer.WriteLine("bytes[i++] = (byte)((" + field.Name + ") ? 1 : 0);");
break;
case FieldType.F32:
writer.WriteLine("Utils.FloatToBytes(" + field.Name + ", bytes, i); i += 4;");
break;
case FieldType.F64:
writer.WriteLine("Utils.DoubleToBytes(" + field.Name + ", bytes, i); i += 8;");
break;
case FieldType.Fixed:
writer.WriteLine("Buffer.BlockCopy(" + field.Name + ", 0, bytes, i, " + field.Count + ");" +
"i += " + field.Count + ";");
break;
case FieldType.IPPORT:
// IPPORT is big endian while U16/S16 is little endian. Go figure
writer.WriteLine("bytes[i++] = (byte)((" + field.Name + " >> 8) % 256);");
writer.WriteLine(" bytes[i++] = (byte)(" + field.Name + " % 256);");
break;
case FieldType.U16:
case FieldType.S16:
writer.WriteLine("bytes[i++] = (byte)(" + field.Name + " % 256);");
writer.WriteLine(" bytes[i++] = (byte)((" + field.Name + " >> 8) % 256);");
break;
case FieldType.LLQuaternion:
case FieldType.LLVector3:
writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 12;");
break;
case FieldType.LLUUID:
case FieldType.LLVector4:
writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 16;");
break;
case FieldType.LLVector3d:
writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 24;");
break;
case FieldType.U8:
writer.WriteLine("bytes[i++] = " + field.Name + ";");
break;
case FieldType.S8:
writer.WriteLine("bytes[i++] = (byte)" + field.Name + ";");
break;
case FieldType.IPADDR:
case FieldType.U32:
writer.WriteLine("Utils.UIntToBytes(" + field.Name + ", bytes, i); i += 4;");
break;
case FieldType.S32:
writer.WriteLine("Utils.IntToBytes(" + field.Name + ", bytes, i); i += 4;");
break;
case FieldType.U64:
writer.WriteLine("Utils.UInt64ToBytes(" + field.Name + ", bytes, i); i += 8;");
break;
case FieldType.Variable:
//writer.WriteLine("if(" + field.Name + " == null) { Console.WriteLine(\"Warning: " + field.Name + " is null, in \" + this.GetType()); }");
//writer.Write(" ");
if (field.Count == 1)
{
writer.WriteLine("bytes[i++] = (byte)" + field.Name + ".Length;");
}
else
{
writer.WriteLine("bytes[i++] = (byte)(" + field.Name + ".Length % 256);");
writer.WriteLine(" bytes[i++] = (byte)((" +
field.Name + ".Length >> 8) % 256);");
}
writer.WriteLine(" Buffer.BlockCopy(" + field.Name + ", 0, bytes, i, " +
field.Name + ".Length); " + "i += " + field.Name + ".Length;");
break;
default:
writer.WriteLine("!!! ERROR: Unhandled FieldType: " + field.Type.ToString() + " !!!");
break;
}
}
static int GetFieldLength(TextWriter writer, MapField field)
{
switch (field.Type)
{
case FieldType.BOOL:
case FieldType.U8:
case FieldType.S8:
return 1;
case FieldType.U16:
case FieldType.S16:
case FieldType.IPPORT:
return 2;
case FieldType.U32:
case FieldType.S32:
case FieldType.F32:
case FieldType.IPADDR:
return 4;
case FieldType.U64:
case FieldType.F64:
return 8;
case FieldType.LLVector3:
case FieldType.LLQuaternion:
return 12;
case FieldType.LLUUID:
case FieldType.LLVector4:
return 16;
case FieldType.LLVector3d:
return 24;
case FieldType.Fixed:
return field.Count;
case FieldType.Variable:
return 0;
default:
writer.WriteLine("!!! ERROR: Unhandled FieldType " + field.Type.ToString() + " !!!");
return 0;
}
}
static void WriteBlockClass(TextWriter writer, MapBlock block, MapPacket packet)
{
int variableFieldCountBytes = 0;
//writer.WriteLine(" /// <summary>" + block.Name + " block</summary>");
writer.WriteLine(" /// <exclude/>");
writer.WriteLine(" public sealed class " + block.Name + "Block : PacketBlock" + Environment.NewLine + " {");
foreach (MapField field in block.Fields)
{
WriteFieldMember(writer, field);
if (field.Type == FieldType.Variable) { variableFieldCountBytes += field.Count; }
}
// Length property
writer.WriteLine("");
//writer.WriteLine(" /// <summary>Length of this block serialized in bytes</summary>");
writer.WriteLine(" public override int Length" + Environment.NewLine +
" {" + Environment.NewLine +
" get" + Environment.NewLine +
" {");
int length = variableFieldCountBytes;
// Figure out the length of this block
foreach (MapField field in block.Fields)
{
length += GetFieldLength(writer, field);
}
if (variableFieldCountBytes == 0)
{
writer.WriteLine(" return " + length + ";");
}
else
{
writer.WriteLine(" int length = " + length + ";");
foreach (MapField field in block.Fields)
{
if (field.Type == FieldType.Variable)
{
writer.WriteLine(" if (" + field.Name +
" != null) { length += " + field.Name + ".Length; }");
}
}
writer.WriteLine(" return length;");
}
writer.WriteLine(" }" + Environment.NewLine + " }" + Environment.NewLine);
// Default constructor
//writer.WriteLine(" /// <summary>Default constructor</summary>");
writer.WriteLine(" public " + block.Name + "Block() { }");
// Constructor for building the class from bytes
//writer.WriteLine(" /// <summary>Constructor for building the block from a byte array</summary>");
writer.WriteLine(" public " + block.Name + "Block(byte[] bytes, ref int i)" + Environment.NewLine +
" {" + Environment.NewLine +
" FromBytes(bytes, ref i);" + Environment.NewLine +
" }" + Environment.NewLine);
// Initiates instance variables from a byte message
writer.WriteLine(" public override void FromBytes(byte[] bytes, ref int i)" + Environment.NewLine +
" {");
// Declare a length variable if we need it for variable fields in this constructor
if (variableFieldCountBytes > 0) { writer.WriteLine(" int length;"); }
// Start of the try catch block
writer.WriteLine(" try" + Environment.NewLine + " {");
foreach (MapField field in block.Fields)
{
WriteFieldFromBytes(writer, field);
}
writer.WriteLine(" }" + Environment.NewLine +
" catch (Exception)" + Environment.NewLine +
" {" + Environment.NewLine +
" throw new MalformedDataException();" + Environment.NewLine +
" }" + Environment.NewLine + " }" + Environment.NewLine);
// ToBytes() function
//writer.WriteLine(" /// <summary>Serialize this block to a byte array</summary>");
writer.WriteLine(" public override void ToBytes(byte[] bytes, ref int i)" + Environment.NewLine +
" {");
foreach (MapField field in block.Fields)
{
WriteFieldToBytes(writer, field);
}
writer.WriteLine(" }" + Environment.NewLine);
writer.WriteLine(" }" + Environment.NewLine);
}
static void WritePacketClass(TextWriter writer, MapPacket packet)
{
bool hasVariableBlocks = false;
string sanitizedName;
//writer.WriteLine(" /// <summary>" + packet.Name + " packet</summary>");
writer.WriteLine(" /// <exclude/>");
writer.WriteLine(" public sealed class " + packet.Name + "Packet : Packet" + Environment.NewLine + " {");
// Write out each block class
foreach (MapBlock block in packet.Blocks)
{
WriteBlockClass(writer, block, packet);
}
// Length member
writer.WriteLine(" public override int Length" + Environment.NewLine +
" {" + Environment.NewLine + " get" + Environment.NewLine +
" {");
int length = 0;
if (packet.Frequency == PacketFrequency.Low) { length = 10; }
else if (packet.Frequency == PacketFrequency.Medium) { length = 8; }
else { length = 7; }
foreach (MapBlock block in packet.Blocks)
{
if (block.Count == -1)
{
hasVariableBlocks = true;
++length;
}
}
writer.WriteLine(" int length = " + length + ";");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" for (int j = 0; j < " + sanitizedName + ".Length; j++)");
writer.WriteLine(" length += " + sanitizedName + "[j].Length;");
}
else if (block.Count == 1)
{
writer.WriteLine(" length += " + sanitizedName + ".Length;");
}
else
{
// Multiple count block
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" length += " + sanitizedName + "[j].Length;");
}
}
writer.WriteLine(" return length;");
writer.WriteLine(" }" + Environment.NewLine + " }");
// Block members
foreach (MapBlock block in packet.Blocks)
{
// TODO: More thorough name blacklisting
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
//writer.WriteLine(" /// <summary>" + block.Name + " block</summary>");
writer.WriteLine(" public " + block.Name + "Block" +
((block.Count != 1) ? "[]" : "") + " " + sanitizedName + ";");
}
writer.WriteLine("");
// Default constructor
//writer.WriteLine(" /// <summary>Default constructor</summary>");
writer.WriteLine(" public " + packet.Name + "Packet()" + Environment.NewLine + " {");
writer.WriteLine(" HasVariableBlocks = " + hasVariableBlocks.ToString().ToLowerInvariant() + ";");
writer.WriteLine(" Type = PacketType." + packet.Name + ";");
writer.WriteLine(" Header = new Header();");
writer.WriteLine(" Header.Frequency = PacketFrequency." + packet.Frequency + ";");
writer.WriteLine(" Header.ID = " + packet.ID + ";");
writer.WriteLine(" Header.Reliable = true;"); // Turn the reliable flag on by default
if (packet.Encoded) { writer.WriteLine(" Header.Zerocoded = true;"); }
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block();");
}
else if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" " + sanitizedName + " = null;");
}
else
{
// Multiple count block
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];");
}
}
writer.WriteLine(" }" + Environment.NewLine);
// Constructor that takes a byte array and beginning position only (no prebuilt header)
bool seenVariable = false;
//writer.WriteLine(" /// <summary>Constructor that takes a byte array and beginning position (no prebuilt header)</summary>");
writer.WriteLine(" public " + packet.Name + "Packet(byte[] bytes, ref int i) : this()" + Environment.NewLine +
" {" + Environment.NewLine +
" int packetEnd = bytes.Length - 1;" + Environment.NewLine +
" FromBytes(bytes, ref i, ref packetEnd, null);" + Environment.NewLine +
" }" + Environment.NewLine);
writer.WriteLine(" override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer)" + Environment.NewLine + " {");
writer.WriteLine(" Header.FromBytes(bytes, ref i, ref packetEnd);");
writer.WriteLine(" if (Header.Zerocoded && zeroBuffer != null)");
writer.WriteLine(" {");
writer.WriteLine(" packetEnd = Helpers.ZeroDecode(bytes, packetEnd + 1, zeroBuffer) - 1;");
writer.WriteLine(" bytes = zeroBuffer;");
writer.WriteLine(" }");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + ".FromBytes(bytes, ref i);");
}
else if (block.Count == -1)
{
// Variable count block
if (!seenVariable)
{
writer.WriteLine(" int count = (int)bytes[i++];");
seenVariable = true;
}
else
{
writer.WriteLine(" count = (int)bytes[i++];");
}
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[count];");
writer.WriteLine(" for(int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
else
{
// Multiple count block
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];");
writer.WriteLine(" for(int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
}
writer.WriteLine(" }" + Environment.NewLine);
seenVariable = false;
// Constructor that takes a byte array and a prebuilt header
//writer.WriteLine(" /// <summary>Constructor that takes a byte array and a prebuilt header</summary>");
writer.WriteLine(" public " + packet.Name + "Packet(Header head, byte[] bytes, ref int i): this()" + Environment.NewLine +
" {" + Environment.NewLine +
" int packetEnd = bytes.Length - 1;" + Environment.NewLine +
" FromBytes(head, bytes, ref i, ref packetEnd);" + Environment.NewLine +
" }" + Environment.NewLine);
writer.WriteLine(" override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd)" + Environment.NewLine +
" {");
writer.WriteLine(" Header = header;");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + ".FromBytes(bytes, ref i);");
}
else if (block.Count == -1)
{
// Variable count block
if (!seenVariable)
{
writer.WriteLine(" int count = (int)bytes[i++];");
seenVariable = true;
}
else
{
writer.WriteLine(" count = (int)bytes[i++];");
}
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != count) {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[count];");
writer.WriteLine(" for(int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
else
{
// Multiple count block
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];");
writer.WriteLine(" for(int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
}
writer.WriteLine(" }" + Environment.NewLine);
#region ToBytes() Function
//writer.WriteLine(" /// <summary>Serialize this packet to a byte array</summary><returns>A byte array containing the serialized packet</returns>");
writer.WriteLine(" public override byte[] ToBytes()" + Environment.NewLine + " {");
writer.Write(" int length = ");
if (packet.Frequency == PacketFrequency.Low) { writer.WriteLine("10;"); }
else if (packet.Frequency == PacketFrequency.Medium) { writer.WriteLine("8;"); }
else { writer.WriteLine("7;"); }
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" length += " + sanitizedName + ".Length;");
}
}
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
writer.WriteLine(" length++;");
writer.WriteLine(" for (int j = 0; j < " + sanitizedName +
".Length; j++) { length += " + sanitizedName + "[j].Length; }");
}
else if (block.Count > 1)
{
writer.WriteLine(" for (int j = 0; j < " + block.Count +
"; j++) { length += " + sanitizedName + "[j].Length; }");
}
}
writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) { length += Header.AckList.Length * 4 + 1; }");
writer.WriteLine(" byte[] bytes = new byte[length];");
writer.WriteLine(" int i = 0;");
writer.WriteLine(" Header.ToBytes(bytes, ref i);");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" bytes[i++] = (byte)" + sanitizedName + ".Length;");
writer.WriteLine(" for (int j = 0; j < " + sanitizedName +
".Length; j++) { " + sanitizedName + "[j].ToBytes(bytes, ref i); }");
}
else if (block.Count == 1)
{
writer.WriteLine(" " + sanitizedName + ".ToBytes(bytes, ref i);");
}
else
{
// Multiple count block
writer.WriteLine(" for (int j = 0; j < " + block.Count +
"; j++) { " + sanitizedName + "[j].ToBytes(bytes, ref i); }");
}
}
writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); }");
writer.WriteLine(" return bytes;" + Environment.NewLine + " }" + Environment.NewLine);
#endregion ToBytes() Function
WriteToBytesMultiple(writer, packet);
writer.WriteLine(" }" + Environment.NewLine);
}
static void WriteToBytesMultiple(TextWriter writer, MapPacket packet)
{
writer.WriteLine(
" public override byte[][] ToBytesMultiple()" + Environment.NewLine +
" {");
// Check if there are any variable blocks
bool hasVariable = false;
bool cannotSplit = false;
foreach (MapBlock block in packet.Blocks)
{
if (block.Count == -1)
{
hasVariable = true;
}
else if (hasVariable)
{
// A fixed or single block showed up after a variable count block.
// Our automatic splitting algorithm won't work for this packet
cannotSplit = true;
break;
}
}
if (hasVariable && !cannotSplit)
{
writer.WriteLine(
" System.Collections.Generic.List<byte[]> packets = new System.Collections.Generic.List<byte[]>();");
writer.WriteLine(
" int i = 0;");
writer.Write(
" int fixedLength = ");
if (packet.Frequency == PacketFrequency.Low) { writer.WriteLine("10;"); }
else if (packet.Frequency == PacketFrequency.Medium) { writer.WriteLine("8;"); }
else { writer.WriteLine("7;"); }
writer.WriteLine();
// ACK serialization
writer.WriteLine(" byte[] ackBytes = null;");
writer.WriteLine(" int acksLength = 0;");
writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) {");
writer.WriteLine(" Header.AppendedAcks = true;");
writer.WriteLine(" ackBytes = new byte[Header.AckList.Length * 4 + 1];");
writer.WriteLine(" Header.AcksToBytes(ackBytes, ref acksLength);");
writer.WriteLine(" }");
writer.WriteLine();
// Count fixed blocks
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" fixedLength += " + sanitizedName + ".Length;");
}
else if (block.Count > 0)
{
// Fixed count block
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { fixedLength += " + sanitizedName + "[j].Length; }");
}
}
// Serialize fixed blocks
writer.WriteLine(
" byte[] fixedBytes = new byte[fixedLength];");
writer.WriteLine(
" Header.ToBytes(fixedBytes, ref i);");
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + ".ToBytes(fixedBytes, ref i);");
}
else if (block.Count > 0)
{
// Fixed count block
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { " + sanitizedName + "[j].ToBytes(fixedBytes, ref i); }");
}
}
int variableCountBlock = 0;
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
++variableCountBlock;
}
}
writer.WriteLine(" fixedLength += " + variableCountBlock + ";");
writer.WriteLine();
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" int " + sanitizedName + "Start = 0;");
}
}
writer.WriteLine(" do");
writer.WriteLine(" {");
// Count how many variable blocks can go in this packet
writer.WriteLine(" int variableLength = 0;");
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" int " + sanitizedName + "Count = 0;");
}
}
writer.WriteLine();
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" i = " + sanitizedName + "Start;");
writer.WriteLine(" while (fixedLength + variableLength + acksLength < Packet.MTU && i < " + sanitizedName + ".Length) {");
writer.WriteLine(" int blockLength = " + sanitizedName + "[i].Length;");
writer.WriteLine(" if (fixedLength + variableLength + blockLength + acksLength <= MTU) {");
writer.WriteLine(" variableLength += blockLength;");
writer.WriteLine(" ++" + sanitizedName + "Count;");
writer.WriteLine(" }");
writer.WriteLine(" else { break; }");
writer.WriteLine(" ++i;");
writer.WriteLine(" }");
writer.WriteLine();
}
}
// Create the packet
writer.WriteLine(" byte[] packet = new byte[fixedLength + variableLength + acksLength];");
writer.WriteLine(" int length = fixedBytes.Length;");
writer.WriteLine(" Buffer.BlockCopy(fixedBytes, 0, packet, 0, length);");
// Remove the appended ACKs flag from subsequent packets
writer.WriteLine(" if (packets.Count > 0) { packet[0] = (byte)(packet[0] & ~0x10); }");
writer.WriteLine();
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
writer.WriteLine(" packet[length++] = (byte)" + sanitizedName + "Count;");
writer.WriteLine(" for (i = " + sanitizedName + "Start; i < " + sanitizedName + "Start + "
+ sanitizedName + "Count; i++) { " + sanitizedName + "[i].ToBytes(packet, ref length); }");
writer.WriteLine(" " + sanitizedName + "Start += " + sanitizedName + "Count;");
writer.WriteLine();
}
}
// ACK appending
writer.WriteLine(" if (acksLength > 0) {");
writer.WriteLine(" Buffer.BlockCopy(ackBytes, 0, packet, length, acksLength);");
writer.WriteLine(" acksLength = 0;");
writer.WriteLine(" }");
writer.WriteLine();
writer.WriteLine(" packets.Add(packet);");
writer.WriteLine(" } while (");
bool first = true;
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
if (first) first = false;
else writer.WriteLine(" ||");
// Variable count block
writer.Write(" " + sanitizedName + "Start < " + sanitizedName + ".Length");
}
}
writer.WriteLine(");");
writer.WriteLine();
writer.WriteLine(" return packets.ToArray();");
writer.WriteLine(" }");
}
else
{
writer.WriteLine(" return new byte[][] { ToBytes() };");
writer.WriteLine(" }");
}
}
static int Main(string[] args)
{
ProtocolManager protocol;
List<string> unused = new List<string>();
TextWriter writer;
try
{
if (args.Length != 4)
{
Console.WriteLine("Usage: [message_template.msg] [template.cs] [unusedpackets.txt] [_Packets_.cs]");
return -1;
}
writer = new StreamWriter(args[3]);
protocol = new ProtocolManager(args[0]);
// Build a list of unused packets
using (StreamReader unusedReader = new StreamReader(args[2]))
{
while (unusedReader.Peek() >= 0)
{
unused.Add(unusedReader.ReadLine().Trim());
}
}
// Read in the template.cs file and write it to our output
TextReader reader = new StreamReader(args[1]);
writer.WriteLine(reader.ReadToEnd());
reader.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return -2;
}
// Prune all of the unused packets out of the protocol
int i = 0;
foreach (MapPacket packet in protocol.LowMaps)
{
if (packet != null && unused.Contains(packet.Name))
protocol.LowMaps[i] = null;
i++;
}
i = 0;
foreach (MapPacket packet in protocol.MediumMaps)
{
if (packet != null && unused.Contains(packet.Name))
protocol.MediumMaps[i] = null;
i++;
}
i = 0;
foreach (MapPacket packet in protocol.HighMaps)
{
if (packet != null && unused.Contains(packet.Name))
protocol.HighMaps[i] = null;
i++;
}
// Write the PacketType enum
writer.WriteLine(" public enum PacketType" + Environment.NewLine + " {" + Environment.NewLine +
" /// <summary>A generic value, not an actual packet type</summary>" + Environment.NewLine +
" Default,");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" " + packet.Name + " = " + (0x10000 | packet.ID) + ",");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" " + packet.Name + " = " + (0x20000 | packet.ID) + ",");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" " + packet.Name + " = " + (0x30000 | packet.ID) + ",");
writer.WriteLine(" }" + Environment.NewLine);
// Write the base Packet class
writer.WriteLine(
" public abstract partial class Packet" + Environment.NewLine + " {" + Environment.NewLine +
" public const int MTU = 1200;" + Environment.NewLine +
Environment.NewLine +
" public Header Header;" + Environment.NewLine +
" public bool HasVariableBlocks;" + Environment.NewLine +
" public PacketType Type;" + Environment.NewLine +
" public abstract int Length { get; }" + Environment.NewLine +
" public abstract void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer);" + Environment.NewLine +
" public abstract void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd);" + Environment.NewLine +
" public abstract byte[] ToBytes();" + Environment.NewLine +
" public abstract byte[][] ToBytesMultiple();"
);
writer.WriteLine();
// Write the Packet.GetType() function
writer.WriteLine(
" public static PacketType GetType(ushort id, PacketFrequency frequency)" + Environment.NewLine +
" {" + Environment.NewLine +
" switch (frequency)" + Environment.NewLine +
" {" + Environment.NewLine +
" case PacketFrequency.Low:" + Environment.NewLine +
" switch (id)" + Environment.NewLine +
" {");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";");
writer.WriteLine(" }" + Environment.NewLine +
" break;" + Environment.NewLine +
" case PacketFrequency.Medium:" + Environment.NewLine +
" switch (id)" + Environment.NewLine + " {");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";");
writer.WriteLine(" }" + Environment.NewLine +
" break;" + Environment.NewLine +
" case PacketFrequency.High:" + Environment.NewLine +
" switch (id)" + Environment.NewLine + " {");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";");
writer.WriteLine(" }" + Environment.NewLine +
" break;" + Environment.NewLine + " }" + Environment.NewLine + Environment.NewLine +
" return PacketType.Default;" + Environment.NewLine + " }" + Environment.NewLine);
// Write the Packet.BuildPacket(PacketType) function
writer.WriteLine(" public static Packet BuildPacket(PacketType type)");
writer.WriteLine(" {");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();");
writer.WriteLine(" return null;" + Environment.NewLine);
writer.WriteLine(" }");
// Write the Packet.BuildPacket() function
writer.WriteLine(@"
public static Packet BuildPacket(byte[] packetBuffer, ref int packetEnd, byte[] zeroBuffer)
{
byte[] bytes;
int i = 0;
Header header = Header.BuildHeader(packetBuffer, ref i, ref packetEnd);
if (header.Zerocoded)
{
packetEnd = Helpers.ZeroDecode(packetBuffer, packetEnd + 1, zeroBuffer) - 1;
bytes = zeroBuffer;
}
else
{
bytes = packetBuffer;
}
Array.Clear(bytes, packetEnd + 1, bytes.Length - packetEnd - 1);
switch (header.Frequency)
{
case PacketFrequency.Low:
switch (header.ID)
{");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);");
writer.WriteLine(@"
}
break;
case PacketFrequency.Medium:
switch (header.ID)
{");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);");
writer.WriteLine(@"
}
break;
case PacketFrequency.High:
switch (header.ID)
{");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);");
writer.WriteLine(@"
}
break;
}
throw new MalformedDataException(""Unknown packet ID "" + header.Frequency + "" "" + header.ID);
}
}");
// Write the packet classes
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null) { WritePacketClass(writer, packet); }
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null) { WritePacketClass(writer, packet); }
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null) { WritePacketClass(writer, packet); }
// Finish up
writer.WriteLine("}");
writer.Close();
return 0;
}
}
}
| |
//
// Scheduler.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2007 Novell, Inc.
// Copyright (C) 2007 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/***************************************************************************
* Scheduler.cs
*
* Copyright (C) 2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Threading;
using System.Collections.Generic;
using Hyena;
namespace Banshee.Kernel
{
public delegate void JobEventHandler(IJob job);
public static class Scheduler
{
private static object this_mutex = new object();
private static IntervalHeap<IJob> heap = new IntervalHeap<IJob>();
private static Thread job_thread;
private static bool disposed;
private static IJob current_running_job;
private static int suspend_count;
public static event JobEventHandler JobStarted;
public static event JobEventHandler JobFinished;
public static event JobEventHandler JobScheduled;
public static event JobEventHandler JobUnscheduled;
public static void Schedule(IJob job)
{
Schedule(job, JobPriority.Normal);
}
public static void Schedule(IJob job, JobPriority priority)
{
lock(this_mutex) {
if(IsDisposed()) {
return;
}
heap.Push(job, (int)priority);
Debug("Job scheduled ({0}, {1})", job, priority);
OnJobScheduled(job);
CheckRun();
}
}
public static void Unschedule(IJob job)
{
lock(this_mutex) {
if(IsDisposed()) {
return;
}
if(heap.Remove(job)) {
Debug("Job unscheduled ({0}), job", job);
OnJobUnscheduled(job);
} else {
Debug("Job not unscheduled; not located in heap");
}
}
}
public static void Unschedule(Type type)
{
lock(this_mutex) {
Queue<IJob> to_remove = new Queue<IJob>();
foreach(IJob job in ScheduledJobs) {
Type job_type = job.GetType();
if((type.IsInterface && job_type.GetInterface(type.Name) != null) ||
job_type == type || job_type.IsSubclassOf(job_type)) {
to_remove.Enqueue(job);
}
}
while(to_remove.Count > 0) {
Unschedule(to_remove.Dequeue());
}
}
}
public static void Suspend()
{
lock(this_mutex) {
Interlocked.Increment(ref suspend_count);
}
}
public static void Resume()
{
lock(this_mutex) {
Interlocked.Decrement(ref suspend_count);
}
}
public static bool IsScheduled(IJob job)
{
lock(this_mutex) {
if(IsDisposed()) {
return false;
}
return heap.Contains(job);
}
}
public static bool IsScheduled(Type type)
{
lock(this_mutex) {
if(IsDisposed()) {
return false;
}
foreach(IJob job in heap) {
if(job.GetType() == type) {
return true;
}
}
return false;
}
}
public static bool IsInstanceCriticalJobScheduled {
get {
lock(this_mutex) {
if(IsDisposed()) {
return false;
}
foreach(IJob job in heap) {
if(job is IInstanceCriticalJob) {
return true;
}
}
return false;
}
}
}
public static IEnumerable<IJob> ScheduledJobs {
get { lock(this_mutex) { return heap; } }
}
public static int ScheduledJobsCount {
get { lock(this_mutex) { return heap.Count; } }
}
public static void Dispose()
{
lock(this_mutex) {
disposed = true;
}
}
private static bool IsDisposed()
{
if(disposed) {
Debug("Job not unscheduled; disposing scheduler");
return true;
}
return false;
}
private static void CheckRun()
{
if(heap.Count <= 0) {
return;
} else if(job_thread == null) {
Debug("execution thread created");
job_thread = new Thread(new ThreadStart(ProcessJobThread));
job_thread.Priority = ThreadPriority.BelowNormal;
job_thread.IsBackground = true;
job_thread.Start();
}
}
private static void ProcessJobThread()
{
while(true) {
current_running_job = null;
if(suspend_count > 0) {
Thread.Sleep(10);
continue;
}
lock(this_mutex) {
if(disposed) {
Log.Debug ("execution thread destroyed, dispose requested");
return;
}
try {
current_running_job = heap.Pop();
} catch(InvalidOperationException) {
Debug("execution thread destroyed, no more jobs scheduled");
job_thread = null;
return;
}
}
try {
Debug("Job started ({0})", current_running_job);
OnJobStarted(current_running_job);
current_running_job.Run();
Debug("Job ended ({0})", current_running_job);
OnJobFinished(current_running_job);
} catch(Exception e) {
Debug("Job threw an unhandled exception: {0}", e);
}
}
}
public static IJob CurrentJob {
get { return current_running_job; }
}
static void OnJobStarted(IJob job)
{
JobStarted?.Invoke (job);
}
static void OnJobFinished(IJob job)
{
JobFinished?.Invoke (job);
}
static void OnJobScheduled(IJob job)
{
JobScheduled?.Invoke (job);
}
static void OnJobUnscheduled(IJob job)
{
JobUnscheduled?.Invoke (job);
}
static void Debug(string message, params object [] args)
{
if(Banshee.Base.Globals.Debugging) {
Console.Error.WriteLine(string.Format("** Scheduler: {0}", message), args);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Collections.Generic;
using System.Reflection;
namespace System.Runtime.Serialization.Formatters.Binary
{
// This class contains information about an object. It is used so that
// the rest of the Formatter routines can use a common interface for
// a normal object, an ISerializable object, and a surrogate object
internal sealed class WriteObjectInfo
{
internal int _objectInfoId;
internal object _obj;
internal Type _objectType;
internal bool _isSi = false;
internal bool _isNamed = false;
internal bool _isArray = false;
internal SerializationInfo _si = null;
internal SerObjectInfoCache _cache = null;
internal object[] _memberData = null;
internal ISerializationSurrogate _serializationSurrogate = null;
internal StreamingContext _context;
internal SerObjectInfoInit _serObjectInfoInit = null;
// Writing and Parsing information
internal long _objectId;
internal long _assemId;
// Binder information
private string _binderTypeName;
private string _binderAssemblyString;
internal WriteObjectInfo() { }
internal void ObjectEnd()
{
PutObjectInfo(_serObjectInfoInit, this);
}
private void InternalInit()
{
_obj = null;
_objectType = null;
_isSi = false;
_isNamed = false;
_isArray = false;
_si = null;
_cache = null;
_memberData = null;
// Writing and Parsing information
_objectId = 0;
_assemId = 0;
// Binder information
_binderTypeName = null;
_binderAssemblyString = null;
}
internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
{
WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit);
woi.InitSerialize(obj, surrogateSelector, context, serObjectInfoInit, converter, objectWriter, binder);
return woi;
}
// Write constructor
internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
{
_context = context;
_obj = obj;
_serObjectInfoInit = serObjectInfoInit;
_objectType = obj.GetType();
if (_objectType.IsArray)
{
_isArray = true;
InitNoMembers();
return;
}
InvokeSerializationBinder(binder);
objectWriter.ObjectManager.RegisterObject(obj);
ISurrogateSelector surrogateSelectorTemp;
if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out surrogateSelectorTemp)) != null)
{
_si = new SerializationInfo(_objectType, converter);
if (!_objectType.GetTypeInfo().IsPrimitive)
{
_serializationSurrogate.GetObjectData(obj, _si, context);
}
InitSiWrite();
}
else if (obj is ISerializable)
{
if (!_objectType.GetTypeInfo().IsSerializable)
{
throw new SerializationException(SR.Format(SR.Serialization_NonSerType, _objectType.FullName, _objectType.GetTypeInfo().Assembly.FullName));
}
_si = new SerializationInfo(_objectType, converter);
((ISerializable)obj).GetObjectData(_si, context);
InitSiWrite();
CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString);
}
else
{
InitMemberInfo();
CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString);
}
}
internal static WriteObjectInfo Serialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
{
WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit);
woi.InitSerialize(objectType, surrogateSelector, context, serObjectInfoInit, converter, binder);
return woi;
}
// Write Constructor used for array types or null members
internal void InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
{
_objectType = objectType;
_context = context;
_serObjectInfoInit = serObjectInfoInit;
if (objectType.IsArray)
{
InitNoMembers();
return;
}
InvokeSerializationBinder(binder);
ISurrogateSelector surrogateSelectorTemp = null;
if (surrogateSelector != null)
{
_serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp);
}
if (_serializationSurrogate != null)
{
// surrogate does not have this problem since user has pass in through the BF's ctor
_si = new SerializationInfo(objectType, converter);
_cache = new SerObjectInfoCache(objectType);
_isSi = true;
}
else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType))
{
_si = new SerializationInfo(objectType, converter);
_cache = new SerObjectInfoCache(objectType);
CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString);
_isSi = true;
}
if (!_isSi)
{
InitMemberInfo();
CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString);
}
}
private void InitSiWrite()
{
SerializationInfoEnumerator siEnum = null;
_isSi = true;
siEnum = _si.GetEnumerator();
int infoLength = 0;
infoLength = _si.MemberCount;
int count = infoLength;
// For ISerializable cache cannot be saved because each object instance can have different values
// BinaryWriter only puts the map on the wire if the ISerializable map cannot be reused.
TypeInformation typeInformation = null;
string fullTypeName = _si.FullTypeName;
string assemblyString = _si.AssemblyName;
bool hasTypeForwardedFrom = false;
if (!_si.IsFullTypeNameSetExplicit)
{
typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType);
fullTypeName = typeInformation.FullTypeName;
hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom;
}
if (!_si.IsAssemblyNameSetExplicit)
{
if (typeInformation == null)
{
typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType);
}
assemblyString = typeInformation.AssemblyString;
hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom;
}
_cache = new SerObjectInfoCache(fullTypeName, assemblyString, hasTypeForwardedFrom);
_cache._memberNames = new string[count];
_cache._memberTypes = new Type[count];
_memberData = new object[count];
siEnum = _si.GetEnumerator();
for (int i = 0; siEnum.MoveNext(); i++)
{
_cache._memberNames[i] = siEnum.Name;
_cache._memberTypes[i] = siEnum.ObjectType;
_memberData[i] = siEnum.Value;
}
_isNamed = true;
}
private static void CheckTypeForwardedFrom(SerObjectInfoCache cache, Type objectType, string binderAssemblyString)
{
// nop
}
private void InitNoMembers()
{
if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache))
{
_cache = new SerObjectInfoCache(_objectType);
_serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache);
}
}
private void InitMemberInfo()
{
if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache))
{
_cache = new SerObjectInfoCache(_objectType);
_cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context);
int count = _cache._memberInfos.Length;
_cache._memberNames = new string[count];
_cache._memberTypes = new Type[count];
// Calculate new arrays
for (int i = 0; i < count; i++)
{
_cache._memberNames[i] = _cache._memberInfos[i].Name;
_cache._memberTypes[i] = ((FieldInfo)_cache._memberInfos[i]).FieldType;
}
_serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache);
}
if (_obj != null)
{
_memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos);
}
_isNamed = true;
}
internal string GetTypeFullName() => _binderTypeName ?? _cache._fullTypeName;
internal string GetAssemblyString() => _binderAssemblyString ?? _cache._assemblyString;
private void InvokeSerializationBinder(SerializationBinder binder) =>
binder?.BindToName(_objectType, out _binderAssemblyString, out _binderTypeName);
internal void GetMemberInfo(out string[] outMemberNames, out Type[] outMemberTypes, out object[] outMemberData)
{
outMemberNames = _cache._memberNames;
outMemberTypes = _cache._memberTypes;
outMemberData = _memberData;
if (_isSi && !_isNamed)
{
throw new SerializationException(SR.Serialization_ISerializableMemberInfo);
}
}
private static WriteObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit)
{
WriteObjectInfo objectInfo;
if (!serObjectInfoInit._oiPool.IsEmpty())
{
objectInfo = (WriteObjectInfo)serObjectInfoInit._oiPool.Pop();
objectInfo.InternalInit();
}
else
{
objectInfo = new WriteObjectInfo();
objectInfo._objectInfoId = serObjectInfoInit._objectInfoIdCount++;
}
return objectInfo;
}
private static void PutObjectInfo(SerObjectInfoInit serObjectInfoInit, WriteObjectInfo objectInfo) =>
serObjectInfoInit._oiPool.Push(objectInfo);
}
internal sealed class ReadObjectInfo
{
internal int _objectInfoId;
internal static int _readObjectInfoCounter;
internal Type _objectType;
internal ObjectManager _objectManager;
internal int _count;
internal bool _isSi = false;
internal bool _isTyped = false;
internal bool _isSimpleAssembly = false;
internal SerObjectInfoCache _cache;
internal string[] _wireMemberNames;
internal Type[] _wireMemberTypes;
private int _lastPosition = 0;
internal ISerializationSurrogate _serializationSurrogate = null;
internal StreamingContext _context;
// Si Read
internal List<Type> _memberTypesList;
internal SerObjectInfoInit _serObjectInfoInit = null;
internal IFormatterConverter _formatterConverter;
internal ReadObjectInfo() { }
internal void ObjectEnd() { }
internal void PrepareForReuse()
{
_lastPosition = 0;
}
internal static ReadObjectInfo Create(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
{
ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit);
roi.Init(objectType, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly);
return roi;
}
internal void Init(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
{
_objectType = objectType;
_objectManager = objectManager;
_context = context;
_serObjectInfoInit = serObjectInfoInit;
_formatterConverter = converter;
_isSimpleAssembly = bSimpleAssembly;
InitReadConstructor(objectType, surrogateSelector, context);
}
internal static ReadObjectInfo Create(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
{
ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit);
roi.Init(objectType, memberNames, memberTypes, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly);
return roi;
}
internal void Init(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
{
_objectType = objectType;
_objectManager = objectManager;
_wireMemberNames = memberNames;
_wireMemberTypes = memberTypes;
_context = context;
_serObjectInfoInit = serObjectInfoInit;
_formatterConverter = converter;
_isSimpleAssembly = bSimpleAssembly;
if (memberTypes != null)
{
_isTyped = true;
}
if (objectType != null)
{
InitReadConstructor(objectType, surrogateSelector, context);
}
}
private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context)
{
if (objectType.IsArray)
{
InitNoMembers();
return;
}
ISurrogateSelector surrogateSelectorTemp = null;
if (surrogateSelector != null)
{
_serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp);
}
if (_serializationSurrogate != null)
{
_isSi = true;
}
else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType))
{
_isSi = true;
}
if (_isSi)
{
InitSiRead();
}
else
{
InitMemberInfo();
}
}
private void InitSiRead()
{
if (_memberTypesList != null)
{
_memberTypesList = new List<Type>(20);
}
}
private void InitNoMembers()
{
_cache = new SerObjectInfoCache(_objectType);
}
private void InitMemberInfo()
{
_cache = new SerObjectInfoCache(_objectType);
_cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context);
_count = _cache._memberInfos.Length;
_cache._memberNames = new string[_count];
_cache._memberTypes = new Type[_count];
// Calculate new arrays
for (int i = 0; i < _count; i++)
{
_cache._memberNames[i] = _cache._memberInfos[i].Name;
_cache._memberTypes[i] = GetMemberType(_cache._memberInfos[i]);
}
_isTyped = true;
}
// Get the memberInfo for a memberName
internal MemberInfo GetMemberInfo(string name)
{
if (_cache == null)
{
return null;
}
if (_isSi)
{
throw new SerializationException(SR.Format(SR.Serialization_MemberInfo, _objectType + " " + name));
}
if (_cache._memberInfos == null)
{
throw new SerializationException(SR.Format(SR.Serialization_NoMemberInfo, _objectType + " " + name));
}
int position = Position(name);
return position != -1 ? _cache._memberInfos[position] : null;
}
// Get the ObjectType for a memberName
internal Type GetType(string name)
{
int position = Position(name);
if (position == -1)
{
return null;
}
Type type = _isTyped ? _cache._memberTypes[position] : _memberTypesList[position];
if (type == null)
{
throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, _objectType + " " + name));
}
return type;
}
// Adds the value for a memberName
internal void AddValue(string name, object value, ref SerializationInfo si, ref object[] memberData)
{
if (_isSi)
{
si.AddValue(name, value);
}
else
{
// If a member in the stream is not found, ignore it
int position = Position(name);
if (position != -1)
{
memberData[position] = value;
}
}
}
internal void InitDataStore(ref SerializationInfo si, ref object[] memberData)
{
if (_isSi)
{
if (si == null)
{
si = new SerializationInfo(_objectType, _formatterConverter);
}
}
else
{
if (memberData == null && _cache != null)
{
memberData = new object[_cache._memberNames.Length];
}
}
}
// Records an objectId in a member when the actual object for that member is not yet known
internal void RecordFixup(long objectId, string name, long idRef)
{
if (_isSi)
{
_objectManager.RecordDelayedFixup(objectId, name, idRef);
}
else
{
int position = Position(name);
if (position != -1)
{
_objectManager.RecordFixup(objectId, _cache._memberInfos[position], idRef);
}
}
}
// Fills in the values for an object
internal void PopulateObjectMembers(object obj, object[] memberData)
{
if (!_isSi && memberData != null)
{
FormatterServices.PopulateObjectMembers(obj, _cache._memberInfos, memberData);
}
}
// Specifies the position in the memberNames array of this name
private int Position(string name)
{
if (_cache == null)
{
return -1;
}
if (_cache._memberNames.Length > 0 && _cache._memberNames[_lastPosition].Equals(name))
{
return _lastPosition;
}
else if ((++_lastPosition < _cache._memberNames.Length) && (_cache._memberNames[_lastPosition].Equals(name)))
{
return _lastPosition;
}
else
{
// Search for name
for (int i = 0; i < _cache._memberNames.Length; i++)
{
if (_cache._memberNames[i].Equals(name))
{
_lastPosition = i;
return _lastPosition;
}
}
_lastPosition = 0;
return -1;
}
}
// Return the member Types in order of memberNames
internal Type[] GetMemberTypes(string[] inMemberNames, Type objectType)
{
if (_isSi)
{
throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, objectType));
}
if (_cache == null)
{
return null;
}
if (_cache._memberTypes == null)
{
_cache._memberTypes = new Type[_count];
for (int i = 0; i < _count; i++)
{
_cache._memberTypes[i] = GetMemberType(_cache._memberInfos[i]);
}
}
bool memberMissing = false;
if (inMemberNames.Length < _cache._memberInfos.Length)
{
memberMissing = true;
}
Type[] outMemberTypes = new Type[_cache._memberInfos.Length];
bool isFound = false;
for (int i = 0; i < _cache._memberInfos.Length; i++)
{
if (!memberMissing && inMemberNames[i].Equals(_cache._memberInfos[i].Name))
{
outMemberTypes[i] = _cache._memberTypes[i];
}
else
{
// MemberNames on wire in different order then memberInfos returned by reflection
isFound = false;
for (int j = 0; j < inMemberNames.Length; j++)
{
if (_cache._memberInfos[i].Name.Equals(inMemberNames[j]))
{
outMemberTypes[i] = _cache._memberTypes[i];
isFound = true;
break;
}
}
if (!isFound)
{
// A field on the type isn't found. See if the field has OptionalFieldAttribute. We only throw
// when the assembly format is set appropriately.
if (!_isSimpleAssembly &&
_cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) == null)
{
throw new SerializationException(SR.Format(SR.Serialization_MissingMember, _cache._memberNames[i], objectType, typeof(OptionalFieldAttribute).FullName));
}
}
}
}
return outMemberTypes;
}
// Retrieves the member type from the MemberInfo
internal Type GetMemberType(MemberInfo objMember)
{
if (objMember is FieldInfo)
{
return ((FieldInfo)objMember).FieldType;
}
throw new SerializationException(SR.Format(SR.Serialization_SerMemberInfo, objMember.GetType()));
}
private static ReadObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit)
{
ReadObjectInfo roi = new ReadObjectInfo();
roi._objectInfoId = Interlocked.Increment(ref _readObjectInfoCounter);
return roi;
}
}
internal sealed class SerObjectInfoInit
{
internal readonly Dictionary<Type, SerObjectInfoCache> _seenBeforeTable = new Dictionary<Type, SerObjectInfoCache>();
internal int _objectInfoIdCount = 1;
internal SerStack _oiPool = new SerStack("SerObjectInfo Pool");
}
internal sealed class SerObjectInfoCache
{
internal readonly string _fullTypeName;
internal readonly string _assemblyString;
internal readonly bool _hasTypeForwardedFrom;
internal MemberInfo[] _memberInfos;
internal string[] _memberNames;
internal Type[] _memberTypes;
internal SerObjectInfoCache(string typeName, string assemblyName, bool hasTypeForwardedFrom)
{
_fullTypeName = typeName;
_assemblyString = assemblyName;
_hasTypeForwardedFrom = hasTypeForwardedFrom;
}
internal SerObjectInfoCache(Type type)
{
TypeInformation typeInformation = BinaryFormatter.GetTypeInformation(type);
_fullTypeName = typeInformation.FullTypeName;
_assemblyString = typeInformation.AssemblyString;
_hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom;
}
}
internal sealed class TypeInformation
{
internal TypeInformation(string fullTypeName, string assemblyString, bool hasTypeForwardedFrom)
{
FullTypeName = fullTypeName;
AssemblyString = assemblyString;
HasTypeForwardedFrom = hasTypeForwardedFrom;
}
internal string FullTypeName { get; }
internal string AssemblyString { get; }
internal bool HasTypeForwardedFrom { get; }
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Graphics.Drawable.Shapes.cs
//
// 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.
#pragma warning disable 1717
namespace Android.Graphics.Drawable.Shapes
{
/// <summary>
/// <para>Defines a rectangle shape. The rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RectShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/RectShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/RectShape", AccessFlags = 33)]
public partial class RectShape : global::Android.Graphics.Drawable.Shapes.Shape
/* scope: __dot42__ */
{
/// <summary>
/// <para>RectShape constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RectShape() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the RectF that defines this rectangle's bounds. </para>
/// </summary>
/// <java-name>
/// rect
/// </java-name>
[Dot42.DexImport("rect", "()Landroid/graphics/RectF;", AccessFlags = 20)]
protected internal global::Android.Graphics.RectF Rect() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.RectF);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RectShape;", AccessFlags = 1)]
public new virtual global::Android.Graphics.Drawable.Shapes.RectShape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.RectShape);
}
}
/// <summary>
/// <para>Defines an oval shape. The oval can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the OvalShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/OvalShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/OvalShape", AccessFlags = 33)]
public partial class OvalShape : global::Android.Graphics.Drawable.Shapes.RectShape
/* scope: __dot42__ */
{
/// <summary>
/// <para>OvalShape constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public OvalShape() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Creates a rounded-corner rectangle. Optionally, an inset (rounded) rectangle can be included (to make a sort of "O" shape). The rounded rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RoundRectShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/RoundRectShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/RoundRectShape", AccessFlags = 33)]
public partial class RoundRectShape : global::Android.Graphics.Drawable.Shapes.RectShape
/* scope: __dot42__ */
{
/// <summary>
/// <para>RoundRectShape constructor. Specifies an outer (round)rect and an optional inner (round)rect.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "([FLandroid/graphics/RectF;[F)V", AccessFlags = 1)]
public RoundRectShape(float[] outerRadii, global::Android.Graphics.RectF inset, float[] innerRadii) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RoundRectShape;", AccessFlags = 1)]
public new virtual global::Android.Graphics.Drawable.Shapes.RoundRectShape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.RoundRectShape);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RoundRectShape() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Creates geometric paths, utilizing the android.graphics.Path class. The path can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the PathShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/PathShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/PathShape", AccessFlags = 33)]
public partial class PathShape : global::Android.Graphics.Drawable.Shapes.Shape
/* scope: __dot42__ */
{
/// <summary>
/// <para>PathShape constructor.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Landroid/graphics/Path;FF)V", AccessFlags = 1)]
public PathShape(global::Android.Graphics.Path path, float stdWidth, float stdHeight) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/PathShape;", AccessFlags = 1)]
public new virtual global::Android.Graphics.Drawable.Shapes.PathShape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.PathShape);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PathShape() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>Defines a generic graphical "shape." Any Shape can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass it to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/Shape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/Shape", AccessFlags = 1057)]
public abstract partial class Shape : global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Shape() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the width of the Shape. </para>
/// </summary>
/// <java-name>
/// getWidth
/// </java-name>
[Dot42.DexImport("getWidth", "()F", AccessFlags = 17)]
public float GetWidth() /* MethodBuilder.Create */
{
return default(float);
}
/// <summary>
/// <para>Returns the height of the Shape. </para>
/// </summary>
/// <java-name>
/// getHeight
/// </java-name>
[Dot42.DexImport("getHeight", "()F", AccessFlags = 17)]
public float GetHeight() /* MethodBuilder.Create */
{
return default(float);
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1025)]
public abstract void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Resizes the dimensions of this shape. Must be called before draw(Canvas,Paint).</para><para></para>
/// </summary>
/// <java-name>
/// resize
/// </java-name>
[Dot42.DexImport("resize", "(FF)V", AccessFlags = 17)]
public void Resize(float width, float height) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Checks whether the Shape is opaque. Default impl returns true. Override if your subclass can be opaque.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if any part of the drawable is <b>not</b> opaque. </para>
/// </returns>
/// <java-name>
/// hasAlpha
/// </java-name>
[Dot42.DexImport("hasAlpha", "()Z", AccessFlags = 1)]
public virtual bool HasAlpha() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Callback method called when resize(float,float) is executed.</para><para></para>
/// </summary>
/// <java-name>
/// onResize
/// </java-name>
[Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)]
protected internal virtual void OnResize(float width, float height) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/Shape;", AccessFlags = 1)]
public virtual global::Android.Graphics.Drawable.Shapes.Shape Clone() /* MethodBuilder.Create */
{
return default(global::Android.Graphics.Drawable.Shapes.Shape);
}
/// <summary>
/// <para>Returns the width of the Shape. </para>
/// </summary>
/// <java-name>
/// getWidth
/// </java-name>
public float Width
{
[Dot42.DexImport("getWidth", "()F", AccessFlags = 17)]
get{ return GetWidth(); }
}
/// <summary>
/// <para>Returns the height of the Shape. </para>
/// </summary>
/// <java-name>
/// getHeight
/// </java-name>
public float Height
{
[Dot42.DexImport("getHeight", "()F", AccessFlags = 17)]
get{ return GetHeight(); }
}
}
/// <summary>
/// <para>Creates an arc shape. The arc shape starts at a specified angle and sweeps clockwise, drawing slices of pie. The arc can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the ArcShape to a android.graphics.drawable.ShapeDrawable. </para>
/// </summary>
/// <java-name>
/// android/graphics/drawable/shapes/ArcShape
/// </java-name>
[Dot42.DexImport("android/graphics/drawable/shapes/ArcShape", AccessFlags = 33)]
public partial class ArcShape : global::Android.Graphics.Drawable.Shapes.RectShape
/* scope: __dot42__ */
{
/// <summary>
/// <para>ArcShape constructor.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(FF)V", AccessFlags = 1)]
public ArcShape(float startAngle, float sweepAngle) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para>
/// </summary>
/// <java-name>
/// draw
/// </java-name>
[Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)]
public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ArcShape() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| |
// 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 Test.Cryptography;
namespace System.Security.Cryptography.X509Certificates.Tests
{
internal static class TestData
{
public static byte[] MsCertificate = (
"308204ec308203d4a003020102021333000000b011af0a8bd03b9fdd00010000" +
"00b0300d06092a864886f70d01010505003079310b3009060355040613025553" +
"311330110603550408130a57617368696e67746f6e3110300e06035504071307" +
"5265646d6f6e64311e301c060355040a13154d6963726f736f667420436f7270" +
"6f726174696f6e312330210603550403131a4d6963726f736f667420436f6465" +
"205369676e696e6720504341301e170d3133303132343232333333395a170d31" +
"34303432343232333333395a308183310b300906035504061302555331133011" +
"0603550408130a57617368696e67746f6e3110300e060355040713075265646d" +
"6f6e64311e301c060355040a13154d6963726f736f667420436f72706f726174" +
"696f6e310d300b060355040b13044d4f5052311e301c060355040313154d6963" +
"726f736f667420436f72706f726174696f6e30820122300d06092a864886f70d" +
"01010105000382010f003082010a0282010100e8af5ca2200df8287cbc057b7f" +
"adeeeb76ac28533f3adb407db38e33e6573fa551153454a5cfb48ba93fa837e1" +
"2d50ed35164eef4d7adb137688b02cf0595ca9ebe1d72975e41b85279bf3f82d" +
"9e41362b0b40fbbe3bbab95c759316524bca33c537b0f3eb7ea8f541155c0865" +
"1d2137f02cba220b10b1109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5" +
"c90a21e2aae3013647fd2f826a8103f5a935dc94579dfb4bd40e82db388f12fe" +
"e3d67a748864e162c4252e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a6" +
"79b5b6dbcef9707b280184b82a29cfbfa90505e1e00f714dfdad5c238329ebc7" +
"c54ac8e82784d37ec6430b950005b14f6571c50203010001a38201603082015c" +
"30130603551d25040c300a06082b06010505070303301d0603551d0e04160414" +
"5971a65a334dda980780ff841ebe87f9723241f230510603551d11044a3048a4" +
"463044310d300b060355040b13044d4f5052313330310603550405132a333135" +
"39352b34666166306237312d616433372d346161332d613637312d3736626330" +
"35323334346164301f0603551d23041830168014cb11e8cad2b4165801c9372e" +
"331616b94c9a0a1f30560603551d1f044f304d304ba049a0478645687474703a" +
"2f2f63726c2e6d6963726f736f66742e636f6d2f706b692f63726c2f70726f64" +
"756374732f4d6963436f645369675043415f30382d33312d323031302e63726c" +
"305a06082b06010505070101044e304c304a06082b06010505073002863e6874" +
"74703a2f2f7777772e6d6963726f736f66742e636f6d2f706b692f6365727473" +
"2f4d6963436f645369675043415f30382d33312d323031302e637274300d0609" +
"2a864886f70d0101050500038201010031d76e2a12573381d59dc6ebf93ad444" +
"4d089eee5edf6a5bb779cf029cbc76689e90a19c0bc37fa28cf14dba9539fb0d" +
"e0e19bf45d240f1b8d88153a7cdbadceb3c96cba392c457d24115426300d0dff" +
"47ea0307e5e4665d2c7b9d1da910fa1cb074f24f696b9ea92484daed96a0df73" +
"a4ef6a1aac4b629ef17cc0147f48cd4db244f9f03c936d42d8e87ce617a09b68" +
"680928f90297ef1103ba6752adc1e9b373a6d263cd4ae23ee4f34efdffa1e0bb" +
"02133b5d20de553fa3ae9040313875285e04a9466de6f57a7940bd1fcde845d5" +
"aee25d3ef575c7e6666360ccd59a84878d2430f7ef34d0631db142674a0e4bbf" +
"3a0eefb6953aa738e4259208a6886682").HexToByteArray();
public static readonly byte[] MsCertificatePemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN CERTIFICATE-----
MIIE7DCCA9SgAwIBAgITMwAAALARrwqL0Duf3QABAAAAsDANBgkqhkiG9w0BAQUF
ADB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMH
UmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSMwIQYDVQQD
ExpNaWNyb3NvZnQgQ29kZSBTaWduaW5nIFBDQTAeFw0xMzAxMjQyMjMzMzlaFw0x
NDA0MjQyMjMzMzlaMIGDMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv
bjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0
aW9uMQ0wCwYDVQQLEwRNT1BSMR4wHAYDVQQDExVNaWNyb3NvZnQgQ29ycG9yYXRp
b24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDor1yiIA34KHy8BXt/
re7rdqwoUz8620B9s44z5lc/pVEVNFSlz7SLqT+oN+EtUO01Fk7vTXrbE3aIsCzw
WVyp6+HXKXXkG4Unm/P4LZ5BNisLQPu+O7q5XHWTFlJLyjPFN7Dz636o9UEVXAhl
HSE38Cy6IgsQsRCddyKFhHxPuRuQsPWj/ov0DJpOoPXJCiHiquMBNkf9L4JqgQP1
qTXclFed+0vUDoLbOI8S/uPWenSIZOFixCUuKq6dGB8OHrbCryS0DlC83hyTXEmm
ebW22875cHsoAYS4KinPv6kFBeHgD3FN/a1cI4Mp68fFSsjoJ4TTfsZDC5UABbFP
ZXHFAgMBAAGjggFgMIIBXDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQU
WXGmWjNN2pgHgP+EHr6H+XIyQfIwUQYDVR0RBEowSKRGMEQxDTALBgNVBAsTBE1P
UFIxMzAxBgNVBAUTKjMxNTk1KzRmYWYwYjcxLWFkMzctNGFhMy1hNjcxLTc2YmMw
NTIzNDRhZDAfBgNVHSMEGDAWgBTLEejK0rQWWAHJNy4zFha5TJoKHzBWBgNVHR8E
TzBNMEugSaBHhkVodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9k
dWN0cy9NaWNDb2RTaWdQQ0FfMDgtMzEtMjAxMC5jcmwwWgYIKwYBBQUHAQEETjBM
MEoGCCsGAQUFBzAChj5odHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRz
L01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEwLmNydDANBgkqhkiG9w0BAQUFAAOCAQEA
MdduKhJXM4HVncbr+TrURE0Inu5e32pbt3nPApy8dmiekKGcC8N/oozxTbqVOfsN
4OGb9F0kDxuNiBU6fNutzrPJbLo5LEV9JBFUJjANDf9H6gMH5eRmXSx7nR2pEPoc
sHTyT2lrnqkkhNrtlqDfc6TvahqsS2Ke8XzAFH9IzU2yRPnwPJNtQtjofOYXoJto
aAko+QKX7xEDumdSrcHps3Om0mPNSuI+5PNO/f+h4LsCEztdIN5VP6OukEAxOHUo
XgSpRm3m9Xp5QL0fzehF1a7iXT71dcfmZmNgzNWahIeNJDD37zTQYx2xQmdKDku/
Og7vtpU6pzjkJZIIpohmgg==
-----END CERTIFICATE-----
");
public const string PfxDataPassword = "12345";
public static byte[] PfxData = (
"308206a20201033082065e06092a864886f70d010701a082064f0482064b3082" +
"0647308203c006092a864886f70d010701a08203b1048203ad308203a9308203" +
"a5060b2a864886f70d010c0a0102a08202b6308202b2301c060a2a864886f70d" +
"010c0103300e04085052002c7da2c2a6020207d0048202907d485e3bfc6e6457" +
"c811394c145d0e8a18325646854e4ff0097bc5a98547f5ad616c8efda8505aa8" +
"7564ed4800a3139759497c60c6688b51f376acae906429c8771cb1428226b68a" +
"6297207bcc9dd7f9563478dd83880aab2304b545759b2275305df4eff9fac24a" +
"3cc9d3b2d672efe45d8f48e24a16506c1d7566fc6d1b269fbf201b3ac3309d3e" +
"bc6fd606257a7a707aa2f790ea3fe7a94a51138540c5319010cba6de9fb9d85f" +
"cdc78da60e33df2f21c46fb9a8554b4f82e0a6edba4db5585d77d331d35daaed" +
"51b6a5a3e000a299880fb799182c8ca3004b7837a9feb8bfc76778089993f3d1" +
"1d70233608af7c50722d680623d2bf54bd4b1e7a604184d9f44e0af8099ffa47" +
"1e5536e7902793829db9902ddb61264a62962950ad274ea516b2d44be9036530" +
"016e607b73f341aeefed2211f6330364738b435b0d2ed6c57747f6c8230a053f" +
"78c4dd65db83b26c6a47836a6cbbab92cbb262c6fb6d08632b4457f5fa8eabfa" +
"65db34157e1d301e9085cc443582cdd15404314872748545eb3fc3c574882655" +
"8c9a85f966e315775bbe9da34d1e8b6dadc3c9e120c6d6a2e1cffe4eb014c3ce" +
"fbc19356ce33dac60f93d67a4de247b0dae13cd8b8c9f15604cc0ec9968e3ad7" +
"f57c9f53c45e2ecb0a0945ec0ba04baa15b48d8596edc9f5fe9165a5d21949fb" +
"5fe30a920ad2c0f78799f6443c300629b8ca4dca19b9dbf1e27aab7b12271228" +
"119a95c9822be6439414beeae24002b46eb97e030e18bd810ade0bcf4213a355" +
"038b56584b2fbcc3f5ea215d0cf667ffd823ea03ab62c3b193dfb4450aabb50b" +
"af306e8088ee7384fa2fdff03e0dd7acd61832223e806a94d46e196462522808" +
"3163f1caf333fdbbe2d54ca86968867ce0b6dd5e5b7f0633c6fab4a19cc14f64" +
"5ec14d0b1436f7623181db301306092a864886f70d0109153106040401000000" +
"305d06092b060104018237110131501e4e004d006900630072006f0073006f00" +
"6600740020005300740072006f006e0067002000430072007900700074006f00" +
"67007200610070006800690063002000500072006f0076006900640065007230" +
"6506092a864886f70d01091431581e5600500076006b0054006d0070003a0034" +
"0064006100340061003100650036002d0066003700380062002d003400360061" +
"0035002d0039003800380033002d003500320063003800330032006100340063" +
"0030006100623082027f06092a864886f70d010706a08202703082026c020100" +
"3082026506092a864886f70d010701301c060a2a864886f70d010c0106300e04" +
"08e0c117e67a75d8eb020207d080820238292882408b31826f0dc635f9bbe7c1" +
"99a48a3b4fefc729dbf95508d6a7d04805a8dd612427f93124f522ac7d3c6f4d" +
"db74d937f57823b5b1e8cfae4ece4a1fffd801558d77ba31985aa7f747d834cb" +
"e84464ef777718c9865c819d6c9daa0fa25e2a2a80b3f2aaa67d40e382eb084c" +
"ca85e314ea40c3ef3ed1593904d7a16f37807c99af06c917093f6c5aaebb12a6" +
"c58c9956d4fbbdde1f1e389989c36e19dd38d4b978d6f47131e458ab68e237e4" +
"0cb6a87f21c8773de845780b50995a51f041106f47c740b3bd946038984f1ac9" +
"e91230616480962f11b0683f8802173c596c4bd554642f51a76f9dfff9053def" +
"7b3c3f759fc7eeac3f2386106c4b8cb669589e004fb235f0357ea5cf0b5a6fc7" +
"8a6d941a3ae44af7b601b59d15cd1ec61bccc481fbb83eae2f83153b41e71ef7" +
"6a2814ab59347f116ab3e9c1621668a573013d34d13d3854e604286733c6bad0" +
"f511d7f8fd6356f7c3198d0cb771af27f4b5a3c3b571fdd083fd68a9a1eea783" +
"152c436f7513613a7e399a1da48d7e55db7504dc47d1145df8d7b6d32eaa4cce" +
"e06f98bb3dda2cc0d0564a962f86dfb122e4f7e2ed6f1b509c58d4a3b2d0a687" +
"88f7e313aecfbdef456c31b96fc13586e02aeb65807ed83bb0cb7c28f157bc95" +
"c9c593c9194691539ae3c620ed1d4d4af0177f6b9483a5341d7b084bc5b425af" +
"b658168ee2d8fb2bfab07a3ba061687a5ecd1f8da9001dd3e7be793923094abb" +
"0f2cf4d24cb071b9e568b18336bb4dc541352c9785c48d0f0e53066eb2009efc" +
"b3e5644ed12252c1bc303b301f300706052b0e03021a0414f90827ae93fd3a91" +
"54c3c0840d7950b0e30ffbaf0414e147930b932899741c92d765226893877025" +
"4a2b020207d0").HexToByteArray();
public static byte[] StoreSavedAsPfxData = (
"3082070406092a864886f70d010702a08206f5308206f10201013100300b0609" +
"2a864886f70d010701a08206d9308201e530820152a0030201020210d5b5bc1c" +
"458a558845bff51cb4dff31c300906052b0e03021d05003011310f300d060355" +
"040313064d794e616d65301e170d3130303430313038303030305a170d313130" +
"3430313038303030305a3011310f300d060355040313064d794e616d6530819f" +
"300d06092a864886f70d010101050003818d0030818902818100b11e30ea8742" +
"4a371e30227e933ce6be0e65ff1c189d0d888ec8ff13aa7b42b68056128322b2" +
"1f2b6976609b62b6bc4cf2e55ff5ae64e9b68c78a3c2dacc916a1bc7322dd353" +
"b32898675cfb5b298b176d978b1f12313e3d865bc53465a11cca106870a4b5d5" +
"0a2c410938240e92b64902baea23eb093d9599e9e372e48336730203010001a3" +
"46304430420603551d01043b3039801024859ebf125e76af3f0d7979b4ac7a96" +
"a1133011310f300d060355040313064d794e616d658210d5b5bc1c458a558845" +
"bff51cb4dff31c300906052b0e03021d0500038181009bf6e2cf830ed485b86d" +
"6b9e8dffdcd65efc7ec145cb9348923710666791fcfa3ab59d689ffd7234b787" +
"2611c5c23e5e0714531abadb5de492d2c736e1c929e648a65cc9eb63cd84e57b" +
"5909dd5ddf5dbbba4a6498b9ca225b6e368b94913bfc24de6b2bd9a26b192b95" +
"7304b89531e902ffc91b54b237bb228be8afcda26476308204ec308203d4a003" +
"020102021333000000b011af0a8bd03b9fdd0001000000b0300d06092a864886" +
"f70d01010505003079310b300906035504061302555331133011060355040813" +
"0a57617368696e67746f6e3110300e060355040713075265646d6f6e64311e30" +
"1c060355040a13154d6963726f736f667420436f72706f726174696f6e312330" +
"210603550403131a4d6963726f736f667420436f6465205369676e696e672050" +
"4341301e170d3133303132343232333333395a170d3134303432343232333333" +
"395a308183310b3009060355040613025553311330110603550408130a576173" +
"68696e67746f6e3110300e060355040713075265646d6f6e64311e301c060355" +
"040a13154d6963726f736f667420436f72706f726174696f6e310d300b060355" +
"040b13044d4f5052311e301c060355040313154d6963726f736f667420436f72" +
"706f726174696f6e30820122300d06092a864886f70d01010105000382010f00" +
"3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" +
"407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" +
"137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" +
"b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" +
"109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" +
"2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" +
"2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" +
"84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" +
"0b950005b14f6571c50203010001a38201603082015c30130603551d25040c30" +
"0a06082b06010505070303301d0603551d0e041604145971a65a334dda980780" +
"ff841ebe87f9723241f230510603551d11044a3048a4463044310d300b060355" +
"040b13044d4f5052313330310603550405132a33313539352b34666166306237" +
"312d616433372d346161332d613637312d373662633035323334346164301f06" +
"03551d23041830168014cb11e8cad2b4165801c9372e331616b94c9a0a1f3056" +
"0603551d1f044f304d304ba049a0478645687474703a2f2f63726c2e6d696372" +
"6f736f66742e636f6d2f706b692f63726c2f70726f64756374732f4d6963436f" +
"645369675043415f30382d33312d323031302e63726c305a06082b0601050507" +
"0101044e304c304a06082b06010505073002863e687474703a2f2f7777772e6d" +
"6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f64536967" +
"5043415f30382d33312d323031302e637274300d06092a864886f70d01010505" +
"00038201010031d76e2a12573381d59dc6ebf93ad4444d089eee5edf6a5bb779" +
"cf029cbc76689e90a19c0bc37fa28cf14dba9539fb0de0e19bf45d240f1b8d88" +
"153a7cdbadceb3c96cba392c457d24115426300d0dff47ea0307e5e4665d2c7b" +
"9d1da910fa1cb074f24f696b9ea92484daed96a0df73a4ef6a1aac4b629ef17c" +
"c0147f48cd4db244f9f03c936d42d8e87ce617a09b68680928f90297ef1103ba" +
"6752adc1e9b373a6d263cd4ae23ee4f34efdffa1e0bb02133b5d20de553fa3ae" +
"9040313875285e04a9466de6f57a7940bd1fcde845d5aee25d3ef575c7e66663" +
"60ccd59a84878d2430f7ef34d0631db142674a0e4bbf3a0eefb6953aa738e425" +
"9208a68866823100").HexToByteArray();
public static byte[] StoreSavedAsCerData = (
"308201e530820152a0030201020210d5b5bc1c458a558845bff51cb4dff31c30" +
"0906052b0e03021d05003011310f300d060355040313064d794e616d65301e17" +
"0d3130303430313038303030305a170d3131303430313038303030305a301131" +
"0f300d060355040313064d794e616d6530819f300d06092a864886f70d010101" +
"050003818d0030818902818100b11e30ea87424a371e30227e933ce6be0e65ff" +
"1c189d0d888ec8ff13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55f" +
"f5ae64e9b68c78a3c2dacc916a1bc7322dd353b32898675cfb5b298b176d978b" +
"1f12313e3d865bc53465a11cca106870a4b5d50a2c410938240e92b64902baea" +
"23eb093d9599e9e372e48336730203010001a346304430420603551d01043b30" +
"39801024859ebf125e76af3f0d7979b4ac7a96a1133011310f300d0603550403" +
"13064d794e616d658210d5b5bc1c458a558845bff51cb4dff31c300906052b0e" +
"03021d0500038181009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb93" +
"48923710666791fcfa3ab59d689ffd7234b7872611c5c23e5e0714531abadb5d" +
"e492d2c736e1c929e648a65cc9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca" +
"225b6e368b94913bfc24de6b2bd9a26b192b957304b89531e902ffc91b54b237" +
"bb228be8afcda26476").HexToByteArray();
public static byte[] StoreSavedAsSerializedCerData = (
"0200000001000000bc0000001c0000006c000000010000000000000000000000" +
"00000000020000007b00370037004500420044003000320044002d0044003800" +
"440045002d0034003700350041002d0038003800360037002d00440032003000" +
"4200300030003600340045003400390046007d00000000004d00690063007200" +
"6f0073006f006600740020005300740072006f006e0067002000430072007900" +
"700074006f0067007200610070006800690063002000500072006f0076006900" +
"64006500720000002000000001000000e9010000308201e530820152a0030201" +
"020210d5b5bc1c458a558845bff51cb4dff31c300906052b0e03021d05003011" +
"310f300d060355040313064d794e616d65301e170d3130303430313038303030" +
"305a170d3131303430313038303030305a3011310f300d060355040313064d79" +
"4e616d6530819f300d06092a864886f70d010101050003818d00308189028181" +
"00b11e30ea87424a371e30227e933ce6be0e65ff1c189d0d888ec8ff13aa7b42" +
"b68056128322b21f2b6976609b62b6bc4cf2e55ff5ae64e9b68c78a3c2dacc91" +
"6a1bc7322dd353b32898675cfb5b298b176d978b1f12313e3d865bc53465a11c" +
"ca106870a4b5d50a2c410938240e92b64902baea23eb093d9599e9e372e48336" +
"730203010001a346304430420603551d01043b3039801024859ebf125e76af3f" +
"0d7979b4ac7a96a1133011310f300d060355040313064d794e616d658210d5b5" +
"bc1c458a558845bff51cb4dff31c300906052b0e03021d0500038181009bf6e2" +
"cf830ed485b86d6b9e8dffdcd65efc7ec145cb9348923710666791fcfa3ab59d" +
"689ffd7234b7872611c5c23e5e0714531abadb5de492d2c736e1c929e648a65c" +
"c9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca225b6e368b94913bfc24de6b" +
"2bd9a26b192b957304b89531e902ffc91b54b237bb228be8afcda26476").HexToByteArray();
public static byte[] StoreSavedAsSerializedStoreData = (
"00000000434552540200000001000000bc0000001c0000006c00000001000000" +
"000000000000000000000000020000007b003700370045004200440030003200" +
"44002d0044003800440045002d0034003700350041002d003800380036003700" +
"2d004400320030004200300030003600340045003400390046007d0000000000" +
"4d006900630072006f0073006f006600740020005300740072006f006e006700" +
"2000430072007900700074006f00670072006100700068006900630020005000" +
"72006f007600690064006500720000002000000001000000e9010000308201e5" +
"30820152a0030201020210d5b5bc1c458a558845bff51cb4dff31c300906052b" +
"0e03021d05003011310f300d060355040313064d794e616d65301e170d313030" +
"3430313038303030305a170d3131303430313038303030305a3011310f300d06" +
"0355040313064d794e616d6530819f300d06092a864886f70d01010105000381" +
"8d0030818902818100b11e30ea87424a371e30227e933ce6be0e65ff1c189d0d" +
"888ec8ff13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55ff5ae64e9" +
"b68c78a3c2dacc916a1bc7322dd353b32898675cfb5b298b176d978b1f12313e" +
"3d865bc53465a11cca106870a4b5d50a2c410938240e92b64902baea23eb093d" +
"9599e9e372e48336730203010001a346304430420603551d01043b3039801024" +
"859ebf125e76af3f0d7979b4ac7a96a1133011310f300d060355040313064d79" +
"4e616d658210d5b5bc1c458a558845bff51cb4dff31c300906052b0e03021d05" +
"00038181009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb9348923710" +
"666791fcfa3ab59d689ffd7234b7872611c5c23e5e0714531abadb5de492d2c7" +
"36e1c929e648a65cc9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca225b6e36" +
"8b94913bfc24de6b2bd9a26b192b957304b89531e902ffc91b54b237bb228be8" +
"afcda264762000000001000000f0040000308204ec308203d4a0030201020213" +
"33000000b011af0a8bd03b9fdd0001000000b0300d06092a864886f70d010105" +
"05003079310b3009060355040613025553311330110603550408130a57617368" +
"696e67746f6e3110300e060355040713075265646d6f6e64311e301c06035504" +
"0a13154d6963726f736f667420436f72706f726174696f6e3123302106035504" +
"03131a4d6963726f736f667420436f6465205369676e696e6720504341301e17" +
"0d3133303132343232333333395a170d3134303432343232333333395a308183" +
"310b3009060355040613025553311330110603550408130a57617368696e6774" +
"6f6e3110300e060355040713075265646d6f6e64311e301c060355040a13154d" +
"6963726f736f667420436f72706f726174696f6e310d300b060355040b13044d" +
"4f5052311e301c060355040313154d6963726f736f667420436f72706f726174" +
"696f6e30820122300d06092a864886f70d01010105000382010f003082010a02" +
"82010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb407db38e33" +
"e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb137688b02c" +
"f0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bbab95c759316" +
"524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1109d772285" +
"847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd2f826a8103" +
"f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c4252e2aae9d18" +
"1f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b280184b82a29cf" +
"bfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec6430b950005b1" +
"4f6571c50203010001a38201603082015c30130603551d25040c300a06082b06" +
"010505070303301d0603551d0e041604145971a65a334dda980780ff841ebe87" +
"f9723241f230510603551d11044a3048a4463044310d300b060355040b13044d" +
"4f5052313330310603550405132a33313539352b34666166306237312d616433" +
"372d346161332d613637312d373662633035323334346164301f0603551d2304" +
"1830168014cb11e8cad2b4165801c9372e331616b94c9a0a1f30560603551d1f" +
"044f304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f6674" +
"2e636f6d2f706b692f63726c2f70726f64756374732f4d6963436f6453696750" +
"43415f30382d33312d323031302e63726c305a06082b06010505070101044e30" +
"4c304a06082b06010505073002863e687474703a2f2f7777772e6d6963726f73" +
"6f66742e636f6d2f706b692f63657274732f4d6963436f645369675043415f30" +
"382d33312d323031302e637274300d06092a864886f70d010105050003820101" +
"0031d76e2a12573381d59dc6ebf93ad4444d089eee5edf6a5bb779cf029cbc76" +
"689e90a19c0bc37fa28cf14dba9539fb0de0e19bf45d240f1b8d88153a7cdbad" +
"ceb3c96cba392c457d24115426300d0dff47ea0307e5e4665d2c7b9d1da910fa" +
"1cb074f24f696b9ea92484daed96a0df73a4ef6a1aac4b629ef17cc0147f48cd" +
"4db244f9f03c936d42d8e87ce617a09b68680928f90297ef1103ba6752adc1e9" +
"b373a6d263cd4ae23ee4f34efdffa1e0bb02133b5d20de553fa3ae9040313875" +
"285e04a9466de6f57a7940bd1fcde845d5aee25d3ef575c7e6666360ccd59a84" +
"878d2430f7ef34d0631db142674a0e4bbf3a0eefb6953aa738e4259208a68866" +
"82000000000000000000000000").HexToByteArray();
public static byte[] DssCer = (
"3082025d3082021da00302010202101e9ae1e91e07de8640ac7af21ac22e8030" +
"0906072a8648ce380403300e310c300a06035504031303466f6f301e170d3135" +
"303232343232313734375a170d3136303232343232313734375a300e310c300a" +
"06035504031303466f6f308201b73082012c06072a8648ce3804013082011f02" +
"818100871018cc42552d14a5a9286af283f3cfba959b8835ec2180511d0dceb8" +
"b979285708c800fc10cb15337a4ac1a48ed31394072015a7a6b525986b49e5e1" +
"139737a794833c1aa1e0eaaa7e9d4efeb1e37a65dbc79f51269ba41e8f0763aa" +
"613e29c81c3b977aeeb3d3c3f6feb25c270cdcb6aee8cd205928dfb33c44d2f2" +
"dbe819021500e241edcf37c1c0e20aadb7b4e8ff7aa8fde4e75d02818100859b" +
"5aeb351cf8ad3fabac22ae0350148fd1d55128472691709ec08481584413e9e5" +
"e2f61345043b05d3519d88c021582ccef808af8f4b15bd901a310fefd518af90" +
"aba6f85f6563db47ae214a84d0b7740c9394aa8e3c7bfef1beedd0dafda079bf" +
"75b2ae4edb7480c18b9cdfa22e68a06c0685785f5cfb09c2b80b1d05431d0381" +
"8400028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371e" +
"bf07bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a" +
"0707ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638bec" +
"ca7786312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3" +
"f2f8bf0963300906072a8648ce380403032f00302c021461f6d143a47a4f7e0e" +
"0ef9848b7f83eacbf83ffd021420e2ac47e656874633e01b0d207a99280c1127" +
"01").HexToByteArray();
public static byte[] CertWithPolicies = (
"308201f33082015ca0030201020210134fb7082cf69bbb4930bfc8e1ca446130" +
"0d06092a864886f70d0101050500300e310c300a06035504031303466f6f301e" +
"170d3135303330313232343735385a170d3136303330313034343735385a300e" +
"310c300a06035504031303466f6f30819f300d06092a864886f70d0101010500" +
"03818d0030818902818100c252d52fb96658ddbb7d19dd9caaf203ec0376f77c" +
"3012bd93e14bb22a6ff2b5ce8060a197e3fd8289fbff826746baae0db8d68b47" +
"a1cf13678717d7db9a16dab028927173a3e843b3a7df8c5a4ff675957ea20703" +
"6389a60a83d643108bd1293e2135a672a1cff10b7d5b3c78ab44d35e20ca6a5c" +
"5b6f714c5bfd66ed4307070203010001a3523050301b06092b06010401823714" +
"02040e1e0c00480065006c006c006f0000301a06092b0601040182371507040d" +
"300b060357080902010302010230150603551d20040e300c3004060262133004" +
"06027021300d06092a864886f70d0101050500038181001be04e59fbea63acfb" +
"c8b6fd3d02dd7442532344cfbc124e924c0bacf23865e4ce2f442ad60ae457d8" +
"4f7a1f05d50fb867c20e778e412a25237054555669ced01c1ce1ba8e8e57510f" +
"73e1167c920f78aa5415dc5281f0c761fb25bb1ebc707bc003dd90911e649915" +
"918cfe4f3176972f8afdc1cccd9705e7fb307a0c17d273").HexToByteArray();
public static byte[] CertWithTemplateData = (
"308201dc30820145a00302010202105101b8242daf6cae4c53bac68a948b0130" +
"0d06092a864886f70d0101050500300e310c300a06035504031303466f6f301e" +
"170d3135303330313232333133395a170d3136303330313034333133395a300e" +
"310c300a06035504031303466f6f30819f300d06092a864886f70d0101010500" +
"03818d0030818902818100a6dcff50bd1fe420301fea5fa56be93a7a53f2599c" +
"e453cf3422bec797bac0ed78a03090a3754569e6494bcd585ac16a5ea5086344" +
"3f25521085ca09580579cf0b46bd6e50015319fba5d2bd3724c53b20cdddf604" +
"74bd7ef426aead9ca5ffea275a4b2b1b6f87c203ab8783559b75e319722886fb" +
"eb784f5f06823906b2a9950203010001a33b3039301b06092b06010401823714" +
"02040e1e0c00480065006c006c006f0000301a06092b0601040182371507040d" +
"300b0603570809020103020102300d06092a864886f70d010105050003818100" +
"962594da079523c26e2d3fc573fd17189ca33bedbeb2c38c92508fc2a865973b" +
"e85ba686f765101aea0a0391b22fcfa6c0760eece91a0eb75501bf6871553f8d" +
"6b089cf2ea63c872e0b4a178795b71826c4569857b45994977895e506dfb8075" +
"ed1b1096987f2c8f65f2d6bbc788b1847b6ba13bee17ef6cb9c6a3392e13003f").HexToByteArray();
public static byte[] ComplexNameInfoCert = (
"308204BE30820427A00302010202080123456789ABCDEF300D06092A864886F70" +
"D01010505003081A43110300E06035504061307436F756E747279310E300C0603" +
"550408130553746174653111300F060355040713084C6F63616C6974793111300" +
"F060355040A13084578616D706C654F31123010060355040B13094578616D706C" +
"654F55311E301C06035504031315636E2E6973737565722E6578616D706C652E6" +
"F72673126302406092A864886F70D0109011617697373756572656D61696C4065" +
"78616D706C652E6F7267301E170D3133313131323134313531365A170D3134313" +
"231333135313631375A3081A63110300E06035504061307436F756E747279310E" +
"300C0603550408130553746174653111300F060355040713084C6F63616C69747" +
"93111300F060355040A13084578616D706C654F31123010060355040B13094578" +
"616D706C654F55311F301D06035504031316636E2E7375626A6563742E6578616" +
"D706C652E6F72673127302506092A864886F70D01090116187375626A65637465" +
"6D61696C406578616D706C652E6F7267305C300D06092A864886F70D010101050" +
"0034B003048024100DC6FBBDA0300520DFBC9F046CC865D8876AEAC353807EA84" +
"F58F92FE45EE03C22E970CAF41031D47F97C8A5117C62718482911A8A31B58D92" +
"328BA3CF9E605230203010001A382023730820233300B0603551D0F0404030200" +
"B0301D0603551D250416301406082B0601050507030106082B060105050703023" +
"081FD0603551D120481F53081F28217646E73312E6973737565722E6578616D70" +
"6C652E6F72678217646E73322E6973737565722E6578616D706C652E6F7267811" +
"569616E656D61696C31406578616D706C652E6F7267811569616E656D61696C32" +
"406578616D706C652E6F7267A026060A2B060104018237140203A0180C1669737" +
"375657275706E31406578616D706C652E6F7267A026060A2B0601040182371402" +
"03A0180C1669737375657275706E32406578616D706C652E6F7267861F6874747" +
"03A2F2F757269312E6973737565722E6578616D706C652E6F72672F861F687474" +
"703A2F2F757269322E6973737565722E6578616D706C652E6F72672F308201030" +
"603551D110481FB3081F88218646E73312E7375626A6563742E6578616D706C65" +
"2E6F72678218646E73322E7375626A6563742E6578616D706C652E6F726781157" +
"3616E656D61696C31406578616D706C652E6F7267811573616E656D61696C3240" +
"6578616D706C652E6F7267A027060A2B060104018237140203A0190C177375626" +
"A65637475706E31406578616D706C652E6F7267A027060A2B0601040182371402" +
"03A0190C177375626A65637475706E32406578616D706C652E6F7267862068747" +
"4703A2F2F757269312E7375626A6563742E6578616D706C652E6F72672F862068" +
"7474703A2F2F757269322E7375626A6563742E6578616D706C652E6F72672F300" +
"D06092A864886F70D0101050500038181005CD44A247FF4DFBF2246CC04D7D57C" +
"EF2B6D3A4BC83FF685F6B5196B65AFC8F992BE19B688E53E353EEA8B63951EC40" +
"29008DE8B851E2C30B6BF73F219BCE651E5972E62D651BA171D1DA9831A449D99" +
"AF4E2F4B9EE3FD0991EF305ADDA633C44EB5E4979751280B3F54F9CCD561AC27D" +
"3426BC6FF32E8E1AAF9F7C0150A726B").HexToByteArray();
internal static readonly byte[] MultiPrivateKeyPfx = (
"30820FD102010330820F9106092A864886F70D010701A0820F8204820F7E3082" +
"0F7A3082076306092A864886F70D010701A0820754048207503082074C308203" +
"A9060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" +
"010C0103300E0408ED42EEFCD77BB2EB020207D00482029048F341D409492D23" +
"D89C0C01DEE7EFFB6715B15D2BB558E9045D635CADFFFEC85C10A4849AB0657D" +
"A17FE7EC578F779BA2DC129FA959664DC7E85DFD13CAC673E487208FE457223A" +
"75732915FFCF3FF70F557B0846D62AD507300EA1770EDED82F7D8E6E75075728" +
"A29D3BF829E75F09EF283A9DDEDDFBABC2E25698DA8C24E4FE34CD43C87554BF" +
"55B1D4B2B0979F399AEC95B781C62CBE9E412329F9A9BCABF20F716A95F1D795" +
"7C379A27587F6BBFA44A0B75FAAC15CA3730629C55E87990EE521BC4657EE2A4" +
"41AF099A226D31707685A89A28EB27CA65512B70DEC09231369AA1A265D4F5C3" +
"C5D17CB11DB54C70AB83EA28F4740D1F79D490F46F926FB267D5F0E4B2FE096D" +
"F161A4FF9E9AC068EFCA999B3ED0A3BD05D8D1E3B67CF51E6A478154B427D87D" +
"C861D0FE2A7A42600483D7B979DC71E8A00D0E805E3BB86E8673234DC1D14987" +
"99272754A5FD5FEC118CF1E2B2A539B604FED5486A4E4D73FAAFF69023263B84" +
"6870D6B8DB01E31CB3A1E4BA3588C1FA81C786745A33B95573D5381AB307827A" +
"549A36AF535FD05E1247BB92C6C6FCB0E76E87F2E4C8136F37C9C19BE3001F59" +
"FC5CB459C620B8E73711BF102D78F665F40E4D1A341370BC1FB7A5567C29359C" +
"FFB938237002904BE59F5605AF96E8A670E2248AB71D27FE63E327077144F095" +
"4CA815E0284E2FF5E1A11B2946276A99B91BF138A79B057436798AF72FD86842" +
"881C5A5ECDA8A961A21553CC930703047F1F45699CEFEF26AAB6B7DBC65C8C62" +
"4CA3286094596F2AA48268B9F5411058613185507332833AFB312D5780CEFF96" +
"6DD05A2CB6E1B252D9656D8E92E63E6C0360F119232E954E11DE777D2DE1C208" +
"F704DDB16E1351F49B42A859E3B6B2D94E1E2B3CD97F06B1123E9CCA049201E6" +
"DB7273C0BDE63CC93181DF301306092A864886F70D0109153106040401000000" +
"305B06092A864886F70D010914314E1E4C007B00310036004200340039004300" +
"320045002D0036004400390043002D0034003200440042002D00410034004500" +
"39002D003000320036003000430030004100450032003600300034007D306B06" +
"092B0601040182371101315E1E5C004D006900630072006F0073006F00660074" +
"00200045006E00680061006E006300650064002000430072007900700074006F" +
"0067007200610070006800690063002000500072006F00760069006400650072" +
"002000760031002E00303082039B060B2A864886F70D010C0A0102A08202B630" +
"8202B2301C060A2A864886F70D010C0103300E04081F85B7ED57F6F934020207" +
"D00482029051A5ADA683AAE06A699761CCF05CB081A4398A7B1256A25084DBE1" +
"115BFAB07A5A9146BC22F2E4223FF25BCA1836AE218691815F20A27A1B98D1FC" +
"78F84AFA7E90A55954EE5BEA47FFA35928A990CB47346767F6F4212DBCD03FFF" +
"1E4D137979006B46B19A9FC3BC9B5036ED6F8582E2007D08DB94B2B576E15471" +
"9CAC90DFB6F238CA875FCBEBCF9E9F933E4451E6A2B60C2A0A8A35B5FD20E5DD" +
"A000008DCCE95BBDF604A8F93001F594E402FF8649A6582DE5901EDF9DED7D6F" +
"9657C5A184D82690EFCFB2F25BFCE02BC56F0FF00595996EBF1BA25475AB6134" +
"61280DD641186237D8A3AB257BD6FB1BDC3768B00719D233E0D5FD26D08BA6EA" +
"B29D732B990FB9423E643E4663ABBA0D8885DD2A276EE02C92778261C7853F70" +
"8E2B9AF8D2E96416F676D0191BD24D0C8430BD419049F43C8E2A0C32F862207B" +
"3DA661577CE5933460D0EF69FAD7323098B55FEF3A9955FE632FBCE8452BB5F3" +
"430AE2A9021EBF756CC7FDFC3E63581C8B0D7AB77760F447F868B5923614DAA9" +
"C36AEBC67DC854B93C38E8A6D3AC11B1EE1D02855CE96ADEB840B626BFC4B3BF" +
"D6487C9073F8A15F55BA945D58AD1636A7AED476EBDB5227A71144BF8745192E" +
"F5CD177818F61836717ED9EB0A83BEEE582ADEDD407035E453083B17E7C23700" +
"9D9F04F355CEAB0C0E9AD6F13A3B54459FA05B19E02275FE2588258B63A125F5" +
"49D1B44C827CDC94260A02F4A1B42A30E675B9760D876685D6CA05C25803BDE1" +
"F33D325CF6020A662B0F5DCCC8D77B941B273AC462F0D3E050CEB5AEF7107C45" +
"372F7063EF1AB420CA555A6C9BE6E1067966755584346CDDE7C05B6132E553B1" +
"1C374DB90B54E5C096062349A1F6CB78A1A2D995C483541750CFA956DEA0EB36" +
"67DE7AD78931C65B6E039B5DE461810B68C344D2723181D1301306092A864886" +
"F70D0109153106040402000000305B06092A864886F70D010914314E1E4C007B" +
"00390044004500340033003500380036002D0039003100320043002D00340036" +
"00370036002D0042003500410041002D00420046004200360030003900370030" +
"0035003800350041007D305D06092B060104018237110131501E4E004D006900" +
"630072006F0073006F006600740020005300740072006F006E00670020004300" +
"72007900700074006F0067007200610070006800690063002000500072006F00" +
"7600690064006500723082080F06092A864886F70D010706A0820800308207FC" +
"020100308207F506092A864886F70D010701301C060A2A864886F70D010C0106" +
"300E04089ADEE71816BCD023020207D0808207C851AA1EA533FECABB26D3846F" +
"AEE8DEDB919C29F8B98BBBF785BC306C12A8ACB1437786C4689161683718BB7E" +
"40EB60D9BE0C87056B5ECF20ACCB8BF7F36033B8FCB84ED1474E97DE0A8709B5" +
"63B6CF8E69DF4B3F970C92324946723C32D08B7C3A76C871C6B6C8C56F2D3C4C" +
"00B8A809E65A4EB5EFECC011E2B10F0E44ECDA07B325417B24924080844F6D7F" +
"1F6E420346EA85825EB830C7E05A5383412A9502A51F1AC07F315ADE357F1F9F" +
"B2E6427976E78B8FF9CD6C2F9841F2D84658AC8747694EFD0C451B7AC5B83D5F" +
"0780808417501666BB452B53CEB0698162D94541DE181A7968DB139F17A1076E" +
"DEB70B38B8881DBC6DE2B694070A5A1AA71E4CDFBF7F4D5DBCF16646768364D3" +
"C74FA212E40CBE3BE7C51A74D271164D00E89F997FD418C51A7C2D73130D7C6F" +
"CAA2CA65082CE38BFB753BB30CC71656529E8DBA4C4D0B7E1A79CF2A052FFEFA" +
"2DEE3373115472AFD1F40A80B23AA6141D5CDE0A378FE6210D4EE69B8771D3E1" +
"92FD989AEC14C26EA4845D261B8A45ABC1C8FA305449DCDEDA9882DD4DDC69B2" +
"DE315645FBC3EE52090907E7687A22A63F538E030AB5A5413CA415F1D70E70CB" +
"567261FB892A8B3BAFC72D632CD2FDCC0559E01D5C246CC27C934863CCFA5249" +
"0E1F01D8D2D0AF2587E4D04011140A494FFA3CA42C5F645B94EE30100DE019B2" +
"7F66FFC035E49A65B2A3F6CB14EB1E2FFF1F25B5C87481BD8506F307E0B042A2" +
"C85B99ECA520B4AAC7DFF2B11C1213E4128A01765DDB27B867336B8CCF148CE7" +
"38465D46E7A0BEA466CD8BBCCE2E11B16E0F9D24FF2F2D7C9F852779ADBB818F" +
"87E4AFF7C21A9C2BC20D38209322A34B0B393B187C96583D3D73D9440F994B2F" +
"320D3274848AB7167942179CFF725C2C7556CCC289A5E788C5B863E6FCDD5E4B" +
"87E41458BEB3F43D14C7E5196C38CA36322F8B83064862178D58925AEF34F444" +
"A31A4FB18431D7D37C65ED519643BC7BD025F801390430022253AAFCEA670726" +
"512C3532EA9F410DB8AA6628CC455E4AB3F478A6981DB9180B7A2A24B365F375" +
"54CE04B08F22B3539D98BF9A1AC623BBF9A08DBEC951E9730C131802B2C40750" +
"AAE6A791B3219A96A5BAC7AE17A2F7EA02FF66D6FB36C2E6B6AB90D821A6322B" +
"F3E8D82969756A474551DB9EAA8C587FC878F996F5FA1E1C39E983F164B0A678" +
"97EB3755C378807FFDFE964C5C0F290784A08E8C925E85775A9B892E278F68C3" +
"C1DE72622AC10EA56D88C909EF4AC9F47ED61376737C1E43DBF0F89337F0684F" +
"A0B96E7A993EC328A6A5FBCDCB809ACBFDAE4ECE192A45480104ED12820238AB" +
"6AC9C88CC9A82585FD29A81A7BC5BC591738A4D49A86D06B4E18BDC83DFFAA60" +
"D8A0D4F70CC63D4E83812CB6753F3744545592D04223793E5B305125AAD8807A" +
"753D235769BD0280E2DE808B0CEE2B98B0F5562FF9EF68161A6B7E08C8B10576" +
"6EBCFC44AC858B1A89E34C099B194A8B24D1DBABC13909EFAF5B9A9E77AEAF7D" +
"D9BE772FA01AB9518EB8864AE6D07D7DD7451797541D2F723BC71A9C14ED1D81" +
"1594E2C4A57017D4CB90FD82C195FA9B823DF1E2FFD965E3139F9A6E8AAC36FA" +
"39CFA4C52E85D2A661F9D0D466720C5AB7ECDE968FF51B535B019A3E9C76058E" +
"6F673A49CDD89EA7EC998BDADE71186EA084020A897A328753B72E213A9D8244" +
"3F7E34D94508199A2A63E71A12BD441C132201E9A3829B2727F23E65C519F4DA" +
"2C40162A3A501B1BD57568ED75447FEAF8B42988CE25407644BFA0B76059D275" +
"EC994BB336055E271751B32233D79A6E5E3AA700F3803CCA50586D28934E3D41" +
"35FA043AF7DFAB977477283602B1739C4AF40E3856E75C34EB98C69A928ADE05" +
"B67A679630EFA14E64B2957EDD1AB4EC0B0E7BC38D4851EBF6792833EACB62FB" +
"6C862B089E3066AE5EAAFD2A8B7FC712DE9BD2F488222EEB1FB91B4E57C2D240" +
"92818965621C123280453EDCFA2EC9D9B50AFA437D1ED09EC36FD232B169ED30" +
"1E0DB0BABE562B67130F90EBC85D325A90931A5B5A94736A4B3AADB8CA295F59" +
"AF7FF08CCFADE5AFBBC2346BC6D78D9E5F470E9BDFF547F2574B10A48DD9D56B" +
"5B03E9E24D65C367B6E342A26A344111A66B1908EDAECD0834930DA74E1CFE2E" +
"4B0636A7C18E51A27AD21992A2DCF466BAACAC227B90B5E61BED799C97DEE7ED" +
"B33CCAF5DAD7AAD3CACCDE59478CF69AE64B9065FCB436E1993514C42872DD48" +
"6ABB75A07A4ED46CDF0E12C0D73FAB83564CF1A814791971EC9C7C6A08A13CE0" +
"453C2C3236C8B2E146D242E3D37A3ECF6C350D0B2AB956CB21057FDC630750A7" +
"1C61C66DE3D4A6DB187BEE2F86DEB93E723C5943EA17E699E93555756920416B" +
"D6B267A4CFAC4EE90E96A6419302B4C0A3B9705509CA09EE92F184FD2817BA09" +
"BE29E465909DB6C93E3C1CAF6DC29E1A5838F3C32CCB220235EF829CD21D1B3E" +
"960518A80D08AE7FF08D3AFB7451C823E9B8D49DAF66F503E4AE5399FECFC958" +
"429D758C06EFF8338BC02457F6FE5053AA3C2F27D360058FD935663B55F026B5" +
"04E39D86E7CE15F04B1C62BBFA0B1CA5E64FF0BD088D94FB1518E05B2F40BF9D" +
"71C61FC43E3AF8440570C44030F59D14B8858B7B8506B136E7E39BB04F9AFEAF" +
"2FA292D28A8822046CEFDE381F2399370BDE9B97BC700418585C31E9C353635A" +
"DAA6A00A833899D0EDA8F5FFC558D822AEB99C7E35526F5297F333F9E758D4CD" +
"53277316608B1F7DB6AC71309A8542A356D407531BA1D3071BA9DC02AE91C7DF" +
"2561AEBC3845A118B00D21913B4A401DDDC40CE983178EF26C4A41343037301F" +
"300706052B0E03021A041438351C5D7948F9BEA3ACECC0F54AF460EC01093B04" +
"14B610EC75D16EA23BF253AAD061FAC376E1EAF684").HexToByteArray();
internal static readonly byte[] EmptyPfx = (
"304F020103301106092A864886F70D010701A004040230003037301F30070605" +
"2B0E03021A0414822078BC83E955E314BDA908D76D4C5177CC94EB0414711018" +
"F2897A44A90E92779CB655EA11814EC598").HexToByteArray();
internal const string ChainPfxPassword = "test";
internal static readonly byte[] ChainPfxBytes = (
"308213D80201033082139406092A864886F70D010701A0821385048213813082" +
"137D308203C606092A864886F70D010701A08203B7048203B3308203AF308203" +
"AB060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" +
"010C0103300E040811E8B9808BA6E96C020207D004820290D11DA8713602105C" +
"95792D65BCDFC1B7E3708483BF6CD83008082F89DAE4D003F86081B153BD4D4A" +
"C122E802752DEA29F07D0B7E8F0FB8A762B4CAA63360F9F72CA5846771980A6F" +
"AE2643CD412E6E4A101625371BBD48CC6E2D25191D256B531B06DB7CDAC04DF3" +
"E10C6DC556D5FE907ABF32F2966A561C988A544C19B46DF1BE531906F2CC2263" +
"A301302A857075C7A9C48A395241925C6A369B60D176419D75E320008D5EFD91" +
"5257B160F6CD643953E85F19EBE4E4F72B9B787CF93E95F819D1E43EF01CCFA7" +
"48F0E7260734EA9BC6039BA7557BE6328C0149718A1D9ECF3355082DE697B6CD" +
"630A9C224D831B7786C7E904F1EF2D9D004E0E825DD74AC4A576CDFCA7CECD14" +
"D8E2E6CCAA3A302871AE0BA979BB25559215D771FAE647905878E797BBA9FC62" +
"50F30F518A8008F5A12B35CE526E31032B56EFE5A4121E1E39DC7339A0CE8023" +
"24CDDB7E9497BA37D8B9F8D826F901C52708935B4CA5B0D4D760A9FB33B0442D" +
"008444D5AEB16E5C32187C7038F29160DD1A2D4DB1F9E9A6C035CF5BCED45287" +
"C5DEBAB18743AAF90E77201FEA67485BA3BBCE90CEA4180C447EE588AC19C855" +
"638B9552D47933D2760351174D9C3493DCCE9708B3EFE4BE398BA64051BF52B7" +
"C1DCA44D2D0ED5A6CFB116DDA41995FA99373C254F3F3EBF0F0049F1159A8A76" +
"4CFE9F9CC56C5489DD0F4E924158C9B1B626030CB492489F6AD0A9DCAF3E141D" +
"B4D4821B2D8A384110B6B0B522F62A9DC0C1315A2A73A7F25F96C530E2F700F9" +
"86829A839B944AE6758B8DD1A1E9257F91C160878A255E299C18424EB9983EDE" +
"6DD1C5F4D5453DD5A56AC87DB1EFA0806E3DBFF10A9623FBAA0BAF352F50AB5D" +
"B16AB1171145860D21E2AB20B45C8865B48390A66057DE3A1ABE45EA65376EF6" +
"A96FE36285C2328C3181E1301306092A864886F70D0109153106040401000000" +
"305D06092A864886F70D01091431501E4E006C0065002D006100340034003100" +
"30003300610064002D0033003500620032002D0034003800340061002D003900" +
"3600610036002D00650030006600610036006600330035006500650065003230" +
"6B06092B0601040182371101315E1E5C004D006900630072006F0073006F0066" +
"007400200045006E00680061006E006300650064002000430072007900700074" +
"006F0067007200610070006800690063002000500072006F0076006900640065" +
"0072002000760031002E003030820FAF06092A864886F70D010706A0820FA030" +
"820F9C02010030820F9506092A864886F70D010701301C060A2A864886F70D01" +
"0C0106300E0408FFCC41FD8C8414F6020207D080820F68092C6010873CF9EC54" +
"D4676BCFB5FA5F523D03C981CB4A3DC096074E7D04365DDD1E80BF366B8F9EC4" +
"BC056E8CE0CAB516B9C28D17B55E1EB744C43829D0E06217852FA99CCF549617" +
"6DEF9A48967C1EEB4A384DB7783E643E35B5B9A50533B76B8D53581F02086B78" +
"2895097860D6CA512514E10D004165C85E561DF5F9AEFD2D89B64F178A7385C7" +
"FA40ECCA899B4B09AE40EE60DAE65B31FF2D1EE204669EFF309A1C7C8D7B0751" +
"AE57276D1D0FB3E8344A801AC5226EA4ED97FCD9399A4EB2E778918B81B17FE4" +
"F65B502595195C79E6B0E37EB8BA36DB12435587E10037D31173285D45304F6B" +
"0056512B3E147D7B5C397709A64E1D74F505D2BD72ED99055161BC57B6200F2F" +
"48CF128229EFBEBFC2707678C0A8C51E3C373271CB4FD8EF34A1345696BF3950" +
"E8CE9831F667D68184F67FE4D30332E24E5C429957694AF23620EA7742F08A38" +
"C9A517A7491083A367B31C60748D697DFA29635548C605F898B64551A48311CB" +
"2A05B1ACA8033128D48E4A5AA263D970FE59FBA49017F29049CF80FFDBD19295" +
"B421FEFF6036B37D2F8DC8A6E36C4F5D707FB05274CC0D8D94AFCC8C6AF546A0" +
"CF49FBD3A67FB6D20B9FE6FDA6321E8ABF5F7CC794CFCC46005DC57A7BAFA899" +
"54E43230402C8100789F11277D9F05C78DF0509ECFBF3A85114FD35F4F17E798" +
"D60C0008064E2557BA7BF0B6F8663A6C014E0220693AE29E2AB4BDE5418B6108" +
"89EC02FF5480BD1B344C87D73E6E4DB98C73F881B22C7D298059FE9D7ADA2192" +
"BB6C87F8D25F323A70D234E382F6C332FEF31BB11C37E41903B9A59ADEA5E0CB" +
"AB06DFB835257ABC179A897DEAD9F19B7DF861BE94C655DC73F628E065F921E5" +
"DE98FFCBDF2A54AC01E677E365DD8B932B5BDA761A0032CE2127AB2A2B9DCB63" +
"F1EA8A51FC360AB5BC0AD435F21F9B6842980D795A6734FDB27A4FA8209F7362" +
"DD632FC5FB1F6DE762473D6EA68BFC4BCF983865E66E6D93159EFACC40AB31AA" +
"178806CF893A76CAAA3279C988824A33AF734FAF8E21020D988640FAB6DB10DF" +
"21D93D01776EEA5DAECF695E0C690ED27AD386E6F2D9C9482EA38946008CCB8F" +
"0BD08F9D5058CF8057CA3AD50BB537116A110F3B3ACD9360322DB4D242CC1A6E" +
"15FA2A95192FC65886BE2672031D04A4FB0B1F43AE8476CF82638B61B416AA97" +
"925A0110B736B4D83D7977456F35D947B3D6C9571D8E2DA0E9DEE1E665A84425" +
"9C17E01E044FAB898AA170F99157F7B525D524B01BD0710D23A7689A6157038A" +
"0697BD48FFE0253ABD6F862093574B2FC9BA38E1A6EC60AF187F10D79FF71F7C" +
"50E87A07CC0A51099899F7336FE742ADEF25E720B8E0F8781EC7957D414CF5D4" +
"4D6998E7E35D2433AFD86442CCA637A1513BE3020B5334614277B3101ED7AD22" +
"AFE50DE99A2AD0E690596C93B881E2962D7E52EE0A770FAF6917106A8FF0298D" +
"F38D6DE926C30834C5D96854FFD053BDB020F7827FB81AD04C8BC2C773B2A59F" +
"DD6DDF7298A052B3486E03FECA5AA909479DDC7FED972192792888F49C40F391" +
"0140C5BE264D3D07BEBF3275117AF51A80C9F66C7028A2C3155414CF93999726" +
"8A1F0AA9059CC3AA7C8BBEF880187E3D1BA8978CBB046E43289A020CAE11B251" +
"40E2247C15A32CF70C7AA186CBB68B258CF2397D2971F1632F6EBC4846444DE4" +
"45673B942F1F110C7D586B6728ECA5B0A62D77696BF25E21ED9196226E5BDA5A" +
"80ECCC785BEEDE917EBC6FFDC2F7124FE8F719B0A937E35E9A720BB9ED72D212" +
"13E68F058D80E9F8D7162625B35CEC4863BD47BC2D8D80E9B9048811BDD8CBB7" +
"0AB215962CD9C40D56AE50B7003630AE26341C6E243B3D12D5933F73F78F15B0" +
"14C5B1C36B6C9F410A77CA997931C8BD5CCB94C332F6723D53A4CCC630BFC9DE" +
"96EFA7FDB66FA519F967D6A2DB1B4898BB188DEB98A41FFA7907AE7601DDE230" +
"E241779A0FDF551FB84D80AAEE3D979F0510CD026D4AE2ED2EFB7468418CCDB3" +
"BD2A29CD7C7DC6419B4637412304D5DA2DC178C0B4669CA8330B9713A812E652" +
"E812135D807E361167F2A6814CEF2A8A9591EFE2C18216A517473B9C3BF2B751" +
"E47844893DA30F7DCD4222D1A55D570C1B6F6A99AD1F9213BA8F84C0B14A6DED" +
"6A26EAFF8F89DF733EEB44117DF0FD357186BA4A15BD5C669F60D6D4C3402832" +
"2D4DDF035302131AB6FD08683804CC90C1791182F1AE3281EE69DDBBCC12B81E" +
"60942FD082286B16BE27DC11E3BB0F18C281E02F3BA66E48C5FD8E8EA3B731BD" +
"B12A4A3F2D9E1F833DD204372003532E1BB11298BDF5092F2959FC439E6BD2DC" +
"6C37E3E775DCBE821B9CBB02E95D84C15E736CEA2FDDAD63F5CD47115B4AD552" +
"27C2A02886CD2700540EBFD5BF18DC5F94C5874972FD5424FE62B30500B1A875" +
"21EA3798D11970220B2BE7EFC915FCB7A6B8962F09ABA005861E839813EDA3E5" +
"9F70D1F9C277B73928DFFC84A1B7B0F78A8B001164EB0824F2510885CA269FDC" +
"BB2C3AE91BDE91A8BBC648299A3EB626E6F4236CCE79E14C803498562BAD6028" +
"F5B619125F80925A2D3B1A56790795D04F417003A8E9E53320B89D3A3109B19B" +
"B17B34CC9700DA138FABB5997EC34D0A44A26553153DBCFF8F6A1B5432B15058" +
"F7AD87C6B37537796C95369DAD53BE5543D86D940892F93983153B4031D4FAB2" +
"5DAB02C1091ACC1DAE2118ABD26D19435CD4F1A02BDE1896236C174743BCA6A3" +
"3FB5429E627EB3FD9F513E81F7BD205B81AAE627C69CF227B043722FA0514139" +
"347D202C9B7B4E55612FC27164F3B5F287F29C443793E22F6ED6D2F353ED82A9" +
"F33EDBA8F5F1B2958F1D6A3943A9614E7411FDBCA597965CD08A8042307081BA" +
"C5A070B467E52D5B91CA58F986C5A33502236B5BAE6DB613B1A408D16B29D356" +
"0F1E94AD840CFA93E83412937A115ABF68322538DA8082F0192D19EAAA41C929" +
"9729D487A9404ECDB6396DDA1534841EAE1E7884FA43574E213AE656116D9EF7" +
"591AA7BDE2B44733DFE27AA59949E5DC0EE00FDF42130A748DDD0FB0053C1A55" +
"986983C8B9CEAC023CAD7EDFFA1C20D3C437C0EF0FC9868D845484D8BE6538EA" +
"ADA6365D48BA776EE239ED045667B101E3798FE53E1D4B9A2ACBBE6AF1E5C88A" +
"3FB03AD616404013E249EC34458F3A7C9363E7772151119FE058BD0939BAB764" +
"A2E545B0B2FDAA650B7E849C8DD4033922B2CAE46D0461C04A2C87657CB4C0FF" +
"BA23DED69D097109EC8BFDC25BB64417FEEB32842DE3EFEF2BF4A47F08B9FCD1" +
"907BC899CA9DA604F5132FB420C8D142D132E7E7B5A4BD0EF4A56D9E9B0ACD88" +
"F0E862D3F8F0440954879FFE3AA7AA90573C6BFDC6D6474C606ACA1CD94C1C34" +
"04349DD83A639B786AFCDEA1779860C05400E0479708F4A9A0DD51429A3F35FB" +
"D5FB9B68CECC1D585F3E35B7BBFC469F3EAEEB8020A6F0C8E4D1804A3EB32EB3" +
"909E80B0A41571B23931E164E0E1D0D05379F9FD3BF51AF04D2BE78BDB84BD78" +
"7D419E85626297CB35FCFB6ED64042EAD2EBC17BB65677A1A33A5C48ADD28023" +
"7FB2451D0EFB3A3C32354222C7AB77A3C92F7A45B5FB10092698D88725864A36" +
"85FBDD0DC741424FCCD8A00B928F3638150892CAAB535CC2813D13026615B999" +
"77F7B8240E914ACA0FF2DCB1A9274BA1F55DF0D24CCD2BAB7741C9EA8B1ECDE9" +
"7477C45F88F034FDF73023502944AEE1FF370260C576992826C4B2E5CE992484" +
"E3B85170FCCAC3413DC0FF6F093593219E637F699A98BD29E8EE4550C128CA18" +
"2680FDA3B10BC07625734EE8A8274B43B170FC3AEC9AA58CD92709D388E166AB" +
"4ADFD5A4876DC47C17DE51FDD42A32AF672515B6A81E7ABECFE748912B321AFD" +
"0CBF4880298DD79403900A4002B5B436230EB6E49192DF49FAE0F6B60EBA75A5" +
"4592587C141AD3B319129006367E9532861C2893E7A2D0D2832DF4377C31845C" +
"B02A1D020282C3D2B7F77221F71FEA7FF0A988FEF15C4B2F6637159EEC5752D8" +
"A7F4AB971117666A977370E754A4EB0DC52D6E8901DC60FCD87B5B6EF9A91AF8" +
"D9A4E11E2FFDAB55FC11AF6EEB5B36557FC8945A1E291B7FF8931BE4A57B8E68" +
"F04B9D4A9A02FC61AE913F2E2DDBEE42C065F4D30F568834D5BB15FDAF691F19" +
"7EF6C25AE87D8E968C6D15351093AAC4813A8E7B191F77E6B19146F839A43E2F" +
"40DE8BE28EB22C0272545BADF3BD396D383B8DA8388147100B347999DDC4125A" +
"B0AA1159BC6776BD2BF51534C1B40522D41466F414BDE333226973BAD1E6D576" +
"39D30AD94BEA1F6A98C047F1CE1294F0067B771778D59E7C722C73C2FF100E13" +
"603206A694BF0ED07303BE0655DC984CA29893FD0A088B122B67AABDC803E73E" +
"5729E868B1CA26F5D05C818D9832C70F5992E7D15E14F9775C6AD24907CF2F21" +
"1CF87167861F94DCF9E3D365CB600B336D93AD44B8B89CA24E59C1F7812C84DB" +
"E3EE57A536ED0D4BF948F7662E5BCBBB388C72243CFCEB720852D5A4A52F018C" +
"2C087E4DB43410FE9ABA3A8EF737B6E8FFDB1AB9832EBF606ED5E4BD62A86BBC" +
"AE115C67682EDEA93E7845D0D6962C146B411F7784545851D2F327BEC7E4344D" +
"68F137CDA217A3F0FF3B752A34C3B5339C79CB8E1AC690C038E85D6FC1337909" +
"0198D3555394D7A2159A23BD5EEF06EB0BCC729BB29B5BE911D02DA78FDA56F0" +
"35E508C722139AD6F25A6C84BED0E98893370164B033A2B52BC40D9BF5163AF9" +
"650AB55EABB23370492A7D3A87E17C11B4D07A7296273F33069C835FD208BA8F" +
"989A3CF8659054E2CCCFB0C983531DC6590F27C4A1D2C3A780FE945F7E52BB9F" +
"FD2E324640E3E348541A620CD62605BBDB284AF97C621A00D5D1D2C31D6BD611" +
"49137B8A0250BC426417A92445A52574E999FB9102C16671914A1542E92DDE54" +
"1B2A0457112AF936DA84707CADFEA43BFEDAE5F58859908640420948086E57FF" +
"D1B867C241D40197CB0D4AD58BB69B3724772E0079406A1272858AAA620668F6" +
"96955102639F3E95CFFC637EAF8AB54F0B5B2131AB292438D06E15F3826352DE" +
"DC653DA5A4AACE2BB97061A498F3B6789A2310471B32F91A6B7A9944DDBB7031" +
"525B3AE387214DC85A1C7749E9168F41272680D0B3C331D61175F23B623EEC40" +
"F984C35C831268036680DE0821E5DEE5BB250C6984775D49B7AF94057371DB72" +
"F81D2B0295FC6A51BCD00A697649D4346FDD59AC0DFAF21BFCC942C23C6134FF" +
"BA2ABABC141FF700B52C5B26496BF3F42665A5B71BAC7F0C19870BD987389023" +
"9C578CDDD8E08A1B0A429312FB24F151A11E4D180359A7FA043E8155453F6726" +
"5CB2812B1C98C144E7675CFC86413B40E35445AE7710227D13DC0B5550C87010" +
"B363C492DA316FB40D3928570BF71BF47638F1401549369B1255DB080E5DFA18" +
"EA666B9ECBE5C9768C06B3FF125D0E94B98BB24B4FD44E770B78D7B336E0214F" +
"D72E77C1D0BE9F313EDCD147957E3463C62E753C10BB98584C85871AAEA9D1F3" +
"97FE9F1A639ADE31D40EAB391B03B588B8B031BCAC6C837C61B06E4B74505247" +
"4D33531086519C39EDD6310F3079EB5AC83289A6EDCBA3DC97E36E837134F730" +
"3B301F300706052B0E03021A04143EE801FCFB9F6CD2B975E2B2BB37DA8E6F29" +
"369B0414DF1D90CD18B3FBC72226B3C66EC2CB1AB351D4D2020207D0").HexToByteArray();
internal static readonly byte[] Pkcs7ChainDerBytes = (
"30820E1606092A864886F70D010702A0820E0730820E030201013100300B0609" +
"2A864886F70D010701A0820DEB3082050B30820474A003020102020A15EAA83A" +
"000100009291300D06092A864886F70D010105050030818131133011060A0992" +
"268993F22C6401191603636F6D31193017060A0992268993F22C64011916096D" +
"6963726F736F667431143012060A0992268993F22C6401191604636F72703117" +
"3015060A0992268993F22C64011916077265646D6F6E643120301E0603550403" +
"13174D532050617373706F7274205465737420537562204341301E170D313330" +
"3131303231333931325A170D3331313231333232323630375A308185310B3009" +
"060355040613025553310B30090603550408130257413110300E060355040713" +
"075265646D6F6E64310D300B060355040A130454455354310D300B060355040B" +
"130454455354311330110603550403130A746573742E6C6F63616C3124302206" +
"092A864886F70D010901161563726973706F70406D6963726F736F66742E636F" +
"6D30819F300D06092A864886F70D010101050003818D0030818902818100B406" +
"851089E9CF7CDB438DD77BEBD819197BEEFF579C35EF9C4652DF9E6330AA7E2E" +
"24B181C59DA4AF10E97220C1DF99F66CE6E97247E9126A016AC647BD2EFD136C" +
"31470C7BE01A20E381243BEEC8530B7F6466C50A051DCE37274ED7FF2AFFF4E5" +
"8AABA61D5A448F4A8A9B3765D1D769F627ED2F2DE9EE67B1A7ECA3D288C90203" +
"010001A38202823082027E300E0603551D0F0101FF0404030204F0301D060355" +
"1D250416301406082B0601050507030106082B06010505070302301D0603551D" +
"0E04160414FB3485708CBF6188F720EF948489405C8D0413A7301F0603551D23" +
"0418301680146A6678620A4FF49CA8B75FD566348F3371E42B133081D0060355" +
"1D1F0481C83081C53081C2A081BFA081BC865F687474703A2F2F707074657374" +
"73756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E636F6D" +
"2F43657274456E726F6C6C2F4D5325323050617373706F727425323054657374" +
"25323053756225323043412831292E63726C865966696C653A2F2F5C5C707074" +
"65737473756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E" +
"636F6D5C43657274456E726F6C6C5C4D532050617373706F7274205465737420" +
"5375622043412831292E63726C3082013806082B060105050701010482012A30" +
"82012630819306082B06010505073002868186687474703A2F2F707074657374" +
"73756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E636F6D" +
"2F43657274456E726F6C6C2F70707465737473756263612E7265646D6F6E642E" +
"636F72702E6D6963726F736F66742E636F6D5F4D5325323050617373706F7274" +
"2532305465737425323053756225323043412831292E63727430818D06082B06" +
"01050507300286818066696C653A2F2F5C5C70707465737473756263612E7265" +
"646D6F6E642E636F72702E6D6963726F736F66742E636F6D5C43657274456E72" +
"6F6C6C5C70707465737473756263612E7265646D6F6E642E636F72702E6D6963" +
"726F736F66742E636F6D5F4D532050617373706F727420546573742053756220" +
"43412831292E637274300D06092A864886F70D0101050500038181009DEBB8B5" +
"A41ED54859795F68EF767A98A61EF7B07AAC190FCC0275228E4CAD360C9BA98B" +
"0AE153C75522EEF42D400E813B4E49E7ACEB963EEE7B61D3C8DA05C183471544" +
"725B2EBD1889877F62134827FB5993B8FDF618BD421ABA18D70D1C5B41ECDD11" +
"695A48CB42EB501F96DA905471830C612B609126559120F6E18EA44830820358" +
"308202C1A00302010202101B9671A4BC128B8341B0E314EAD9A191300D06092A" +
"864886F70D01010505003081A13124302206092A864886F70D01090116156173" +
"6D656D6F6E406D6963726F736F66742E636F6D310B3009060355040613025553" +
"310B30090603550408130257413110300E060355040713075265646D6F6E6431" +
"123010060355040A13094D6963726F736F667431163014060355040B130D5061" +
"7373706F727420546573743121301F060355040313184D532050617373706F72" +
"74205465737420526F6F74204341301E170D3035303132363031333933325A17" +
"0D3331313231333232323630375A3081A13124302206092A864886F70D010901" +
"161561736D656D6F6E406D6963726F736F66742E636F6D310B30090603550406" +
"13025553310B30090603550408130257413110300E060355040713075265646D" +
"6F6E6431123010060355040A13094D6963726F736F667431163014060355040B" +
"130D50617373706F727420546573743121301F060355040313184D5320506173" +
"73706F7274205465737420526F6F7420434130819F300D06092A864886F70D01" +
"0101050003818D0030818902818100C4673C1226254F6BBD01B01D21BB05264A" +
"9AA5B77AC51748EAC52048706DA6B890DCE043C6426FC44E76D70F9FE3A4AC85" +
"5F533E3D08E140853DB769EE24DBDB7269FABEC0FDFF6ADE0AA85F0085B78864" +
"58E7585E433B0924E81600433CB1177CE6AD5F2477B2A0E2D1A34B41F6C6F5AD" +
"E4A9DD7D565C65F02C2AAA01C8E0C10203010001A3818E30818B301306092B06" +
"0104018237140204061E0400430041300B0603551D0F040403020186300F0603" +
"551D130101FF040530030101FF301D0603551D0E04160414F509C1D6267FC39F" +
"CA1DE648C969C74FB111FE10301206092B060104018237150104050203010002" +
"302306092B0601040182371502041604147F7A5208411D4607C0057C98F0C473" +
"07010CB3DE300D06092A864886F70D0101050500038181004A8EAC73D8EA6D7E" +
"893D5880945E0E3ABFC79C40BFA60A680CF8A8BF63EDC3AD9C11C081F1F44408" +
"9581F5C8DCB23C0AEFA27571D971DBEB2AA9A1B3F7B9B0877E9311D36098A65B" +
"7D03FC69A835F6C3096DEE135A864065F9779C82DEB0C777B9C4DB49F0DD11A0" +
"EAB287B6E352F7ECA467D0D3CA2A8081119388BAFCDD25573082057C308204E5" +
"A003020102020A6187C7F200020000001B300D06092A864886F70D0101050500" +
"3081A13124302206092A864886F70D010901161561736D656D6F6E406D696372" +
"6F736F66742E636F6D310B3009060355040613025553310B3009060355040813" +
"0257413110300E060355040713075265646D6F6E6431123010060355040A1309" +
"4D6963726F736F667431163014060355040B130D50617373706F727420546573" +
"743121301F060355040313184D532050617373706F7274205465737420526F6F" +
"74204341301E170D3039313032373231333133395A170D333131323133323232" +
"3630375A30818131133011060A0992268993F22C6401191603636F6D31193017" +
"060A0992268993F22C64011916096D6963726F736F667431143012060A099226" +
"8993F22C6401191604636F727031173015060A0992268993F22C640119160772" +
"65646D6F6E643120301E060355040313174D532050617373706F727420546573" +
"742053756220434130819F300D06092A864886F70D010101050003818D003081" +
"8902818100A6A4918F93C5D23B3C3A325AD8EC77043D207A0DDC294AD3F5BDE0" +
"4033FADD4097BB1DB042B1D3B2F26A42CC3CB88FA9357710147AB4E1020A0DFB" +
"2597AB8031DB62ABDC48398067EB79E4E2BBE5762F6B4C5EA7629BAC23F70269" +
"06D46EC106CC6FBB4D143F7D5ADADEDE19B021EEF4A6BCB9D01DAEBB9A947703" +
"40B748A3490203010001A38202D7308202D3300F0603551D130101FF04053003" +
"0101FF301D0603551D0E041604146A6678620A4FF49CA8B75FD566348F3371E4" +
"2B13300B0603551D0F040403020186301206092B060104018237150104050203" +
"010001302306092B060104018237150204160414A0A485AE8296EA4944C6F6F3" +
"886A8603FD07472C301906092B0601040182371402040C1E0A00530075006200" +
"430041301F0603551D23041830168014F509C1D6267FC39FCA1DE648C969C74F" +
"B111FE103081D60603551D1F0481CE3081CB3081C8A081C5A081C28663687474" +
"703A2F2F70617373706F72747465737463612E7265646D6F6E642E636F72702E" +
"6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F4D532532305061" +
"7373706F727425323054657374253230526F6F7425323043412831292E63726C" +
"865B66696C653A2F2F50415353504F52545445535443412E7265646D6F6E642E" +
"636F72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F4D53" +
"2050617373706F7274205465737420526F6F742043412831292E63726C308201" +
"4406082B06010505070101048201363082013230819A06082B06010505073002" +
"86818D687474703A2F2F70617373706F72747465737463612E7265646D6F6E64" +
"2E636F72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F50" +
"415353504F52545445535443412E7265646D6F6E642E636F72702E6D6963726F" +
"736F66742E636F6D5F4D5325323050617373706F727425323054657374253230" +
"526F6F7425323043412832292E63727430819206082B06010505073002868185" +
"66696C653A2F2F50415353504F52545445535443412E7265646D6F6E642E636F" +
"72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F50415353" +
"504F52545445535443412E7265646D6F6E642E636F72702E6D6963726F736F66" +
"742E636F6D5F4D532050617373706F7274205465737420526F6F742043412832" +
"292E637274300D06092A864886F70D010105050003818100C44788F8C4F5C2DC" +
"84976F66417CBAE19FBFA82C257DA4C7FED6267BC711D113C78B1C097154A62A" +
"B462ADC84A434AEBAE38DEB9605FAB534A3CAF7B72C199448E58640388911296" +
"115ED6B3478D0E741D990F2D59D66F12E58669D8983489AB0406E37462164B56" +
"6AA1D9B273C406FA694A2556D1D3ACE723382C19871B8C143100").HexToByteArray();
internal static readonly byte[] Pkcs7ChainPemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN PKCS7-----
MIIOFgYJKoZIhvcNAQcCoIIOBzCCDgMCAQExADALBgkqhkiG9w0BBwGggg3rMIIF
CzCCBHSgAwIBAgIKFeqoOgABAACSkTANBgkqhkiG9w0BAQUFADCBgTETMBEGCgmS
JomT8ixkARkWA2NvbTEZMBcGCgmSJomT8ixkARkWCW1pY3Jvc29mdDEUMBIGCgmS
JomT8ixkARkWBGNvcnAxFzAVBgoJkiaJk/IsZAEZFgdyZWRtb25kMSAwHgYDVQQD
ExdNUyBQYXNzcG9ydCBUZXN0IFN1YiBDQTAeFw0xMzAxMTAyMTM5MTJaFw0zMTEy
MTMyMjI2MDdaMIGFMQswCQYDVQQGEwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcT
B1JlZG1vbmQxDTALBgNVBAoTBFRFU1QxDTALBgNVBAsTBFRFU1QxEzARBgNVBAMT
CnRlc3QubG9jYWwxJDAiBgkqhkiG9w0BCQEWFWNyaXNwb3BAbWljcm9zb2Z0LmNv
bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtAaFEInpz3zbQ43Xe+vYGRl7
7v9XnDXvnEZS355jMKp+LiSxgcWdpK8Q6XIgwd+Z9mzm6XJH6RJqAWrGR70u/RNs
MUcMe+AaIOOBJDvuyFMLf2RmxQoFHc43J07X/yr/9OWKq6YdWkSPSoqbN2XR12n2
J+0vLenuZ7Gn7KPSiMkCAwEAAaOCAoIwggJ+MA4GA1UdDwEB/wQEAwIE8DAdBgNV
HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwHQYDVR0OBBYEFPs0hXCMv2GI9yDv
lISJQFyNBBOnMB8GA1UdIwQYMBaAFGpmeGIKT/ScqLdf1WY0jzNx5CsTMIHQBgNV
HR8EgcgwgcUwgcKggb+ggbyGX2h0dHA6Ly9wcHRlc3RzdWJjYS5yZWRtb25kLmNv
cnAubWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL01TJTIwUGFzc3BvcnQlMjBUZXN0
JTIwU3ViJTIwQ0EoMSkuY3JshllmaWxlOi8vXFxwcHRlc3RzdWJjYS5yZWRtb25k
LmNvcnAubWljcm9zb2Z0LmNvbVxDZXJ0RW5yb2xsXE1TIFBhc3Nwb3J0IFRlc3Qg
U3ViIENBKDEpLmNybDCCATgGCCsGAQUFBwEBBIIBKjCCASYwgZMGCCsGAQUFBzAC
hoGGaHR0cDovL3BwdGVzdHN1YmNhLnJlZG1vbmQuY29ycC5taWNyb3NvZnQuY29t
L0NlcnRFbnJvbGwvcHB0ZXN0c3ViY2EucmVkbW9uZC5jb3JwLm1pY3Jvc29mdC5j
b21fTVMlMjBQYXNzcG9ydCUyMFRlc3QlMjBTdWIlMjBDQSgxKS5jcnQwgY0GCCsG
AQUFBzAChoGAZmlsZTovL1xccHB0ZXN0c3ViY2EucmVkbW9uZC5jb3JwLm1pY3Jv
c29mdC5jb21cQ2VydEVucm9sbFxwcHRlc3RzdWJjYS5yZWRtb25kLmNvcnAubWlj
cm9zb2Z0LmNvbV9NUyBQYXNzcG9ydCBUZXN0IFN1YiBDQSgxKS5jcnQwDQYJKoZI
hvcNAQEFBQADgYEAneu4taQe1UhZeV9o73Z6mKYe97B6rBkPzAJ1Io5MrTYMm6mL
CuFTx1Ui7vQtQA6BO05J56zrlj7ue2HTyNoFwYNHFURyWy69GImHf2ITSCf7WZO4
/fYYvUIauhjXDRxbQezdEWlaSMtC61AfltqQVHGDDGErYJEmVZEg9uGOpEgwggNY
MIICwaADAgECAhAblnGkvBKLg0Gw4xTq2aGRMA0GCSqGSIb3DQEBBQUAMIGhMSQw
IgYJKoZIhvcNAQkBFhVhc21lbW9uQG1pY3Jvc29mdC5jb20xCzAJBgNVBAYTAlVT
MQswCQYDVQQIEwJXQTEQMA4GA1UEBxMHUmVkbW9uZDESMBAGA1UEChMJTWljcm9z
b2Z0MRYwFAYDVQQLEw1QYXNzcG9ydCBUZXN0MSEwHwYDVQQDExhNUyBQYXNzcG9y
dCBUZXN0IFJvb3QgQ0EwHhcNMDUwMTI2MDEzOTMyWhcNMzExMjEzMjIyNjA3WjCB
oTEkMCIGCSqGSIb3DQEJARYVYXNtZW1vbkBtaWNyb3NvZnQuY29tMQswCQYDVQQG
EwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcTB1JlZG1vbmQxEjAQBgNVBAoTCU1p
Y3Jvc29mdDEWMBQGA1UECxMNUGFzc3BvcnQgVGVzdDEhMB8GA1UEAxMYTVMgUGFz
c3BvcnQgVGVzdCBSb290IENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDE
ZzwSJiVPa70BsB0huwUmSpqlt3rFF0jqxSBIcG2muJDc4EPGQm/ETnbXD5/jpKyF
X1M+PQjhQIU9t2nuJNvbcmn6vsD9/2reCqhfAIW3iGRY51heQzsJJOgWAEM8sRd8
5q1fJHeyoOLRo0tB9sb1reSp3X1WXGXwLCqqAcjgwQIDAQABo4GOMIGLMBMGCSsG
AQQBgjcUAgQGHgQAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0G
A1UdDgQWBBT1CcHWJn/Dn8od5kjJacdPsRH+EDASBgkrBgEEAYI3FQEEBQIDAQAC
MCMGCSsGAQQBgjcVAgQWBBR/elIIQR1GB8AFfJjwxHMHAQyz3jANBgkqhkiG9w0B
AQUFAAOBgQBKjqxz2Optfok9WICUXg46v8ecQL+mCmgM+Ki/Y+3DrZwRwIHx9EQI
lYH1yNyyPArvonVx2XHb6yqpobP3ubCHfpMR02CYplt9A/xpqDX2wwlt7hNahkBl
+Xecgt6wx3e5xNtJ8N0RoOqyh7bjUvfspGfQ08oqgIERk4i6/N0lVzCCBXwwggTl
oAMCAQICCmGHx/IAAgAAABswDQYJKoZIhvcNAQEFBQAwgaExJDAiBgkqhkiG9w0B
CQEWFWFzbWVtb25AbWljcm9zb2Z0LmNvbTELMAkGA1UEBhMCVVMxCzAJBgNVBAgT
AldBMRAwDgYDVQQHEwdSZWRtb25kMRIwEAYDVQQKEwlNaWNyb3NvZnQxFjAUBgNV
BAsTDVBhc3Nwb3J0IFRlc3QxITAfBgNVBAMTGE1TIFBhc3Nwb3J0IFRlc3QgUm9v
dCBDQTAeFw0wOTEwMjcyMTMxMzlaFw0zMTEyMTMyMjI2MDdaMIGBMRMwEQYKCZIm
iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MRQwEgYKCZIm
iZPyLGQBGRYEY29ycDEXMBUGCgmSJomT8ixkARkWB3JlZG1vbmQxIDAeBgNVBAMT
F01TIFBhc3Nwb3J0IFRlc3QgU3ViIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
iQKBgQCmpJGPk8XSOzw6MlrY7HcEPSB6DdwpStP1veBAM/rdQJe7HbBCsdOy8mpC
zDy4j6k1dxAUerThAgoN+yWXq4Ax22Kr3Eg5gGfreeTiu+V2L2tMXqdim6wj9wJp
BtRuwQbMb7tNFD99Wtre3hmwIe70pry50B2uu5qUdwNAt0ijSQIDAQABo4IC1zCC
AtMwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUamZ4YgpP9Jyot1/VZjSPM3Hk
KxMwCwYDVR0PBAQDAgGGMBIGCSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYBBAGCNxUC
BBYEFKCkha6ClupJRMb284hqhgP9B0csMBkGCSsGAQQBgjcUAgQMHgoAUwB1AGIA
QwBBMB8GA1UdIwQYMBaAFPUJwdYmf8Ofyh3mSMlpx0+xEf4QMIHWBgNVHR8Egc4w
gcswgciggcWggcKGY2h0dHA6Ly9wYXNzcG9ydHRlc3RjYS5yZWRtb25kLmNvcnAu
bWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL01TJTIwUGFzc3BvcnQlMjBUZXN0JTIw
Um9vdCUyMENBKDEpLmNybIZbZmlsZTovL1BBU1NQT1JUVEVTVENBLnJlZG1vbmQu
Y29ycC5taWNyb3NvZnQuY29tL0NlcnRFbnJvbGwvTVMgUGFzc3BvcnQgVGVzdCBS
b290IENBKDEpLmNybDCCAUQGCCsGAQUFBwEBBIIBNjCCATIwgZoGCCsGAQUFBzAC
hoGNaHR0cDovL3Bhc3Nwb3J0dGVzdGNhLnJlZG1vbmQuY29ycC5taWNyb3NvZnQu
Y29tL0NlcnRFbnJvbGwvUEFTU1BPUlRURVNUQ0EucmVkbW9uZC5jb3JwLm1pY3Jv
c29mdC5jb21fTVMlMjBQYXNzcG9ydCUyMFRlc3QlMjBSb290JTIwQ0EoMikuY3J0
MIGSBggrBgEFBQcwAoaBhWZpbGU6Ly9QQVNTUE9SVFRFU1RDQS5yZWRtb25kLmNv
cnAubWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL1BBU1NQT1JUVEVTVENBLnJlZG1v
bmQuY29ycC5taWNyb3NvZnQuY29tX01TIFBhc3Nwb3J0IFRlc3QgUm9vdCBDQSgy
KS5jcnQwDQYJKoZIhvcNAQEFBQADgYEAxEeI+MT1wtyEl29mQXy64Z+/qCwlfaTH
/tYme8cR0RPHixwJcVSmKrRirchKQ0rrrjjeuWBfq1NKPK97csGZRI5YZAOIkRKW
EV7Ws0eNDnQdmQ8tWdZvEuWGadiYNImrBAbjdGIWS1Zqodmyc8QG+mlKJVbR06zn
IzgsGYcbjBQxAA==
-----END PKCS7-----");
internal static readonly byte[] Pkcs7EmptyPemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN PKCS7-----
MCcGCSqGSIb3DQEHAqAaMBgCAQExADALBgkqhkiG9w0BBwGgAKEAMQA=
-----END PKCS7-----");
internal static readonly byte[] Pkcs7EmptyDerBytes = (
"302706092A864886F70D010702A01A30180201013100300B06092A864886F70D" +
"010701A000A1003100").HexToByteArray();
internal static readonly byte[] Pkcs7SingleDerBytes = (
"3082021406092A864886F70D010702A0820205308202010201013100300B0609" +
"2A864886F70D010701A08201E9308201E530820152A0030201020210D5B5BC1C" +
"458A558845BFF51CB4DFF31C300906052B0E03021D05003011310F300D060355" +
"040313064D794E616D65301E170D3130303430313038303030305A170D313130" +
"3430313038303030305A3011310F300D060355040313064D794E616D6530819F" +
"300D06092A864886F70D010101050003818D0030818902818100B11E30EA8742" +
"4A371E30227E933CE6BE0E65FF1C189D0D888EC8FF13AA7B42B68056128322B2" +
"1F2B6976609B62B6BC4CF2E55FF5AE64E9B68C78A3C2DACC916A1BC7322DD353" +
"B32898675CFB5B298B176D978B1F12313E3D865BC53465A11CCA106870A4B5D5" +
"0A2C410938240E92B64902BAEA23EB093D9599E9E372E48336730203010001A3" +
"46304430420603551D01043B3039801024859EBF125E76AF3F0D7979B4AC7A96" +
"A1133011310F300D060355040313064D794E616D658210D5B5BC1C458A558845" +
"BFF51CB4DFF31C300906052B0E03021D0500038181009BF6E2CF830ED485B86D" +
"6B9E8DFFDCD65EFC7EC145CB9348923710666791FCFA3AB59D689FFD7234B787" +
"2611C5C23E5E0714531ABADB5DE492D2C736E1C929E648A65CC9EB63CD84E57B" +
"5909DD5DDF5DBBBA4A6498B9CA225B6E368B94913BFC24DE6B2BD9A26B192B95" +
"7304B89531E902FFC91B54B237BB228BE8AFCDA264763100").HexToByteArray();
internal static readonly byte[] Pkcs7SinglePemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN PKCS7-----
MIICFAYJKoZIhvcNAQcCoIICBTCCAgECAQExADALBgkqhkiG9w0BBwGgggHpMIIB
5TCCAVKgAwIBAgIQ1bW8HEWKVYhFv/UctN/zHDAJBgUrDgMCHQUAMBExDzANBgNV
BAMTBk15TmFtZTAeFw0xMDA0MDEwODAwMDBaFw0xMTA0MDEwODAwMDBaMBExDzAN
BgNVBAMTBk15TmFtZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsR4w6odC
SjceMCJ+kzzmvg5l/xwYnQ2Ijsj/E6p7QraAVhKDIrIfK2l2YJtitrxM8uVf9a5k
6baMeKPC2syRahvHMi3TU7MomGdc+1spixdtl4sfEjE+PYZbxTRloRzKEGhwpLXV
CixBCTgkDpK2SQK66iPrCT2VmenjcuSDNnMCAwEAAaNGMEQwQgYDVR0BBDswOYAQ
JIWevxJedq8/DXl5tKx6lqETMBExDzANBgNVBAMTBk15TmFtZYIQ1bW8HEWKVYhF
v/UctN/zHDAJBgUrDgMCHQUAA4GBAJv24s+DDtSFuG1rno3/3NZe/H7BRcuTSJI3
EGZnkfz6OrWdaJ/9cjS3hyYRxcI+XgcUUxq6213kktLHNuHJKeZIplzJ62PNhOV7
WQndXd9du7pKZJi5yiJbbjaLlJE7/CTeayvZomsZK5VzBLiVMekC/8kbVLI3uyKL
6K/NomR2MQA=
-----END PKCS7-----");
internal static readonly byte[] MicrosoftDotComSslCertBytes = (
"308205943082047CA00302010202103DF70C5D9903F8D8868B9B8CCF20DF6930" +
"0D06092A864886F70D01010B05003077310B3009060355040613025553311D30" +
"1B060355040A131453796D616E74656320436F72706F726174696F6E311F301D" +
"060355040B131653796D616E746563205472757374204E6574776F726B312830" +
"260603550403131F53796D616E74656320436C61737320332045562053534C20" +
"4341202D204733301E170D3134313031353030303030305A170D313631303135" +
"3233353935395A3082010F31133011060B2B0601040182373C02010313025553" +
"311B3019060B2B0601040182373C0201020C0A57617368696E67746F6E311D30" +
"1B060355040F131450726976617465204F7267616E697A6174696F6E31123010" +
"06035504051309363030343133343835310B3009060355040613025553310E30" +
"0C06035504110C0539383035323113301106035504080C0A57617368696E6774" +
"6F6E3110300E06035504070C075265646D6F6E643118301606035504090C0F31" +
"204D6963726F736F667420576179311E301C060355040A0C154D6963726F736F" +
"667420436F72706F726174696F6E310E300C060355040B0C054D53434F4D311A" +
"301806035504030C117777772E6D6963726F736F66742E636F6D30820122300D" +
"06092A864886F70D01010105000382010F003082010A0282010100A46861FA9D" +
"5DB763633BF5A64EF6E7C2C2367F48D2D46643A22DFCFCCB24E58A14D0F06BDC" +
"956437F2A56BA4BEF70BA361BF12964A0D665AFD84B0F7494C8FA4ABC5FCA2E0" +
"17C06178AEF2CDAD1B5F18E997A14B965C074E8F564970607276B00583932240" +
"FE6E2DD013026F9AE13D7C91CC07C4E1E8E87737DC06EF2B575B89D62EFE4685" +
"9F8255A123692A706C68122D4DAFE11CB205A7B3DE06E553F7B95F978EF8601A" +
"8DF819BF32040BDF92A0DE0DF269B4514282E17AC69934E8440A48AB9D1F5DF8" +
"9A502CEF6DFDBE790045BD45E0C94E5CA8ADD76A013E9C978440FC8A9E2A9A49" +
"40B2460819C3E302AA9C9F355AD754C86D3ED77DDAA3DA13810B4D0203010001" +
"A38201803082017C30310603551D11042A302882117777772E6D6963726F736F" +
"66742E636F6D821377777771612E6D6963726F736F66742E636F6D3009060355" +
"1D1304023000300E0603551D0F0101FF0404030205A0301D0603551D25041630" +
"1406082B0601050507030106082B0601050507030230660603551D20045F305D" +
"305B060B6086480186F84501071706304C302306082B06010505070201161768" +
"747470733A2F2F642E73796D63622E636F6D2F637073302506082B0601050507" +
"020230191A1768747470733A2F2F642E73796D63622E636F6D2F727061301F06" +
"03551D230418301680140159ABE7DD3A0B59A66463D6CF200757D591E76A302B" +
"0603551D1F042430223020A01EA01C861A687474703A2F2F73722E73796D6362" +
"2E636F6D2F73722E63726C305706082B06010505070101044B3049301F06082B" +
"060105050730018613687474703A2F2F73722E73796D63642E636F6D30260608" +
"2B06010505073002861A687474703A2F2F73722E73796D63622E636F6D2F7372" +
"2E637274300D06092A864886F70D01010B0500038201010015F8505B627ED7F9" +
"F96707097E93A51E7A7E05A3D420A5C258EC7A1CFE1843EC20ACF728AAFA7A1A" +
"1BC222A7CDBF4AF90AA26DEEB3909C0B3FB5C78070DAE3D645BFCF840A4A3FDD" +
"988C7B3308BFE4EB3FD66C45641E96CA3352DBE2AEB4488A64A9C5FB96932BA7" +
"0059CE92BD278B41299FD213471BD8165F924285AE3ECD666C703885DCA65D24" +
"DA66D3AFAE39968521995A4C398C7DF38DFA82A20372F13D4A56ADB21B582254" +
"9918015647B5F8AC131CC5EB24534D172BC60218A88B65BCF71C7F388CE3E0EF" +
"697B4203720483BB5794455B597D80D48CD3A1D73CBBC609C058767D1FF060A6" +
"09D7E3D4317079AF0CD0A8A49251AB129157F9894A036487").HexToByteArray();
internal static readonly byte[] MicrosoftDotComIssuerBytes = (
"3082052B30820413A00302010202107EE14A6F6FEFF2D37F3FAD654D3ADAB430" +
"0D06092A864886F70D01010B05003081CA310B30090603550406130255533117" +
"3015060355040A130E566572695369676E2C20496E632E311F301D060355040B" +
"1316566572695369676E205472757374204E6574776F726B313A303806035504" +
"0B1331286329203230303620566572695369676E2C20496E632E202D20466F72" +
"20617574686F72697A656420757365206F6E6C79314530430603550403133C56" +
"6572695369676E20436C6173732033205075626C6963205072696D6172792043" +
"657274696669636174696F6E20417574686F72697479202D204735301E170D31" +
"33313033313030303030305A170D3233313033303233353935395A3077310B30" +
"09060355040613025553311D301B060355040A131453796D616E74656320436F" +
"72706F726174696F6E311F301D060355040B131653796D616E74656320547275" +
"7374204E6574776F726B312830260603550403131F53796D616E74656320436C" +
"61737320332045562053534C204341202D20473330820122300D06092A864886" +
"F70D01010105000382010F003082010A0282010100D8A1657423E82B64E232D7" +
"33373D8EF5341648DD4F7F871CF84423138EFB11D8445A18718E601626929BFD" +
"170BE1717042FEBFFA1CC0AAA3A7B571E8FF1883F6DF100A1362C83D9CA7DE2E" +
"3F0CD91DE72EFB2ACEC89A7F87BFD84C041532C9D1CC9571A04E284F84D935FB" +
"E3866F9453E6728A63672EBE69F6F76E8E9C6004EB29FAC44742D27898E3EC0B" +
"A592DCB79ABD80642B387C38095B66F62D957A86B2342E859E900E5FB75DA451" +
"72467013BF67F2B6A74D141E6CB953EE231A4E8D48554341B189756A4028C57D" +
"DDD26ED202192F7B24944BEBF11AA99BE3239AEAFA33AB0A2CB7F46008DD9F1C" +
"CDDD2D016680AFB32F291D23B88AE1A170070C340F0203010001A382015D3082" +
"0159302F06082B0601050507010104233021301F06082B060105050730018613" +
"687474703A2F2F73322E73796D63622E636F6D30120603551D130101FF040830" +
"060101FF02010030650603551D20045E305C305A0604551D2000305230260608" +
"2B06010505070201161A687474703A2F2F7777772E73796D617574682E636F6D" +
"2F637073302806082B06010505070202301C1A1A687474703A2F2F7777772E73" +
"796D617574682E636F6D2F72706130300603551D1F042930273025A023A02186" +
"1F687474703A2F2F73312E73796D63622E636F6D2F706361332D67352E63726C" +
"300E0603551D0F0101FF04040302010630290603551D1104223020A41E301C31" +
"1A30180603550403131153796D616E746563504B492D312D353333301D060355" +
"1D0E041604140159ABE7DD3A0B59A66463D6CF200757D591E76A301F0603551D" +
"230418301680147FD365A7C2DDECBBF03009F34339FA02AF333133300D06092A" +
"864886F70D01010B050003820101004201557BD0161A5D58E8BB9BA84DD7F3D7" +
"EB139486D67F210B47BC579B925D4F059F38A4107CCF83BE0643468D08BC6AD7" +
"10A6FAABAF2F61A863F265DF7F4C8812884FB369D9FF27C00A97918F56FB89C4" +
"A8BB922D1B73B0C6AB36F4966C2008EF0A1E6624454F670040C8075474333BA6" +
"ADBB239F66EDA2447034FB0EEA01FDCF7874DFA7AD55B75F4DF6D63FE086CE24" +
"C742A9131444354BB6DFC960AC0C7FD993214BEE9CE4490298D3607B5CBCD530" +
"2F07CE4442C40B99FEE69FFCB07886516DD12C9DC696FB8582BB042FF76280EF" +
"62DA7FF60EAC90B856BD793FF2806EA3D9B90F5D3A071D9193864B294CE1DCB5" +
"E1E0339DB3CB36914BFEA1B4EEF0F9").HexToByteArray();
internal static readonly byte[] MicrosoftDotComRootBytes = (
"308204D3308203BBA003020102021018DAD19E267DE8BB4A2158CDCC6B3B4A30" +
"0D06092A864886F70D01010505003081CA310B30090603550406130255533117" +
"3015060355040A130E566572695369676E2C20496E632E311F301D060355040B" +
"1316566572695369676E205472757374204E6574776F726B313A303806035504" +
"0B1331286329203230303620566572695369676E2C20496E632E202D20466F72" +
"20617574686F72697A656420757365206F6E6C79314530430603550403133C56" +
"6572695369676E20436C6173732033205075626C6963205072696D6172792043" +
"657274696669636174696F6E20417574686F72697479202D204735301E170D30" +
"36313130383030303030305A170D3336303731363233353935395A3081CA310B" +
"300906035504061302555331173015060355040A130E566572695369676E2C20" +
"496E632E311F301D060355040B1316566572695369676E205472757374204E65" +
"74776F726B313A3038060355040B133128632920323030362056657269536967" +
"6E2C20496E632E202D20466F7220617574686F72697A656420757365206F6E6C" +
"79314530430603550403133C566572695369676E20436C617373203320507562" +
"6C6963205072696D6172792043657274696669636174696F6E20417574686F72" +
"697479202D20473530820122300D06092A864886F70D01010105000382010F00" +
"3082010A0282010100AF240808297A359E600CAAE74B3B4EDC7CBC3C451CBB2B" +
"E0FE2902F95708A364851527F5F1ADC831895D22E82AAAA642B38FF8B955B7B1" +
"B74BB3FE8F7E0757ECEF43DB66621561CF600DA4D8DEF8E0C362083D5413EB49" +
"CA59548526E52B8F1B9FEBF5A191C23349D843636A524BD28FE870514DD18969" +
"7BC770F6B3DC1274DB7B5D4B56D396BF1577A1B0F4A225F2AF1C926718E5F406" +
"04EF90B9E400E4DD3AB519FF02BAF43CEEE08BEB378BECF4D7ACF2F6F03DAFDD" +
"759133191D1C40CB7424192193D914FEAC2A52C78FD50449E48D6347883C6983" +
"CBFE47BD2B7E4FC595AE0E9DD4D143C06773E314087EE53F9F73B8330ACF5D3F" +
"3487968AEE53E825150203010001A381B23081AF300F0603551D130101FF0405" +
"30030101FF300E0603551D0F0101FF040403020106306D06082B060105050701" +
"0C0461305FA15DA05B3059305730551609696D6167652F6769663021301F3007" +
"06052B0E03021A04148FE5D31A86AC8D8E6BC3CF806AD448182C7B192E302516" +
"23687474703A2F2F6C6F676F2E766572697369676E2E636F6D2F76736C6F676F" +
"2E676966301D0603551D0E041604147FD365A7C2DDECBBF03009F34339FA02AF" +
"333133300D06092A864886F70D0101050500038201010093244A305F62CFD81A" +
"982F3DEADC992DBD77F6A5792238ECC4A7A07812AD620E457064C5E797662D98" +
"097E5FAFD6CC2865F201AA081A47DEF9F97C925A0869200DD93E6D6E3C0D6ED8" +
"E606914018B9F8C1EDDFDB41AAE09620C9CD64153881C994EEA284290B136F8E" +
"DB0CDD2502DBA48B1944D2417A05694A584F60CA7E826A0B02AA251739B5DB7F" +
"E784652A958ABD86DE5E8116832D10CCDEFDA8822A6D281F0D0BC4E5E71A2619" +
"E1F4116F10B595FCE7420532DBCE9D515E28B69E85D35BEFA57D4540728EB70E" +
"6B0E06FB33354871B89D278BC4655F0D86769C447AF6955CF65D320833A454B6" +
"183F685CF2424A853854835FD1E82CF2AC11D6A8ED636A").HexToByteArray();
internal static readonly byte[] Rsa384CertificatePemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN CERTIFICATE-----
MIICTzCCAgmgAwIBAgIJAMQtYhFJ0+5jMA0GCSqGSIb3DQEBBQUAMIGSMQswCQYD
VQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwHUmVkbW9uZDEY
MBYGA1UECgwPTWljcm9zb2Z0IENvcnAuMSAwHgYDVQQLDBcuTkVUIEZyYW1ld29y
ayAoQ29yZUZ4KTEgMB4GA1UEAwwXUlNBIDM4NC1iaXQgQ2VydGlmaWNhdGUwHhcN
MTYwMzAyMTY1OTA0WhcNMTYwNDAxMTY1OTA0WjCBkjELMAkGA1UEBhMCVVMxEzAR
BgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1JlZG1vbmQxGDAWBgNVBAoMD01p
Y3Jvc29mdCBDb3JwLjEgMB4GA1UECwwXLk5FVCBGcmFtZXdvcmsgKENvcmVGeCkx
IDAeBgNVBAMMF1JTQSAzODQtYml0IENlcnRpZmljYXRlMEwwDQYJKoZIhvcNAQEB
BQADOwAwOAIxANrMIthuZxV1Ay4x8gbc/BksZeLVEInlES0JbyiCr9tbeM22Vy/S
9h2zkEciMuPZ9QIDAQABo1AwTjAdBgNVHQ4EFgQU5FG2Fmi86hJOCf4KnjaxOGWV
dRUwHwYDVR0jBBgwFoAU5FG2Fmi86hJOCf4KnjaxOGWVdRUwDAYDVR0TBAUwAwEB
/zANBgkqhkiG9w0BAQUFAAMxAEzDg/u8TlApCnE8qxhcbTXk2MbX+2n5PCn+MVrW
wggvPj3b2WMXsVWiPr4S1Y/nBA==
-----END CERTIFICATE-----");
internal static readonly ECDsaCngKeyValues ECDsaCng256PublicKey =
new ECDsaCngKeyValues()
{
QX = "448d98ee08aeba0d8b40f3c6dbd500e8b69f07c70c661771655228ea5a178a91".HexToByteArray(),
QY = "0ef5cb1759f6f2e062021d4f973f5bb62031be87ae915cff121586809e3219af".HexToByteArray(),
D = "692837e9cf613c0e290462a6f08faadcc7002398f75598d5554698a0cb51cf47".HexToByteArray(),
};
internal static readonly byte[] ECDsa256Certificate =
("308201223081c9a00302010202106a3c9e85ba6af1ac4f08111d8bdda340300906072a8648ce3d0401301431123010060355"
+ "04031309456332353655736572301e170d3135303931303231333533305a170d3136303931303033333533305a3014311230"
+ "10060355040313094563323536557365723059301306072a8648ce3d020106082a8648ce3d03010703420004448d98ee08ae"
+ "ba0d8b40f3c6dbd500e8b69f07c70c661771655228ea5a178a910ef5cb1759f6f2e062021d4f973f5bb62031be87ae915cff"
+ "121586809e3219af300906072a8648ce3d04010349003046022100f221063dca71955d17c8f0e0f63a144c4065578fd9f68e"
+ "1ae6a7683e209ea742022100ed1db6a8be27cfb20ab43e0ca061622ceff26f7249a0f791e4d6be1a4e52adfa").HexToByteArray();
internal static readonly ECDsaCngKeyValues ECDsaCng384PublicKey =
new ECDsaCngKeyValues()
{
QX = "c59eca607aa5559e6b2f8ac2eeb12d9ab47f420feabeb444c3f71520d7f2280439979323ab5a67344811d296fef6d1bd".HexToByteArray(),
QY = "d15f307cc6cc6c8baeeeb168bfb02c34d6eb0621efb3d06ad31c06b29eaf6ec2ec67bf288455e729d82e5a6439f70901".HexToByteArray(),
D = "f55ba33e28cea32a014e2fe1213bb4d41cef361f1fee022116b15be50feb96bc946b10a46a9a7a94176787e0928a3e1d".HexToByteArray(),
};
internal static readonly byte[] ECDsa384Certificate =
("3082015f3081e6a00302010202101e78eb573e70a2a64744672296988ad7300906072a8648ce3d0401301431123010060355"
+ "04031309456333383455736572301e170d3135303931303231333634365a170d3136303931303033333634365a3014311230"
+ "10060355040313094563333834557365723076301006072a8648ce3d020106052b8104002203620004c59eca607aa5559e6b"
+ "2f8ac2eeb12d9ab47f420feabeb444c3f71520d7f2280439979323ab5a67344811d296fef6d1bdd15f307cc6cc6c8baeeeb1"
+ "68bfb02c34d6eb0621efb3d06ad31c06b29eaf6ec2ec67bf288455e729d82e5a6439f70901300906072a8648ce3d04010369"
+ "003066023100a8fbaeeae61953897eae5f0beeeffaca48e89bc0cb782145f39f4ba5b03390ce6a28e432e664adf5ebc6a802"
+ "040b238b023100dcc19109383b9482fdda68f40a63ee41797dbb8f25c0284155cc4238d682fbb3fb6e86ea0933297e850a26"
+ "16f6c39bbf").HexToByteArray();
internal static readonly ECDsaCngKeyValues ECDsaCng521PublicKey =
new ECDsaCngKeyValues()
{
QX = "0134af29d1fe5e581fd2ff6194263abcb6f8cb4d9c08bdb384ede9b8663ae2f4e1af6c85eacc69dc768fbfcd856630792e05484cefb1fefb693081dc6490dac579c0".HexToByteArray(),
QY = "00bfe103f53cbcb039873b1a3e81a9da9abd71995e722318367281d30b35a338bf356662342b653eff38e85881863b7128ddbb856d8ae158365550bb6330b93d4ef0".HexToByteArray(),
D = "0153603164bcef5c9f62388d06dcbf5681479be4397c07ff6f44bb848465e3397537d5f61abc7bc9266d4df6bae1df4847fcfd3dabdda37a2fe549b821ea858d088d".HexToByteArray(),
};
internal static readonly byte[] ECDsa521Certificate =
("308201a93082010ca00302010202102c3134fe79bb9daa48df6431f4c1e4f3300906072a8648ce3d04013014311230100603"
+ "5504031309456335323155736572301e170d3135303931303231333832305a170d3136303931303033333832305a30143112"
+ "30100603550403130945633532315573657230819b301006072a8648ce3d020106052b8104002303818600040134af29d1fe"
+ "5e581fd2ff6194263abcb6f8cb4d9c08bdb384ede9b8663ae2f4e1af6c85eacc69dc768fbfcd856630792e05484cefb1fefb"
+ "693081dc6490dac579c000bfe103f53cbcb039873b1a3e81a9da9abd71995e722318367281d30b35a338bf356662342b653e"
+ "ff38e85881863b7128ddbb856d8ae158365550bb6330b93d4ef0300906072a8648ce3d040103818b0030818702420090bdf5"
+ "dfb328501910da4b02ba3ccd41f2bb073608c55f0f2b2e1198496c59b44db9e516a6a63ba7841d22cf590e39d3f09636d0eb"
+ "cd59a92c105f499e1329615602414285111634719b9bbd10eb7d08655b2fa7d7eb5e225bfdafef15562ae2f9f0c6a943a7bd"
+ "f0e39223d807b5e2e617a8e424294d90869567326531bcad0f893a0f3a").HexToByteArray();
internal static readonly byte[] EccCert_KeyAgreement = (
"308201553081FDA00302010202105A1C956450FFED894E85DC61E11CD968300A" +
"06082A8648CE3D04030230143112301006035504030C09454344482054657374" +
"301E170D3135303433303138303131325A170D3136303433303138323131325A" +
"30143112301006035504030C094543444820546573743059301306072A8648CE" +
"3D020106082A8648CE3D0301070342000477DE73EA00A82250B69E3F24A14CDD" +
"C4C47C83993056DD0A2C6C17D5C8E7A054216B9253533D12C082E0C8B91B3B10" +
"CDAB564820D417E6D056E4E34BCCA87301A331302F300E0603551D0F0101FF04" +
"0403020009301D0603551D0E0416041472DE05F588BF2741C8A28FF99EA399F7" +
"AAB2C1B3300A06082A8648CE3D040302034700304402203CDF0CC71C63747BDA" +
"2D2D563115AE68D34867E74BCA02738086C316B846CDF2022079F3990E5DCCEE" +
"627B2E6E42317D4D279181EE695EE239D0C8516DD53A896EC3").HexToByteArray();
internal static readonly byte[] ECDsa224Certificate = (
"3082026630820214A003020102020900B94BCCE3179BAA21300A06082A8648CE" +
"3D040302308198310B30090603550406130255533113301106035504080C0A57" +
"617368696E67746F6E3110300E06035504070C075265646D6F6E64311E301C06" +
"0355040A0C154D6963726F736F667420436F72706F726174696F6E3120301E06" +
"0355040B0C172E4E4554204672616D65776F726B2028436F7265465829312030" +
"1E06035504030C174E4953542F53454320502D3232342054657374204B657930" +
"1E170D3135313233313232353532345A170D3136303133303232353532345A30" +
"8198310B30090603550406130255533113301106035504080C0A57617368696E" +
"67746F6E3110300E06035504070C075265646D6F6E64311E301C060355040A0C" +
"154D6963726F736F667420436F72706F726174696F6E3120301E060355040B0C" +
"172E4E4554204672616D65776F726B2028436F72654658293120301E06035504" +
"030C174E4953542F53454320502D3232342054657374204B6579304E30100607" +
"2A8648CE3D020106052B81040021033A000452FF02B55AE35AA7FFF1B0A82DC2" +
"260083DD7D5893E85FBAD1D663B718176F7D5D9A04B8AEA968E9FECFEE348CDB" +
"49A938401783BADAC484A350304E301D0603551D0E041604140EA9C5C4681A6E" +
"48CE64E47EE8BBB0BA5FF8AB3E301F0603551D230418301680140EA9C5C4681A" +
"6E48CE64E47EE8BBB0BA5FF8AB3E300C0603551D13040530030101FF300A0608" +
"2A8648CE3D040302034000303D021D00AC10B79B6FD6BEE113573A1B68A3B771" +
"3B9DA2719A9588376E334811021C1AAC3CA829DA79CE223FA83283E6F0A5A59D" +
"2399E140D957C1C9DDAF").HexToByteArray();
internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_Windows = (
"3082046D0201033082042906092A864886F70D010701A082041A048204163082" +
"04123082019306092A864886F70D010701A0820184048201803082017C308201" +
"78060B2A864886F70D010C0A0102A081CC3081C9301C060A2A864886F70D010C" +
"0103300E0408EC154269C5878209020207D00481A80BAA4AF8660E6FAB7B050B" +
"8EF604CFC378652B54FE005DC3C7E2F12E5EFC7FE2BB0E1B3828CAFE752FD64C" +
"7CA04AF9FBC5A1F36E30D7D299C52BF6AE65B54B9240CC37C04E7E06330C24E9" +
"6D19A67B7015A6BF52C172FFEA719B930DBE310EEBC756BDFF2DF2846EE973A6" +
"6C63F4E9130083D64487B35C1941E98B02B6D5A92972293742383C62CCAFB996" +
"EAD71A1DF5D0380EFFF25BA60B233A39210FD7D55A9B95CD8A440DF666318199" +
"301306092A864886F70D0109153106040401000000302306092A864886F70D01" +
"091431161E140045004300440053004100540065007300740031305D06092B06" +
"0104018237110131501E4E004D006900630072006F0073006F00660074002000" +
"53006F0066007400770061007200650020004B00650079002000530074006F00" +
"72006100670065002000500072006F007600690064006500723082027706092A" +
"864886F70D010706A0820268308202640201003082025D06092A864886F70D01" +
"0701301C060A2A864886F70D010C0106300E0408175CCB1790C48584020207D0" +
"80820230E956E38768A035D8EA911283A63F2E5B6E5B73231CFC4FFD386481DE" +
"24B7BB1B0995D614A0D1BD086215CE0054E01EF9CF91B7D80A4ACB6B596F1DFD" +
"6CBCA71476F610C0D6DD24A301E4B79BA6993F15D34A8ADB7115A8605E797A2C" +
"6826A4379B6590B56CA29F7C36997119257A827C3CA0EC7F8F819536208C650E" +
"324C8F88479478705F833155463A4EFC02B5D5E2608B83F3CAF6C9BB97C1BBBF" +
"C6C5584BDCD39C46A3944915B3845C41429C7792EB4FA3A7EDECCD801F31A4B6" +
"EF57D808AEEAAF3D1F55F378EF8EF9632CED16EDA3EFBE4A9D5C5F608CA90A9A" +
"C8D3F86462AC219BFFD0B8A87DDD22CF029230369B33FC2B488B5F82702EFC3F" +
"270F912EAD2E2402D99F8324164C5CD5959F22DEC0D1D212345B4B3F62848E7D" +
"9CFCE2224B61976C107E1B218B4B7614FF65BCCA388F85D6920270D4C588DEED" +
"323C416D014F5F648CC2EE941855EB3C889DCB9A345ED11CAE94041A86ED23E5" +
"789137A3DE225F4023D260BB686901F2149B5D7E37102FFF5282995892BDC2EA" +
"B48BD5DA155F72B1BD05EE3EDD32160AC852E5B47CA9AEACE24946062E9D7DCD" +
"A642F945C9E7C98640DFAC7A2B88E76A560A0B4156611F9BE8B3613C71870F03" +
"5062BD4E3D9FD896CF373CBFBFD31410972CDE50739FFB8EC9180A52D7F5415E" +
"BC997E5A4221349B4BB7D53614630EEEA729A74E0C0D20726FDE5814321D6C26" +
"5A7DC6BA24CAF2FCE8C8C162733D58E02E08921E70EF838B95C96A5818489782" +
"563AE8A2A85F64A95EB350FF8EF6D625AD031BCD303B301F300706052B0E0302" +
"1A0414C5D73B6AEC769928C4951FDEDA090D1116F48A230414B59D4FECA9944D" +
"40EEFDE7FB96196D167B0FA511020207D0").HexToByteArray();
// The PFX in ECDsaP256_DigitalSignature_Pfx_Windows washed through OpenSSL
internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_OpenSsl = (
"308203BE0201033082038406092A864886F70D010701A0820375048203713082" +
"036D308201FF06092A864886F70D010706A08201F0308201EC020100308201E5" +
"06092A864886F70D010701301C060A2A864886F70D010C0106300E040888F579" +
"00302DB63A02020800808201B8F5EDB44F8B2572E85E52946B233A47F03DF776" +
"BC3A05CB74B4145A9D3AE3C7FD61B330194E1E154B89929F3FA3908FEE95512A" +
"052FDDE8E1913E2CCFD803EE6D868696D86934DCF5300DC951F36BE93E3F4AA2" +
"096B926CF8410AF77FFA087213F84F17EB1D36B61AF4AAD87288301569239B9A" +
"B66392ADA3D468DC33F42FCEC3BEE78148CA72686BB733DB89FC951AE92FD0F7" +
"D5937DE78B1AF984BD13E5127F73A91D40097976AEF00157DCC34B16C1724E5B" +
"88090A1A2DA7337C72720A7ED8F1A89C09AB4143C3F6D80B1925AB8F744069F6" +
"399D997827F7D0931DCB5E3B09783D1D8555910906B33AD03759D292021C21A2" +
"9EA2F29CF9BA4D66E4E69AA9FDCCCB4D49A806DBB804EBEBAED7AE0DD4AD2133" +
"1482A3CC5DB246CE59998824B7E46F337F8887D990FA1756D6A039D293B243BB" +
"DCFB19AD613A42C5778E7094EA43C3136EF359209790462A36CF87D89B6D76CF" +
"BD8C34B8C41D96C83683751B8B067F42017A37D05B599B82B70830B5A93499A0" +
"A4791F5DAB2143C8DF35EC7E88B71A0990E7F6FEA304CE594C9280D7B9120816" +
"45C87112B1ED85124533792ABEF8B4946F811FB9FE922F6F786E5BFD7D7C43F6" +
"48AB43C43F3082016606092A864886F70D010701A0820157048201533082014F" +
"3082014B060B2A864886F70D010C0A0102A081B43081B1301C060A2A864886F7" +
"0D010C0103300E0408F58B95D6E307213C02020800048190E0FB35890FFB6F30" +
"7DD0BD8B10EB10488EAB18702E5AC9F67C557409DF8E3F382D06060FB3B5A08D" +
"1EA31313E80A0488B4034C8906BD873A5308E412783684A35DBD9EEACF5D090D" +
"AE7390E3309D016C41133946A6CF70E32BE8002CD4F06A90F5BBCE6BF932EC71" +
"F634312D315310CE2015B30C51FCC54B60FB3D6E7B734C1ADEBE37056A46AB3C" +
"23276B16603FC50C318184302306092A864886F70D01091531160414F20D17B7" +
"9B898999F0AA1D5EA333FAEF2BDB2A29305D06092B060104018237110131501E" +
"4E004D006900630072006F0073006F0066007400200053006F00660074007700" +
"61007200650020004B00650079002000530074006F0072006100670065002000" +
"500072006F0076006900640065007230313021300906052B0E03021A05000414" +
"96C2244022AB2B809E0F97270F7F4EA7769DD26F04084C0E2946D65F8F220202" +
"0800").HexToByteArray();
internal struct ECDsaCngKeyValues
{
public byte[] QX;
public byte[] QY;
public byte[] D;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.Core.Common.Models;
using Orchard.Core.Containers.Models;
using Orchard.Core.Containers.Services;
using Orchard.Core.Containers.ViewModels;
using Orchard.Core.Contents;
using Orchard.Core.Contents.ViewModels;
using Orchard.Core.Title.Models;
using Orchard.Data;
using Orchard.DisplayManagement;
using Orchard.Lists.Helpers;
using Orchard.Lists.ViewModels;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;
using ContentOptions = Orchard.Lists.ViewModels.ContentOptions;
using ContentsBulkAction = Orchard.Lists.ViewModels.ContentsBulkAction;
using ListContentsViewModel = Orchard.Lists.ViewModels.ListContentsViewModel;
namespace Orchard.Lists.Controllers {
public class AdminController : Controller {
private readonly IContentManager _contentManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IOrchardServices _services;
private readonly IContainerService _containerService;
private readonly IListViewService _listViewService;
private readonly ITransactionManager _transactionManager;
public AdminController(
IOrchardServices services,
IContentDefinitionManager contentDefinitionManager,
IShapeFactory shapeFactory,
IContainerService containerService,
IListViewService listViewService,
ITransactionManager transactionManager) {
_services = services;
_contentManager = services.ContentManager;
_contentDefinitionManager = contentDefinitionManager;
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
Shape = shapeFactory;
_containerService = containerService;
_listViewService = listViewService;
_transactionManager = transactionManager;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
dynamic Shape { get; set; }
public ActionResult Index(Core.Contents.ViewModels.ListContentsViewModel model, PagerParameters pagerParameters) {
var query = _containerService.GetContainersQuery(VersionOptions.Latest);
if (!String.IsNullOrEmpty(model.TypeName)) {
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.TypeName);
if (contentTypeDefinition == null)
return HttpNotFound();
model.TypeDisplayName = !String.IsNullOrWhiteSpace(contentTypeDefinition.DisplayName)
? contentTypeDefinition.DisplayName
: contentTypeDefinition.Name;
query = query.ForType(model.TypeName);
}
switch (model.Options.OrderBy) {
case ContentsOrder.Modified:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.ModifiedUtc);
break;
case ContentsOrder.Published:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.PublishedUtc);
break;
case ContentsOrder.Created:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.CreatedUtc);
break;
}
model.Options.SelectedFilter = model.TypeName;
model.Options.FilterOptions = _containerService.GetContainerTypes()
.Select(ctd => new KeyValuePair<string, string>(ctd.Name, ctd.DisplayName))
.ToList().OrderBy(kvp => kvp.Value);
var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters);
var pagerShape = Shape.Pager(pager).TotalItemCount(query.Count());
var pageOfLists = query.Slice(pager.GetStartIndex(), pager.PageSize);
var listsShape = Shape.List();
listsShape.AddRange(pageOfLists.Select(x => _contentManager.BuildDisplay(x, "SummaryAdmin")).ToList());
var viewModel = Shape.ViewModel()
.Lists(listsShape)
.Pager(pagerShape)
.Options(model.Options);
return View(viewModel);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.Filter")]
public ActionResult ListFilterPOST(ContentOptions options) {
var routeValues = ControllerContext.RouteData.Values;
if (options != null) {
routeValues["Options.OrderBy"] = options.OrderBy;
if (_containerService.GetContainerTypes().Any(ctd => string.Equals(ctd.Name, options.SelectedFilter, StringComparison.OrdinalIgnoreCase))) {
routeValues["id"] = options.SelectedFilter;
}
else {
routeValues.Remove("id");
}
}
return RedirectToAction("Index", routeValues);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.BulkEdit")]
public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, PagerParameters pagerParameters) {
if (itemIds != null) {
var checkedContentItems = _contentManager.GetMany<ContentItem>(itemIds, VersionOptions.Latest, QueryHints.Empty);
switch (options.BulkAction) {
case ContentsBulkAction.None:
break;
case ContentsBulkAction.PublishNow:
foreach (var item in checkedContentItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't publish selected lists."))) {
_transactionManager.Cancel();
return new HttpUnauthorizedResult();
}
_contentManager.Publish(item);
}
_services.Notifier.Success(T("Lists successfully published."));
break;
case ContentsBulkAction.Unpublish:
foreach (var item in checkedContentItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't unpublish selected lists."))) {
_transactionManager.Cancel();
return new HttpUnauthorizedResult();
}
_contentManager.Unpublish(item);
}
_services.Notifier.Success(T("Lists successfully unpublished."));
break;
case ContentsBulkAction.Remove:
foreach (var item in checkedContentItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.DeleteContent, item, T("Couldn't remove selected lists."))) {
_transactionManager.Cancel();
return new HttpUnauthorizedResult();
}
_contentManager.Remove(item);
}
_services.Notifier.Success(T("Lists successfully removed."));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return RedirectToAction("Index", new { page = pagerParameters.Page, pageSize = pagerParameters.PageSize });
}
public ActionResult Create(string id) {
if (String.IsNullOrWhiteSpace(id)) {
var containerTypes = _containerService.GetContainerTypes().ToList();
if (containerTypes.Count > 1) {
return RedirectToAction("SelectType");
}
return RedirectToAction("Create", new {id = containerTypes.First().Name});
}
return RedirectToAction("Create", "Admin", new {area = "Contents", id, returnUrl = Url.Action("Index", "Admin", new { area = "Orchard.Lists" })});
}
public ActionResult SelectType() {
var viewModel = Shape.ViewModel().ContainerTypes(_containerService.GetContainerTypes().ToList());
return View(viewModel);
}
public ActionResult List(ListContentsViewModel model, PagerParameters pagerParameters) {
var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters);
var container = _contentManager.GetLatest(model.ContainerId);
if (container == null || !container.Has<ContainerPart>()) {
return HttpNotFound();
}
model.ContainerDisplayName = container.ContentManager.GetItemMetadata(container).DisplayText;
if (string.IsNullOrEmpty(model.ContainerDisplayName)) {
model.ContainerDisplayName = container.ContentType;
}
var query = GetListContentItemQuery(model.ContainerId);
if (query == null) {
return HttpNotFound();
}
var containerPart = container.As<ContainerPart>();
if (containerPart.EnablePositioning) {
query = OrderByPosition(query);
}
else {
switch (model.Options.OrderBy) {
case SortBy.Modified:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.ModifiedUtc);
break;
case SortBy.Published:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.PublishedUtc);
break;
case SortBy.Created:
query = query.OrderByDescending<CommonPartRecord>(cr => cr.CreatedUtc);
break;
case SortBy.DisplayText:
// Note: This will obviously not work for items without a TitlePart, but we're OK with that.
query = query.OrderBy<TitlePartRecord>(cr => cr.Title);
break;
}
}
var listView = containerPart.AdminListView.BuildDisplay(new BuildListViewDisplayContext {
New = _services.New,
Container = containerPart,
ContentQuery = query,
Pager = pager,
ContainerDisplayName = model.ContainerDisplayName
});
var viewModel = Shape.ViewModel()
.Pager(pager)
.ListView(listView)
.ListViewProvider(containerPart.AdminListView)
.ListViewProviders(_listViewService.Providers.ToList())
.Options(model.Options)
.Container(container)
.ContainerId(model.ContainerId)
.ContainerDisplayName(model.ContainerDisplayName)
.ContainerContentType(container.ContentType)
.ItemContentTypes(container.As<ContainerPart>().ItemContentTypes.ToList())
;
if (containerPart.Is<ContainablePart>()) {
viewModel.ListNavigation(_services.New.ListNavigation(ContainablePart: containerPart.As<ContainablePart>()));
}
return View(viewModel);
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.Order")]
public ActionResult ListOrderPOST(ContentOptions options) {
var routeValues = ControllerContext.RouteData.Values;
if (options != null) {
routeValues["Options.OrderBy"] = options.OrderBy;
}
return RedirectToAction("List", routeValues);
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.BulkEdit")]
public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, int? targetContainerId, PagerParameters pagerParameters, string returnUrl) {
if (itemIds != null) {
switch (options.BulkAction) {
case ContentsBulkAction.None:
break;
case ContentsBulkAction.PublishNow:
if (!BulkPublishNow(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.Unpublish:
if (!BulkUnpublish(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.Remove:
if (!BulkRemove(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.RemoveFromList:
if (!BulkRemoveFromList(itemIds)) {
return new HttpUnauthorizedResult();
}
break;
case ContentsBulkAction.MoveToList:
if (!BulkMoveToList(itemIds, targetContainerId)) {
return new HttpUnauthorizedResult();
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("List", new { page = pagerParameters.Page, pageSize = pagerParameters.PageSize }));
}
[HttpPost]
public ActionResult Insert(int containerId, int itemId, PagerParameters pagerParameters) {
var container = _containerService.Get(containerId, VersionOptions.Latest);
var item = _contentManager.Get(itemId, VersionOptions.Latest, QueryHints.Empty.ExpandParts<CommonPart, ContainablePart>());
var commonPart = item.As<CommonPart>();
var previousItemContainer = commonPart.Container;
var itemMetadata = _contentManager.GetItemMetadata(item);
var containerMetadata = _contentManager.GetItemMetadata(container);
var position = _containerService.GetFirstPosition(containerId) + 1;
LocalizedString message;
if (previousItemContainer == null) {
message = T("{0} was moved to <a href=\"{1}\">{2}</a>", itemMetadata.DisplayText, Url.RouteUrl(containerMetadata.AdminRouteValues), containerMetadata.DisplayText);
}
else if (previousItemContainer.Id != containerId) {
var previousItemContainerMetadata = _contentManager.GetItemMetadata(commonPart.Container);
message = T("{0} was moved from <a href=\"{3}\">{4}</a> to <a href=\"{1}\">{2}</a>",
itemMetadata.DisplayText,
Url.RouteUrl(containerMetadata.AdminRouteValues),
containerMetadata.DisplayText,
Url.RouteUrl(previousItemContainerMetadata.AdminRouteValues),
previousItemContainerMetadata.DisplayText);
}
else {
message = T("{0} is already part of this list and was moved to the top.", itemMetadata.DisplayText);
}
_containerService.MoveItem(item.As<ContainablePart>(), container, position);
_services.Notifier.Information(message);
return RedirectToAction("List", new { containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize });
}
[HttpPost]
public ActionResult UpdatePositions(int containerId, int oldIndex, int newIndex, PagerParameters pagerParameters) {
var pager = new Pager(_services.WorkContext.CurrentSite, pagerParameters);
var query = OrderByPosition(GetListContentItemQuery(containerId));
if (query == null) {
return HttpNotFound();
}
var pageOfContentItems = query.Slice(pager.GetStartIndex(), pager.PageSize).ToList();
var contentItem = pageOfContentItems[oldIndex];
pageOfContentItems.Remove(contentItem);
pageOfContentItems.Insert(newIndex, contentItem);
var index = pager.GetStartIndex() + pageOfContentItems.Count;
foreach (var item in pageOfContentItems.Select(x => x.As<ContainablePart>())) {
item.Position = --index;
RePublish(item);
}
return new EmptyResult();
}
[ActionName("List")]
[HttpPost, FormValueRequired("submit.ListOp")]
public ActionResult ListOperation(int containerId, ListOperation operation, SortBy? sortBy, SortDirection? sortByDirection, PagerParameters pagerParameters) {
var items = _containerService.GetContentItems(containerId, VersionOptions.Latest).Select(x => x.As<ContainablePart>());
switch (operation) {
case ViewModels.ListOperation.Reverse:
_containerService.Reverse(items);
_services.Notifier.Success(T("The list has been reversed."));
break;
case ViewModels.ListOperation.Shuffle:
_containerService.Shuffle(items);
_services.Notifier.Success(T("The list has been shuffled."));
break;
case ViewModels.ListOperation.Sort:
_containerService.Sort(items, sortBy.GetValueOrDefault(), sortByDirection.GetValueOrDefault());
_services.Notifier.Success(T("The list has been sorted."));
break;
default:
_services.Notifier.Error(T("Please select an operation to perform on the list."));
break;
}
return RedirectToAction("List", new {containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize});
}
[HttpPost, ActionName("List")]
[FormValueRequired("listViewName")]
public ActionResult ChangeListView(int containerId, string listViewName, PagerParameters pagerParameters) {
var container = _containerService.Get(containerId, VersionOptions.Latest);
if (container == null || !container.Has<ContainerPart>()) {
return HttpNotFound();
}
container.Record.AdminListViewName = listViewName;
return RedirectToAction("List", new { containerId, page = pagerParameters.Page, pageSize = pagerParameters.PageSize });
}
/// <summary>
/// Only publishes the content if it is already published.
/// </summary>
private void RePublish(IContent content) {
if(content.ContentItem.VersionRecord.Published)
_contentManager.Publish(content.ContentItem);
}
private IContentQuery<ContentItem> GetListContentItemQuery(int containerId) {
var containableTypes = GetContainableTypes().Select(ctd => ctd.Name).ToList();
if (containableTypes.Count == 0) {
// Force the name to be matched against empty and return no items in the query
containableTypes.Add(string.Empty);
}
var query = _contentManager
.Query(VersionOptions.Latest, containableTypes.ToArray())
.Join<CommonPartRecord>().Where(cr => cr.Container.Id == containerId);
return query;
}
private IContentQuery<ContentItem> OrderByPosition(IContentQuery<ContentItem> query) {
return query.Join<ContainablePartRecord>().OrderByDescending(x => x.Position);
}
private IEnumerable<ContentTypeDefinition> GetContainableTypes() {
return _contentDefinitionManager.ListTypeDefinitions().Where(ctd => ctd.Parts.Any(c => c.PartDefinition.Name == "ContainablePart"));
}
private bool BulkMoveToList(IEnumerable<int> selectedIds, int? targetContainerId) {
if (!targetContainerId.HasValue) {
_services.Notifier.Information(T("Please select the list to move the items to."));
return true;
}
var id = targetContainerId.Value;
var targetContainer = _contentManager.Get<ContainerPart>(id);
if (targetContainer == null) {
_services.Notifier.Information(T("Please select the list to move the items to."));
return true;
}
var itemContentTypes = targetContainer.ItemContentTypes.ToList();
var containerDisplayText = _contentManager.GetItemMetadata(targetContainer).DisplayText ?? targetContainer.ContentItem.ContentType;
var selectedItems = _contentManager.GetMany<ContainablePart>(selectedIds, VersionOptions.Latest, QueryHints.Empty);
foreach (var item in selectedItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent, item, T("Couldn't move selected content."))) {
return false;
}
// Ensure the item can be in that container.
if (itemContentTypes.Any() && itemContentTypes.All(x => x.Name != item.ContentItem.ContentType)) {
_services.TransactionManager.Cancel();
_services.Notifier.Warning(T("One or more items could not be moved to '{0}' because it is restricted to containing items of type '{1}'.", containerDisplayText, itemContentTypes.Select(x => x.DisplayName).ToOrString(T)));
return true; // todo: transactions
}
_containerService.MoveItem(item, targetContainer);
}
_services.Notifier.Success(T("Content successfully moved to <a href=\"{0}\">{1}</a>.", Url.Action("List", new { containerId = targetContainerId }), containerDisplayText));
return true;
}
private bool BulkRemoveFromList(IEnumerable<int> itemIds) {
var selectedItems = _contentManager.GetMany<ContainablePart>(itemIds, VersionOptions.Latest, QueryHints.Empty);
foreach (var item in selectedItems) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent, item, T("Couldn't remove selected content from the list."))) {
_services.TransactionManager.Cancel();
return false;
}
item.As<CommonPart>().Record.Container = null;
_containerService.UpdateItemPath(item.ContentItem);
}
_services.Notifier.Success(T("Content successfully removed from the list."));
return true;
}
private bool BulkRemove(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.DeleteContent, item, T("Couldn't remove selected content."))) {
_services.TransactionManager.Cancel();
return false;
}
_contentManager.Remove(item);
}
_services.Notifier.Success(T("Content successfully removed."));
return true;
}
private bool BulkUnpublish(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't unpublish selected content."))) {
_services.TransactionManager.Cancel();
return false;
}
_contentManager.Unpublish(item);
}
_services.Notifier.Success(T("Content successfully unpublished."));
return true;
}
private bool BulkPublishNow(IEnumerable<int> itemIds) {
foreach (var item in itemIds.Select(itemId => _contentManager.GetLatest(itemId))) {
if (!_services.Authorizer.Authorize(Orchard.Core.Contents.Permissions.PublishContent, item, T("Couldn't publish selected content."))) {
_services.TransactionManager.Cancel();
return false;
}
_contentManager.Publish(item);
}
_services.Notifier.Success(T("Content successfully published."));
return 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.Collections.Generic;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using Xunit;
namespace System.ComponentModel.Composition
{
public class ExportProviderEventTests
{
[Fact]
public void BatchAdd_ShouldFireEvents()
{
var container = ContainerFactory.Create();
var eventListener = new ExportProviderListener(container, container);
var batch = new CompositionBatch();
batch.AddExportedValue<object>("MyExport", new object());
eventListener.VerifyCompose(batch);
}
[Fact]
public void BatchRemove_ShouldFireEvents()
{
var container = ContainerFactory.Create();
var batch = new CompositionBatch();
var exportPart = batch.AddExportedValue<object>("MyExport", new object());
container.Compose(batch);
var eventListener = new ExportProviderListener(container, container);
batch = new CompositionBatch();
batch.RemovePart(exportPart);
eventListener.VerifyCompose(batch);
}
[Fact]
public void BatchAddRemove_ShouldFireEvents()
{
var container = ContainerFactory.Create();
var batch = new CompositionBatch();
var exportPart = batch.AddExportedValue<object>("MyExport", new object());
container.Compose(batch);
var eventListener = new ExportProviderListener(container, container);
batch = new CompositionBatch();
batch.RemovePart(exportPart);
batch.AddExportedValue<object>("MyExport2", new object());
eventListener.VerifyCompose(batch);
}
[Fact]
public void BatchMultipleAdds_ShouldFireEvents()
{
var container = ContainerFactory.Create();
var eventListener = new ExportProviderListener(container, container);
var batch = new CompositionBatch();
batch.AddExportedValue<object>("MyExport", new object());
batch.AddExportedValue<object>("MyExport2", new object());
batch.AddExportedValue<object>("MyExport3", new object());
eventListener.VerifyCompose(batch);
}
[Fact]
public void BatchNestedContainerAdds_ShouldFireEvents()
{
var parentContainer = ContainerFactory.Create();
var container = ContainerFactory.Create(parentContainer);
var eventListener = new ExportProviderListener(parentContainer, container);
var batch = new CompositionBatch();
batch.AddExportedValue<object>("MyExport", new object());
eventListener.VerifyCompose(batch);
}
[Export]
public class SampleCatalogExport { }
[Fact]
public void CatalogAdd_ShouldFireEvents()
{
var catalog = new TypeCatalog(typeof(SampleCatalogExport));
var aggCat = new AggregateCatalog();
var container = ContainerFactory.Create(aggCat);
var eventListener = new ExportProviderListener(container, container);
eventListener.VerifyCatalogAdd(() => aggCat.Catalogs.Add(catalog), typeof(SampleCatalogExport));
}
[Fact]
public void CatalogRemove_ShouldFireEvents()
{
var catalog = new TypeCatalog(typeof(SampleCatalogExport));
var aggCat = new AggregateCatalog();
var container = ContainerFactory.Create(aggCat);
aggCat.Catalogs.Add(catalog);
var eventListener = new ExportProviderListener(container, container);
eventListener.VerifyCatalogRemove(() => aggCat.Catalogs.Remove(catalog), typeof(SampleCatalogExport));
}
[Export]
public class SampleCatalogExport2 { }
[Fact]
[ActiveIssue(812029)]
public void CatalogMultipleAdds_ShouldFireEvents()
{
var catalog = new TypeCatalog(typeof(SampleCatalogExport));
var aggCat = new AggregateCatalog();
var container = ContainerFactory.Create(aggCat);
var eventListener = new ExportProviderListener(container, container);
var otherAggCat = new AggregateCatalog(new TypeCatalog(typeof(SampleCatalogExport)), new TypeCatalog(typeof(SampleCatalogExport2)));
eventListener.VerifyCatalogAdd(() => aggCat.Catalogs.Add(otherAggCat), typeof(SampleCatalogExport), typeof(SampleCatalogExport2));
}
[Fact]
public void CatalogNestedContainerAdds_ShouldFireEvents()
{
var catalog = new TypeCatalog(typeof(SampleCatalogExport));
var aggCat = new AggregateCatalog();
var parentContainer = ContainerFactory.Create(aggCat);
var container = ContainerFactory.Create(parentContainer);
var eventListener = new ExportProviderListener(parentContainer, container);
eventListener.VerifyCatalogAdd(() => aggCat.Catalogs.Add(catalog), typeof(SampleCatalogExport));
}
public class ExportProviderListener
{
private CompositionContainer _container;
private ExportProvider _watchedProvider;
private string[] _expectedAdds;
private string[] _expectedRemoves;
private int _changedEventCount;
private int _changingEventCount;
public ExportProviderListener(CompositionContainer container, ExportProvider watchExportProvider)
{
watchExportProvider.ExportsChanged += OnExportsChanged;
watchExportProvider.ExportsChanging += OnExportsChanging;
this._watchedProvider = watchExportProvider;
this._container = container;
}
public void VerifyCompose(CompositionBatch batch)
{
this._expectedAdds = GetContractNames(batch.PartsToAdd);
this._expectedRemoves = GetContractNames(batch.PartsToRemove);
this._container.Compose(batch);
Assert.True(this._changingEventCount == 1);
Assert.True(this._changedEventCount == 1);
ResetState();
}
public void VerifyCatalogAdd(Action doAdd, params Type[] expectedTypesAdded)
{
this._expectedAdds = GetContractNames(expectedTypesAdded);
doAdd();
Assert.True(this._changingEventCount == 1);
Assert.True(this._changedEventCount == 1);
ResetState();
}
public void VerifyCatalogRemove(Action doRemove, params Type[] expectedTypesRemoved)
{
this._expectedRemoves = GetContractNames(expectedTypesRemoved);
doRemove();
Assert.True(this._changingEventCount == 1);
Assert.True(this._changedEventCount == 1);
ResetState();
}
public void OnExportsChanging(object sender, ExportsChangeEventArgs args)
{
Assert.True(this._expectedAdds != null || this._expectedRemoves != null);
if (this._expectedAdds == null)
{
Assert.Empty(args.AddedExports);
}
else
{
Assert.All(_expectedAdds, add =>
{
Assert.False(this._container.IsPresent(add));
});
}
if (this._expectedRemoves == null)
{
Assert.Empty(args.RemovedExports);
}
else
{
Assert.All(_expectedRemoves, remove =>
{
Assert.True(this._container.IsPresent(remove));
});
}
this._changingEventCount++;
}
public void OnExportsChanged(object sender, ExportsChangeEventArgs args)
{
Assert.True(this._expectedAdds != null || this._expectedRemoves != null);
if (this._expectedAdds == null)
{
Assert.Empty(args.AddedExports);
}
else
{
Assert.All(_expectedAdds, add =>
{
Assert.True(this._container.IsPresent(add));
});
}
if (this._expectedRemoves == null)
{
Assert.Empty(args.RemovedExports);
}
else
{
Assert.All(_expectedRemoves, remove =>
{
Assert.False(this._container.IsPresent(remove));
});
}
Assert.Null(args.AtomicComposition);
this._changedEventCount++;
}
private void ResetState()
{
this._expectedAdds = null;
this._expectedRemoves = null;
this._changedEventCount = 0;
this._changingEventCount = 0;
}
private static string[] GetContractNames(IEnumerable<ExportDefinition> definitions)
{
return definitions.Select(e => e.ContractName).ToArray();
}
private static string[] GetContractNames(IEnumerable<ComposablePart> parts)
{
return GetContractNames(parts.SelectMany(p => p.ExportDefinitions));
}
private static string[] GetContractNames(IEnumerable<Type> types)
{
return GetContractNames(types.Select(t => AttributedModelServices.CreatePartDefinition(t, null)).SelectMany(p => p.ExportDefinitions));
}
}
}
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using DataServiceUtil;
using NBIAService;
namespace SearchComponent
{
internal partial class NBIASearchCoordinator
{
private class QueryForStudiesCommand : SearchCommand
{
private readonly NBIAQueryParameters _queryParameters;
public QueryForStudiesCommand(NBIAQueryParameters queryParameters)
{
_queryParameters = queryParameters;
}
public override void Execute()
{
List<NBIASearchResult> results = new List<NBIASearchResult>();
NBIAStudy studyService = new NBIAStudy();
try
{
DataTable dtStudies = studyService.getStudyInfo(_queryParameters, SearchSettings.Default.NBIADataServiceUrl);
if (dtStudies != null)
{
foreach (DataRow studyUid in dtStudies.Rows)
{
if (base.CancelRequested)
break;
NBIASearchResult result = new NBIASearchResult();
result.Study.StudyInstanceUid = studyUid["studyInstanceUID"].ToString();
results.Add(result);
}
}
}
catch (GridServicerException ex)
{
base.SetError(ex.Message);
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to query grid for Study data");
}
base.AddResultsToTable(results);
foreach (NBIASearchResult result in base.SearchResults)
{
if (base.CancelRequested)
break;
NBIAQueryParameters nbiaQueryParameters = _queryParameters.Clone();
nbiaQueryParameters.StudyInstanceUID = new QueryData(result.Study.StudyInstanceUid, QueryPredicate.EQUAL_TO);
base.EnqueueNextCommand(new QueryForPatientInfoCommand(nbiaQueryParameters, result));
base.EnqueueNextCommand(new QueryForClinicalTrialProtocolDataCommand(nbiaQueryParameters, result));
base.EnqueueNextCommand(new QueryForTrialDataProvenanceCommand(nbiaQueryParameters, result));
base.EnqueueNextCommand(new QueryForClinicalTrialSiteDataCommand(nbiaQueryParameters, result));
base.EnqueueNextCommand(new QueryForSeriesDataCommand(nbiaQueryParameters, result));
}
base.OnCommandExecuted();
}
}
private class QueryForPatientInfoCommand : SearchCommand
{
private readonly NBIAQueryParameters _queryParameters;
private readonly NBIASearchResult _result;
public QueryForPatientInfoCommand(NBIAQueryParameters queryParameters, NBIASearchResult result)
{
_queryParameters = queryParameters;
_result = result;
}
public override void Execute()
{
if (!base.CancelRequested)
{
NBIAPatient patientService = new NBIAPatient();
try
{
DataTable dtStudies = patientService.getPatientInfo(_queryParameters, SearchSettings.Default.NBIADataServiceUrl);
if (dtStudies != null && dtStudies.Rows.Count > 0)
{
_result.Patient.PatientId = dtStudies.Rows[0]["patientId"].ToString();
_result.Patient.PatientsName = dtStudies.Rows[0]["patientName"].ToString();
_result.Patient.PatientsSex = dtStudies.Rows[0]["patientSex"].ToString();
if (!string.IsNullOrEmpty(dtStudies.Rows[0]["patientBirthDate"].ToString()))
{
try
{
_result.Patient.PatientBirthDate = DateTime.Parse(dtStudies.Rows[0]["patientBirthDate"].ToString());
}
catch (Exception)
{
}
}
base.OnResultUpdated(_result);
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to query grid for Patient data");
}
}
base.OnCommandExecuted();
}
}
private class QueryForClinicalTrialProtocolDataCommand : SearchCommand
{
private readonly NBIAQueryParameters _queryParameters;
private readonly NBIASearchResult _result;
public QueryForClinicalTrialProtocolDataCommand(NBIAQueryParameters queryParameters, NBIASearchResult result)
{
_queryParameters = queryParameters;
_result = result;
}
public override void Execute()
{
if (!base.CancelRequested)
{
NBIAClinicalTrialProtocol clinicalTrailProtocolService = new NBIAClinicalTrialProtocol();
try
{
DataTable dtStudies = clinicalTrailProtocolService.getClinicalTrialProtocolInfo(_queryParameters, SearchSettings.Default.NBIADataServiceUrl);
if (dtStudies != null && dtStudies.Rows.Count > 0)
{
_result.ClinicalTrialProtocol.ProtocolId = dtStudies.Rows[0]["protocolId"].ToString();
_result.ClinicalTrialProtocol.ProtocolName = dtStudies.Rows[0]["protocolName"].ToString();
base.OnResultUpdated(_result);
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to query grid for ClinicalTrialProtocol data");
}
}
base.OnCommandExecuted();
}
}
private class QueryForTrialDataProvenanceCommand : SearchCommand
{
private readonly NBIAQueryParameters _queryParameters;
private readonly NBIASearchResult _result;
public QueryForTrialDataProvenanceCommand(NBIAQueryParameters queryParameters, NBIASearchResult result)
{
_queryParameters = queryParameters;
_result = result;
}
public override void Execute()
{
if (!base.CancelRequested)
{
NBIATrialDataProvenance trailDataProvenanceService = new NBIATrialDataProvenance();
try
{
DataTable dtStudies = trailDataProvenanceService.getTrialDataProvenanceInfo(_queryParameters, SearchSettings.Default.NBIADataServiceUrl);
if (dtStudies != null && dtStudies.Rows.Count > 0)
{
_result.TrialDataProvenance.Project = _queryParameters.ProjectName.SelectedValue;
base.OnResultUpdated(_result);
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to query grid for TrialDataProvenance data");
}
}
base.OnCommandExecuted();
}
}
private class QueryForClinicalTrialSiteDataCommand : SearchCommand
{
private readonly NBIAQueryParameters _queryParameters;
private readonly NBIASearchResult _result;
public QueryForClinicalTrialSiteDataCommand(NBIAQueryParameters queryParameters, NBIASearchResult result)
{
_queryParameters = queryParameters;
_result = result;
}
public override void Execute()
{
if (!base.CancelRequested)
{
NBIAClinicalTrialSite clinicalTrialSiteService = new NBIAClinicalTrialSite();
try
{
DataTable dtStudies = clinicalTrialSiteService.getClinicalTrialSiteInfo(_queryParameters, SearchSettings.Default.NBIADataServiceUrl);
if (dtStudies != null && dtStudies.Rows.Count > 0)
{
_result.ClinicalTrialSite.SiteId = dtStudies.Rows[0]["siteId"].ToString();
_result.ClinicalTrialSite.SiteName = dtStudies.Rows[0]["siteName"].ToString();
base.OnResultUpdated(_result);
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to query grid for ClinicalTrialSiteData data");
}
}
base.OnCommandExecuted();
}
}
private class QueryForSeriesDataCommand : SearchCommand
{
private readonly NBIAQueryParameters _queryParameters;
private readonly NBIASearchResult _result;
public QueryForSeriesDataCommand(NBIAQueryParameters queryParameters, NBIASearchResult result)
{
_queryParameters = queryParameters;
_result = result;
}
public override void Execute()
{
if (!base.CancelRequested)
{
NBIASeries seriesService = new NBIASeries();
try
{
DataTable dtStudies = seriesService.getSeriesInfo(_queryParameters, SearchSettings.Default.NBIADataServiceUrl);
if (dtStudies != null)
{
Console.WriteLine("Project: " + dtStudies.Rows[0].ToString());
Dictionary<string, string> modalities = new Dictionary<string, string>();
foreach (DataRow row in dtStudies.Rows)
{
if (!string.IsNullOrEmpty(row["modality"].ToString().Trim()))
modalities[row["modality"].ToString().Trim()] = string.Empty;
}
if (modalities.Count > 0)
{
_result.Series.Modality = StringUtilities.Combine(modalities.Keys, ",");
base.OnResultUpdated(_result);
}
}
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to query grid for Series data");
}
}
base.OnCommandExecuted();
}
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Presentation.Internal.PropertyEditing
{
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Collections.Generic;
// <summary>
// Collection of simple utilities that deal with the VisualTree
// </summary>
internal static class VisualTreeUtils
{
// The depth of the visual tree we explore in looking for templated children
// (see GetTemplateChild<>())
private const int MaxSearchDepth = 5;
// The maxium wpf visual tree depth
// this value should be kept in [....] with WPF's limit
private const int MaxAllowedTreeDepth = 250;
// <summary>
// Examines the visual children of the given element and returns the one
// with the specified name and type, if one exists
// </summary>
// <typeparam name="T">Type of child to look for</typeparam>
// <param name="container">Container to look in</param>
// <param name="name">Name to look for</param>
// <returns>The specified named child if found, null otherwise</returns>
public static T GetNamedChild<T>(DependencyObject container, string name)
where T : FrameworkElement
{
return GetNamedChild<T>(container, name, 0);
}
// <summary>
// Examines the visual children of the given element and returns the one
// with the specified name and type, if one exists
// </summary>
// <typeparam name="T">Type of child to look for</typeparam>
// <param name="container">Container to look in</param>
// <param name="name">Name to look for</param>
// <param name="searchDepth">Visual depth to search in. Default is 0.</param>
// <returns>The specified named child if found, null otherwise</returns>
public static T GetNamedChild<T>(DependencyObject container, string name, int searchDepth)
where T : FrameworkElement
{
if (container == null || string.IsNullOrEmpty(name) || searchDepth < 0)
{
return null;
}
if (container is T && string.Equals( name, ((T)container).Name))
{
return (T)container;
}
int childCount = VisualTreeHelper.GetChildrenCount(container);
if (childCount == 0)
{
return null;
}
// Look for the first child that matches
for (int index = 0; index < childCount; index++)
{
FrameworkElement child = VisualTreeHelper.GetChild(container, index) as FrameworkElement;
if (child == null)
{
continue;
}
// Search recursively until we reach the requested search depth
T namedChild =
(child.FindName(name) as T) ??
(searchDepth > 0 ? GetNamedChild<T>(child, name, searchDepth - 1) : null);
if (namedChild != null)
{
return namedChild;
}
}
return null;
}
// <summary>
// Helper method that goes down the first-child visual tree and looks for the visual element of the
// specified type. Useful for when you have one control that is templated to look like another
// and you need to get to the template instance itself.
// </summary>
// <typeparam name="T">Type of the visual template to look for</typeparam>
// <param name="element">Element to start from</param>
// <returns>The first matching instance in the visual tree of first children, null otherwise</returns>
public static T GetTemplateChild<T>(DependencyObject element) where T : DependencyObject
{
int availableSearchDepth = MaxSearchDepth;
while (availableSearchDepth > 0 && element != null)
{
int childrenCount = VisualTreeHelper.GetChildrenCount(element);
if (childrenCount < 1)
{
return null;
}
// Just worry about the first child, since we are looking for a template control,
// not a complicated visual tree
//
element = VisualTreeHelper.GetChild(element, 0);
T childAsT = element as T;
if (childAsT != null)
{
return childAsT;
}
availableSearchDepth--;
}
return null;
}
// <summary>
// Goes up the visual tree, looking for an ancestor of the specified Type
// </summary>
// <typeparam name="T">Type to look for</typeparam>
// <param name="child">Starting point</param>
// <returns>Visual ancestor, if any, of the specified starting point and Type</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static T FindVisualAncestor<T>(DependencyObject child) where T : DependencyObject
{
if (child == null)
{
return null;
}
do
{
child = VisualTreeHelper.GetParent(child);
}
while (child != null && !typeof(T).IsAssignableFrom(child.GetType()));
return child as T;
}
// <summary>
// Recursively looks through all the children and looks for and returns the first
// element with IsFocusable set to true.
// </summary>
// <param name="reference">Starting point for the search</param>
// <typeparam name="T">Type of child to look for</typeparam>
// <returns>The first focusable child of the specified Type, null otherwise.</returns>
public static T FindFocusableElement<T>(T reference) where T : UIElement
{
if (reference == null || (reference.Focusable && reference.Visibility == Visibility.Visible))
{
return reference;
}
int childCount = VisualTreeHelper.GetChildrenCount(reference);
for (int i = 0; i < childCount; i++)
{
T child = VisualTreeHelper.GetChild(reference, i) as T;
if (child == null)
{
continue;
}
if (child.Visibility != Visibility.Visible)
{
continue;
}
if (child.Focusable)
{
return child;
}
child = FindFocusableElement<T>(child);
if (child != null)
{
return child;
}
}
return null;
}
// <summary>
// Walks up the parent tree and returns the first
// element with IsFocusable set to true.
// </summary>
// <param name="reference">Starting point for the search</param>
// <typeparam name="T">Type of parent to look for</typeparam>
// <returns>The first focusable parent of the specified Type, null otherwise.</returns>
public static T FindFocusableParent<T>(UIElement reference) where T : UIElement
{
if (null != reference)
{
UIElement parent = VisualTreeHelper.GetParent(reference) as UIElement;
while (null != parent)
{
if (parent.Visibility == Visibility.Visible && parent is T && parent.Focusable)
{
return parent as T;
}
parent = VisualTreeHelper.GetParent(parent) as UIElement;
}
}
return null;
}
// <summary>
// Helper method identical to VisualTreeHelper.GetParent() but that also returns the index of the given child
// with respect to any of its visual siblings
// </summary>
// <param name="child">Child to examine</param>
// <param name="childrenCount">Total number of children that the specified child's parent has</param>
// <param name="childIndex">Index of the specified child in the parent's visual children array</param>
// <returns>Visual parent of the specified child, if any</returns>
public static DependencyObject GetIndexedVisualParent(DependencyObject child, out int childrenCount, out int childIndex)
{
childrenCount = 0;
DependencyObject parent = VisualTreeHelper.GetParent(child);
if (parent != null)
{
childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (childIndex = 0; childIndex < childrenCount; childIndex++)
{
if (child.Equals(VisualTreeHelper.GetChild(parent, childIndex)))
{
return parent;
}
}
}
childIndex = -1;
return null;
}
// <summary>
// Helper method that goes up the visual tree checking the visibility flag of the specified element
// and all its parents. If an invisible parent is found, the method return false. Otherwise it returns
// true.
// </summary>
// <param name="element">Element to check</param>
// <returns>True if the specified element and all of its visual parents are visible,
// false otherwise.</returns>
public static bool IsVisible(UIElement element)
{
UIElement parent = element;
while (parent != null)
{
if (parent.Visibility != Visibility.Visible)
{
return false;
}
parent = VisualTreeHelper.GetParent(parent) as UIElement;
}
return true;
}
/// <summary>
/// Helper method that trasverse the visual tree checking for immediate parent of specified type that has children
/// that is too deep for WPF visual tree
/// </summary>
/// <typeparam name="T">The type of parent to look for</typeparam>
/// <param name="root">The root element to start checking</param>
/// <returns></returns>
public static ICollection<T> PrunVisualTree<T>(Visual root) where T : DependencyObject
{
HashSet<T> deepElements = new HashSet<T>();
Stack<VisualState> stack = new Stack<VisualState>();
VisualState currentObject = new VisualState(root, GetTreeDepth(root));
stack.Push(currentObject);
int totalChildCount = 0;
Visual child;
T violatingParent;
//doing a depth first walk of the visual tree.
while (stack.Count > 0)
{
currentObject = stack.Pop();
// currentObject.Depth + 1 is the children's depth
// if it's too deep, we would try to find the parent and stop traversing
// this node further
if (currentObject.Depth + 1 >= MaxAllowedTreeDepth)
{
violatingParent = currentObject.Visual as T;
if (violatingParent != null)
{
deepElements.Add(violatingParent);
}
else
{
violatingParent = FindVisualAncestor<T>(currentObject.Visual);
if (violatingParent != null)
{
deepElements.Add(violatingParent);
}
}
}
else // continue the depth first traversal
{
totalChildCount = VisualTreeHelper.GetChildrenCount(currentObject.Visual);
for (int i = 0; i < totalChildCount; i++)
{
child = VisualTreeHelper.GetChild(currentObject.Visual, i) as Visual;
if (child != null)
{
stack.Push(new VisualState(child, currentObject.Depth + 1));
}
}
}
}
return deepElements;
}
//find the depth of an DependencyObject
public static uint GetTreeDepth(DependencyObject element)
{
uint depth = 0;
while (element != null)
{
depth++;
if (element is Visual || element is Visual3D)
{
element = VisualTreeHelper.GetParent(element);
}
else
{
element = LogicalTreeHelper.GetParent(element);
}
}
return depth;
}
private class VisualState
{
internal Visual Visual { get; set; }
internal uint Depth { get; set; }
internal VisualState(Visual visual, uint depth)
{
this.Visual = visual;
this.Depth = depth;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.ClientStack.LindenUDP;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Hypergrid;
using OpenMetaverse;
using OpenMetaverse.Packets;
using log4net;
using Nini.Config;
using Mono.Addins;
using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
namespace OpenSim.Region.CoreModules.Framework.UserManagement
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserManagementModule")]
public class UserManagementModule : ISharedRegionModule, IUserManagement, IPeople
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled;
protected List<Scene> m_Scenes = new List<Scene>();
protected IServiceThrottleModule m_ServiceThrottle;
// The cache
protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>();
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
string umanmod = config.Configs["Modules"].GetString("UserManagementModule", Name);
if (umanmod == Name)
{
m_Enabled = true;
Init();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name);
}
}
public bool IsSharedModule
{
get { return true; }
}
public virtual string Name
{
get { return "BasicUserManagementModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IUserManagement>(this);
scene.RegisterModuleInterface<IPeople>(this);
scene.EventManager.OnNewClient += new EventManager.OnNewClientDelegate(EventManager_OnNewClient);
scene.EventManager.OnPrimsLoaded += new EventManager.PrimsLoaded(EventManager_OnPrimsLoaded);
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IUserManagement>(this);
m_Scenes.Remove(scene);
}
}
public void RegionLoaded(Scene s)
{
if (m_Enabled && m_ServiceThrottle == null)
m_ServiceThrottle = s.RequestModuleInterface<IServiceThrottleModule>();
}
public void PostInitialise()
{
}
public void Close()
{
m_Scenes.Clear();
lock (m_UserCache)
m_UserCache.Clear();
}
#endregion ISharedRegionModule
#region Event Handlers
void EventManager_OnPrimsLoaded(Scene s)
{
// let's sniff all the user names referenced by objects in the scene
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Caching creators' data from {0} ({1} objects)...", s.RegionInfo.RegionName, s.GetEntities().Length);
s.ForEachSOG(delegate(SceneObjectGroup sog) { CacheCreators(sog); });
}
void EventManager_OnNewClient(IClientAPI client)
{
client.OnConnectionClosed += new Action<IClientAPI>(HandleConnectionClosed);
client.OnNameFromUUIDRequest += new UUIDNameRequest(HandleUUIDNameRequest);
client.OnAvatarPickerRequest += new AvatarPickerRequest(HandleAvatarPickerRequest);
}
void HandleConnectionClosed(IClientAPI client)
{
client.OnNameFromUUIDRequest -= new UUIDNameRequest(HandleUUIDNameRequest);
client.OnAvatarPickerRequest -= new AvatarPickerRequest(HandleAvatarPickerRequest);
}
void HandleUUIDNameRequest(UUID uuid, IClientAPI client)
{
// m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: Handling request for name binding of UUID {0} from {1}",
// uuid, remote_client.Name);
if (m_Scenes[0].LibraryService != null && (m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid))
{
client.SendNameReply(uuid, "Mr", "OpenSim");
}
else
{
string[] names = new string[2];
if (TryGetUserNamesFromCache(uuid, names))
{
client.SendNameReply(uuid, names[0], names[1]);
return;
}
// Not found in cache, queue continuation
m_ServiceThrottle.Enqueue("name", uuid.ToString(), delegate
{
//m_log.DebugFormat("[YYY]: Name request {0}", uuid);
// As least upto September 2013, clients permanently cache UUID -> Name bindings. Some clients
// appear to clear this when the user asks it to clear the cache, but others may not.
//
// So to avoid clients
// (particularly Hypergrid clients) permanently binding "Unknown User" to a given UUID, we will
// instead drop the request entirely.
if (TryGetUserNames(uuid, names))
client.SendNameReply(uuid, names[0], names[1]);
// else
// m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: No bound name for {0} found, ignoring request from {1}",
// uuid, client.Name);
});
}
}
public void HandleAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query)
{
//EventManager.TriggerAvatarPickerRequest();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: HandleAvatarPickerRequest for {0}", query);
List<UserData> users = GetUserData(query, 500, 1);
AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply);
// TODO: don't create new blocks if recycling an old packet
AvatarPickerReplyPacket.DataBlock[] searchData =
new AvatarPickerReplyPacket.DataBlock[users.Count];
AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock();
agentData.AgentID = avatarID;
agentData.QueryID = RequestID;
replyPacket.AgentData = agentData;
//byte[] bytes = new byte[AvatarResponses.Count*32];
int i = 0;
foreach (UserData item in users)
{
UUID translatedIDtem = item.Id;
searchData[i] = new AvatarPickerReplyPacket.DataBlock();
searchData[i].AvatarID = translatedIDtem;
searchData[i].FirstName = Utils.StringToBytes((string)item.FirstName);
searchData[i].LastName = Utils.StringToBytes((string)item.LastName);
i++;
}
if (users.Count == 0)
{
searchData = new AvatarPickerReplyPacket.DataBlock[0];
}
replyPacket.Data = searchData;
AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs();
agent_data.AgentID = replyPacket.AgentData.AgentID;
agent_data.QueryID = replyPacket.AgentData.QueryID;
List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>();
for (i = 0; i < replyPacket.Data.Length; i++)
{
AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs();
data_arg.AvatarID = replyPacket.Data[i].AvatarID;
data_arg.FirstName = replyPacket.Data[i].FirstName;
data_arg.LastName = replyPacket.Data[i].LastName;
data_args.Add(data_arg);
}
client.SendAvatarPickerReply(agent_data, data_args);
}
protected virtual void AddAdditionalUsers(string query, List<UserData> users)
{
}
#endregion Event Handlers
#region IPeople
public List<UserData> GetUserData(string query, int page_size, int page_number)
{
// search the user accounts service
List<UserAccount> accs = m_Scenes[0].UserAccountService.GetUserAccounts(m_Scenes[0].RegionInfo.ScopeID, query);
List<UserData> users = new List<UserData>();
if (accs != null)
{
foreach (UserAccount acc in accs)
{
UserData ud = new UserData();
ud.FirstName = acc.FirstName;
ud.LastName = acc.LastName;
ud.Id = acc.PrincipalID;
users.Add(ud);
}
}
// search the local cache
lock (m_UserCache)
{
foreach (UserData data in m_UserCache.Values)
{
if (data.Id != UUID.Zero &&
users.Find(delegate(UserData d) { return d.Id == data.Id; }) == null &&
(data.FirstName.ToLower().StartsWith(query.ToLower()) || data.LastName.ToLower().StartsWith(query.ToLower())))
users.Add(data);
}
}
AddAdditionalUsers(query, users);
return users;
}
#endregion IPeople
private void CacheCreators(SceneObjectGroup sog)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: processing {0} {1}; {2}", sog.RootPart.Name, sog.RootPart.CreatorData, sog.RootPart.CreatorIdentification);
AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData);
foreach (SceneObjectPart sop in sog.Parts)
{
AddUser(sop.CreatorID, sop.CreatorData);
foreach (TaskInventoryItem item in sop.TaskInventory.Values)
AddUser(item.CreatorID, item.CreatorData);
}
}
/// <summary>
///
/// </summary>
/// <param name="uuid"></param>
/// <param name="names">Caller please provide a properly instantiated array for names, string[2]</param>
/// <returns></returns>
private bool TryGetUserNames(UUID uuid, string[] names)
{
if (names == null)
names = new string[2];
if (TryGetUserNamesFromCache(uuid, names))
return true;
if (TryGetUserNamesFromServices(uuid, names))
return true;
return false;
}
private bool TryGetUserNamesFromCache(UUID uuid, string[] names)
{
lock (m_UserCache)
{
if (m_UserCache.ContainsKey(uuid))
{
names[0] = m_UserCache[uuid].FirstName;
names[1] = m_UserCache[uuid].LastName;
return true;
}
}
return false;
}
/// <summary>
/// Try to get the names bound to the given uuid, from the services.
/// </summary>
/// <returns>True if the name was found, false if not.</returns>
/// <param name='uuid'></param>
/// <param name='names'>The array of names if found. If not found, then names[0] = "Unknown" and names[1] = "User"</param>
private bool TryGetUserNamesFromServices(UUID uuid, string[] names)
{
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, uuid);
if (account != null)
{
names[0] = account.FirstName;
names[1] = account.LastName;
UserData user = new UserData();
user.FirstName = account.FirstName;
user.LastName = account.LastName;
lock (m_UserCache)
m_UserCache[uuid] = user;
return true;
}
else
{
// Let's try the GridUser service
GridUserInfo uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString());
if (uInfo != null)
{
string url, first, last, tmp;
UUID u;
if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp))
{
AddUser(uuid, first, last, url);
if (m_UserCache.ContainsKey(uuid))
{
names[0] = m_UserCache[uuid].FirstName;
names[1] = m_UserCache[uuid].LastName;
return true;
}
}
else
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID);
}
else
{
m_log.DebugFormat("[USER MANAGEMENT MODULE]: No grid user found for {0}", uuid);
}
names[0] = "Unknown";
names[1] = "UserUMMTGUN9";
return false;
}
}
#region IUserManagement
public UUID GetUserIdByName(string name)
{
string[] parts = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
throw new Exception("Name must have 2 components");
return GetUserIdByName(parts[0], parts[1]);
}
public UUID GetUserIdByName(string firstName, string lastName)
{
// TODO: Optimize for reverse lookup if this gets used by non-console commands.
lock (m_UserCache)
{
foreach (UserData user in m_UserCache.Values)
{
if (user.FirstName == firstName && user.LastName == lastName)
return user.Id;
}
}
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
if (account != null)
return account.PrincipalID;
return UUID.Zero;
}
public string GetUserName(UUID uuid)
{
string[] names = new string[2];
TryGetUserNames(uuid, names);
return names[0] + " " + names[1];
}
public string GetUserHomeURL(UUID userID)
{
lock (m_UserCache)
{
if (m_UserCache.ContainsKey(userID))
return m_UserCache[userID].HomeURL;
}
return string.Empty;
}
public string GetUserServerURL(UUID userID, string serverType)
{
UserData userdata;
lock (m_UserCache)
m_UserCache.TryGetValue(userID, out userdata);
if (userdata != null)
{
// m_log.DebugFormat("[USER MANAGEMENT MODULE]: Requested url type {0} for {1}", serverType, userID);
if (userdata.ServerURLs != null)
{
object url;
if (userdata.ServerURLs.TryGetValue(serverType, out url))
return url.ToString();
}
else if (!string.IsNullOrEmpty(userdata.HomeURL))
{
//m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: Did not find url type {0} so requesting urls from '{1}' for {2}",
// serverType, userdata.HomeURL, userID);
UserAgentServiceConnector uConn = new UserAgentServiceConnector(userdata.HomeURL);
try
{
userdata.ServerURLs = uConn.GetServerURLs(userID);
}
catch (Exception e)
{
m_log.Debug("[USER MANAGEMENT MODULE]: GetServerURLs call failed ", e);
userdata.ServerURLs = new Dictionary<string, object>();
}
object url;
if (userdata.ServerURLs.TryGetValue(serverType, out url))
return url.ToString();
}
}
return string.Empty;
}
public string GetUserUUI(UUID userID)
{
UserData ud;
lock (m_UserCache)
m_UserCache.TryGetValue(userID, out ud);
if (ud == null) // It's not in the cache
{
string[] names = new string[2];
// This will pull the data from either UserAccounts or GridUser
// and stick it into the cache
TryGetUserNamesFromServices(userID, names);
lock (m_UserCache)
m_UserCache.TryGetValue(userID, out ud);
}
if (ud != null)
{
string homeURL = ud.HomeURL;
string first = ud.FirstName, last = ud.LastName;
if (ud.LastName.StartsWith("@"))
{
string[] parts = ud.FirstName.Split('.');
if (parts.Length >= 2)
{
first = parts[0];
last = parts[1];
}
return userID + ";" + homeURL + ";" + first + " " + last;
}
}
return userID.ToString();
}
public void AddUser(UUID uuid, string first, string last)
{
lock (m_UserCache)
{
if (m_UserCache.ContainsKey(uuid))
return;
}
UserData user = new UserData();
user.Id = uuid;
user.FirstName = first;
user.LastName = last;
AddUserInternal(user);
}
public void AddUser(UUID uuid, string first, string last, string homeURL)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, first {1}, last {2}, url {3}", uuid, first, last, homeURL);
if (homeURL == string.Empty)
return;
AddUser(uuid, homeURL + ";" + first + " " + last);
}
public void AddUser(UUID id, string creatorData)
{
//m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, creatorData {1}", id, creatorData);
UserData oldUser;
lock (m_UserCache)
m_UserCache.TryGetValue(id, out oldUser);
if (oldUser != null)
{
if (string.IsNullOrEmpty(creatorData))
{
//ignore updates without creator data
return;
}
//try update unknown users, but don't update anyone else
if (oldUser.FirstName == "Unknown" && !creatorData.Contains("Unknown"))
{
lock (m_UserCache)
m_UserCache.Remove(id);
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Re-adding user with id {0}, creatorData [{1}] and old HomeURL {2}", id, creatorData, oldUser.HomeURL);
}
else
{
//we have already a valid user within the cache
return;
}
}
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, id);
if (account != null)
{
AddUser(id, account.FirstName, account.LastName);
}
else
{
UserData user = new UserData();
user.Id = id;
if (!string.IsNullOrEmpty(creatorData))
{
//creatorData = <endpoint>;<name>
string[] parts = creatorData.Split(';');
if (parts.Length >= 2)
user.FirstName = parts[1].Replace(' ', '.');
if (parts.Length >= 1)
{
user.HomeURL = parts[0];
try
{
Uri uri = new Uri(parts[0]);
user.LastName = "@" + uri.Authority;
}
catch (UriFormatException)
{
m_log.DebugFormat(
"[USER MANAGEMENT MODULE]: Unable to parse home URL {0} for user name {1}, ID {2} from original creator data {3} when adding user info.",
parts[0], user.FirstName ?? "Unknown", id, creatorData);
user.LastName = "@unknown";
}
}
}
else
{
// Temporarily add unknown user entries of this type into the cache so that we can distinguish
// this source from other recent (hopefully resolved) bugs that fail to retrieve a user name binding
// TODO: Can be removed when GUN* unknown users have definitely dropped significantly or
// disappeared.
user.FirstName = "Unknown";
user.LastName = "UserUMMAU4";
}
AddUserInternal(user);
}
}
void AddUserInternal(UserData user)
{
lock (m_UserCache)
m_UserCache[user.Id] = user;
//m_log.DebugFormat(
// "[USER MANAGEMENT MODULE]: Added user {0} {1} {2} {3}",
// user.Id, user.FirstName, user.LastName, user.HomeURL);
}
public bool IsLocalGridUser(UUID uuid)
{
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid);
if (account == null || (account != null && !account.LocalToGrid))
return false;
return true;
}
#endregion IUserManagement
protected void Init()
{
AddUser(UUID.Zero, "Unknown", "User");
RegisterConsoleCmds();
}
protected void RegisterConsoleCmds()
{
MainConsole.Instance.Commands.AddCommand("Users", true,
"show name",
"show name <uuid>",
"Show the bindings between a single user UUID and a user name",
String.Empty,
HandleShowUser);
MainConsole.Instance.Commands.AddCommand("Users", true,
"show names",
"show names",
"Show the bindings between user UUIDs and user names",
String.Empty,
HandleShowUsers);
MainConsole.Instance.Commands.AddCommand("Users", true,
"reset user cache",
"reset user cache",
"reset user cache to allow changed settings to be applied",
String.Empty,
HandleResetUserCache);
}
private void HandleResetUserCache(string module, string[] cmd)
{
lock(m_UserCache)
{
m_UserCache.Clear();
}
}
private void HandleShowUser(string module, string[] cmd)
{
if (cmd.Length < 3)
{
MainConsole.Instance.OutputFormat("Usage: show name <uuid>");
return;
}
UUID userId;
if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, cmd[2], out userId))
return;
UserData ud;
lock (m_UserCache)
{
if (!m_UserCache.TryGetValue(userId, out ud))
{
MainConsole.Instance.OutputFormat("No name known for user with id {0}", userId);
return;
}
}
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("UUID", 36);
cdt.AddColumn("Name", 30);
cdt.AddColumn("HomeURL", 40);
cdt.AddRow(userId, string.Format("{0} {1}", ud.FirstName, ud.LastName), ud.HomeURL);
MainConsole.Instance.Output(cdt.ToString());
}
private void HandleShowUsers(string module, string[] cmd)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("UUID", 36);
cdt.AddColumn("Name", 30);
cdt.AddColumn("HomeURL", 40);
lock (m_UserCache)
{
foreach (KeyValuePair<UUID, UserData> kvp in m_UserCache)
cdt.AddRow(kvp.Key, string.Format("{0} {1}", kvp.Value.FirstName, kvp.Value.LastName), kvp.Value.HomeURL);
}
MainConsole.Instance.Output(cdt.ToString());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Diagnostics;
using System.Xml;
namespace System.ServiceModel.Channels
{
internal class RequestReplyCorrelator : IRequestReplyCorrelator
{
private Dictionary<Key, object> _states;
internal RequestReplyCorrelator()
{
_states = new Dictionary<Key, object>();
}
void IRequestReplyCorrelator.Add<T>(Message request, T state)
{
UniqueId messageId = request.Headers.MessageId;
Type stateType = typeof(T);
Key key = new Key(messageId, stateType);
// add the correlator key to the request, this will be needed for cleaning up the correlator table in case of
// channel aborting or faulting while there are pending requests
ICorrelatorKey value = state as ICorrelatorKey;
if (value != null)
{
value.RequestCorrelatorKey = key;
}
lock (_states)
{
_states.Add(key, state);
}
}
T IRequestReplyCorrelator.Find<T>(Message reply, bool remove)
{
UniqueId relatesTo = GetRelatesTo(reply);
Type stateType = typeof(T);
Key key = new Key(relatesTo, stateType);
T value;
lock (_states)
{
value = (T)_states[key];
if (remove)
_states.Remove(key);
}
return value;
}
// This method is used to remove the request from the correlator table when the
// reply is lost. This will avoid leaking the correlator table in cases where the
// channel faults or aborts while there are pending requests.
internal void RemoveRequest(ICorrelatorKey request)
{
Fx.Assert(request != null, "request cannot be null");
if (request.RequestCorrelatorKey != null)
{
lock (_states)
{
_states.Remove(request.RequestCorrelatorKey);
}
}
}
private UniqueId GetRelatesTo(Message reply)
{
UniqueId relatesTo = reply.Headers.RelatesTo;
if (relatesTo == null)
throw TraceUtility.ThrowHelperError(new ArgumentException(SR.SuppliedMessageIsNotAReplyItHasNoRelatesTo0), reply);
return relatesTo;
}
internal static bool AddressReply(Message reply, Message request)
{
ReplyToInfo info = RequestReplyCorrelator.ExtractReplyToInfo(request);
return RequestReplyCorrelator.AddressReply(reply, info);
}
internal static bool AddressReply(Message reply, ReplyToInfo info)
{
EndpointAddress destination = null;
if (info.HasFaultTo && (reply.IsFault))
{
destination = info.FaultTo;
}
else if (info.HasReplyTo)
{
destination = info.ReplyTo;
}
if (destination != null)
{
destination.ApplyTo(reply);
return !destination.IsNone;
}
else
{
return true;
}
}
internal static ReplyToInfo ExtractReplyToInfo(Message message)
{
return new ReplyToInfo(message);
}
internal static void PrepareRequest(Message request)
{
MessageHeaders requestHeaders = request.Headers;
if (requestHeaders.MessageId == null)
{
requestHeaders.MessageId = new UniqueId();
}
request.Properties.AllowOutputBatching = false;
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(request);
}
}
internal static void PrepareReply(Message reply, UniqueId messageId)
{
if (object.ReferenceEquals(messageId, null))
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MissingMessageID), reply);
MessageHeaders replyHeaders = reply.Headers;
if (object.ReferenceEquals(replyHeaders.RelatesTo, null))
{
replyHeaders.RelatesTo = messageId;
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(reply);
}
}
internal static void PrepareReply(Message reply, Message request)
{
UniqueId messageId = request.Headers.MessageId;
if (messageId != null)
{
MessageHeaders replyHeaders = reply.Headers;
if (object.ReferenceEquals(replyHeaders.RelatesTo, null))
{
replyHeaders.RelatesTo = messageId;
}
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(reply);
}
}
internal struct ReplyToInfo
{
private readonly EndpointAddress _faultTo;
private readonly EndpointAddress _from;
private readonly EndpointAddress _replyTo;
internal ReplyToInfo(Message message)
{
_faultTo = message.Headers.FaultTo;
_replyTo = message.Headers.ReplyTo;
_from = null;
}
internal EndpointAddress FaultTo
{
get { return _faultTo; }
}
internal EndpointAddress From
{
get { return _from; }
}
internal bool HasFaultTo
{
get { return !IsTrivial(this.FaultTo); }
}
internal bool HasFrom
{
get { return !IsTrivial(this.From); }
}
internal bool HasReplyTo
{
get { return !IsTrivial(this.ReplyTo); }
}
internal EndpointAddress ReplyTo
{
get { return _replyTo; }
}
private bool IsTrivial(EndpointAddress address)
{
// Note: even if address.IsAnonymous, it may have identity, reference parameters, etc.
return (address == null) || (address == EndpointAddress.AnonymousAddress);
}
}
internal class Key
{
internal UniqueId MessageId;
internal Type StateType;
internal Key(UniqueId messageId, Type stateType)
{
MessageId = messageId;
StateType = stateType;
}
public override bool Equals(object obj)
{
Key other = obj as Key;
if (other == null)
return false;
return other.MessageId == this.MessageId && other.StateType == this.StateType;
}
[SuppressMessage(FxCop.Category.Usage, "CA2303:FlagTypeGetHashCode", Justification = "The hashcode is not used for identity purposes for embedded types.")]
public override int GetHashCode()
{
return MessageId.GetHashCode() ^ StateType.GetHashCode();
}
public override string ToString()
{
return typeof(Key).ToString() + ": {" + MessageId + ", " + StateType.ToString() + "}";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
public partial struct Vector2
{
/// <summary>
/// The X component of the vector.
/// </summary>
public float X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public float Y;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[Intrinsic]
public Vector2(float value) : this(value, value) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
[Intrinsic]
public Vector2(float x, float y)
{
X = x;
Y = y;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
/// <param name="array">The destination array.</param>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void CopyTo(float[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from the given index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array
/// or if there are not enough elements to copy.</exception>
[Intrinsic]
public readonly void CopyTo(float[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 2)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector2 is equal to this Vector2 instance.
/// </summary>
/// <param name="other">The Vector2 to compare this instance to.</param>
/// <returns>True if the other Vector2 is equal to this instance; False otherwise.</returns>
[Intrinsic]
public readonly bool Equals(Vector2 other)
{
return this.X == other.X && this.Y == other.Y;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The dot product.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector2 value1, Vector2 value2)
{
return value1.X * value2.X +
value1.Y * value2.Y;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors
/// </summary>
/// <param name="value1">The first source vector</param>
/// <param name="value2">The second source vector</param>
/// <returns>The maximized vector</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Abs(Vector2 value)
{
return new Vector2(MathF.Abs(value.X), MathF.Abs(value.Y));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 SquareRoot(Vector2 value)
{
return new Vector2(MathF.Sqrt(value.X), MathF.Sqrt(value.Y));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator +(Vector2 left, Vector2 right)
{
return new Vector2(left.X + right.X, left.Y + right.Y);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 left, Vector2 right)
{
return new Vector2(left.X - right.X, left.Y - right.Y);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, Vector2 right)
{
return new Vector2(left.X * right.X, left.Y * right.Y);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(float left, Vector2 right)
{
return new Vector2(left, left) * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, float right)
{
return left * new Vector2(right, right);
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 left, Vector2 right)
{
return new Vector2(left.X / right.X, left.Y / right.Y);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 value1, float value2)
{
return value1 / new Vector2(value2);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector2 left, Vector2 right)
{
return !(left == right);
}
#endregion Public Static Operators
}
}
| |
// 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.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics
{
public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase
{
[Fact]
public void SpeculationAnalyzerDifferentOverloads()
{
Test(@"
class Program
{
void Vain(int arg = 3) { }
void Vain(string arg) { }
void Main()
{
[|Vain(5)|];
}
} ", "Vain(string.Empty)", true);
}
[Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")]
public void SpeculationAnalyzerExtensionMethodExplicitInvocation()
{
Test(@"
static class Program
{
public static void Vain(this int arg) { }
static void Main()
{
[|5.Vain()|];
}
} ", "Vain(5)", false);
}
[Fact]
public void SpeculationAnalyzerImplicitBaseClassConversion()
{
Test(@"
using System;
class Program
{
void Main()
{
Exception ex = [|(Exception)new InvalidOperationException()|];
}
} ", "new InvalidOperationException()", false);
}
[Fact]
public void SpeculationAnalyzerImplicitNumericConversion()
{
Test(@"
class Program
{
void Main()
{
long i = [|(long)5|];
}
} ", "5", false);
}
[Fact]
public void SpeculationAnalyzerImplicitUserConversion()
{
Test(@"
class From
{
public static implicit operator To(From from) { return new To(); }
}
class To { }
class Program
{
void Main()
{
To to = [|(To)new From()|];
}
} ", "new From()", true);
}
[Fact]
public void SpeculationAnalyzerExplicitConversion()
{
Test(@"
using System;
class Program
{
void Main()
{
Exception ex1 = new InvalidOperationException();
var ex2 = [|(InvalidOperationException)ex1|];
}
} ", "ex1", true);
}
[Fact]
public void SpeculationAnalyzerArrayImplementingNonGenericInterface()
{
Test(@"
using System.Collections;
class Program
{
void Main()
{
var a = new[] { 1, 2, 3 };
[|((IEnumerable)a).GetEnumerator()|];
}
} ", "a.GetEnumerator()", false);
}
[Fact]
public void SpeculationAnalyzerVirtualMethodWithBaseConversion()
{
Test(@"
using System;
using System.IO;
class Program
{
void Main()
{
var s = new MemoryStream();
[|((Stream)s).Flush()|];
}
} ", "s.Flush()", false);
}
[Fact]
public void SpeculationAnalyzerNonVirtualMethodImplementingInterface()
{
Test(@"
using System;
class Class : IComparable
{
public int CompareTo(object other) { return 1; }
}
class Program
{
static void Main()
{
var c = new Class();
[|((IComparable)c).CompareTo(null)|];
}
} ", "c.CompareTo(null)", true);
}
[Fact]
public void SpeculationAnalyzerSealedClassImplementingInterface()
{
Test(@"
using System;
sealed class Class : IComparable
{
public int CompareTo(object other) { return 1; }
}
class Program
{
static void Main()
{
var c = new Class();
[|((IComparable)c).CompareTo(null)|];
}
} ", "c.CompareTo(null)", false);
}
[Fact]
public void SpeculationAnalyzerValueTypeImplementingInterface()
{
Test(@"
using System;
class Program
{
void Main()
{
decimal d = 5;
[|((IComparable<decimal>)d).CompareTo(6)|];
}
} ", "d.CompareTo(6)", false);
}
[Fact]
public void SpeculationAnalyzerBinaryExpressionIntVsLong()
{
Test(@"
class Program
{
void Main()
{
var r = [|1+1L|];
}
} ", "1+1", true);
}
[Fact]
public void SpeculationAnalyzerQueryExpressionSelectType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = [|from i in Enumerable.Range(0, 3) select (long)i|];
}
} ", "from i in Enumerable.Range(0, 3) select i", true);
}
[Fact]
public void SpeculationAnalyzerQueryExpressionFromType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = [|from i in new long[0] select i|];
}
} ", "from i in new int[0] select i", true);
}
[Fact]
public void SpeculationAnalyzerQueryExpressionGroupByType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|];
}
} ", "from i in Enumerable.Range(0, 3) group i by i", true);
}
[Fact]
public void SpeculationAnalyzerQueryExpressionOrderByType()
{
Test(@"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i;
}
} ", "i", true);
}
[Fact]
public void SpeculationAnalyzerDifferentAttributeConstructors()
{
Test(@"
using System;
class AnAttribute : Attribute
{
public AnAttribute(string a, long b) { }
public AnAttribute(int a, int b) { }
}
class Program
{
[An([|""5""|], 6)]
static void Main() { }
} ", "5", false, "6");
// Note: the answer should have been that the replacement does change semantics (true),
// however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains,
// which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API
}
[Fact]
public void SpeculationAnalyzerCollectionInitializers()
{
Test(@"
using System.Collections;
class Collection : IEnumerable
{
public IEnumerator GetEnumerator() { return null; }
public void Add(string s) { }
public void Add(int i) { }
void Main()
{
var c = new Collection { [|""5""|] };
}
} ", "5", true);
}
[Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")]
public void SpeculationAnalyzerBrokenCode()
{
Test(@"
public interface IRogueAction
{
public string Name { get; private set; }
protected IRogueAction(string name)
{
[|this.Name|] = name;
}
} ", "Name", semanticChanges: false, isBrokenCode: true);
}
[Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")]
public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast()
{
Test(@"
class Program
{
static void Main(string[] args)
{
object thing = new { shouldBeAnInt = [|(int)Directions.South|] };
}
public enum Directions { North, East, South, West }
} ", "Directions.South", semanticChanges: true);
}
[Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")]
public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast()
{
Test(@"
class Program
{
static void Main(string[] args)
{
object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] };
}
public enum Directions { North, East, South, West }
} ", "Directions.South", semanticChanges: false);
}
protected override SyntaxTree Parse(string text)
{
return SyntaxFactory.ParseSyntaxTree(text);
}
protected override bool IsExpressionNode(SyntaxNode node)
{
return node is ExpressionSyntax;
}
protected override Compilation CreateCompilation(SyntaxTree tree)
{
return CSharpCompilation.Create(
CompilationName,
new[] { tree },
References,
TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePair.Create("CS0219", ReportDiagnostic.Suppress) }));
}
protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream)
{
var langCompilation = compilation;
Func<Diagnostic, bool> isProblem = d => d.Severity >= DiagnosticSeverity.Warning;
return !langCompilation.GetDiagnostics().Any(isProblem) &&
!langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem);
}
protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel)
{
return new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
protected class State
{
public string Name { get; private set; }
public bool NameIsVerbatim { get; private set; }
// The name node that we're on. Will be used to the name the type if it's
// generated.
public TSimpleNameSyntax SimpleName { get; private set; }
// The entire expression containing the name, not including the creation. i.e. "X.Foo"
// in "new X.Foo()".
public TExpressionSyntax NameOrMemberAccessExpression { get; private set; }
// The object creation node if we have one. i.e. if we're on the 'Foo' in "new X.Foo()".
public TObjectCreationExpressionSyntax ObjectCreationExpressionOpt { get; private set; }
// One of these will be non null. It's also possible for both to be non null. For
// example, if you have "class C { Foo f; }", then "Foo" can be generated inside C or
// inside the global namespace. The namespace can be null or the type can be null if the
// user has something like "ExistingType.NewType" or "ExistingNamespace.NewType". In
// that case they're being explicit about what they want to generate into.
public INamedTypeSymbol TypeToGenerateInOpt { get; private set; }
public string NamespaceToGenerateInOpt { get; private set; }
// If we can infer a base type or interface for this type.
//
// i.e.: "IList<int> foo = new MyList();"
public INamedTypeSymbol BaseTypeOrInterfaceOpt { get; private set; }
public bool IsInterface { get; private set; }
public bool IsStruct { get; private set; }
public bool IsAttribute { get; private set; }
public bool IsException { get; private set; }
public bool IsMembersWithModule { get; private set; }
public bool IsTypeGeneratedIntoNamespaceFromMemberAccess { get; private set; }
public bool IsSimpleNameGeneric { get; private set; }
public bool IsPublicAccessibilityForTypeGeneration { get; private set; }
public bool IsInterfaceOrEnumNotAllowedInTypeContext { get; private set; }
public IMethodSymbol DelegateMethodSymbol { get; private set; }
public bool IsDelegateAllowed { get; private set; }
public bool IsEnumNotAllowed { get; private set; }
public Compilation Compilation { get; }
public bool IsDelegateOnly { get; private set; }
public bool IsClassInterfaceTypes { get; private set; }
public List<TSimpleNameSyntax> PropertiesToGenerate { get; private set; }
private State(Compilation compilation)
{
Compilation = compilation;
}
public static State Generate(
TService service,
SemanticDocument document,
SyntaxNode node,
CancellationToken cancellationToken)
{
var state = new State(document.SemanticModel.Compilation);
if (!state.TryInitialize(service, document, node, cancellationToken))
{
return null;
}
return state;
}
private bool TryInitialize(
TService service,
SemanticDocument document,
SyntaxNode node,
CancellationToken cancellationToken)
{
if (!(node is TSimpleNameSyntax))
{
return false;
}
this.SimpleName = (TSimpleNameSyntax)node;
string name;
int arity;
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
syntaxFacts.GetNameAndArityOfSimpleName(this.SimpleName, out name, out arity);
this.Name = name;
this.NameIsVerbatim = syntaxFacts.IsVerbatimIdentifier(this.SimpleName.GetFirstToken());
if (string.IsNullOrWhiteSpace(this.Name))
{
return false;
}
// We only support simple names or dotted names. i.e. "(some + expr).Foo" is not a
// valid place to generate a type for Foo.
GenerateTypeServiceStateOptions generateTypeServiceStateOptions;
if (!service.TryInitializeState(document, this.SimpleName, cancellationToken, out generateTypeServiceStateOptions))
{
return false;
}
this.NameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression;
this.ObjectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt;
var semanticModel = document.SemanticModel;
var info = semanticModel.GetSymbolInfo(this.SimpleName, cancellationToken);
if (info.Symbol != null)
{
// This bound, so no need to generate anything.
return false;
}
var semanticFacts = document.Project.LanguageServices.GetService<ISemanticFactsService>();
if (!semanticFacts.IsTypeContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsExpressionContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsStatementContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsNameOfContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken) &&
!semanticFacts.IsNamespaceContext(semanticModel, this.NameOrMemberAccessExpression.SpanStart, cancellationToken))
{
return false;
}
// If this isn't something that can be created, then don't bother offering to create
// it.
if (info.CandidateReason == CandidateReason.NotCreatable)
{
return false;
}
if (info.CandidateReason == CandidateReason.Inaccessible ||
info.CandidateReason == CandidateReason.NotReferencable ||
info.CandidateReason == CandidateReason.OverloadResolutionFailure)
{
// We bound to something inaccessible, or overload resolution on a
// constructor call failed. Don't want to offer GenerateType here.
return false;
}
if (this.ObjectCreationExpressionOpt != null)
{
// If we're new'ing up something illegal, then don't offer generate type.
var typeInfo = semanticModel.GetTypeInfo(this.ObjectCreationExpressionOpt, cancellationToken);
if (typeInfo.Type.IsModuleType())
{
return false;
}
}
DetermineNamespaceOrTypeToGenerateIn(service, document, cancellationToken);
// Now, try to infer a possible base type for this new class/interface.
this.InferBaseType(service, document, cancellationToken);
this.IsInterface = GenerateInterface(service, cancellationToken);
this.IsStruct = GenerateStruct(service, semanticModel, cancellationToken);
this.IsAttribute = this.BaseTypeOrInterfaceOpt != null && this.BaseTypeOrInterfaceOpt.Equals(semanticModel.Compilation.AttributeType());
this.IsException = this.BaseTypeOrInterfaceOpt != null && this.BaseTypeOrInterfaceOpt.Equals(semanticModel.Compilation.ExceptionType());
this.IsMembersWithModule = generateTypeServiceStateOptions.IsMembersWithModule;
this.IsTypeGeneratedIntoNamespaceFromMemberAccess = generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess;
this.IsInterfaceOrEnumNotAllowedInTypeContext = generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext;
this.IsDelegateAllowed = generateTypeServiceStateOptions.IsDelegateAllowed;
this.IsDelegateOnly = generateTypeServiceStateOptions.IsDelegateOnly;
this.IsEnumNotAllowed = generateTypeServiceStateOptions.IsEnumNotAllowed;
this.DelegateMethodSymbol = generateTypeServiceStateOptions.DelegateCreationMethodSymbol;
this.IsClassInterfaceTypes = generateTypeServiceStateOptions.IsClassInterfaceTypes;
this.IsSimpleNameGeneric = service.IsGenericName(this.SimpleName);
this.PropertiesToGenerate = generateTypeServiceStateOptions.PropertiesToGenerate;
if (this.IsAttribute && this.TypeToGenerateInOpt.GetAllTypeParameters().Any())
{
this.TypeToGenerateInOpt = null;
}
return this.TypeToGenerateInOpt != null || this.NamespaceToGenerateInOpt != null;
}
private void InferBaseType(
TService service,
SemanticDocument document,
CancellationToken cancellationToken)
{
// See if we can find a possible base type for the type being generated.
// NOTE(cyrusn): I currently limit this to when we have an object creation node.
// That's because that's when we would have an expression that could be conerted to
// somethign else. i.e. if the user writes "IList<int> list = new Foo()" then we can
// infer a base interface for 'Foo'. However, if they write "IList<int> list = Foo"
// then we don't really want to infer a base type for 'Foo'.
// However, there are a few other cases were we can infer a base type.
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
if (service.IsInCatchDeclaration(this.NameOrMemberAccessExpression))
{
this.BaseTypeOrInterfaceOpt = document.SemanticModel.Compilation.ExceptionType();
}
else if (syntaxFacts.IsAttributeName(this.NameOrMemberAccessExpression))
{
this.BaseTypeOrInterfaceOpt = document.SemanticModel.Compilation.AttributeType();
}
else if (
service.IsArrayElementType(this.NameOrMemberAccessExpression) ||
service.IsInVariableTypeContext(this.NameOrMemberAccessExpression) ||
this.ObjectCreationExpressionOpt != null)
{
var expr = this.ObjectCreationExpressionOpt ?? this.NameOrMemberAccessExpression;
var typeInference = document.Project.LanguageServices.GetService<ITypeInferenceService>();
var baseType = typeInference.InferType(document.SemanticModel, expr, objectAsDefault: true, cancellationToken: cancellationToken) as INamedTypeSymbol;
SetBaseType(baseType);
}
}
private void SetBaseType(INamedTypeSymbol baseType)
{
if (baseType == null)
{
return;
}
// A base type need to be non class or interface type. Also, being 'object' is
// redundant as the base type.
if (baseType.IsSealed || baseType.IsStatic || baseType.SpecialType == SpecialType.System_Object)
{
return;
}
if (baseType.TypeKind != TypeKind.Class && baseType.TypeKind != TypeKind.Interface)
{
return;
}
this.BaseTypeOrInterfaceOpt = baseType;
}
private bool GenerateStruct(TService service, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return service.IsInValueTypeConstraintContext(semanticModel, this.NameOrMemberAccessExpression, cancellationToken);
}
private bool GenerateInterface(
TService service,
CancellationToken cancellationToken)
{
if (!this.IsAttribute &&
!this.IsException &&
this.Name.LooksLikeInterfaceName() &&
this.ObjectCreationExpressionOpt == null &&
(this.BaseTypeOrInterfaceOpt == null || this.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface))
{
return true;
}
return service.IsInInterfaceList(this.NameOrMemberAccessExpression);
}
private void DetermineNamespaceOrTypeToGenerateIn(
TService service,
SemanticDocument document,
CancellationToken cancellationToken)
{
DetermineNamespaceOrTypeToGenerateInWorker(service, document.SemanticModel, cancellationToken);
// Can only generate into a type if it's a class and it's from source.
if (this.TypeToGenerateInOpt != null)
{
if (this.TypeToGenerateInOpt.TypeKind != TypeKind.Class &&
this.TypeToGenerateInOpt.TypeKind != TypeKind.Module)
{
this.TypeToGenerateInOpt = null;
}
else
{
var symbol = SymbolFinder.FindSourceDefinitionAsync(this.TypeToGenerateInOpt, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
if (symbol == null ||
!symbol.IsKind(SymbolKind.NamedType) ||
!symbol.Locations.Any(loc => loc.IsInSource))
{
this.TypeToGenerateInOpt = null;
return;
}
var sourceTreeToBeGeneratedIn = symbol.Locations.First(loc => loc.IsInSource).SourceTree;
var documentToBeGeneratedIn = document.Project.Solution.GetDocument(sourceTreeToBeGeneratedIn);
if (documentToBeGeneratedIn == null)
{
this.TypeToGenerateInOpt = null;
return;
}
// If the 2 documents are in different project then we must have Public Accessibility.
// If we are generating in a website project, we also want to type to be public so the
// designer files can access the type.
if (documentToBeGeneratedIn.Project != document.Project ||
service.GeneratedTypesMustBePublic(documentToBeGeneratedIn.Project))
{
this.IsPublicAccessibilityForTypeGeneration = true;
}
this.TypeToGenerateInOpt = (INamedTypeSymbol)symbol;
}
}
if (this.TypeToGenerateInOpt != null)
{
if (!CodeGenerator.CanAdd(document.Project.Solution, this.TypeToGenerateInOpt, cancellationToken))
{
this.TypeToGenerateInOpt = null;
}
}
}
private bool DetermineNamespaceOrTypeToGenerateInWorker(
TService service,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// If we're on the right of a dot, see if we can figure out what's on the left. If
// it doesn't bind to a type or a namespace, then we can't proceed.
if (this.SimpleName != this.NameOrMemberAccessExpression)
{
return DetermineNamespaceOrTypeToGenerateIn(
service, semanticModel,
service.GetLeftSideOfDot(this.SimpleName), cancellationToken);
}
else
{
// The name is standing alone. We can either generate the type into our
// containing type, or into our containing namespace.
//
// TODO(cyrusn): We need to make this logic work if the type is in the
// base/interface list of a type.
var format = SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
this.TypeToGenerateInOpt = service.DetermineTypeToGenerateIn(semanticModel, this.SimpleName, cancellationToken);
if (this.TypeToGenerateInOpt != null)
{
this.NamespaceToGenerateInOpt = this.TypeToGenerateInOpt.ContainingNamespace.ToDisplayString(format);
}
else
{
var namespaceSymbol = semanticModel.GetEnclosingNamespace(this.SimpleName.SpanStart, cancellationToken);
if (namespaceSymbol != null)
{
this.NamespaceToGenerateInOpt = namespaceSymbol.ToDisplayString(format);
}
}
}
return true;
}
private bool DetermineNamespaceOrTypeToGenerateIn(
TService service,
SemanticModel semanticModel,
TExpressionSyntax leftSide,
CancellationToken cancellationToken)
{
var leftSideInfo = semanticModel.GetSymbolInfo(leftSide, cancellationToken);
if (leftSideInfo.Symbol != null)
{
var symbol = leftSideInfo.Symbol;
if (symbol is INamespaceSymbol)
{
this.NamespaceToGenerateInOpt = symbol.ToNameDisplayString();
return true;
}
else if (symbol is INamedTypeSymbol)
{
// TODO: Code coverage
this.TypeToGenerateInOpt = (INamedTypeSymbol)symbol.OriginalDefinition;
return true;
}
// We bound to something other than a namespace or named type. Can't generate a
// type inside this.
return false;
}
else
{
// If it's a dotted name, then perhaps it's a namespace. i.e. the user wrote
// "new Foo.Bar.Baz()". In this case we want to generate a namespace for
// "Foo.Bar".
IList<string> nameParts;
if (service.TryGetNameParts(leftSide, out nameParts))
{
this.NamespaceToGenerateInOpt = string.Join(".", nameParts);
return true;
}
}
return false;
}
}
protected class GenerateTypeServiceStateOptions
{
public TExpressionSyntax NameOrMemberAccessExpression { get; set; }
public TObjectCreationExpressionSyntax ObjectCreationExpressionOpt { get; set; }
public IMethodSymbol DelegateCreationMethodSymbol { get; set; }
public List<TSimpleNameSyntax> PropertiesToGenerate { get; }
public bool IsMembersWithModule { get; set; }
public bool IsTypeGeneratedIntoNamespaceFromMemberAccess { get; set; }
public bool IsInterfaceOrEnumNotAllowedInTypeContext { get; set; }
public bool IsDelegateAllowed { get; set; }
public bool IsEnumNotAllowed { get; set; }
public bool IsDelegateOnly { get; internal set; }
public bool IsClassInterfaceTypes { get; internal set; }
public GenerateTypeServiceStateOptions()
{
NameOrMemberAccessExpression = null;
ObjectCreationExpressionOpt = null;
DelegateCreationMethodSymbol = null;
IsMembersWithModule = false;
PropertiesToGenerate = new List<TSimpleNameSyntax>();
IsTypeGeneratedIntoNamespaceFromMemberAccess = false;
IsInterfaceOrEnumNotAllowedInTypeContext = false;
IsDelegateAllowed = true;
IsEnumNotAllowed = false;
IsDelegateOnly = false;
}
}
}
}
| |
using HueApi.Models;
using HueApi.Models.Requests;
using HueApi.Models.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace HueApi
{
public delegate void EventStreamMessage(List<EventStreamResponse> events);
public abstract class BaseHueApi
{
protected HttpClient client = default!;
public event EventStreamMessage? OnEventStreamMessage;
private CancellationTokenSource? eventStreamCancellationTokenSource;
protected const string EventStreamUrl = "eventstream/clip/v2";
protected const string ResourceUrl = "clip/v2/resource";
protected const string LightUrl = $"{ResourceUrl}/light";
protected const string SceneUrl = $"{ResourceUrl}/scene";
protected const string RoomUrl = $"{ResourceUrl}/room";
protected const string ZoneUrl = $"{ResourceUrl}/zone";
protected const string BridgeHomeUrl = $"{ResourceUrl}/bridge_home";
protected const string GroupedLightUrl = $"{ResourceUrl}/grouped_light";
protected const string DeviceUrl = $"{ResourceUrl}/device";
protected const string BridgeUrl = $"{ResourceUrl}/bridge";
protected const string DevicePowerUrl = $"{ResourceUrl}/device_power";
protected const string ZigbeeConnectivityUrl = $"{ResourceUrl}/zigbee_connectivity";
protected const string ZgpConnectivityUrl = $"{ResourceUrl}/zgp_connectivity";
protected const string MotionUrl = $"{ResourceUrl}/motion";
protected const string TemperatureUrl = $"{ResourceUrl}/temperature";
protected const string LightLevelUrl = $"{ResourceUrl}/light_level";
protected const string ButtonUrl = $"{ResourceUrl}/button";
protected const string BehaviorScriptUrl = $"{ResourceUrl}/behavior_script";
protected const string BehaviorInstanceUrl = $"{ResourceUrl}/behavior_instance";
protected const string GeofenceClientUrl = $"{ResourceUrl}/geofence_client";
protected const string GeolocationUrl = $"{ResourceUrl}/geolocation";
protected const string EntertainmentConfigurationUrl = $"{ResourceUrl}/entertainment_configuration";
protected const string EntertainmentUrl = $"{ResourceUrl}/entertainment";
protected const string HomekitUrl = $"{ResourceUrl}/homekit";
protected string ResourceIdUrl(string resourceUrl, Guid id) => $"{resourceUrl}/{id}";
#region Light
public Task<HueResponse<Light>> GetLights() => HueGetRequest<Light>(LightUrl);
public Task<HueResponse<Light>> GetLight(Guid id) => HueGetRequest<Light>(ResourceIdUrl(LightUrl, id));
public Task<HuePutResponse> UpdateLight(Guid id, UpdateLight data) => HuePutRequest(ResourceIdUrl(LightUrl, id), data);
#endregion
#region Scene
public Task<HueResponse<Scene>> GetScenes() => HueGetRequest<Scene>(SceneUrl);
public Task<HuePostResponse> CreateScene(CreateScene data) => HuePostRequest(SceneUrl, data);
public Task<HueResponse<Scene>> GetScene(Guid id) => HueGetRequest<Scene>(ResourceIdUrl(SceneUrl, id));
public Task<HuePutResponse> UpdateScene(Guid id, UpdateScene data) => HuePutRequest(ResourceIdUrl(SceneUrl, id), data);
public Task<HueDeleteResponse> DeleteScene(Guid id) => HueDeleteRequest(ResourceIdUrl(SceneUrl, id));
#endregion
#region Room
public Task<HueResponse<Room>> GetRooms() => HueGetRequest<Room>(RoomUrl);
public Task<HuePostResponse> CreateRoom(BaseResourceRequest data) => HuePostRequest(RoomUrl, data);
public Task<HueResponse<Room>> GetRoom(Guid id) => HueGetRequest<Room>(ResourceIdUrl(RoomUrl, id));
public Task<HuePutResponse> UpdateRoom(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(RoomUrl, id), data);
public Task<HueDeleteResponse> DeleteRoom(Guid id) => HueDeleteRequest(ResourceIdUrl(RoomUrl, id));
#endregion
#region Zone
public Task<HueResponse<Zone>> GetZones() => HueGetRequest<Zone>(ZoneUrl);
public Task<HuePostResponse> CreateZone(CreateZone data) => HuePostRequest(ZoneUrl, data);
public Task<HueResponse<Zone>> GetZone(Guid id) => HueGetRequest<Zone>(ResourceIdUrl(ZoneUrl, id));
public Task<HuePutResponse> UpdateZone(Guid id, UpdateZone data) => HuePutRequest(ResourceIdUrl(ZoneUrl, id), data);
public Task<HueDeleteResponse> DeleteZone(Guid id) => HueDeleteRequest(ResourceIdUrl(ZoneUrl, id));
#endregion
#region BridgeHome
public Task<HueResponse<BridgeHome>> GetBridgeHomes() => HueGetRequest<BridgeHome>(BridgeHomeUrl);
public Task<HueResponse<BridgeHome>> GetBridgeHome(Guid id) => HueGetRequest<BridgeHome>(ResourceIdUrl(BridgeHomeUrl, id));
public Task<HuePutResponse> UpdateBridgeHome(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(BridgeHomeUrl, id), data);
#endregion
#region GroupedLight
public Task<HueResponse<GroupedLight>> GetGroupedLights() => HueGetRequest<GroupedLight>(GroupedLightUrl);
public Task<HueResponse<GroupedLight>> GetGroupedLight(Guid id) => HueGetRequest<GroupedLight>(ResourceIdUrl(GroupedLightUrl, id));
public Task<HuePutResponse> UpdateGroupedLight(Guid id, UpdateGroupedLight data) => HuePutRequest(ResourceIdUrl(GroupedLightUrl, id), data);
#endregion
#region Device
public Task<HueResponse<Device>> GetDevices() => HueGetRequest<Device>(DeviceUrl);
public Task<HueResponse<Device>> GetDevice(Guid id) => HueGetRequest<Device>(ResourceIdUrl(DeviceUrl, id));
public Task<HuePutResponse> UpdateDevice(Guid id, UpdateDevice data) => HuePutRequest(ResourceIdUrl(DeviceUrl, id), data);
#endregion
#region Bridge
public Task<HueResponse<Bridge>> GetBridges() => HueGetRequest<Bridge>(BridgeUrl);
public Task<HueResponse<Bridge>> GetBridge(Guid id) => HueGetRequest<Bridge>(ResourceIdUrl(BridgeUrl, id));
public Task<HuePutResponse> UpdateBridge(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(BridgeUrl, id), data);
#endregion
#region DevicePower
public Task<HueResponse<DevicePower>> GetDevicePowers() => HueGetRequest<DevicePower>(DevicePowerUrl);
public Task<HueResponse<DevicePower>> GetDevicePower(Guid id) => HueGetRequest<DevicePower>(ResourceIdUrl(DevicePowerUrl, id));
public Task<HuePutResponse> UpdateDevicePower(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(DevicePowerUrl, id), data);
#endregion
#region ZigbeeConnectivity
public Task<HueResponse<ZigbeeConnectivity>> GetZigbeeConnectivity() => HueGetRequest<ZigbeeConnectivity>(ZigbeeConnectivityUrl);
public Task<HueResponse<ZigbeeConnectivity>> GetZigbeeConnectivity(Guid id) => HueGetRequest<ZigbeeConnectivity>(ResourceIdUrl(ZigbeeConnectivityUrl, id));
public Task<HuePutResponse> UpdateZigbeeConnectivity(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(ZigbeeConnectivityUrl, id), data);
#endregion
#region ZgpConnectivity
public Task<HueResponse<ZgpConnectivity>> GetZgpConnectivity() => HueGetRequest<ZgpConnectivity>(ZgpConnectivityUrl);
public Task<HueResponse<ZgpConnectivity>> GetZgpConnectivity(Guid id) => HueGetRequest<ZgpConnectivity>(ResourceIdUrl(ZgpConnectivityUrl, id));
public Task<HuePutResponse> UpdateZgpConnectivity(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(ZgpConnectivityUrl, id), data);
#endregion
#region Motion
public Task<HueResponse<Motion>> GetMotions() => HueGetRequest<Motion>(MotionUrl);
public Task<HueResponse<Motion>> GetMotion(Guid id) => HueGetRequest<Motion>(ResourceIdUrl(MotionUrl, id));
public Task<HuePutResponse> UpdateMotion(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(MotionUrl, id), data);
#endregion
#region Temperature
public Task<HueResponse<Temperature>> GetTemperatures() => HueGetRequest<Temperature>(TemperatureUrl);
public Task<HueResponse<Temperature>> GetTemperature(Guid id) => HueGetRequest<Temperature>(ResourceIdUrl(TemperatureUrl, id));
public Task<HuePutResponse> UpdateTemperature(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(TemperatureUrl, id), data);
#endregion
#region LightLevel
public Task<HueResponse<LightLevel>> GetLightLevels() => HueGetRequest<LightLevel>(LightLevelUrl);
public Task<HueResponse<LightLevel>> GetLightLevel(Guid id) => HueGetRequest<LightLevel>(ResourceIdUrl(LightLevelUrl, id));
public Task<HuePutResponse> UpdateLightLevel(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(LightLevelUrl, id), data);
#endregion
#region Button
public Task<HueResponse<Button>> GetButtons() => HueGetRequest<Button>(ButtonUrl);
public Task<HueResponse<Button>> GetButton(Guid id) => HueGetRequest<Button>(ResourceIdUrl(ButtonUrl, id));
public Task<HuePutResponse> UpdateButton(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(ButtonUrl, id), data);
#endregion
#region BehaviorScript
public Task<HueResponse<BehaviorScript>> GetBehaviorScripts() => HueGetRequest<BehaviorScript>(BehaviorScriptUrl);
public Task<HueResponse<BehaviorScript>> GetBehaviorScript(Guid id) => HueGetRequest<BehaviorScript>(ResourceIdUrl(BehaviorScriptUrl, id));
public Task<HuePutResponse> UpdateBehaviorScript(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(BehaviorScriptUrl, id), data);
#endregion
#region BehaviorInstance
public Task<HueResponse<BehaviorInstance>> GetBehaviorInstances() => HueGetRequest<BehaviorInstance>(BehaviorInstanceUrl);
public Task<HuePostResponse> CreateBehaviorInstance(BaseResourceRequest data) => HuePostRequest(BehaviorInstanceUrl, data);
public Task<HueResponse<BehaviorInstance>> GetBehaviorInstance(Guid id) => HueGetRequest<BehaviorInstance>(ResourceIdUrl(BehaviorInstanceUrl, id));
public Task<HuePutResponse> UpdateBehaviorInstance(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(BehaviorInstanceUrl, id), data);
public Task<HueDeleteResponse> DeleteBehaviorInstance(Guid id) => HueDeleteRequest(ResourceIdUrl(BehaviorInstanceUrl, id));
#endregion
#region GeofenceClient
public Task<HueResponse<GeofenceClient>> GetGeofenceClients() => HueGetRequest<GeofenceClient>(GeofenceClientUrl);
public Task<HuePostResponse> CreateGeofenceClient(BaseResourceRequest data) => HuePostRequest(GeofenceClientUrl, data);
public Task<HueResponse<GeofenceClient>> GetGeofenceClient(Guid id) => HueGetRequest<GeofenceClient>(ResourceIdUrl(GeofenceClientUrl, id));
public Task<HuePutResponse> UpdateGeofenceClient(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(GeofenceClientUrl, id), data);
public Task<HueDeleteResponse> DeleteGeofenceClient(Guid id) => HueDeleteRequest(ResourceIdUrl(GeofenceClientUrl, id));
#endregion
#region Geolocation
public Task<HueResponse<Geolocation>> GetGeolocations() => HueGetRequest<Geolocation>(GeolocationUrl);
public Task<HueResponse<Geolocation>> GetGeolocation(Guid id) => HueGetRequest<Geolocation>(ResourceIdUrl(GeolocationUrl, id));
public Task<HuePutResponse> UpdateGeolocation(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(GeolocationUrl, id), data);
#endregion
#region EntertainmentConfiguration
public Task<HueResponse<EntertainmentConfiguration>> GetEntertainmentConfigurations() => HueGetRequest<EntertainmentConfiguration>(EntertainmentConfigurationUrl);
public Task<HuePostResponse> CreateEntertainmentConfiguration(UpdateEntertainmentConfiguration data) => HuePostRequest(EntertainmentConfigurationUrl, data);
public Task<HueResponse<EntertainmentConfiguration>> GetEntertainmentConfiguration(Guid id) => HueGetRequest<EntertainmentConfiguration>(ResourceIdUrl(EntertainmentConfigurationUrl, id));
public Task<HuePutResponse> UpdateEntertainmentConfiguration(Guid id, UpdateEntertainmentConfiguration data) => HuePutRequest(ResourceIdUrl(EntertainmentConfigurationUrl, id), data);
public Task<HueDeleteResponse> DeleteEntertainmentConfiguration(Guid id) => HueDeleteRequest(ResourceIdUrl(EntertainmentConfigurationUrl, id));
#endregion
#region Entertainment
public Task<HueResponse<Entertainment>> GetEntertainmentServices() => HueGetRequest<Entertainment>(EntertainmentUrl);
public Task<HueResponse<Entertainment>> GetEntertainmentService(Guid id) => HueGetRequest<Entertainment>(ResourceIdUrl(EntertainmentUrl, id));
public Task<HuePutResponse> UpdateEntertainmentService(Guid id, UpdateEntertainment data) => HuePutRequest(ResourceIdUrl(EntertainmentUrl, id), data);
#endregion
#region Homekit
public Task<HueResponse<Homekit>> GetHomekits() => HueGetRequest<Homekit>(HomekitUrl);
public Task<HueResponse<Homekit>> GetHomekit(Guid id) => HueGetRequest<Homekit>(ResourceIdUrl(HomekitUrl, id));
public Task<HuePutResponse> UpdateHomekit(Guid id, BaseResourceRequest data) => HuePutRequest(ResourceIdUrl(HomekitUrl, id), data);
#endregion
#region Resource
public Task<HueResponse<HueResource>> GetResources() => HueGetRequest<HueResource>(ResourceUrl);
#endregion
protected async Task<HueResponse<T>> HueGetRequest<T>(string url)
{
var response = await client.GetAsync(url);
return await ProcessResponse<HueResponse<T>>(response);
}
protected async Task<HueDeleteResponse> HueDeleteRequest(string url)
{
var response = await client.DeleteAsync(url);
return await ProcessResponse<HueDeleteResponse>(response);
}
protected async Task<HuePutResponse> HuePutRequest<D>(string url, D data)
{
JsonSerializerOptions options = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
var response = await client.PutAsJsonAsync(url, data, options);
return await ProcessResponse<HuePutResponse>(response);
}
protected async Task<HuePostResponse> HuePostRequest<D>(string url, D data)
{
JsonSerializerOptions options = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
var response = await client.PostAsJsonAsync(url, data, options);
return await ProcessResponse<HuePostResponse>(response);
}
protected async Task<T> ProcessResponse<T>(HttpResponseMessage? response) where T : HueErrorResponse, new()
{
if (response == null)
return new T();
if (response.IsSuccessStatusCode)
{
return (await response.Content.ReadFromJsonAsync<T>()) ?? new();
}
else if(response.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
throw new UnauthorizedAccessException();
}
else
{
var errorResponse = await response.Content.ReadFromJsonAsync<HueErrorResponse>();
var result = new T();
if (errorResponse != null)
result.Errors = errorResponse.Errors;
return result;
}
}
public async void StartEventStream(CancellationToken? cancellationToken = null)
{
this.eventStreamCancellationTokenSource?.Cancel();
if (cancellationToken.HasValue)
this.eventStreamCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken.Value);
else
this.eventStreamCancellationTokenSource = new CancellationTokenSource();
var cancelToken = this.eventStreamCancellationTokenSource.Token;
try
{
while (!cancelToken.IsCancellationRequested) //Auto retry on stop
{
using (var streamReader = new StreamReader(await client.GetStreamAsync(EventStreamUrl, cancelToken)))
{
while (!streamReader.EndOfStream)
{
var jsonMsg = await streamReader.ReadLineAsync();
//Console.WriteLine($"Received message: {message}");
if (jsonMsg != null)
{
var data = System.Text.Json.JsonSerializer.Deserialize<List<EventStreamResponse>>(jsonMsg);
if (data != null && data.Any())
{
OnEventStreamMessage?.Invoke(data);
}
}
}
}
}
}
catch(TaskCanceledException)
{
//Ignore task canceled
}
}
public void StopEventStream()
{
this.eventStreamCancellationTokenSource?.Cancel();
}
}
}
| |
#region Namespaces
using System;
using System.Data;
using System.Xml;
using System.Collections.Generic;
using Epi;
using Epi.Collections;
#endregion //Namespaces
namespace Epi.Fields
{
/// <summary>
/// Grid field
/// </summary>
public class GridField : FieldWithSeparatePrompt
{
#region Private Members
private XmlElement viewElement;
private XmlNode fieldNode;
private List<GridColumnBase> columns;
private DataTable dataSource;
#endregion Private Members
#region Public Events
#endregion
#region Constructors
/// <summary>
/// Constructor for the class. Receives Page object.
/// </summary>
/// <param name="page">The page this field belongs to.</param>
public GridField(Page page)
: base(page)
{
}
/// <summary>
/// Constructor for the class. Receives View object.
/// </summary>
/// <param name="view">The view this field belongs to.</param>
public GridField(View view)
: base(view)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">The page this field belongs to.</param>
/// <param name="viewElement">The Xml view element of the GridField.</param>
public GridField(Page page, XmlElement viewElement)
: base(page)
{
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
///
/// </summary>
/// <param name="view"></param>
/// <param name="fieldNode"></param>
public GridField(View view, XmlNode fieldNode)
: base(view)
{
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
public GridField Clone()
{
GridField clone = (GridField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
#endregion Constructors
#region Protected Properties
#endregion Protected Properties
#region Public Methods
/// <summary>
/// Deletes the field
/// </summary>
public override void Delete()
{
GetMetadata().DeleteField(this);
view.MustRefreshFieldCollection = true;
}
/// <summary>
/// Constructs a GridColumnBase object from a MetaFieldType enum
/// </summary>
/// <param name="columnType">A MetaFieldType enum</param>
/// <returns>A GridColumnBase object</returns>
public GridColumnBase CreateGridColumn(MetaFieldType columnType)
{
switch (columnType)
{
case MetaFieldType.UniqueKey:
return new UniqueKeyColumn(this);
case MetaFieldType.RecStatus:
return new RecStatusColumn(this);
case MetaFieldType.ForeignKey:
return new ForeignKeyColumn(this);
case MetaFieldType.Text:
return new TextColumn(this);
case MetaFieldType.PhoneNumber:
return new PhoneNumberColumn(this);
case MetaFieldType.Date:
return new DateColumn(this);
case MetaFieldType.Number:
return new NumberColumn(this);
default:
return new TextColumn(this);
}
}
public void SetNewRecordValue()
{
if (DataSource is DataTable)
{
foreach (DataRow row in ((DataTable)DataSource).Rows)
{
if (row.RowState != DataRowState.Deleted)
{
foreach (GridColumnBase column in Columns)
{
if (column is GridColumnBase && ((GridColumnBase)column).ShouldRepeatLast == false)
{
row[column.Name] = DBNull.Value;
}
}
}
}
DataSource.AcceptChanges();
}
}
#endregion
#region Public Properties
/// <summary>
/// Database Table Name of the page
/// </summary>
public string TableName
{
get
{
if (this.Page == null)
{
return null;
}
else
{
return this.Page.TableName + this.Name;
}
}
}
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.Grid;
}
}
/// <summary>
/// Gets the column collection
/// </summary>
public List<GridColumnBase> Columns
{
get
{
if (this.columns == null && !this.Id.Equals(0))
{
this.columns = GetMetadata().GetGridColumnCollection(this);
if (this.columns.Count.Equals(0))
{
UniqueRowIdColumn uniqueRowIdColumn = new UniqueRowIdColumn(this);
RecStatusColumn recStatusColumn = new RecStatusColumn(this);
ForeignKeyColumn foreignKeyColumn = new ForeignKeyColumn(this);
GlobalRecordIdColumn globalRecordIdColumn = new GlobalRecordIdColumn(this);
uniqueRowIdColumn.SaveToDb();
recStatusColumn.SaveToDb();
foreignKeyColumn.SaveToDb();
globalRecordIdColumn.SaveToDb();
columns = GetMetadata().GetGridColumnCollection(this);
}
}
return this.columns;
}
set
{
this.columns = value;
}
}
/// <summary>
/// In-memory storage of rows editing in Epi.Enter.
/// This allows the datagrid control's contents to be persisted to the database.
/// </summary>
public DataTable DataSource
{
get
{
return dataSource;
}
set
{
dataSource = value;
}
}
/// <summary>
/// The view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
if (columns != null)
{
foreach (GridColumnBase column in columns)
{
column.Id = 0;
((Epi.Fields.Field)(column.Grid)).Id = this.Id;
}
}
SaveColumnsToDb();
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
SaveColumnsToDb();
}
#endregion Protected Methods
#region Private Methods
private void SaveColumnsToDb()
{
foreach (GridColumnBase gridColumn in Columns)
{
gridColumn.SaveToDb();
}
}
#endregion Private Methods
#region Event Handlers
#endregion
}
}
| |
/*
* DokiScriptTokenizer.cs
*
* THIS FILE HAS BEEN GENERATED AUTOMATICALLY. DO NOT EDIT!
*/
using System.IO;
using PerCederberg.Grammatica.Runtime;
/**
* <remarks>A character stream tokenizer.</remarks>
*/
internal class DokiScriptTokenizer : Tokenizer {
/**
* <summary>Creates a new tokenizer for the specified input
* stream.</summary>
*
* <param name='input'>the input stream to read</param>
*
* <exception cref='ParserCreationException'>if the tokenizer
* couldn't be initialized correctly</exception>
*/
public DokiScriptTokenizer(TextReader input)
: base(input, false) {
CreatePatterns();
}
/**
* <summary>Initializes the tokenizer by creating all the token
* patterns.</summary>
*
* <exception cref='ParserCreationException'>if the tokenizer
* couldn't be initialized correctly</exception>
*/
private void CreatePatterns() {
TokenPattern pattern;
pattern = new TokenPattern((int) DokiScriptConstants.WORLD,
"WORLD",
TokenPattern.PatternType.STRING,
"world");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.BACKGROUND,
"BACKGROUND",
TokenPattern.PatternType.STRING,
"background");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.WEATHER,
"WEATHER",
TokenPattern.PatternType.STRING,
"weather");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.SOUND,
"SOUND",
TokenPattern.PatternType.STRING,
"sound");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.BGM,
"BGM",
TokenPattern.PatternType.STRING,
"bgm");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.VIDEO,
"VIDEO",
TokenPattern.PatternType.STRING,
"video");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.MOVE,
"MOVE",
TokenPattern.PatternType.STRING,
"move");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.POSTURE,
"POSTURE",
TokenPattern.PatternType.STRING,
"posture");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.VOICE,
"VOICE",
TokenPattern.PatternType.STRING,
"voice");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.ROLE,
"ROLE",
TokenPattern.PatternType.STRING,
"role");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.OTHER,
"OTHER",
TokenPattern.PatternType.STRING,
"other");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.SRC,
"SRC",
TokenPattern.PatternType.STRING,
"src");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.TRANSITION,
"TRANSITION",
TokenPattern.PatternType.STRING,
"transition");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.TIME,
"TIME",
TokenPattern.PatternType.STRING,
"time");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.TYPE,
"TYPE",
TokenPattern.PatternType.STRING,
"type");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.LEVEL,
"LEVEL",
TokenPattern.PatternType.STRING,
"level");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.MODE,
"MODE",
TokenPattern.PatternType.STRING,
"mode");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.POSITION,
"POSITION",
TokenPattern.PatternType.STRING,
"position");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.NAME,
"NAME",
TokenPattern.PatternType.STRING,
"name");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.ANCHOR,
"ANCHOR",
TokenPattern.PatternType.STRING,
"anchor");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.TAG_PARAMETER,
"TAG_PARAMETER",
TokenPattern.PatternType.STRING,
"tag");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY1,
"KEY1",
TokenPattern.PatternType.STRING,
"key1");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY2,
"KEY2",
TokenPattern.PatternType.STRING,
"key2");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY3,
"KEY3",
TokenPattern.PatternType.STRING,
"key3");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY4,
"KEY4",
TokenPattern.PatternType.STRING,
"key4");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY5,
"KEY5",
TokenPattern.PatternType.STRING,
"key5");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY6,
"KEY6",
TokenPattern.PatternType.STRING,
"key6");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY7,
"KEY7",
TokenPattern.PatternType.STRING,
"key7");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY8,
"KEY8",
TokenPattern.PatternType.STRING,
"key8");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.KEY9,
"KEY9",
TokenPattern.PatternType.STRING,
"key9");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.LIVE2D,
"LIVE2D",
TokenPattern.PatternType.STRING,
"live2d");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.ZOOM,
"ZOOM",
TokenPattern.PatternType.STRING,
"zoom");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.BRACKET_LEFT,
"BRACKET_LEFT",
TokenPattern.PatternType.STRING,
"{");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.BRACKET_RIGHT,
"BRACKET_RIGHT",
TokenPattern.PatternType.STRING,
"}");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.SQUARE_BRACKET_LEFT,
"SQUARE_BRACKET_LEFT",
TokenPattern.PatternType.STRING,
"[");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.SQUARE_BRACKET_RIGHT,
"SQUARE_BRACKET_RIGHT",
TokenPattern.PatternType.STRING,
"]");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.PARENTHESE_LEFT,
"PARENTHESE_LEFT",
TokenPattern.PatternType.STRING,
"(");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.PARENTHESE_RIGHT,
"PARENTHESE_RIGHT",
TokenPattern.PatternType.STRING,
")");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.ANGLE_BRACKET_LEFT,
"ANGLE_BRACKET_LEFT",
TokenPattern.PatternType.STRING,
"<");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.DOUBLE_QUOTE,
"DOUBLE_QUOTE",
TokenPattern.PatternType.STRING,
"\"");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.PERIOD,
"PERIOD",
TokenPattern.PatternType.STRING,
".");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.COMMA,
"COMMA",
TokenPattern.PatternType.STRING,
",");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.SEMICOLON,
"SEMICOLON",
TokenPattern.PatternType.STRING,
";");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.EQUAL,
"EQUAL",
TokenPattern.PatternType.STRING,
"=");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.CLICK,
"CLICK",
TokenPattern.PatternType.STRING,
">");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.CLICK_NEXT_DIALOGUE_PAGE,
"CLICK_NEXT_DIALOGUE_PAGE",
TokenPattern.PatternType.STRING,
">>");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.OR,
"OR",
TokenPattern.PatternType.STRING,
"|");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.TAB,
"TAB",
TokenPattern.PatternType.REGEXP,
"\\t+");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.RETURN,
"RETURN",
TokenPattern.PatternType.REGEXP,
"[\\n\\r]+");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.SPACE,
"SPACE",
TokenPattern.PatternType.REGEXP,
" +");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.IDENTIFIER,
"IDENTIFIER",
TokenPattern.PatternType.REGEXP,
"[a-zA-Z_][0-9a-zA-Z_]*");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.DECIMAL,
"DECIMAL",
TokenPattern.PatternType.REGEXP,
"\\d+\\.?\\d*");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.TEXT,
"TEXT",
TokenPattern.PatternType.REGEXP,
">.*");
AddPattern(pattern);
pattern = new TokenPattern((int) DokiScriptConstants.QUOTED_TEXT,
"QUOTED_TEXT",
TokenPattern.PatternType.REGEXP,
"\"[^\"]*\"");
AddPattern(pattern);
}
}
| |
// Copyright (c) 2014-2016 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using BuildDependency.Artifacts;
using BuildDependency.Manager.Tools;
using BuildDependency.TeamCity;
using BuildDependency.TeamCity.RestClasses;
using BuildDependency.Tools;
using Eto.Drawing;
using Eto.Forms;
namespace BuildDependency.Manager.Dialogs
{
public sealed class BuildDependencyManagerDialog: Form
{
private readonly List<ArtifactTemplate> _artifacts;
private List<Server> _servers;
private readonly GridView _gridView;
private readonly SelectableFilterCollection<ArtifactTemplate> _dataStore;
private readonly Spinner _spinner;
private string _fileName;
private bool _fileWaitingToBeLoaded;
public BuildDependencyManagerDialog(string fileName = null)
{
Application.Instance.UnhandledException += OnUnhandledException;
Application.Instance.Initialized += OnApplicationInitialized;
Application.Instance.Name = "Build Dependency Manager";
_artifacts = new List<ArtifactTemplate>();
Title = "Build Dependency Manager";
ClientSize = new Size(700, 400);
Menu = new MenuBar
{
Items =
{
new ButtonMenuItem
{
Text = "&File",
Items =
{
new Command(OnFileNew) { MenuText = "&New" },
new Command(OnFileOpen) { MenuText = "&Open..." },
new Command(OnFileSave) { MenuText = "&Save" },
new Command(OnFileSaveAs) { MenuText = "Save &As..." },
new Command(OnFileImport) { MenuText = "&Import..." },
}
},
new ButtonMenuItem
{
Text = "&Tools",
Items =
{
new Command(OnToolsServers) { MenuText = "&Servers" },
new Command(OnToolsSort) { MenuText = "S&ort" }
}
},
new ButtonMenuItem
{
Text = "&Help",
Items =
{
new Command(OnHelpAbout) { MenuText = "&About" }
}
}
},
QuitItem = new Command((sender, e) => Application.Instance.Quit())
{
MenuText = "E&xit",
}
};
_spinner = new Spinner { Size = new Size(30, 30), Visible = false };
_gridView = new GridView
{
GridLines = GridLines.Both,
ShowHeader = true,
Size = new Size(680, 350)
};
_dataStore = new SelectableFilterCollection<ArtifactTemplate>(_gridView, _artifacts);
_gridView.DataStore = _dataStore;
_gridView.CellDoubleClick += OnEditArtifact;
_gridView.Columns.Add(new GridColumn
{
HeaderText = "Artifacts source",
DataCell = new TextBoxCell("Source"),
AutoSize = true,
Resizable = true,
Sortable = true,
});
_gridView.Columns.Add(new GridColumn
{
HeaderText = "Artifacts path",
DataCell = new TextBoxCell("PathRules"),
//AutoSize = true,
Resizable = true,
Sortable = true
});
_gridView.ContextMenu = new ContextMenu(
new ButtonMenuItem(new Command(OnEditArtifact) { MenuText = "&Edit" }),
new ButtonMenuItem(new Command(OnDeleteArtifact) { MenuText = "&Delete" }));
var button = new Button { Text = "Add Artifact" };
button.Click += OnAddArtifact;
var content = new TableLayout
{
Padding = new Padding(10, 10, 10, 5),
Spacing = new Size(5, 5),
Rows =
{
new TableRow(_gridView) { ScaleHeight = true },
new StackLayout
{
Orientation = Orientation.Horizontal,
Spacing = 5,
Items = { _spinner, null, button }
}
}
};
Content = content;
if (string.IsNullOrEmpty(fileName))
OnFileNew(this, EventArgs.Empty);
else
{
FileName = fileName;
_fileWaitingToBeLoaded = true;
}
}
private void OnApplicationInitialized(object sender, EventArgs e)
{
if (_fileWaitingToBeLoaded)
{
using (new WaitSpinner(_spinner))
{
OpenFile(FileName);
_fileWaitingToBeLoaded = false;
}
}
}
private void OnUnhandledException(object sender, Eto.UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
var errorReport = new ErrorReport(ex);
if (errorReport.ShowModal(this))
{
if (ex != null)
{
ExceptionLogging.Client.Notify(ex, Bugsnag.Severity.Error);
}
}
Application.Instance.Quit();
}
private void OnAddArtifact(object sender, EventArgs e)
{
using (new WaitSpinner(_spinner))
{
using (var dlg = new AddOrEditArtifactDependencyDialog(true, _servers))
{
dlg.ShowModal(this);
if (dlg.Result)
{
var artifact = dlg.GetArtifact();
_dataStore.Add(artifact);
}
}
}
}
private void OnEditArtifact(object sender, EventArgs e)
{
var item = _gridView.SelectedItem as ArtifactTemplate;
if (item == null)
return;
var artifactIndex = _dataStore.IndexOf(item);
using (var dlg = new AddOrEditArtifactDependencyDialog(_servers, item))
{
dlg.ShowModal();
if (dlg.Result)
{
var artifact = dlg.GetArtifact();
_dataStore.Remove(item);
_dataStore.Insert(artifactIndex, artifact);
}
}
}
private void OnDeleteArtifact(object sender, EventArgs e)
{
var item = _gridView.SelectedItem as ArtifactTemplate;
if (item == null)
return;
_dataStore.Remove(item);
}
private string FileName
{
get => _fileName;
set
{
_fileName = value;
Title = $"Build Dependency Manager - {Path.GetFileName(_fileName)}";
}
}
private void OnFileNew(object sender, EventArgs e)
{
_dataStore.Clear();
_servers = new List<Server>();
var server = Server.CreateServer(ServerType.TeamCity);
server.Name = "TC";
server.Url = "https://build.palaso.org";
_servers.Add(server);
}
private static void AddFileFilters(FileDialog dlg)
{
dlg.Filters.Add(new FileFilter("Dependency File (*.dep)", "*.dep"));
dlg.Filters.Add(new FileFilter("All Files (*.*)", "*"));
dlg.CurrentFilterIndex = 0;
}
public async void OpenFile(string fileName)
{
FileName = fileName;
await LoadFileAsync(FileName);
}
private async void OnFileOpen(object sender, EventArgs e)
{
using (new WaitSpinner(_spinner))
{
using (var dlg = new OpenFileDialog())
{
AddFileFilters(dlg);
if (dlg.ShowDialog(this) != DialogResult.Ok)
return;
FileName = dlg.FileName;
await LoadFileAsync(FileName);
}
}
}
private async Task LoadFileAsync(string filename)
{
_dataStore.Clear();
_dataStore.AddRange(await DependencyFile.LoadFileAsync(filename, new LogHelper()));
}
private async void OnFileSave(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(FileName))
{
OnFileSaveAs(sender, e);
return;
}
var fileName = FileName;
await Task.Run(() =>
{
DependencyFile.SaveFile(fileName, _servers, _artifacts);
JobsFile.WriteJobsFile(Path.ChangeExtension(fileName, ".files"), _artifacts);
});
}
private async void OnFileSaveAs(object sender, EventArgs e)
{
using (var dlg = new SaveFileDialog())
{
AddFileFilters(dlg);
if (dlg.ShowDialog(this) != DialogResult.Ok)
return;
var fileName = dlg.FileName;
using (new WaitSpinner(_spinner))
{
await Task.Run(() =>
{
if (string.IsNullOrEmpty(Path.GetExtension(fileName)))
fileName += ".dep";
DependencyFile.SaveFile(fileName, _servers, _artifacts);
JobsFile.WriteJobsFile(Path.ChangeExtension(fileName, ".files"), _artifacts);
});
FileName = fileName;
}
}
}
private async void OnFileImport(object sender, EventArgs e)
{
using (new WaitSpinner(_spinner))
{
using (var dlg = new ImportDialog(_servers))
{
dlg.ShowModal();
if (dlg.Result)
{
var configId = dlg.SelectedBuildConfig;
var condition = dlg.Condition;
var server = dlg.Server as TeamCityApi;
if (server == null)
return;
await Task.Run(async () =>
{
foreach (var dep in await server.GetArtifactDependenciesAsync(configId))
{
if (dep == null)
continue;
var artifact =
new ArtifactTemplate(server, new ArtifactProperties(dep.Properties), dep.BuildType) {Condition = condition};
_dataStore.Add(artifact);
}
});
}
}
}
}
private void OnToolsServers(object sender, EventArgs e)
{
using (var dlg = new ServersDialog(_servers))
{
dlg.ShowModal();
if (dlg.Result)
{
_servers = dlg.Servers;
}
}
}
private async void OnToolsSort(object sender, EventArgs e)
{
using (new WaitSpinner(_spinner))
{
await Task.Run(() =>
{
_dataStore.Sort = (x, y) => string.Compare(x.ConfigName, y.ConfigName, StringComparison.Ordinal);
});
}
}
private void OnHelpAbout(object sender, EventArgs e)
{
using (var dlg = new AboutDialog())
{
dlg.ShowModal();
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="System.SessionBinding", Namespace="urn:iControl")]
public partial class SystemSession : iControlInterface {
public SystemSession() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// get_active_folder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_active_folder(
) {
object [] results = this.Invoke("get_active_folder", new object [0]);
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_active_folder(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_active_folder", new object[0], callback, asyncState);
}
public string Endget_active_folder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_dtd_processing_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState get_dtd_processing_state(
) {
object [] results = this.Invoke("get_dtd_processing_state", new object [0]);
return ((CommonEnabledState)(results[0]));
}
public System.IAsyncResult Beginget_dtd_processing_state(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_dtd_processing_state", new object[0], callback, asyncState);
}
public CommonEnabledState Endget_dtd_processing_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState)(results[0]));
}
//-----------------------------------------------------------------------
// get_force_sessions_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState get_force_sessions_state(
) {
object [] results = this.Invoke("get_force_sessions_state", new object [0]);
return ((CommonEnabledState)(results[0]));
}
public System.IAsyncResult Beginget_force_sessions_state(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_force_sessions_state", new object[0], callback, asyncState);
}
public CommonEnabledState Endget_force_sessions_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState)(results[0]));
}
//-----------------------------------------------------------------------
// get_maximum_sessions
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long get_maximum_sessions(
) {
object [] results = this.Invoke("get_maximum_sessions", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginget_maximum_sessions(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_sessions", new object[0], callback, asyncState);
}
public long Endget_maximum_sessions(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// get_recursive_query_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState get_recursive_query_state(
) {
object [] results = this.Invoke("get_recursive_query_state", new object [0]);
return ((CommonEnabledState)(results[0]));
}
public System.IAsyncResult Beginget_recursive_query_state(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_recursive_query_state", new object[0], callback, asyncState);
}
public CommonEnabledState Endget_recursive_query_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState)(results[0]));
}
//-----------------------------------------------------------------------
// get_returned_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemSessionReturnedPath get_returned_path(
) {
object [] results = this.Invoke("get_returned_path", new object [0]);
return ((SystemSessionReturnedPath)(results[0]));
}
public System.IAsyncResult Beginget_returned_path(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_returned_path", new object[0], callback, asyncState);
}
public SystemSessionReturnedPath Endget_returned_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemSessionReturnedPath)(results[0]));
}
//-----------------------------------------------------------------------
// get_session_identifier
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long get_session_identifier(
) {
object [] results = this.Invoke("get_session_identifier", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginget_session_identifier(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_session_identifier", new object[0], callback, asyncState);
}
public long Endget_session_identifier(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// get_session_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long get_session_timeout(
) {
object [] results = this.Invoke("get_session_timeout", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginget_session_timeout(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_session_timeout", new object[0], callback, asyncState);
}
public long Endget_session_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// get_transaction_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long get_transaction_timeout(
) {
object [] results = this.Invoke("get_transaction_timeout", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginget_transaction_timeout(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_transaction_timeout", new object[0], callback, asyncState);
}
public long Endget_transaction_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// rollback_transaction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void rollback_transaction(
) {
this.Invoke("rollback_transaction", new object [0]);
}
public System.IAsyncResult Beginrollback_transaction(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("rollback_transaction", new object[0], callback, asyncState);
}
public void Endrollback_transaction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_active_folder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_active_folder(
string folder
) {
this.Invoke("set_active_folder", new object [] {
folder});
}
public System.IAsyncResult Beginset_active_folder(string folder, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_active_folder", new object[] {
folder}, callback, asyncState);
}
public void Endset_active_folder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_dtd_processing_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_dtd_processing_state(
CommonEnabledState state
) {
this.Invoke("set_dtd_processing_state", new object [] {
state});
}
public System.IAsyncResult Beginset_dtd_processing_state(CommonEnabledState state, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_dtd_processing_state", new object[] {
state}, callback, asyncState);
}
public void Endset_dtd_processing_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_force_sessions_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_force_sessions_state(
CommonEnabledState state
) {
this.Invoke("set_force_sessions_state", new object [] {
state});
}
public System.IAsyncResult Beginset_force_sessions_state(CommonEnabledState state, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_force_sessions_state", new object[] {
state}, callback, asyncState);
}
public void Endset_force_sessions_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_sessions
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_maximum_sessions(
long sessions
) {
this.Invoke("set_maximum_sessions", new object [] {
sessions});
}
public System.IAsyncResult Beginset_maximum_sessions(long sessions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_sessions", new object[] {
sessions}, callback, asyncState);
}
public void Endset_maximum_sessions(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_recursive_query_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_recursive_query_state(
CommonEnabledState state
) {
this.Invoke("set_recursive_query_state", new object [] {
state});
}
public System.IAsyncResult Beginset_recursive_query_state(CommonEnabledState state, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_recursive_query_state", new object[] {
state}, callback, asyncState);
}
public void Endset_recursive_query_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_returned_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_returned_path(
SystemSessionReturnedPath path
) {
this.Invoke("set_returned_path", new object [] {
path});
}
public System.IAsyncResult Beginset_returned_path(SystemSessionReturnedPath path, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_returned_path", new object[] {
path}, callback, asyncState);
}
public void Endset_returned_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_session_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_session_timeout(
long timeout
) {
this.Invoke("set_session_timeout", new object [] {
timeout});
}
public System.IAsyncResult Beginset_session_timeout(long timeout, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_session_timeout", new object[] {
timeout}, callback, asyncState);
}
public void Endset_session_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_transaction_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void set_transaction_timeout(
long timeout
) {
this.Invoke("set_transaction_timeout", new object [] {
timeout});
}
public System.IAsyncResult Beginset_transaction_timeout(long timeout, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_transaction_timeout", new object[] {
timeout}, callback, asyncState);
}
public void Endset_transaction_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// start_transaction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long start_transaction(
) {
object [] results = this.Invoke("start_transaction", new object [0]);
return ((long)(results[0]));
}
public System.IAsyncResult Beginstart_transaction(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("start_transaction", new object[0], callback, asyncState);
}
public long Endstart_transaction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long)(results[0]));
}
//-----------------------------------------------------------------------
// submit_transaction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/Session",
RequestNamespace="urn:iControl:System/Session", ResponseNamespace="urn:iControl:System/Session")]
public void submit_transaction(
) {
this.Invoke("submit_transaction", new object [0]);
}
public System.IAsyncResult Beginsubmit_transaction(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("submit_transaction", new object[0], callback, asyncState);
}
public void Endsubmit_transaction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.Session.ReturnedPath", Namespace = "urn:iControl")]
public enum SystemSessionReturnedPath
{
PATH_UNKNOWN,
PATH_FULL,
PATH_RELATIVE,
PATH_BARE,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Transactions.Diagnostics;
namespace System.Transactions
{
internal delegate void FinishVolatileDelegate(InternalEnlistment enlistment);
// Base class for all volatile enlistment states
internal abstract class VolatileEnlistmentState : EnlistmentState
{
// Double-checked locking pattern requires volatile for read/write synchronization
private static volatile VolatileEnlistmentActive s_volatileEnlistmentActive;
private static volatile VolatileEnlistmentPreparing s_volatileEnlistmentPreparing;
private static volatile VolatileEnlistmentPrepared s_volatileEnlistmentPrepared;
private static volatile VolatileEnlistmentSPC s_volatileEnlistmentSPC;
private static volatile VolatileEnlistmentPreparingAborting s_volatileEnlistmentPreparingAborting;
private static volatile VolatileEnlistmentAborting s_volatileEnlistmentAborting;
private static volatile VolatileEnlistmentCommitting s_volatileEnlistmentCommitting;
private static volatile VolatileEnlistmentInDoubt s_volatileEnlistmentInDoubt;
private static volatile VolatileEnlistmentEnded s_volatileEnlistmentEnded;
private static volatile VolatileEnlistmentDone s_volatileEnlistmentDone;
// Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
private static object s_classSyncObject;
internal static VolatileEnlistmentActive VolatileEnlistmentActive
{
get
{
if (s_volatileEnlistmentActive == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentActive == null)
{
VolatileEnlistmentActive temp = new VolatileEnlistmentActive();
s_volatileEnlistmentActive = temp;
}
}
}
return s_volatileEnlistmentActive;
}
}
protected static VolatileEnlistmentPreparing VolatileEnlistmentPreparing
{
get
{
if (s_volatileEnlistmentPreparing == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentPreparing == null)
{
VolatileEnlistmentPreparing temp = new VolatileEnlistmentPreparing();
s_volatileEnlistmentPreparing = temp;
}
}
}
return s_volatileEnlistmentPreparing;
}
}
protected static VolatileEnlistmentPrepared VolatileEnlistmentPrepared
{
get
{
if (s_volatileEnlistmentPrepared == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentPrepared == null)
{
VolatileEnlistmentPrepared temp = new VolatileEnlistmentPrepared();
s_volatileEnlistmentPrepared = temp;
}
}
}
return s_volatileEnlistmentPrepared;
}
}
protected static VolatileEnlistmentSPC VolatileEnlistmentSPC
{
get
{
if (s_volatileEnlistmentSPC == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentSPC == null)
{
VolatileEnlistmentSPC temp = new VolatileEnlistmentSPC();
s_volatileEnlistmentSPC = temp;
}
}
}
return s_volatileEnlistmentSPC;
}
}
protected static VolatileEnlistmentPreparingAborting VolatileEnlistmentPreparingAborting
{
get
{
if (s_volatileEnlistmentPreparingAborting == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentPreparingAborting == null)
{
VolatileEnlistmentPreparingAborting temp = new VolatileEnlistmentPreparingAborting();
s_volatileEnlistmentPreparingAborting = temp;
}
}
}
return s_volatileEnlistmentPreparingAborting;
}
}
protected static VolatileEnlistmentAborting VolatileEnlistmentAborting
{
get
{
if (s_volatileEnlistmentAborting == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentAborting == null)
{
VolatileEnlistmentAborting temp = new VolatileEnlistmentAborting();
s_volatileEnlistmentAborting = temp;
}
}
}
return s_volatileEnlistmentAborting;
}
}
protected static VolatileEnlistmentCommitting VolatileEnlistmentCommitting
{
get
{
if (s_volatileEnlistmentCommitting == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentCommitting == null)
{
VolatileEnlistmentCommitting temp = new VolatileEnlistmentCommitting();
s_volatileEnlistmentCommitting = temp;
}
}
}
return s_volatileEnlistmentCommitting;
}
}
protected static VolatileEnlistmentInDoubt VolatileEnlistmentInDoubt
{
get
{
if (s_volatileEnlistmentInDoubt == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentInDoubt == null)
{
VolatileEnlistmentInDoubt temp = new VolatileEnlistmentInDoubt();
s_volatileEnlistmentInDoubt = temp;
}
}
}
return s_volatileEnlistmentInDoubt;
}
}
protected static VolatileEnlistmentEnded VolatileEnlistmentEnded
{
get
{
if (s_volatileEnlistmentEnded == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentEnded == null)
{
VolatileEnlistmentEnded temp = new VolatileEnlistmentEnded();
s_volatileEnlistmentEnded = temp;
}
}
}
return s_volatileEnlistmentEnded;
}
}
protected static VolatileEnlistmentDone VolatileEnlistmentDone
{
get
{
if (s_volatileEnlistmentDone == null)
{
lock (ClassSyncObject)
{
if (s_volatileEnlistmentDone == null)
{
VolatileEnlistmentDone temp = new VolatileEnlistmentDone();
s_volatileEnlistmentDone = temp;
}
}
}
return s_volatileEnlistmentDone;
}
}
// Helper object for static synchronization
private static object ClassSyncObject
{
get
{
if (s_classSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_classSyncObject, o, null);
}
return s_classSyncObject;
}
}
// Override of get_RecoveryInformation to be more specific with the exception string.
internal override byte[] RecoveryInformation(InternalEnlistment enlistment)
{
throw TransactionException.CreateInvalidOperationException(SR.TraceSourceLtm,
SR.VolEnlistNoRecoveryInfo, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
}
// Active state for a volatile enlistment indicates that the enlistment has been created
// but no one has begun committing or aborting the transaction. From this state the enlistment
// can abort the transaction or call read only to indicate that it does not want to
// participate further in the transaction.
internal class VolatileEnlistmentActive : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
// Yeah it's active.
}
#region IEnlistment Related Events
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// End this enlistment
VolatileEnlistmentDone.EnterState(enlistment);
// Note another enlistment finished.
enlistment.FinishEnlistment();
}
#endregion
#region State Change Events
internal override void ChangeStatePreparing(InternalEnlistment enlistment)
{
VolatileEnlistmentPreparing.EnterState(enlistment);
}
internal override void ChangeStateSinglePhaseCommit(InternalEnlistment enlistment)
{
VolatileEnlistmentSPC.EnterState(enlistment);
}
#endregion
#region Internal Events
internal override void InternalAborted(InternalEnlistment enlistment)
{
// Change the enlistment state to aborting.
VolatileEnlistmentAborting.EnterState(enlistment);
}
#endregion
}
// Preparing state is the time after prepare has been called but no response has been received.
internal class VolatileEnlistmentPreparing : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
Monitor.Exit(enlistment.Transaction);
try // Don't hold this lock while calling into the application code.
{
if (DiagnosticTrace.Verbose)
{
EnlistmentNotificationCallTraceRecord.Trace(SR.TraceSourceLtm,
enlistment.EnlistmentTraceId,
NotificationCall.Prepare
);
}
enlistment.EnlistmentNotification.Prepare(enlistment.PreparingEnlistment);
}
finally
{
Monitor.Enter(enlistment.Transaction);
}
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
VolatileEnlistmentDone.EnterState(enlistment);
// Process Finished InternalEnlistment
enlistment.FinishEnlistment();
}
internal override void Prepared(InternalEnlistment enlistment)
{
// Change the enlistments state to prepared.
VolatileEnlistmentPrepared.EnterState(enlistment);
// Process Finished InternalEnlistment
enlistment.FinishEnlistment();
}
// The enlistment says to abort start the abort sequence.
internal override void ForceRollback(InternalEnlistment enlistment, Exception e)
{
// Change enlistment state to aborting
VolatileEnlistmentEnded.EnterState(enlistment);
// Start the transaction aborting
enlistment.Transaction.State.ChangeStateTransactionAborted(enlistment.Transaction, e);
// Process Finished InternalEnlistment
enlistment.FinishEnlistment();
}
internal override void ChangeStatePreparing(InternalEnlistment enlistment)
{
// If the transaction promotes during phase 0 then the transition to
// the promoted phase 0 state for the transaction may cause this
// notification to be delivered again. So in this case it should be
// ignored.
}
internal override void InternalAborted(InternalEnlistment enlistment)
{
VolatileEnlistmentPreparingAborting.EnterState(enlistment);
}
}
// SPC state for a volatile enlistment is the point at which there is exactly 1 enlisment
// and it supports SPC. The TM will send a single phase commit to the enlistment and wait
// for the response from the TM.
internal class VolatileEnlistmentSPC : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
bool spcCommitted = false;
// Set the enlistment state
enlistment.State = this;
// Send Single Phase Commit to the enlistment
if (DiagnosticTrace.Verbose)
{
EnlistmentNotificationCallTraceRecord.Trace(SR.TraceSourceLtm,
enlistment.EnlistmentTraceId,
NotificationCall.SinglePhaseCommit
);
}
Monitor.Exit(enlistment.Transaction);
try // Don't hold this lock while calling into the application code.
{
enlistment.SinglePhaseNotification.SinglePhaseCommit(enlistment.SinglePhaseEnlistment);
spcCommitted = true;
}
finally
{
if (!spcCommitted)
{
//If we have an exception thrown in SPC, we don't know the if the enlistment is committed or not
//reply indoubt
enlistment.SinglePhaseEnlistment.InDoubt();
}
Monitor.Enter(enlistment.Transaction);
}
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
VolatileEnlistmentEnded.EnterState(enlistment);
enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction);
}
internal override void Committed(InternalEnlistment enlistment)
{
VolatileEnlistmentEnded.EnterState(enlistment);
enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction);
}
internal override void Aborted(InternalEnlistment enlistment, Exception e)
{
VolatileEnlistmentEnded.EnterState(enlistment);
enlistment.Transaction.State.ChangeStateTransactionAborted(enlistment.Transaction, e);
}
internal override void InDoubt(InternalEnlistment enlistment, Exception e)
{
VolatileEnlistmentEnded.EnterState(enlistment);
if (enlistment.Transaction._innerException == null)
{
enlistment.Transaction._innerException = e;
}
enlistment.Transaction.State.InDoubtFromEnlistment(enlistment.Transaction);
}
}
// Prepared state for a volatile enlistment is the point at which prepare has been called
// and the enlistment has responded prepared. No enlistment operations are valid at this
// point. The RM must wait for the TM to take the next action.
internal class VolatileEnlistmentPrepared : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
// Wait for Committed
}
internal override void InternalAborted(InternalEnlistment enlistment)
{
VolatileEnlistmentAborting.EnterState(enlistment);
}
internal override void InternalCommitted(InternalEnlistment enlistment)
{
VolatileEnlistmentCommitting.EnterState(enlistment);
}
internal override void InternalIndoubt(InternalEnlistment enlistment)
{
// Change the enlistment state to InDoubt.
VolatileEnlistmentInDoubt.EnterState(enlistment);
}
internal override void ChangeStatePreparing(InternalEnlistment enlistment)
{
// This would happen in the second pass of a phase 0 wave.
}
}
// Aborting state is when Rollback has been sent to the enlistment.
internal class VolatileEnlistmentPreparingAborting : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// Move this enlistment to the ended state
VolatileEnlistmentEnded.EnterState(enlistment);
}
internal override void Prepared(InternalEnlistment enlistment)
{
// The enlistment has respondend so changes it's state to aborting.
VolatileEnlistmentAborting.EnterState(enlistment);
// Process Finished InternalEnlistment
enlistment.FinishEnlistment();
}
// The enlistment says to abort start the abort sequence.
internal override void ForceRollback(InternalEnlistment enlistment, Exception e)
{
// Change enlistment state to aborting
VolatileEnlistmentEnded.EnterState(enlistment);
// Record the exception in the transaction
if (enlistment.Transaction._innerException == null)
{
// Arguably this is the second call to ForceRollback and not the call that
// aborted the transaction but just in case.
enlistment.Transaction._innerException = e;
}
// Process Finished InternalEnlistment
enlistment.FinishEnlistment();
}
internal override void InternalAborted(InternalEnlistment enlistment)
{
// If this event comes from multiple places just ignore it. Continue
// waiting for the enlistment to respond so that we can respond to it.
}
}
// Aborting state is when Rollback has been sent to the enlistment.
internal class VolatileEnlistmentAborting : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
Monitor.Exit(enlistment.Transaction);
try // Don't hold this lock while calling into the application code.
{
if (DiagnosticTrace.Verbose)
{
EnlistmentNotificationCallTraceRecord.Trace(SR.TraceSourceLtm,
enlistment.EnlistmentTraceId,
NotificationCall.Rollback
);
}
enlistment.EnlistmentNotification.Rollback(enlistment.SinglePhaseEnlistment);
}
finally
{
Monitor.Enter(enlistment.Transaction);
}
}
internal override void ChangeStatePreparing(InternalEnlistment enlistment)
{
// This enlistment was told to abort before being told to prepare
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// Move this enlistment to the ended state
VolatileEnlistmentEnded.EnterState(enlistment);
}
internal override void InternalAborted(InternalEnlistment enlistment)
{
// Already working on it.
}
}
// Committing state is when Commit has been sent to the enlistment.
internal class VolatileEnlistmentCommitting : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
Monitor.Exit(enlistment.Transaction);
try // Don't hold this lock while calling into the application code.
{
if (DiagnosticTrace.Verbose)
{
EnlistmentNotificationCallTraceRecord.Trace(SR.TraceSourceLtm,
enlistment.EnlistmentTraceId,
NotificationCall.Commit
);
}
// Forward the notification to the enlistment
enlistment.EnlistmentNotification.Commit(enlistment.Enlistment);
}
finally
{
Monitor.Enter(enlistment.Transaction);
}
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// Move this enlistment to the ended state
VolatileEnlistmentEnded.EnterState(enlistment);
}
}
// InDoubt state is for an enlistment that has sent indoubt but has not been responeded to.
internal class VolatileEnlistmentInDoubt : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
Monitor.Exit(enlistment.Transaction);
try // Don't hold this lock while calling into the application code.
{
if (DiagnosticTrace.Verbose)
{
EnlistmentNotificationCallTraceRecord.Trace(SR.TraceSourceLtm,
enlistment.EnlistmentTraceId,
NotificationCall.InDoubt
);
}
// Forward the notification to the enlistment
enlistment.EnlistmentNotification.InDoubt(enlistment.PreparingEnlistment);
}
finally
{
Monitor.Enter(enlistment.Transaction);
}
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// Move this enlistment to the ended state
VolatileEnlistmentEnded.EnterState(enlistment);
}
}
// Ended state is the state that is entered when the transaction has committed,
// aborted, or said read only for an enlistment. At this point there are no valid
// operations on the enlistment.
internal class VolatileEnlistmentEnded : VolatileEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
// Nothing to do.
}
internal override void ChangeStatePreparing(InternalEnlistment enlistment)
{
// This enlistment was told to abort before being told to prepare
}
internal override void InternalAborted(InternalEnlistment enlistment)
{
// Ignore this in case the enlistment gets here before
// the transaction tells it to do so
}
internal override void InternalCommitted(InternalEnlistment enlistment)
{
// Ignore this in case the enlistment gets here before
// the transaction tells it to do so
}
internal override void InternalIndoubt(InternalEnlistment enlistment)
{
// Ignore this in case the enlistment gets here before
// the transaction tells it to do so
}
internal override void InDoubt(InternalEnlistment enlistment, Exception e)
{
// Ignore this in case the enlistment gets here before
// the transaction tells it to do so
}
}
// At some point either early or late the enlistment responded ReadOnly
internal class VolatileEnlistmentDone : VolatileEnlistmentEnded
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
// Nothing to do.
}
internal override void ChangeStatePreparing(InternalEnlistment enlistment)
{
enlistment.CheckComplete();
}
}
}
| |
/* ====================================================================
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.Collections;
using System.Text;
using NPOI.Util;
using System.Collections.Generic;
/**
* Record that Contains the functionality page _breaks (horizontal and vertical)
*
* The other two classes just specifically Set the SIDS for record creation.
*
* REFERENCE: Microsoft Excel SDK page 322 and 420
*
* @see HorizontalPageBreakRecord
* @see VerticalPageBreakRecord
* @author Danny Mui (dmui at apache dot org)
*/
internal class PageBreakRecord : StandardRecord
{
private const bool IS_EMPTY_RECORD_WRITTEN = false;
private static int[] EMPTY_INT_ARRAY = { };
public short sid=0;
// fix warning CS0169 "never used": private short numBreaks;
private IList<Break> _breaks;
private Hashtable _breakMap;
/**
* Since both records store 2byte integers (short), no point in
* differentiating it in the records.
*
* The subs (rows or columns, don't seem to be able to Set but excel Sets
* them automatically)
*/
internal class Break
{
public static int ENCODED_SIZE = 6;
public int main;
public int subFrom;
public int subTo;
public Break(RecordInputStream in1)
{
main = in1.ReadUShort() - 1;
subFrom = in1.ReadUShort();
subTo = in1.ReadUShort();
}
public Break(int main, int subFrom, int subTo)
{
this.main = main;
this.subFrom = subFrom;
this.subTo = subTo;
}
public void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(main + 1);
out1.WriteShort(subFrom);
out1.WriteShort(subTo);
}
}
public PageBreakRecord()
{
_breaks = new List<Break>();
_breakMap = new Hashtable();
}
public PageBreakRecord(RecordInputStream in1)
{
int nBreaks = in1.ReadShort();
_breaks = new List<Break>(nBreaks + 2);
_breakMap = new Hashtable();
for (int k = 0; k < nBreaks; k++)
{
Break br = new Break(in1);
_breaks.Add(br);
_breakMap[br.main] = br;
}
}
public override short Sid
{
get { return sid; }
}
//public override int Serialize(int offset, byte[] data)
//{
// int nBreaks = _breaks.Count;
// if (!IS_EMPTY_RECORD_WRITTEN && nBreaks < 1)
// {
// return 0;
// }
// int dataSize = DataSize;
// LittleEndian.PutUShort(data, offset + 0, Sid);
// LittleEndian.PutUShort(data, offset + 2, dataSize);
// LittleEndian.PutUShort(data, offset + 4, nBreaks);
// int pos = 6;
// for (int i = 0; i < nBreaks; i++)
// {
// Break br = (Break)_breaks[i];
// pos += br.Serialize(offset + pos, data);
// }
// return 4 + dataSize;
//}
public override void Serialize(ILittleEndianOutput out1)
{
int nBreaks = _breaks.Count;
out1.WriteShort(nBreaks);
for (int i = 0; i < nBreaks; i++)
{
_breaks[i].Serialize(out1);
}
}
protected override int DataSize
{
get
{
return 2 + _breaks.Count * Break.ENCODED_SIZE;
}
}
public IEnumerator<Break> GetBreaksEnumerator()
{
//if (_breaks == null)
// return new ArrayList().GetEnumerator();
//else
return _breaks.GetEnumerator();
}
public override String ToString()
{
StringBuilder retval = new StringBuilder();
//if (Sid != HORIZONTAL_SID && Sid != VERTICAL_SID)
// return "[INVALIDPAGEBREAK]\n .Sid =" + Sid + "[INVALIDPAGEBREAK]";
String label;
String mainLabel;
String subLabel;
if (Sid == HorizontalPageBreakRecord.sid)
{
label = "HORIZONTALPAGEBREAK";
mainLabel = "row";
subLabel = "col";
}
else
{
label = "VERTICALPAGEBREAK";
mainLabel = "column";
subLabel = "row";
}
retval.Append("[" + label + "]").Append("\n");
retval.Append(" .Sid =").Append(Sid).Append("\n");
retval.Append(" .num_breaks =").Append(NumBreaks).Append("\n");
IEnumerator iterator = GetBreaksEnumerator();
for (int k = 0; k < NumBreaks; k++)
{
Break region = (Break)iterator.Current;
retval.Append(" .").Append(mainLabel).Append(" (zero-based) =").Append(region.main).Append("\n");
retval.Append(" .").Append(subLabel).Append("From =").Append(region.subFrom).Append("\n");
retval.Append(" .").Append(subLabel).Append("To =").Append(region.subTo).Append("\n");
}
retval.Append("[" + label + "]").Append("\n");
return retval.ToString();
}
/**
* Adds the page break at the specified parameters
* @param main Depending on sid, will determine row or column to put page break (zero-based)
* @param subFrom No user-interface to Set (defaults to minumum, 0)
* @param subTo No user-interface to Set
*/
public void AddBreak(int main, int subFrom, int subTo)
{
//if (_breaks == null)
//{
// _breaks = new ArrayList(NumBreaks + 10);
// _breakMap = new Hashtable();
//}
int key = (int)main;
Break region = (Break)_breakMap[key];
if (region != null)
{
region.main = main;
region.subFrom = subFrom;
region.subTo = subTo;
}
else
{
region = new Break(main, subFrom, subTo);
_breaks.Add(region);
}
_breakMap[key] = region;
}
/**
* Removes the break indicated by the parameter
* @param main (zero-based)
*/
public void RemoveBreak(int main)
{
int rowKey = main;
Break region = (Break)_breakMap[rowKey];
_breaks.Remove(region);
_breakMap.Remove(rowKey);
}
public override int RecordSize
{
get {
int nBreaks = _breaks.Count;
if (!IS_EMPTY_RECORD_WRITTEN && nBreaks < 1)
{
return 0;
}
return 4 + DataSize;
}
}
public int NumBreaks
{
get
{
return _breaks.Count;
}
}
public bool IsEmpty
{
get
{
return _breaks.Count==0;
}
}
/**
* Retrieves the region at the row/column indicated
* @param main FIXME: Document this!
* @return The Break or null if no break exists at the row/col specified.
*/
public Break GetBreak(int main)
{
//if (_breakMap == null)
// return null;
//int rowKey = (int)main;
return (Break)_breakMap[main];
}
public int[] GetBreaks()
{
int count = NumBreaks;
if (count < 1)
{
return EMPTY_INT_ARRAY;
}
int[] result = new int[count];
for (int i = 0; i < count; i++)
{
Break breakItem = _breaks[i];
result[i] = breakItem.main;
}
return result;
}
}
}
| |
// These interfaces serve as an extension to the BCL's SymbolStore interfaces.
namespace OpenRiaServices.DomainServices.Tools.Pdb.SymStore
{
// Interface does not need to be marked with the serializable attribute
using System;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
[
ComImport,
Guid("68005D0F-B8E0-3B01-84D5-A11A94154942"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedScope
{
void GetMethod([MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedMethod pRetVal);
void GetParent([MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedScope pRetVal);
void GetChildren(int cChildren,
out int pcChildren,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedScope[] children);
void GetStartOffset(out int pRetVal);
void GetEndOffset(out int pRetVal);
void GetLocalCount(out int pRetVal);
void GetLocals(int cLocals,
out int pcLocals,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedVariable[] locals);
void GetNamespaces(int cNameSpaces,
out int pcNameSpaces,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedNamespace[] namespaces);
};
[
ComImport,
Guid("AE932FBA-3FD8-4dba-8232-30A2309B02DB"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedScope2 : ISymUnmanagedScope
{
// ISymUnmanagedScope methods (need to define the base interface methods also, per COM interop requirements)
new void GetMethod([MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedMethod pRetVal);
new void GetParent([MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedScope pRetVal);
new void GetChildren(int cChildren,
out int pcChildren,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ISymUnmanagedScope[] children);
new void GetStartOffset(out int pRetVal);
new void GetEndOffset(out int pRetVal);
new void GetLocalCount(out int pRetVal);
new void GetLocals(int cLocals,
out int pcLocals,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ISymUnmanagedVariable[] locals);
new void GetNamespaces(int cNameSpaces,
out int pcNameSpaces,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ISymUnmanagedNamespace[] namespaces);
// ISymUnmanagedScope2 methods
void GetConstantCount(out int pRetVal);
void GetConstants(int cConstants,
out int pcConstants,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedConstant[] constants);
}
internal class SymScope : ISymbolScope, ISymbolScope2
{
ISymUnmanagedScope m_target;
internal SymScope(ISymUnmanagedScope target)
{
// We should not wrap null instances
if (target == null)
throw new ArgumentNullException("target");
m_target = target;
}
public ISymbolMethod Method
{
get
{
ISymUnmanagedMethod uMethod = null;
m_target.GetMethod(out uMethod);
if (uMethod == null)
return null;
return new SymMethod(uMethod);
}
}
public ISymbolScope Parent
{
get
{
ISymUnmanagedScope uScope = null;
m_target.GetParent(out uScope);
if (uScope == null)
return null;
return new SymScope(uScope);
}
}
public ISymbolScope[] GetChildren()
{
int count;
m_target.GetChildren(0, out count, null);
ISymUnmanagedScope[] uScopes = new ISymUnmanagedScope[count];
m_target.GetChildren(count, out count, uScopes);
int i;
ISymbolScope[] scopes = new ISymbolScope[count];
for (i = 0; i < count; i++)
{
scopes[i] = new SymScope(uScopes[i]);
}
return scopes;
}
public int StartOffset
{
get
{
int offset;
m_target.GetStartOffset(out offset);
return offset;
}
}
public int EndOffset
{
get
{
int offset;
m_target.GetEndOffset(out offset);
return offset;
}
}
public ISymbolVariable[] GetLocals()
{
int count;
m_target.GetLocals(0, out count, null);
ISymUnmanagedVariable[] uVariables = new ISymUnmanagedVariable[count];
m_target.GetLocals(count, out count, uVariables);
int i;
ISymbolVariable[] variables = new ISymbolVariable[count];
for (i = 0; i < count; i++)
{
variables[i] = new SymVariable(uVariables[i]);
}
return variables;
}
public ISymbolNamespace[] GetNamespaces()
{
int count;
m_target.GetNamespaces(0, out count, null);
ISymUnmanagedNamespace[] uNamespaces = new ISymUnmanagedNamespace[count];
m_target.GetNamespaces(count, out count, uNamespaces);
int i;
ISymbolNamespace[] namespaces = new ISymbolNamespace[count];
for (i = 0; i < count; i++)
{
namespaces[i] = new SymNamespace(uNamespaces[i]);
}
return namespaces;
}
public int LocalCount
{
get
{
int count;
m_target.GetLocalCount(out count);
return count;
}
}
public int ConstantCount
{
get
{
int count;
((ISymUnmanagedScope2)m_target).GetConstantCount(out count);
return count;
}
}
public ISymbolConstant[] GetConstants()
{
int count;
((ISymUnmanagedScope2)m_target).GetConstants(0, out count, null);
ISymUnmanagedConstant[] uConstants = new ISymUnmanagedConstant[count];
((ISymUnmanagedScope2)m_target).GetConstants(count, out count, uConstants);
int i;
ISymbolConstant[] Constants = new ISymbolConstant[count];
for (i = 0; i < count; i++)
{
Constants[i] = new SymConstant(uConstants[i]);
}
return Constants;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Semmle.Util.Logging;
using Mono.Unix;
namespace Semmle.Util
{
/// <summary>
/// Interface for obtaining canonical paths.
/// </summary>
public interface IPathCache
{
string GetCanonicalPath(string path);
}
/// <summary>
/// Algorithm for determining a canonical path.
/// For example some strategies may preserve symlinks
/// or only work on certain platforms.
/// </summary>
public abstract class PathStrategy
{
/// <summary>
/// Obtain a canonical path.
/// </summary>
/// <param name="path">The path to canonicalise.</param>
/// <param name="cache">A cache for making subqueries.</param>
/// <returns>The canonical path.</returns>
public abstract string GetCanonicalPath(string path, IPathCache cache);
/// <summary>
/// Constructs a canonical path for a file
/// which doesn't yet exist.
/// </summary>
/// <param name="path">Path to canonicalise.</param>
/// <param name="cache">The PathCache.</param>
/// <returns>A canonical path.</returns>
protected static string ConstructCanonicalPath(string path, IPathCache cache)
{
var parent = Directory.GetParent(path);
return parent is not null ?
Path.Combine(cache.GetCanonicalPath(parent.FullName), Path.GetFileName(path)) :
path.ToUpperInvariant();
}
}
/// <summary>
/// Determine canonical paths using the Win32 function
/// GetFinalPathNameByHandle(). Follows symlinks.
/// </summary>
internal class GetFinalPathNameByHandleStrategy : PathStrategy
{
/// <summary>
/// Call GetFinalPathNameByHandle() to get a canonical filename.
/// Follows symlinks.
/// </summary>
///
/// <remarks>
/// GetFinalPathNameByHandle() only works on open file handles,
/// so if the path doesn't yet exist, construct the path
/// by appending the filename to the canonical parent directory.
/// </remarks>
///
/// <param name="path">The path to canonicalise.</param>
/// <param name="cache">Subquery cache.</param>
/// <returns>The canonical path.</returns>
public override string GetCanonicalPath(string path, IPathCache cache)
{
using var hFile = Win32.CreateFile( // lgtm[cs/call-to-unmanaged-code]
path,
0,
Win32.FILE_SHARE_READ | Win32.FILE_SHARE_WRITE,
IntPtr.Zero,
Win32.OPEN_EXISTING,
Win32.FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero);
if (hFile.IsInvalid)
{
// File/directory does not exist.
return ConstructCanonicalPath(path, cache);
}
var outPath = new StringBuilder(Win32.MAX_PATH);
var length = Win32.GetFinalPathNameByHandle(hFile, outPath, outPath.Capacity, 0); // lgtm[cs/call-to-unmanaged-code]
if (length >= outPath.Capacity)
{
// Path length exceeded MAX_PATH.
// Possible if target has a long path.
outPath = new StringBuilder(length + 1);
length = Win32.GetFinalPathNameByHandle(hFile, outPath, outPath.Capacity, 0); // lgtm[cs/call-to-unmanaged-code]
}
const int preamble = 4; // outPath always starts \\?\
if (length <= preamble)
{
// Failed. GetFinalPathNameByHandle() failed somehow.
return ConstructCanonicalPath(path, cache);
}
var result = outPath.ToString(preamble, length - preamble); // Trim off leading \\?\
return result.StartsWith("UNC")
? @"\" + result.Substring(3)
: result;
}
}
/// <summary>
/// Determine file case by querying directory contents.
/// Preserves symlinks.
/// </summary>
internal class QueryDirectoryStrategy : PathStrategy
{
public override string GetCanonicalPath(string path, IPathCache cache)
{
var parent = Directory.GetParent(path);
if (parent is null)
{
// We are at a root of the filesystem.
// Convert drive letters, UNC paths etc. to uppercase.
// On UNIX, this should be "/" or "".
return path.ToUpperInvariant();
}
var name = Path.GetFileName(path);
var parentPath = cache.GetCanonicalPath(parent.FullName);
try
{
var entries = Directory.GetFileSystemEntries(parentPath, name);
return entries.Length == 1
? entries[0]
: Path.Combine(parentPath, name);
}
catch // lgtm[cs/catch-of-all-exceptions]
{
// IO error or security error querying directory.
return Path.Combine(parentPath, name);
}
}
}
/// <summary>
/// Uses Mono.Unix.UnixPath to resolve symlinks.
/// Not available on Windows.
/// </summary>
internal class PosixSymlinkStrategy : PathStrategy
{
public PosixSymlinkStrategy()
{
GetRealPath("."); // Test that it works
}
private static string GetRealPath(string path)
{
path = UnixPath.GetFullPath(path);
return UnixPath.GetCompleteRealPath(path);
}
public override string GetCanonicalPath(string path, IPathCache cache)
{
try
{
return GetRealPath(path);
}
catch // lgtm[cs/catch-of-all-exceptions]
{
// File does not exist
return ConstructCanonicalPath(path, cache);
}
}
}
/// <summary>
/// Class which computes canonical paths.
/// Contains a simple thread-safe cache of files and directories.
/// </summary>
public class CanonicalPathCache : IPathCache
{
/// <summary>
/// The maximum number of items in the cache.
/// </summary>
private readonly int maxCapacity;
/// <summary>
/// How to handle symlinks.
/// </summary>
public enum Symlinks
{
Follow,
Preserve
}
/// <summary>
/// Algorithm for computing the canonical path.
/// </summary>
private readonly PathStrategy pathStrategy;
/// <summary>
/// Create cache with a given capacity.
/// </summary>
/// <param name="pathStrategy">The algorithm for determining the canonical path.</param>
/// <param name="capacity">The size of the cache.</param>
public CanonicalPathCache(int maxCapacity, PathStrategy pathStrategy)
{
if (maxCapacity <= 0)
throw new ArgumentOutOfRangeException(nameof(maxCapacity), maxCapacity, "Invalid cache size specified");
this.maxCapacity = maxCapacity;
this.pathStrategy = pathStrategy;
}
/// <summary>
/// Create a CanonicalPathCache.
/// </summary>
///
/// <remarks>
/// Creates the appropriate PathStrategy object which encapsulates
/// the correct algorithm. Falls back to different implementations
/// depending on platform.
/// </remarks>
///
/// <param name="maxCapacity">Size of the cache.</param>
/// <param name="symlinks">Policy for following symlinks.</param>
/// <returns>A new CanonicalPathCache.</returns>
public static CanonicalPathCache Create(ILogger logger, int maxCapacity)
{
var preserveSymlinks =
Environment.GetEnvironmentVariable("CODEQL_PRESERVE_SYMLINKS") == "true" ||
Environment.GetEnvironmentVariable("SEMMLE_PRESERVE_SYMLINKS") == "true";
return Create(logger, maxCapacity, preserveSymlinks ? CanonicalPathCache.Symlinks.Preserve : CanonicalPathCache.Symlinks.Follow);
}
/// <summary>
/// Create a CanonicalPathCache.
/// </summary>
///
/// <remarks>
/// Creates the appropriate PathStrategy object which encapsulates
/// the correct algorithm. Falls back to different implementations
/// depending on platform.
/// </remarks>
///
/// <param name="maxCapacity">Size of the cache.</param>
/// <param name="symlinks">Policy for following symlinks.</param>
/// <returns>A new CanonicalPathCache.</returns>
public static CanonicalPathCache Create(ILogger logger, int maxCapacity, Symlinks symlinks)
{
PathStrategy pathStrategy;
switch (symlinks)
{
case Symlinks.Follow:
try
{
pathStrategy = Win32.IsWindows() ?
(PathStrategy)new GetFinalPathNameByHandleStrategy() :
(PathStrategy)new PosixSymlinkStrategy();
}
catch // lgtm[cs/catch-of-all-exceptions]
{
// Failed to late-bind a suitable library.
logger.Log(Severity.Warning, "Preserving symlinks in canonical paths");
pathStrategy = new QueryDirectoryStrategy();
}
break;
case Symlinks.Preserve:
pathStrategy = new QueryDirectoryStrategy();
break;
default:
throw new ArgumentOutOfRangeException(nameof(symlinks), symlinks, "Invalid symlinks option");
}
return new CanonicalPathCache(maxCapacity, pathStrategy);
}
/// <summary>
/// Map of path to canonical path.
/// </summary>
private readonly IDictionary<string, string> cache = new Dictionary<string, string>();
/// <summary>
/// Used to evict random cache items when the cache is full.
/// </summary>
private readonly Random random = new Random();
/// <summary>
/// The current number of items in the cache.
/// </summary>
public int CacheSize
{
get
{
lock (cache)
return cache.Count;
}
}
/// <summary>
/// Adds a path to the cache.
/// Removes items from cache as needed.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="canonical">The canonical form of path.</param>
private void AddToCache(string path, string canonical)
{
if (cache.Count >= maxCapacity)
{
/* A simple strategy for limiting the cache size, given that
* C# doesn't have a convenient dictionary+list data structure.
*/
cache.Remove(cache.ElementAt(random.Next(maxCapacity)));
}
cache[path] = canonical;
}
/// <summary>
/// Retrieve the canonical path for a given path.
/// Caches the result.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>The canonical path.</returns>
public string GetCanonicalPath(string path)
{
lock (cache)
{
if (!cache.TryGetValue(path, out var canonicalPath))
{
canonicalPath = pathStrategy.GetCanonicalPath(path, this);
AddToCache(path, canonicalPath);
}
return canonicalPath;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
#if FRB_MDX
#elif FRB_XNA
using Microsoft.Xna.Framework.Graphics;
#elif SILVERLIGHT
#endif
using System.Xml;
using System.Xml.Serialization;
using FlatRedBall;
using AnimationFrame = FlatRedBall.Graphics.Animation.AnimationFrame;
using AnimationChainList = FlatRedBall.Graphics.Animation.AnimationChainList;
using FileManager = FlatRedBall.IO.FileManager;
using FlatRedBall.IO;
using FlatRedBall.Graphics.Texture;
using FlatRedBall.Graphics;
namespace FlatRedBall.Content.AnimationChain
{
[XmlType("AnimationChainArraySave")]
public class AnimationChainListSave :AnimationChainListSaveBase<AnimationChainSave>
{
#if WINDOWS_PHONE || XBOX360 || ANDROID || IOS
public static bool ManualDeserialization = true;
#else
public static bool ManualDeserialization = false;
#endif
#region Fields
private List<string> mToRuntimeErrors = new List<string>();
#endregion
#region Properties
[XmlIgnore]
public List<string> ToRuntimeErrors
{
get { return mToRuntimeErrors; }
}
#endregion
#region Methods
#region Constructor
public AnimationChainListSave()
{
AnimationChains = new List<AnimationChainSave>();
}
#endregion
public static AnimationChainListSave FromFile(string fileName)
{
AnimationChainListSave toReturn = null;
if (ManualDeserialization)
{
toReturn = DeserializeManually(fileName);
}
else
{
toReturn =
FileManager.XmlDeserialize<AnimationChainListSave>(fileName);
}
if (FileManager.IsRelative(fileName))
fileName = FileManager.MakeAbsolute(fileName);
toReturn.mFileName = fileName;
return toReturn;
}
/// <summary>
/// Create a "save" object from a regular animation chain list
/// </summary>
public static AnimationChainListSave FromAnimationChainList(AnimationChainList chainList)
{
AnimationChainListSave achlist = new AnimationChainListSave();
achlist.FileRelativeTextures = chainList.FileRelativeTextures;
achlist.TimeMeasurementUnit = chainList.TimeMeasurementUnit;
achlist.mFileName = chainList.Name;
List<AnimationChainSave> newChains = new List<AnimationChainSave>(chainList.Count);
for (int i = 0; i < chainList.Count; i++)
{
AnimationChainSave ach = AnimationChainSave.FromAnimationChain(chainList[i], achlist.TimeMeasurementUnit);
newChains.Add(ach);
}
achlist.AnimationChains = newChains;
return achlist;
}
public List<string> GetReferencedFiles(RelativeType relativeType)
{
List<string> referencedFiles = new List<string>();
foreach (AnimationChainSave acs in this.AnimationChains)
{
//if(acs.ParentFile
if (acs.ParentFile != null && acs.ParentFile.EndsWith(".gif"))
{
referencedFiles.Add(acs.ParentFile);
}
else
{
foreach (AnimationFrameSave afs in acs.Frames)
{
string texture = FileManager.Standardize( afs.TextureName, null, false );
if (FileManager.GetExtension(texture).StartsWith("gif"))
{
texture = FileManager.RemoveExtension(texture) + ".gif";
}
if (!string.IsNullOrEmpty(texture) && !referencedFiles.Contains(texture))
{
referencedFiles.Add(texture);
}
}
}
}
if (relativeType == RelativeType.Absolute)
{
string directory = FileManager.GetDirectory(FileName);
for (int i = 0; i < referencedFiles.Count; i++)
{
referencedFiles[i] = directory + referencedFiles[i];
}
}
return referencedFiles;
}
public void Save(string fileName)
{
if (FileRelativeTextures)
{
MakeRelative(fileName);
}
FileManager.XmlSerialize(this, fileName);
}
public AnimationChainList ToAnimationChainList(string contentManagerName)
{
return ToAnimationChainList(contentManagerName, true);
}
public AnimationChainList ToAnimationChainList(string contentManagerName, bool throwError)
{
mToRuntimeErrors.Clear();
AnimationChainList list = new AnimationChainList();
list.FileRelativeTextures = FileRelativeTextures;
list.TimeMeasurementUnit = TimeMeasurementUnit;
list.Name = mFileName;
string oldRelativeDirectory = FileManager.RelativeDirectory;
try
{
if (this.FileRelativeTextures)
{
FileManager.RelativeDirectory = FileManager.GetDirectory(mFileName);
}
foreach (AnimationChainSave animationChain in this.AnimationChains)
{
try
{
FlatRedBall.Graphics.Animation.AnimationChain newChain = null;
newChain = animationChain.ToAnimationChain(contentManagerName, this.TimeMeasurementUnit, this.CoordinateType);
newChain.mIndexInLoadedAchx = list.Count;
newChain.ParentAchxFileName = mFileName;
list.Add(newChain);
}
catch (Exception e)
{
mToRuntimeErrors.Add(e.ToString());
if (throwError)
{
throw new Exception("Error loading AnimationChain", e);
}
}
}
}
finally
{
FileManager.RelativeDirectory = oldRelativeDirectory;
}
return list;
}
//AnimationChainList ToAnimationChainList(string contentManagerName, TextureAtlas textureAtlas, bool throwError)
//{
// mToRuntimeErrors.Clear();
// AnimationChainList list = new AnimationChainList();
// list.FileRelativeTextures = FileRelativeTextures;
// list.TimeMeasurementUnit = TimeMeasurementUnit;
// list.Name = mFileName;
// string oldRelativeDirectory = FileManager.RelativeDirectory;
// try
// {
// if (this.FileRelativeTextures)
// {
// FileManager.RelativeDirectory = FileManager.GetDirectory(mFileName);
// }
// foreach (AnimationChainSave animationChain in this.AnimationChains)
// {
// try
// {
// FlatRedBall.Graphics.Animation.AnimationChain newChain = null;
// if (textureAtlas == null)
// {
// newChain = animationChain.ToAnimationChain(contentManagerName, this.TimeMeasurementUnit, this.CoordinateType);
// }
// else
// {
// newChain = animationChain.ToAnimationChain(textureAtlas, this.TimeMeasurementUnit);
// }
// newChain.mIndexInLoadedAchx = list.Count;
// newChain.ParentAchxFileName = mFileName;
// list.Add(newChain);
// }
// catch (Exception e)
// {
// mToRuntimeErrors.Add(e.ToString());
// if (throwError)
// {
// throw new Exception("Error loading AnimationChain", e);
// }
// }
// }
// }
// finally
// {
// FileManager.RelativeDirectory = oldRelativeDirectory;
// }
// return list;
//}
//public AnimationChainList ToAnimationChainList(Graphics.Texture.TextureAtlas textureAtlas)
//{
// return ToAnimationChainList(null, textureAtlas, true);
//}
private void MakeRelative(string fileName)
{
string oldRelativeDirectory = FileManager.RelativeDirectory;
string newRelativeDirectory = FileManager.GetDirectory(fileName);
FileManager.RelativeDirectory = newRelativeDirectory;
foreach (AnimationChainSave acs in AnimationChains)
{
acs.MakeRelative();
}
FileManager.RelativeDirectory = oldRelativeDirectory;
}
private static AnimationChainListSave DeserializeManually(string fileName)
{
AnimationChainListSave toReturn = new AnimationChainListSave();
System.Xml.Linq.XDocument xDocument = null;
using (var stream = FileManager.GetStreamForFile(fileName))
{
xDocument = System.Xml.Linq.XDocument.Load(stream);
}
System.Xml.Linq.XElement foundElement = null;
foreach (var element in xDocument.Elements())
{
if (element.Name.LocalName == "AnimationChainArraySave")
{
foundElement = element;
break;
}
}
LoadFromElement(toReturn, foundElement);
return toReturn;
}
private static void LoadFromElement(AnimationChainListSave toReturn, System.Xml.Linq.XElement element)
{
foreach (var subElement in element.Elements())
{
switch (subElement.Name.LocalName)
{
case "FileRelativeTextures":
toReturn.FileRelativeTextures = AsBool(subElement);
break;
case "TimeMeasurementUnit":
toReturn.TimeMeasurementUnit =
(TimeMeasurementUnit)Enum.Parse(typeof(TimeMeasurementUnit), subElement.Value, true);
break;
case "CoordinateType":
toReturn.CoordinateType =
(TextureCoordinateType)Enum.Parse(typeof(TextureCoordinateType), subElement.Value, true);
break;
case "AnimationChain":
toReturn.AnimationChains.Add(AnimationChainSave.FromXElement(subElement));
break;
}
}
}
internal static bool AsBool(System.Xml.Linq.XElement subElement)
{
return bool.Parse(subElement.Value);
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type FileAttachmentRequest.
/// </summary>
public partial class FileAttachmentRequest : BaseRequest, IFileAttachmentRequest
{
/// <summary>
/// Constructs a new FileAttachmentRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public FileAttachmentRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified FileAttachment using POST.
/// </summary>
/// <param name="fileAttachmentToCreate">The FileAttachment to create.</param>
/// <returns>The created FileAttachment.</returns>
public System.Threading.Tasks.Task<FileAttachment> CreateAsync(FileAttachment fileAttachmentToCreate)
{
return this.CreateAsync(fileAttachmentToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified FileAttachment using POST.
/// </summary>
/// <param name="fileAttachmentToCreate">The FileAttachment to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created FileAttachment.</returns>
public async System.Threading.Tasks.Task<FileAttachment> CreateAsync(FileAttachment fileAttachmentToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<FileAttachment>(fileAttachmentToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified FileAttachment.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified FileAttachment.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<FileAttachment>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified FileAttachment.
/// </summary>
/// <returns>The FileAttachment.</returns>
public System.Threading.Tasks.Task<FileAttachment> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified FileAttachment.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The FileAttachment.</returns>
public async System.Threading.Tasks.Task<FileAttachment> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<FileAttachment>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified FileAttachment using PATCH.
/// </summary>
/// <param name="fileAttachmentToUpdate">The FileAttachment to update.</param>
/// <returns>The updated FileAttachment.</returns>
public System.Threading.Tasks.Task<FileAttachment> UpdateAsync(FileAttachment fileAttachmentToUpdate)
{
return this.UpdateAsync(fileAttachmentToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified FileAttachment using PATCH.
/// </summary>
/// <param name="fileAttachmentToUpdate">The FileAttachment to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated FileAttachment.</returns>
public async System.Threading.Tasks.Task<FileAttachment> UpdateAsync(FileAttachment fileAttachmentToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<FileAttachment>(fileAttachmentToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IFileAttachmentRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IFileAttachmentRequest Expand(Expression<Func<FileAttachment, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IFileAttachmentRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IFileAttachmentRequest Select(Expression<Func<FileAttachment, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="fileAttachmentToInitialize">The <see cref="FileAttachment"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(FileAttachment fileAttachmentToInitialize)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Apache.Cordova {
// Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']"
[ObsoleteAttribute (@"This class is obsoleted in this android platform")]
[global::Android.Runtime.Register ("org/apache/cordova/ExifHelper", DoNotGenerateAcw=true)]
public partial class ExifHelper : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/apache/cordova/ExifHelper", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (ExifHelper); }
}
protected ExifHelper (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']/constructor[@name='ExifHelper' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public ExifHelper () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (ExifHelper)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor);
}
static Delegate cb_getOrientation;
#pragma warning disable 0169
static Delegate GetGetOrientationHandler ()
{
if (cb_getOrientation == null)
cb_getOrientation = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetOrientation);
return cb_getOrientation;
}
static int n_GetOrientation (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.ExifHelper __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.ExifHelper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.Orientation;
}
#pragma warning restore 0169
static IntPtr id_getOrientation;
public virtual int Orientation {
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']/method[@name='getOrientation' and count(parameter)=0]"
[Register ("getOrientation", "()I", "GetGetOrientationHandler")]
get {
if (id_getOrientation == IntPtr.Zero)
id_getOrientation = JNIEnv.GetMethodID (class_ref, "getOrientation", "()I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getOrientation);
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getOrientation", "()I"));
}
}
static Delegate cb_createInFile_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetCreateInFile_Ljava_lang_String_Handler ()
{
if (cb_createInFile_Ljava_lang_String_ == null)
cb_createInFile_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_CreateInFile_Ljava_lang_String_);
return cb_createInFile_Ljava_lang_String_;
}
static void n_CreateInFile_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.ExifHelper __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.ExifHelper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.CreateInFile (p0);
}
#pragma warning restore 0169
static IntPtr id_createInFile_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']/method[@name='createInFile' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("createInFile", "(Ljava/lang/String;)V", "GetCreateInFile_Ljava_lang_String_Handler")]
public virtual void CreateInFile (string p0)
{
if (id_createInFile_Ljava_lang_String_ == IntPtr.Zero)
id_createInFile_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "createInFile", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_createInFile_Ljava_lang_String_, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createInFile", "(Ljava/lang/String;)V"), new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_createOutFile_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetCreateOutFile_Ljava_lang_String_Handler ()
{
if (cb_createOutFile_Ljava_lang_String_ == null)
cb_createOutFile_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_CreateOutFile_Ljava_lang_String_);
return cb_createOutFile_Ljava_lang_String_;
}
static void n_CreateOutFile_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.ExifHelper __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.ExifHelper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.CreateOutFile (p0);
}
#pragma warning restore 0169
static IntPtr id_createOutFile_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']/method[@name='createOutFile' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("createOutFile", "(Ljava/lang/String;)V", "GetCreateOutFile_Ljava_lang_String_Handler")]
public virtual void CreateOutFile (string p0)
{
if (id_createOutFile_Ljava_lang_String_ == IntPtr.Zero)
id_createOutFile_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "createOutFile", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_createOutFile_Ljava_lang_String_, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "createOutFile", "(Ljava/lang/String;)V"), new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_readExifData;
#pragma warning disable 0169
static Delegate GetReadExifDataHandler ()
{
if (cb_readExifData == null)
cb_readExifData = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_ReadExifData);
return cb_readExifData;
}
static void n_ReadExifData (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.ExifHelper __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.ExifHelper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.ReadExifData ();
}
#pragma warning restore 0169
static IntPtr id_readExifData;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']/method[@name='readExifData' and count(parameter)=0]"
[Register ("readExifData", "()V", "GetReadExifDataHandler")]
public virtual void ReadExifData ()
{
if (id_readExifData == IntPtr.Zero)
id_readExifData = JNIEnv.GetMethodID (class_ref, "readExifData", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_readExifData);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "readExifData", "()V"));
}
static Delegate cb_resetOrientation;
#pragma warning disable 0169
static Delegate GetResetOrientationHandler ()
{
if (cb_resetOrientation == null)
cb_resetOrientation = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_ResetOrientation);
return cb_resetOrientation;
}
static void n_ResetOrientation (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.ExifHelper __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.ExifHelper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.ResetOrientation ();
}
#pragma warning restore 0169
static IntPtr id_resetOrientation;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']/method[@name='resetOrientation' and count(parameter)=0]"
[Register ("resetOrientation", "()V", "GetResetOrientationHandler")]
public virtual void ResetOrientation ()
{
if (id_resetOrientation == IntPtr.Zero)
id_resetOrientation = JNIEnv.GetMethodID (class_ref, "resetOrientation", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_resetOrientation);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "resetOrientation", "()V"));
}
static Delegate cb_writeExifData;
#pragma warning disable 0169
static Delegate GetWriteExifDataHandler ()
{
if (cb_writeExifData == null)
cb_writeExifData = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_WriteExifData);
return cb_writeExifData;
}
static void n_WriteExifData (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.ExifHelper __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.ExifHelper> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.WriteExifData ();
}
#pragma warning restore 0169
static IntPtr id_writeExifData;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='ExifHelper']/method[@name='writeExifData' and count(parameter)=0]"
[Register ("writeExifData", "()V", "GetWriteExifDataHandler")]
public virtual void WriteExifData ()
{
if (id_writeExifData == IntPtr.Zero)
id_writeExifData = JNIEnv.GetMethodID (class_ref, "writeExifData", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_writeExifData);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "writeExifData", "()V"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public partial class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
Add,
Union,
Remove,
Except,
Last,
}
protected override bool IncludesGetHashCodeDerivative
{
get { return false; }
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedSet<int>();
var actual = ImmutableSortedSet<int>.Empty;
int seed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the set.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.Union:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the set.", inputLength);
expected.UnionWith(values);
actual = actual.Union(values);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
int element = expected.Skip(position).First();
Debug.WriteLine("Removing element \"{0}\" from the set.", element);
Assert.True(expected.Remove(element));
actual = actual.Remove(element);
}
break;
case Operation.Except:
var elements = expected.Where(el => random.Next(2) == 0).ToArray();
Debug.WriteLine("Removing {0} elements from the set.", elements.Length);
expected.ExceptWith(elements);
actual = actual.Except(elements);
break;
}
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal),
true,
new[] { "apple", "APPLE" },
new[] { "APPLE", "apple" });
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
true,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeSortComparer()
{
var ordinalSet = ImmutableSortedSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToUnorderedTest()
{
var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet();
Assert.True(result.Contains(3));
}
[Fact]
public void ToImmutableSortedSetFromArrayTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[Theory]
[InlineData(new int[] { }, new int[] { })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void ToImmutableSortedSetFromEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = enumerableInput.ToImmutableSortedSet();
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Theory]
[InlineData(new int[] { }, new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void UnionWithEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = ImmutableSortedSet.Create(1).Union(enumerableInput);
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Fact]
public void IndexOfTest()
{
var set = ImmutableSortedSet<int>.Empty;
Assert.Equal(~0, set.IndexOf(5));
set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
Assert.Equal(0, set.IndexOf(10));
Assert.Equal(1, set.IndexOf(20));
Assert.Equal(4, set.IndexOf(50));
Assert.Equal(8, set.IndexOf(90));
Assert.Equal(9, set.IndexOf(100));
Assert.Equal(~0, set.IndexOf(5));
Assert.Equal(~1, set.IndexOf(15));
Assert.Equal(~2, set.IndexOf(25));
Assert.Equal(~5, set.IndexOf(55));
Assert.Equal(~9, set.IndexOf(95));
Assert.Equal(~10, set.IndexOf(105));
var nullableSet = ImmutableSortedSet<int?>.Empty;
Assert.Equal(~0, nullableSet.IndexOf(null));
nullableSet = nullableSet.Add(null).Add(0);
Assert.Equal(0, nullableSet.IndexOf(null));
}
[Fact]
public void IndexGetTest()
{
var set = ImmutableSortedSet<int>.Empty
.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
int i = 0;
foreach (var item in set)
{
AssertAreSame(item, set[i++]);
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => set[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => set[set.Count]);
}
[Fact]
public void ReverseTest()
{
var range = Enumerable.Range(1, 10);
var set = ImmutableSortedSet<int>.Empty.Union(range);
var expected = range.Reverse().ToList();
var actual = set.Reverse().ToList();
Assert.Equal<int>(expected, actual);
}
[Fact]
public void MaxTest()
{
Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max);
}
[Fact]
public void MinTest()
{
Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min);
}
[Fact]
public void InitialBulkAdd()
{
Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count);
Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count);
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> set = ImmutableSortedSet.Create<string>();
Assert.Throws<NotSupportedException>(() => set.Add("a"));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove("a"));
Assert.True(set.IsReadOnly);
}
[Fact]
public void IListOfTMethods()
{
IList<string> set = ImmutableSortedSet.Create<string>("b");
Assert.Throws<NotSupportedException>(() => set.Insert(0, "a"));
Assert.Throws<NotSupportedException>(() => set.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => set[0] = "a");
Assert.Equal("b", set[0]);
Assert.True(set.IsReadOnly);
}
[Fact]
public void UnionOptimizationsTest()
{
var set = ImmutableSortedSet.Create(1, 2, 3);
var builder = set.ToBuilder();
Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder));
Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>()));
var smallSet = ImmutableSortedSet.Create(1);
var unionSet = smallSet.Union(set);
Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableSortedSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create(default(string));
Assert.Equal(1, set.Count);
set = ImmutableSortedSet.CreateRange(new[] { null, "a", null, "b" });
Assert.Equal(3, set.Count);
}
[Fact]
public void IListMethods()
{
IList list = ImmutableSortedSet.Create("a", "b");
Assert.True(list.Contains("a"));
Assert.Equal("a", list[0]);
Assert.Equal("b", list[1]);
Assert.Equal(0, list.IndexOf("a"));
Assert.Equal(1, list.IndexOf("b"));
Assert.Throws<NotSupportedException>(() => list.Add("b"));
Assert.Throws<NotSupportedException>(() => list[3] = "c");
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, "b"));
Assert.Throws<NotSupportedException>(() => list.Remove("a"));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.True(list.IsFixedSize);
Assert.True(list.IsReadOnly);
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.Create<int>());
ImmutableSortedSet<string> set = ImmutableSortedSet.Create("1", "2", "3");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(set);
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedSet.Create<object>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
string[] items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(set, items);
}
[Fact]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSortedSet.Create("1", "2", "3"));
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void SymmetricExceptWithComparerTests()
{
var set = ImmutableSortedSet.Create<string>("a").WithComparer(StringComparer.OrdinalIgnoreCase);
var otherCollection = new[] {"A"};
var expectedSet = new SortedSet<string>(set, set.KeyComparer);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
}
[Fact]
public void ItemRef()
{
var array = new[] { 1, 2, 3 }.ToImmutableSortedSet();
ref readonly var safeRef = ref array.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, array.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, array.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var array = new[] { 1, 2, 3 }.ToImmutableSortedSet();
Assert.Throws<ArgumentOutOfRangeException>(() => array.ItemRef(5));
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected ImmutableSortedSet<T> EmptyTyped<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new SortedSet<T>();
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
namespace DiscUtils.Streams
{
public class StripedStream : SparseStream
{
private readonly bool _canRead;
private readonly bool _canWrite;
private readonly long _length;
private readonly Ownership _ownsWrapped;
private long _position;
private readonly long _stripeSize;
private List<SparseStream> _wrapped;
public StripedStream(long stripeSize, Ownership ownsWrapped, params SparseStream[] wrapped)
{
_wrapped = new List<SparseStream>(wrapped);
_stripeSize = stripeSize;
_ownsWrapped = ownsWrapped;
_canRead = _wrapped[0].CanRead;
_canWrite = _wrapped[0].CanWrite;
long subStreamLength = _wrapped[0].Length;
foreach (SparseStream stream in _wrapped)
{
if (stream.CanRead != _canRead || stream.CanWrite != _canWrite)
{
throw new ArgumentException("All striped streams must have the same read/write permissions",
nameof(wrapped));
}
if (stream.Length != subStreamLength)
{
throw new ArgumentException("All striped streams must have the same length", nameof(wrapped));
}
}
_length = subStreamLength * wrapped.Length;
}
public override bool CanRead
{
get { return _canRead; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return _canWrite; }
}
public override IEnumerable<StreamExtent> Extents
{
get
{
// Temporary, indicate there are no 'unstored' extents.
// Consider combining extent information from all wrapped streams in future.
yield return new StreamExtent(0, _length);
}
}
public override long Length
{
get { return _length; }
}
public override long Position
{
get { return _position; }
set { _position = value; }
}
public override void Flush()
{
foreach (SparseStream stream in _wrapped)
{
stream.Flush();
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (!CanRead)
{
throw new InvalidOperationException("Attempt to read to non-readable stream");
}
int maxToRead = (int)Math.Min(_length - _position, count);
int totalRead = 0;
while (totalRead < maxToRead)
{
long stripe = _position / _stripeSize;
long stripeOffset = _position % _stripeSize;
int stripeToRead = (int)Math.Min(maxToRead - totalRead, _stripeSize - stripeOffset);
int streamIdx = (int)(stripe % _wrapped.Count);
long streamStripe = stripe / _wrapped.Count;
Stream targetStream = _wrapped[streamIdx];
targetStream.Position = streamStripe * _stripeSize + stripeOffset;
int numRead = targetStream.Read(buffer, offset + totalRead, stripeToRead);
_position += numRead;
totalRead += numRead;
}
return totalRead;
}
public override long Seek(long offset, SeekOrigin origin)
{
long effectiveOffset = offset;
if (origin == SeekOrigin.Current)
{
effectiveOffset += _position;
}
else if (origin == SeekOrigin.End)
{
effectiveOffset += _length;
}
if (effectiveOffset < 0)
{
throw new IOException("Attempt to move before beginning of stream");
}
_position = effectiveOffset;
return _position;
}
public override void SetLength(long value)
{
if (value != _length)
{
throw new InvalidOperationException("Changing the stream length is not permitted for striped streams");
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite)
{
throw new InvalidOperationException("Attempt to write to read-only stream");
}
if (_position + count > _length)
{
throw new IOException("Attempt to write beyond end of stream");
}
int totalWritten = 0;
while (totalWritten < count)
{
long stripe = _position / _stripeSize;
long stripeOffset = _position % _stripeSize;
int stripeToWrite = (int)Math.Min(count - totalWritten, _stripeSize - stripeOffset);
int streamIdx = (int)(stripe % _wrapped.Count);
long streamStripe = stripe / _wrapped.Count;
Stream targetStream = _wrapped[streamIdx];
targetStream.Position = streamStripe * _stripeSize + stripeOffset;
targetStream.Write(buffer, offset + totalWritten, stripeToWrite);
_position += stripeToWrite;
totalWritten += stripeToWrite;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _ownsWrapped == Ownership.Dispose && _wrapped != null)
{
foreach (SparseStream stream in _wrapped)
{
stream.Dispose();
}
_wrapped = null;
}
}
finally
{
base.Dispose(disposing);
}
}
}
}
| |
using System;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Its.Domain.Sql
{
/// <summary>
/// A reservation service backed by a SQL store.
/// </summary>
public class SqlReservationService : IReservationService, ISynchronousReservationService
{
public Func<DbContext> CreateReservationServiceDbContext = () => new ReservationServiceDbContext();
internal Func<DbSet<ReservedValue>, string, DateTimeOffset, Task<ReservedValue>> GetValueToReserve =
async (reservedValues, scope, now) =>
await reservedValues.FirstOrDefaultAsync(r => r.Scope == scope
&& r.Expiration < now
&& r.Expiration != null);
internal Func<DbSet<ReservedValue>, string, DateTimeOffset, ReservedValue> GetValueToReserveSynchronous =
(reservedValues, scope, now) =>
reservedValues.FirstOrDefault(r => r.Scope == scope
&& r.Expiration < now
&& r.Expiration != null);
public async Task<bool> Reserve(string value, string scope, string ownerToken, TimeSpan? lease = null)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
var now = Clock.Now();
using (var db = CreateReservationServiceDbContext())
{
var reservedValues = db.Set<ReservedValue>();
var expiration = now + (lease ?? TimeSpan.FromMinutes(1));
// see if there is a pre-existing lease by the same actor
var reservedValue = reservedValues.SingleOrDefault(r => r.Scope == scope &&
r.Value == value);
if (reservedValue == null)
{
// if not, create a new ticket
reservedValue = new ReservedValue
{
OwnerToken = ownerToken,
Scope = scope,
Value = value,
Expiration = expiration,
ConfirmationToken = value
};
reservedValues.Add(reservedValue);
}
else if (reservedValue.Expiration == null)
{
return reservedValue.OwnerToken == ownerToken;
}
else if (reservedValue.OwnerToken == ownerToken)
{
// if it's the same, extend the lease
reservedValue.Expiration = expiration;
}
else if (reservedValue.Expiration < now)
{
// take ownership if the reserved value has expired
reservedValue.OwnerToken = ownerToken;
reservedValue.Expiration = expiration;
}
else
{
return false;
}
try
{
await db.SaveChangesAsync();
return true;
}
catch (Exception exception)
{
if (!exception.IsConcurrencyException())
{
throw;
}
}
return false;
}
}
public async Task<bool> Confirm(string value, string scope, string ownerToken)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
using (var db = CreateReservationServiceDbContext())
{
var reservedValue = await db.Set<ReservedValue>()
.SingleOrDefaultAsync(v => v.Scope == scope &&
v.ConfirmationToken == value &&
v.OwnerToken == ownerToken);
if (reservedValue != null)
{
reservedValue.Expiration = null;
await db.SaveChangesAsync();
return true;
}
return false;
}
}
public async Task<bool> Cancel(string value, string scope, string ownerToken)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
using (var db = CreateReservationServiceDbContext())
{
var reservedValues = db.Set<ReservedValue>();
var reservedValue = await reservedValues
.SingleOrDefaultAsync(v => v.Scope == scope && v.Value == value && v.OwnerToken == ownerToken);
if (reservedValue != null)
{
reservedValues.Remove(reservedValue);
await db.SaveChangesAsync();
return true;
}
return false;
}
}
public async Task<string> ReserveAny(string scope, string ownerToken, TimeSpan? lease = null, string confirmationToken = null)
{
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
var now = Clock.Now();
using (var db = CreateReservationServiceDbContext())
{
var reservedValues = db.Set<ReservedValue>();
var expiration = now + (lease ?? TimeSpan.FromMinutes(1));
ReservedValue valueToReserve;
do
{
valueToReserve = await reservedValues.SingleOrDefaultAsync(r => r.OwnerToken == ownerToken &&
r.ConfirmationToken == confirmationToken &&
r.Expiration != null);
if (valueToReserve == null)
{
valueToReserve = await GetValueToReserve(reservedValues, scope, now);
}
if (valueToReserve == null)
{
return null;
}
valueToReserve.Expiration = expiration;
valueToReserve.OwnerToken = ownerToken;
if (confirmationToken != null)
{
valueToReserve.ConfirmationToken = confirmationToken;
}
try
{
await db.SaveChangesAsync();
return valueToReserve.Value;
}
catch (DbUpdateException exception)
{
if (exception.InnerException is OptimisticConcurrencyException)
{
db.Entry(valueToReserve).State = EntityState.Unchanged;
}
else if (exception.IsUniquenessConstraint())
{
return null;
}
else
{
throw;
}
}
} while (valueToReserve != null); //retry on concurrency exception
}
return null;
}
bool ISynchronousReservationService.Reserve(string value, string scope, string ownerToken, TimeSpan? lease)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
var now = Clock.Now();
using (var db = CreateReservationServiceDbContext())
{
var reservedValues = db.Set<ReservedValue>();
var expiration = now + (lease ?? TimeSpan.FromMinutes(1));
// see if there is a pre-existing lease by the same actor
var reservedValue = reservedValues.SingleOrDefault(r => r.Scope == scope &&
r.Value == value);
if (reservedValue == null)
{
// if not, create a new ticket
reservedValue = new ReservedValue
{
OwnerToken = ownerToken,
Scope = scope,
Value = value,
Expiration = expiration,
ConfirmationToken = value
};
reservedValues.Add(reservedValue);
}
else if (reservedValue.Expiration == null)
{
return reservedValue.OwnerToken == ownerToken;
}
else if (reservedValue.OwnerToken == ownerToken)
{
// if it's the same, extend the lease
reservedValue.Expiration = expiration;
}
else if (reservedValue.Expiration < now)
{
// take ownership if the reserved value has expired
reservedValue.OwnerToken = ownerToken;
reservedValue.Expiration = expiration;
}
else
{
return false;
}
try
{
db.SaveChanges();
return true;
}
catch (Exception exception)
{
if (!exception.IsConcurrencyException())
{
throw;
}
}
return false;
}
}
bool ISynchronousReservationService.Confirm(string value, string scope, string ownerToken)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
using (var db = CreateReservationServiceDbContext())
{
var reservedValue = db.Set<ReservedValue>()
.SingleOrDefault(v => v.Scope == scope &&
v.ConfirmationToken == value &&
v.OwnerToken == ownerToken);
if (reservedValue != null)
{
reservedValue.Expiration = null;
db.SaveChanges();
return true;
}
return false;
}
}
bool ISynchronousReservationService.Cancel(string value, string scope, string ownerToken)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
using (var db = CreateReservationServiceDbContext())
{
var reservedValues = db.Set<ReservedValue>();
var reservedValue = reservedValues
.SingleOrDefault(v => v.Scope == scope && v.Value == value && v.OwnerToken == ownerToken);
if (reservedValue != null)
{
reservedValues.Remove(reservedValue);
db.SaveChanges();
return true;
}
return false;
}
}
string ISynchronousReservationService.ReserveAny(string scope, string ownerToken, TimeSpan? lease, string confirmationToken)
{
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (ownerToken == null)
{
throw new ArgumentNullException("ownerToken");
}
var now = Clock.Now();
using (var db = CreateReservationServiceDbContext())
{
var reservedValues = db.Set<ReservedValue>();
var expiration = now + (lease ?? TimeSpan.FromMinutes(1));
ReservedValue valueToReserve;
do
{
valueToReserve = reservedValues.SingleOrDefault(r => r.OwnerToken == ownerToken &&
r.ConfirmationToken == confirmationToken &&
r.Expiration != null);
if (valueToReserve == null)
{
valueToReserve = GetValueToReserveSynchronous(reservedValues, scope, now);
}
if (valueToReserve == null)
{
return null;
}
valueToReserve.Expiration = expiration;
valueToReserve.OwnerToken = ownerToken;
if (confirmationToken != null)
{
valueToReserve.ConfirmationToken = confirmationToken;
}
try
{
db.SaveChanges();
return valueToReserve.Value;
}
catch (DbUpdateException exception)
{
if (exception.InnerException is OptimisticConcurrencyException)
{
db.Entry(valueToReserve).State = EntityState.Unchanged;
}
else if (exception.IsUniquenessConstraint())
{
return null;
}
else
{
throw;
}
}
} while (valueToReserve != null); //retry on concurrency exception
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Orleans.Runtime;
using OrleansSQLUtils.Storage;
namespace Orleans.SqlUtils
{
/// <summary>
/// A class for all relational storages that support all systems stores : membership, reminders and statistics
/// </summary>
internal class RelationalOrleansQueries
{
/// <summary>
/// the underlying storage
/// </summary>
private readonly IRelationalStorage storage;
/// <summary>
/// When inserting statistics and generating a batch insert clause, these are the columns in the statistics
/// table that will be updated with multiple values. The other ones are updated with one value only.
/// </summary>
private readonly static string[] InsertStatisticsMultiupdateColumns =
{
$"@{DbStoredQueries.Columns.IsValueDelta}",
$"@{DbStoredQueries.Columns.StatValue}",
$"@{DbStoredQueries.Columns.Statistic}"
};
/// <summary>
/// the orleans functional queries
/// </summary>
private readonly DbStoredQueries dbStoredQueries;
/// <summary>
/// Constructor
/// </summary>
/// <param name="storage">the underlying relational storage</param>
/// <param name="dbStoredQueries">Orleans functional queries</param>
private RelationalOrleansQueries(IRelationalStorage storage, DbStoredQueries dbStoredQueries)
{
this.storage = storage;
this.dbStoredQueries = dbStoredQueries;
}
/// <summary>
/// Creates an instance of a database of type <see cref="RelationalOrleansQueries"/> and Initializes Orleans queries from the database.
/// Orleans uses only these queries and the variables therein, nothing more.
/// </summary>
/// <param name="invariantName">The invariant name of the connector for this database.</param>
/// <param name="connectionString">The connection string this database should use for database operations.</param>
internal static async Task<RelationalOrleansQueries> CreateInstance(string invariantName, string connectionString)
{
var storage = RelationalStorage.CreateInstance(invariantName, connectionString);
var queries = await storage.ReadAsync(DbStoredQueries.GetQueriesKey, DbStoredQueries.Converters.GetQueryKeyAndValue, null);
return new RelationalOrleansQueries(storage, new DbStoredQueries(queries.ToDictionary(q => q.Key, q => q.Value)));
}
private Task ExecuteAsync(string query, Func<IDbCommand, DbStoredQueries.Columns> parameterProvider)
{
return storage.ExecuteAsync(query, command => parameterProvider(command));
}
private async Task<TAggregate> ReadAsync<TResult, TAggregate>(string query,
Func<IDataRecord, TResult> selector,
Func<IDbCommand, DbStoredQueries.Columns> parameterProvider,
Func<IEnumerable<TResult>, TAggregate> aggregator)
{
var ret = await storage.ReadAsync(query, selector, command => parameterProvider(command));
return aggregator(ret);
}
/// <summary>
/// Either inserts or updates a silo metrics row.
/// </summary>
/// <param name="deploymentId">The deployment ID.</param>
/// <param name="siloId">The silo ID.</param>
/// <param name="gateway">The gateway information.</param>
/// <param name="siloAddress">The silo address information.</param>
/// <param name="hostName">The host name.</param>
/// <param name="siloMetrics">The silo metrics to be either updated or inserted.</param>
/// <returns></returns>
internal Task UpsertSiloMetricsAsync(string deploymentId, string siloId, IPEndPoint gateway,
SiloAddress siloAddress, string hostName, ISiloPerformanceMetrics siloMetrics)
{
return ExecuteAsync(dbStoredQueries.UpsertSiloMetricsKey, command =>
new DbStoredQueries.Columns(command)
{
DeploymentId = deploymentId,
HostName = hostName,
SiloMetrics = siloMetrics,
SiloAddress = siloAddress,
GatewayAddress = gateway.Address,
GatewayPort = gateway.Port,
SiloId = siloId
});
}
/// <summary>
/// Either inserts or updates a silo metrics row.
/// </summary>
/// <param name="deploymentId">The deployment ID.</param>
/// <param name="clientId">The client ID.</param>
/// <param name="address">The client address information.</param>
/// <param name="hostName">The hostname.</param>
/// <param name="clientMetrics">The client metrics to be either updated or inserted.</param>
/// <returns></returns>
internal Task UpsertReportClientMetricsAsync(string deploymentId, string clientId, IPAddress address,
string hostName, IClientPerformanceMetrics clientMetrics)
{
return ExecuteAsync(dbStoredQueries.UpsertReportClientMetricsKey, command =>
new DbStoredQueries.Columns(command)
{
DeploymentId = deploymentId,
HostName = hostName,
ClientMetrics = clientMetrics,
ClientId = clientId,
Address = address
});
}
/// <summary>
/// Inserts the given statistics counters to the Orleans database.
/// </summary>
/// <param name="deploymentId">The deployment ID.</param>
/// <param name="hostName">The hostname.</param>
/// <param name="siloOrClientName">The silo or client name.</param>
/// <param name="id">The silo address or client ID.</param>
/// <param name="counters">The counters to be inserted.</param>
internal Task InsertStatisticsCountersAsync(string deploymentId, string hostName, string siloOrClientName,
string id, List<ICounter> counters)
{
var queryTemplate = dbStoredQueries.InsertOrleansStatisticsKey;
//Zero statistic values mean either that the system is not running or no updates. Such values are not inserted and pruned
//here so that no insert query or parameters are generated.
counters =
counters.Where(i => !"0".Equals(i.IsValueDelta ? i.GetDeltaString() : i.GetValueString())).ToList();
if (counters.Count == 0)
{
return TaskDone.Done;
}
//Note that the following is almost the same as RelationalStorageExtensions.ExecuteMultipleInsertIntoAsync
//the only difference being that some columns are skipped. Likely it would be beneficial to introduce
//a "skip list" to RelationalStorageExtensions.ExecuteMultipleInsertIntoAsync.
//The template contains an insert for online. The part after SELECT is copied
//out so that certain parameters can be multiplied by their count. Effectively
//this turns a query of type (transaction details vary by vendor)
//BEGIN TRANSACTION; INSERT INTO [OrleansStatisticsTable] <columns> SELECT <variables>; COMMIT TRANSACTION;
//to BEGIN TRANSACTION; INSERT INTO [OrleansStatisticsTable] <columns> SELECT <variables>; UNION ALL <variables> COMMIT TRANSACTION;
//where the UNION ALL is multiplied as many times as there are counters to insert.
int startFrom = queryTemplate.IndexOf("SELECT", StringComparison.Ordinal) + "SELECT".Length + 1;
//This +1 is to have a space between SELECT and the first parameter name to not to have a SQL syntax error.
int lastSemicolon = queryTemplate.LastIndexOf(";", StringComparison.Ordinal);
int endTo = lastSemicolon > 0 ? queryTemplate.LastIndexOf(";", lastSemicolon - 1, StringComparison.Ordinal) : -1;
var template = queryTemplate.Substring(startFrom, endTo - startFrom);
var parameterNames = template.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).ToArray();
var collectionOfParametersToBeUnionized = new List<string>();
var parametersToBeUnioned = new string[parameterNames.Length];
for (int counterIndex = 0; counterIndex < counters.Count; ++counterIndex)
{
for (int parameterNameIndex = 0; parameterNameIndex < parameterNames.Length; ++parameterNameIndex)
{
if (InsertStatisticsMultiupdateColumns.Contains(parameterNames[parameterNameIndex]))
{
//These parameters change for each row. The format is
//@StatValue0, @StatValue1, @StatValue2, ... @sStatValue{counters.Count}.
parametersToBeUnioned[parameterNameIndex] = $"{parameterNames[parameterNameIndex]}{counterIndex}";
}
else
{
//These parameters remain constant for every and each row.
parametersToBeUnioned[parameterNameIndex] = parameterNames[parameterNameIndex];
}
}
collectionOfParametersToBeUnionized.Add($"{string.Join(",", parametersToBeUnioned)}");
}
var storageConsts = DbConstantsStore.GetDbConstants(storage.InvariantName);
var query = queryTemplate.Replace(template, string.Join(storageConsts.UnionAllSelectTemplate, collectionOfParametersToBeUnionized));
return ExecuteAsync(query, command =>
new DbStoredQueries.Columns(command)
{
DeploymentId = deploymentId,
HostName = hostName,
Counters = counters,
Name = siloOrClientName,
Id = id
});
}
/// <summary>
/// Reads Orleans reminder data from the tables.
/// </summary>
/// <param name="serviceId">The service ID.</param>
/// <param name="grainRef">The grain reference (ID).</param>
/// <returns>Reminder table data.</returns>
internal Task<ReminderTableData> ReadReminderRowsAsync(string serviceId, GrainReference grainRef)
{
return ReadAsync(dbStoredQueries.ReadReminderRowsKey, DbStoredQueries.Converters.GetReminderEntry, command =>
new DbStoredQueries.Columns(command) {ServiceId = serviceId, GrainId = grainRef.ToKeyString()},
ret => new ReminderTableData(ret.ToList()));
}
/// <summary>
/// Reads Orleans reminder data from the tables.
/// </summary>
/// <param name="serviceId">The service ID.</param>
/// <param name="beginHash">The begin hash.</param>
/// <param name="endHash">The end hash.</param>
/// <returns>Reminder table data.</returns>
internal Task<ReminderTableData> ReadReminderRowsAsync(string serviceId, uint beginHash, uint endHash)
{
var query = (int) beginHash < (int) endHash ? dbStoredQueries.ReadRangeRows1Key : dbStoredQueries.ReadRangeRows2Key;
return ReadAsync(query, DbStoredQueries.Converters.GetReminderEntry, command =>
new DbStoredQueries.Columns(command) {ServiceId = serviceId, BeginHash = beginHash, EndHash = endHash},
ret => new ReminderTableData(ret.ToList()));
}
/// <summary>
/// Reads one row of reminder data.
/// </summary>
/// <param name="serviceId">Service ID.</param>
/// <param name="grainRef">The grain reference (ID).</param>
/// <param name="reminderName">The reminder name to retrieve.</param>
/// <returns>A remainder entry.</returns>
internal Task<ReminderEntry> ReadReminderRowAsync(string serviceId, GrainReference grainRef,
string reminderName)
{
return ReadAsync(dbStoredQueries.ReadReminderRowKey, DbStoredQueries.Converters.GetReminderEntry, command =>
new DbStoredQueries.Columns(command)
{
ServiceId = serviceId,
GrainId = grainRef.ToKeyString(),
ReminderName = reminderName
}, ret => ret.FirstOrDefault());
}
/// <summary>
/// Either inserts or updates a reminder row.
/// </summary>
/// <param name="serviceId">The service ID.</param>
/// <param name="grainRef">The grain reference (ID).</param>
/// <param name="reminderName">The reminder name to retrieve.</param>
/// <param name="startTime">Start time of the reminder.</param>
/// <param name="period">Period of the reminder.</param>
/// <returns>The new etag of the either or updated or inserted reminder row.</returns>
internal Task<string> UpsertReminderRowAsync(string serviceId, GrainReference grainRef,
string reminderName, DateTime startTime, TimeSpan period)
{
return ReadAsync(dbStoredQueries.UpsertReminderRowKey, DbStoredQueries.Converters.GetVersion, command =>
new DbStoredQueries.Columns(command)
{
ServiceId = serviceId,
GrainHash = grainRef.GetUniformHashCode(),
GrainId = grainRef.ToKeyString(),
ReminderName = reminderName,
StartTime = startTime,
Period = period
}, ret => ret.First().ToString());
}
/// <summary>
/// Deletes a reminder
/// </summary>
/// <param name="serviceId">Service ID.</param>
/// <param name="grainRef"></param>
/// <param name="reminderName"></param>
/// <param name="etag"></param>
/// <returns></returns>
internal Task<bool> DeleteReminderRowAsync(string serviceId, GrainReference grainRef, string reminderName,
string etag)
{
return ReadAsync(dbStoredQueries.DeleteReminderRowKey, DbStoredQueries.Converters.GetSingleBooleanValue, command =>
new DbStoredQueries.Columns(command)
{
ServiceId = serviceId,
GrainId = grainRef.ToKeyString(),
ReminderName = reminderName,
Version = etag
}, ret => ret.First());
}
/// <summary>
/// Deletes all reminders rows of a service id.
/// </summary>
/// <param name="serviceId"></param>
/// <returns></returns>
internal Task DeleteReminderRowsAsync(string serviceId)
{
return ExecuteAsync(dbStoredQueries.DeleteReminderRowsKey, command =>
new DbStoredQueries.Columns(command) {ServiceId = serviceId});
}
/// <summary>
/// Lists active gateways. Used mainly by Orleans clients.
/// </summary>
/// <param name="deploymentId">The deployment for which to query the gateways.</param>
/// <returns>The gateways for the silo.</returns>
internal Task<List<Uri>> ActiveGatewaysAsync(string deploymentId)
{
return ReadAsync(dbStoredQueries.GatewaysQueryKey, DbStoredQueries.Converters.GetGatewayUri, command =>
new DbStoredQueries.Columns(command) {DeploymentId = deploymentId, Status = SiloStatus.Active},
ret => ret.ToList());
}
/// <summary>
/// Queries Orleans membership data.
/// </summary>
/// <param name="deploymentId">The deployment for which to query data.</param>
/// <param name="siloAddress">Silo data used as parameters in the query.</param>
/// <returns>Membership table data.</returns>
internal Task<MembershipTableData> MembershipReadRowAsync(string deploymentId, SiloAddress siloAddress)
{
return ReadAsync(dbStoredQueries.MembershipReadRowKey, DbStoredQueries.Converters.GetMembershipEntry, command =>
new DbStoredQueries.Columns(command) {DeploymentId = deploymentId, SiloAddress = siloAddress},
ConvertToMembershipTableData);
}
/// <summary>
/// returns all membership data for a deployment id
/// </summary>
/// <param name="deploymentId"></param>
/// <returns></returns>
internal Task<MembershipTableData> MembershipReadAllAsync(string deploymentId)
{
return ReadAsync(dbStoredQueries.MembershipReadAllKey, DbStoredQueries.Converters.GetMembershipEntry, command =>
new DbStoredQueries.Columns(command) {DeploymentId = deploymentId}, ConvertToMembershipTableData);
}
/// <summary>
/// deletes all membership entries for a deployment id
/// </summary>
/// <param name="deploymentId"></param>
/// <returns></returns>
internal Task DeleteMembershipTableEntriesAsync(string deploymentId)
{
return ExecuteAsync(dbStoredQueries.DeleteMembershipTableEntriesKey, command =>
new DbStoredQueries.Columns(command) {DeploymentId = deploymentId});
}
/// <summary>
/// Updates IAmAlive for a silo
/// </summary>
/// <param name="deploymentId"></param>
/// <param name="siloAddress"></param>
/// <param name="iAmAliveTime"></param>
/// <returns></returns>
internal Task UpdateIAmAliveTimeAsync(string deploymentId, SiloAddress siloAddress,DateTime iAmAliveTime)
{
return ExecuteAsync(dbStoredQueries.UpdateIAmAlivetimeKey, command =>
new DbStoredQueries.Columns(command)
{
DeploymentId = deploymentId,
SiloAddress = siloAddress,
IAmAliveTime = iAmAliveTime
});
}
/// <summary>
/// Inserts a version row if one does not already exist.
/// </summary>
/// <param name="deploymentId">The deployment for which to query data.</param>
/// <returns><em>TRUE</em> if a row was inserted. <em>FALSE</em> otherwise.</returns>
internal Task<bool> InsertMembershipVersionRowAsync(string deploymentId)
{
return ReadAsync(dbStoredQueries.InsertMembershipVersionKey, DbStoredQueries.Converters.GetSingleBooleanValue, command =>
new DbStoredQueries.Columns(command) {DeploymentId = deploymentId}, ret => ret.First());
}
/// <summary>
/// Inserts a membership row if one does not already exist.
/// </summary>
/// <param name="deploymentId">The deployment with which to insert row.</param>
/// <param name="membershipEntry">The membership entry data to insert.</param>
/// <param name="etag">The table expected version etag.</param>
/// <returns><em>TRUE</em> if insert succeeds. <em>FALSE</em> otherwise.</returns>
internal Task<bool> InsertMembershipRowAsync(string deploymentId, MembershipEntry membershipEntry,
string etag)
{
return ReadAsync(dbStoredQueries.InsertMembershipKey, DbStoredQueries.Converters.GetSingleBooleanValue, command =>
new DbStoredQueries.Columns(command)
{
DeploymentId = deploymentId,
IAmAliveTime = membershipEntry.IAmAliveTime,
HostName = membershipEntry.HostName,
SiloAddress = membershipEntry.SiloAddress,
StartTime = membershipEntry.StartTime,
Status = membershipEntry.Status,
ProxyPort = membershipEntry.ProxyPort,
Version = etag
}, ret => ret.First());
}
/// <summary>
/// Updates membership row data.
/// </summary>
/// <param name="deploymentId">The deployment with which to insert row.</param>
/// <param name="membershipEntry">The membership data to used to update database.</param>
/// <param name="etag">The table expected version etag.</param>
/// <returns><em>TRUE</em> if update SUCCEEDS. <em>FALSE</em> ot</returns>
internal Task<bool> UpdateMembershipRowAsync(string deploymentId, MembershipEntry membershipEntry,
string etag)
{
return ReadAsync(dbStoredQueries.UpdateMembershipKey, DbStoredQueries.Converters.GetSingleBooleanValue, command =>
new DbStoredQueries.Columns(command)
{
DeploymentId = deploymentId,
SiloAddress = membershipEntry.SiloAddress,
IAmAliveTime = membershipEntry.IAmAliveTime,
Status = membershipEntry.Status,
SuspectTimes = membershipEntry.SuspectTimes,
Version = etag
}, ret => ret.First());
}
private static MembershipTableData ConvertToMembershipTableData(IEnumerable<Tuple<MembershipEntry, int>> ret)
{
var retList = ret.ToList();
var tableVersionEtag = retList[0].Item2;
var membershipEntries = new List<Tuple<MembershipEntry, string>>();
if (retList[0].Item1 != null)
{
membershipEntries.AddRange(retList.Select(i => new Tuple<MembershipEntry, string>(i.Item1, string.Empty)));
}
return new MembershipTableData(membershipEntries, new TableVersion(tableVersionEtag, tableVersionEtag.ToString()));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Tests.SqlUtils;
using Tester.RelationalUtilities;
namespace UnitTests.General
{
public abstract class RelationalStorageForTesting
{
private static readonly Dictionary<string, Func<string, RelationalStorageForTesting>> instanceFactory =
new Dictionary<string, Func<string, RelationalStorageForTesting>>
{
{AdoNetInvariants.InvariantNameSqlServer, cs => new SqlServerStorageForTesting(cs)},
{AdoNetInvariants.InvariantNameMySql, cs => new MySqlStorageForTesting(cs)},
{AdoNetInvariants.InvariantNamePostgreSql, cs => new PostgreSqlStorageForTesting(cs)}
};
public IRelationalStorage Storage { get; private set; }
public string CurrentConnectionString
{
get { return Storage.ConnectionString; }
}
/// <summary>
/// Default connection string for testing
/// </summary>
public abstract string DefaultConnectionString { get; }
/// <summary>
/// A delayed query that is then cancelled in a test to see if cancellation works.
/// </summary>
public abstract string CancellationTestQuery { get; }
public abstract string CreateStreamTestTable { get; }
public virtual string DeleteStreamTestTable { get { return "DELETE StreamingTest;"; } }
public virtual string StreamTestSelect { get { return "SELECT Id, StreamData FROM StreamingTest WHERE Id = @streamId;"; } }
public virtual string StreamTestInsert { get { return "INSERT INTO StreamingTest(Id, StreamData) VALUES(@id, @streamData);"; } }
/// <summary>
/// The script that creates Orleans schema in the database, usually CreateOrleansTables_xxxx.sql
/// </summary>
protected abstract string[] SetupSqlScriptFileNames { get; }
/// <summary>
/// A query template to create a database with a given name.
/// </summary>
protected abstract string CreateDatabaseTemplate { get; }
/// <summary>
/// A query template to drop a database with a given name.
/// </summary>
protected abstract string DropDatabaseTemplate { get; }
/// <summary>
/// A query template if a database with a given name exists.
/// </summary>
protected abstract string ExistsDatabaseTemplate { get; }
/// <summary>
/// Converts the given script into batches to execute sequentially
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
/// <param name="databaseName">the name of the database</param>
protected abstract IEnumerable<string> ConvertToExecutableBatches(string setupScript, string databaseName);
public static async Task<RelationalStorageForTesting> SetupInstance(string invariantName, string testDatabaseName, string connectionString = null)
{
if (string.IsNullOrWhiteSpace(invariantName))
{
throw new ArgumentException("The name of invariant must contain characters", "invariantName");
}
if (string.IsNullOrWhiteSpace(testDatabaseName))
{
throw new ArgumentException("database string must contain characters", "testDatabaseName");
}
Console.WriteLine("Initializing relational databases...");
RelationalStorageForTesting testStorage;
if(connectionString == null)
{
testStorage = CreateTestInstance(invariantName);
}
else
{
testStorage = CreateTestInstance(invariantName, connectionString);
}
Console.WriteLine("Dropping and recreating database '{0}' with connectionstring '{1}'", testDatabaseName, connectionString ?? testStorage.DefaultConnectionString);
if (await testStorage.ExistsDatabaseAsync(testDatabaseName))
{
await testStorage.DropDatabaseAsync(testDatabaseName);
}
await testStorage.CreateDatabaseAsync(testDatabaseName);
//The old storage instance has the previous connection string, time have a new handle with a new connection string...
testStorage = testStorage.CopyInstance(testDatabaseName);
Console.WriteLine("Creating database tables...");
var setupScript = String.Empty;
// Concatenate scripts
foreach (var fileName in testStorage.SetupSqlScriptFileNames)
{
setupScript += File.ReadAllText(fileName);
// Just in case add a CRLF between files, but they should end in a new line.
setupScript += "\r\n";
}
await testStorage.ExecuteSetupScript(setupScript, testDatabaseName);
Console.WriteLine("Initializing relational databases done.");
return testStorage;
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName, string connectionString)
{
return instanceFactory[invariantName](connectionString);
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName)
{
return CreateTestInstance(invariantName, CreateTestInstance(invariantName, "notempty").DefaultConnectionString);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="invariantName"></param>
/// <param name="connectionString"></param>
protected RelationalStorageForTesting(string invariantName, string connectionString)
{
Storage = RelationalStorage.CreateInstance(invariantName, connectionString);
}
/// <summary>
/// Executes the given script in a test context.
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
/// <param name="dataBaseName">the target database to be populated</param>
/// <returns></returns>
private async Task ExecuteSetupScript(string setupScript, string dataBaseName)
{
var splitScripts = ConvertToExecutableBatches(setupScript, dataBaseName);
foreach (var script in splitScripts)
{
var res1 = await Storage.ExecuteAsync(script);
}
}
/// <summary>
/// Checks the existence of a database using the given <see paramref="storage"/> storage object.
/// </summary>
/// <param name="databaseName">The name of the database existence of which to check.</param>
/// <returns><em>TRUE</em> if the given database exists. <em>FALSE</em> otherwise.</returns>
private async Task<bool> ExistsDatabaseAsync(string databaseName)
{
var ret = await Storage.ReadAsync(string.Format(ExistsDatabaseTemplate, databaseName), command =>
{ }, (selector, resultSetCount, cancellationToken) => { return Task.FromResult(selector.GetBoolean(0)); }).ConfigureAwait(continueOnCapturedContext: false);
return ret.First();
}
/// <summary>
/// Creates a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to create.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private async Task CreateDatabaseAsync(string databaseName)
{
await Storage.ExecuteAsync(string.Format(CreateDatabaseTemplate, databaseName), command => { }).ConfigureAwait(continueOnCapturedContext: false);
}
/// <summary>
/// Drops a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to drop.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private Task DropDatabaseAsync(string databaseName)
{
return Storage.ExecuteAsync(string.Format(DropDatabaseTemplate, databaseName), command => { });
}
/// <summary>
/// Creates a new instance of the storage based on the old connection string by changing the database name.
/// </summary>
/// <param name="newDatabaseName">Connection string instance name of the database.</param>
/// <returns>A new <see cref="RelationalStorageForTesting"/> instance with having the same connection string but with with a new databaseName.</returns>
private RelationalStorageForTesting CopyInstance(string newDatabaseName)
{
var csb = new DbConnectionStringBuilder();
csb.ConnectionString = Storage.ConnectionString;
csb["Database"] = newDatabaseName;
return CreateTestInstance(Storage.InvariantName, csb.ConnectionString);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using C1.Win.C1Input;
using C1.Win.C1TrueDBGrid;
using PCSComProduction.WorkOrder.BO;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSProduction.WorkOrder
{
/// <summary>
/// Summary description for SelectWorkOrders.
/// </summary>
public class SelectWorkOrders : Form
{
private C1TrueDBGrid dgrdData;
private CheckBox chkSelectAll;
private Button btnClose;
private Button btnHelp;
private Button btnSelect;
private C1DateEdit dtmToStartDate;
private C1DateEdit dtmFromStartDate;
private Label lblToStartDate;
private Button btnSearch;
private Label lblCCN;
private Button btnSearchBeginWO;
private TextBox txtBeginWO;
private Label lblMasLoc;
private Label lblFromStartDate;
private Label lblWO;
private Label lblMasLocValue;
private Label lblCCNValue;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
DataSet dtbData = new DataSet();
private const string THIS = "PCSProduction.WorkOrder.SelectWorkOrders";
private const string HASBIN = "HasBin";
private const string REMAIN_WO_FOR_ISSUE_VIEW = "v_RemainWOForIssue";
private const string REMAIN_COMPONENT_FOR_ISSUE_VIEW = "v_RemainComponentForWOIssueWithParentInfo";
private DataTable dtStoreGridLayout;
SelectWorkOrdersBO objSelectWorkOrdersBO = new SelectWorkOrdersBO();
private int mMasterLocationID;
private string mMasterLocCode;
private int mCCNID;
private string mCCNCode;
private int intWorkOrderMasterID;
private StringBuilder sbCondition = new StringBuilder();
private const string SELECTED_COL = "SELECTED";
#region Properties
private int mToLocationID = 0;
DataSet mReturnResult;
public DataSet SelectedResultDataSet
{
get{ return mReturnResult;}
}
public int ToLocationID
{
set{ mToLocationID = value;}
get{ return mToLocationID;}
}
public int MasterLocationID
{
set{ mMasterLocationID = value;}
}
public string MasterLocationCode
{
set{ mMasterLocCode = value;}
}
public int CCNID
{
set{ mCCNID = value;}
}
public string CCNCode
{
set{ mCCNCode = value;}
}
#endregion Properties
public SelectWorkOrders()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SelectWorkOrders));
this.dgrdData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
this.chkSelectAll = new System.Windows.Forms.CheckBox();
this.btnClose = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnSelect = new System.Windows.Forms.Button();
this.dtmToStartDate = new C1.Win.C1Input.C1DateEdit();
this.dtmFromStartDate = new C1.Win.C1Input.C1DateEdit();
this.lblToStartDate = new System.Windows.Forms.Label();
this.btnSearch = new System.Windows.Forms.Button();
this.lblCCN = new System.Windows.Forms.Label();
this.btnSearchBeginWO = new System.Windows.Forms.Button();
this.txtBeginWO = new System.Windows.Forms.TextBox();
this.lblMasLoc = new System.Windows.Forms.Label();
this.lblFromStartDate = new System.Windows.Forms.Label();
this.lblWO = new System.Windows.Forms.Label();
this.lblMasLocValue = new System.Windows.Forms.Label();
this.lblCCNValue = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dtmToStartDate)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromStartDate)).BeginInit();
this.SuspendLayout();
//
// dgrdData
//
this.dgrdData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dgrdData.DataView = C1.Win.C1TrueDBGrid.DataViewEnum.GroupBy;
this.dgrdData.FilterBar = true;
this.dgrdData.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.dgrdData.GroupByAreaVisible = false;
this.dgrdData.GroupByCaption = "";
this.dgrdData.Images.Add(((System.Drawing.Image)(resources.GetObject("dgrdData.Images"))));
this.dgrdData.Location = new System.Drawing.Point(4, 74);
this.dgrdData.MultiSelect = C1.Win.C1TrueDBGrid.MultiSelectEnum.None;
this.dgrdData.Name = "dgrdData";
this.dgrdData.PreviewInfo.Location = new System.Drawing.Point(0, 0);
this.dgrdData.PreviewInfo.Size = new System.Drawing.Size(0, 0);
this.dgrdData.PreviewInfo.ZoomFactor = 75;
this.dgrdData.PrintInfo.PageSettings = ((System.Drawing.Printing.PageSettings)(resources.GetObject("dgrdData.PrintInfo.PageSettings")));
this.dgrdData.Size = new System.Drawing.Size(762, 350);
this.dgrdData.TabIndex = 9;
this.dgrdData.AfterColUpdate += new C1.Win.C1TrueDBGrid.ColEventHandler(this.dgrdData_AfterColUpdate);
this.dgrdData.PropBag = resources.GetString("dgrdData.PropBag");
//
// chkSelectAll
//
this.chkSelectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.chkSelectAll.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.chkSelectAll.Location = new System.Drawing.Point(74, 427);
this.chkSelectAll.Name = "chkSelectAll";
this.chkSelectAll.Size = new System.Drawing.Size(81, 23);
this.chkSelectAll.TabIndex = 11;
this.chkSelectAll.Text = "Select &All";
this.chkSelectAll.Click += new System.EventHandler(this.chkSelectAll_Click);
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClose.Location = new System.Drawing.Point(704, 427);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(60, 23);
this.btnClose.TabIndex = 13;
this.btnClose.Text = "&Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnHelp
//
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnHelp.Location = new System.Drawing.Point(640, 427);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(64, 23);
this.btnHelp.TabIndex = 12;
this.btnHelp.Text = "&Help";
//
// btnSelect
//
this.btnSelect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnSelect.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnSelect.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSelect.Location = new System.Drawing.Point(4, 427);
this.btnSelect.Name = "btnSelect";
this.btnSelect.Size = new System.Drawing.Size(67, 23);
this.btnSelect.TabIndex = 10;
this.btnSelect.Text = "S&elect";
this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
//
// dtmToStartDate
//
this.dtmToStartDate.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(177)))), ((int)(((byte)(187)))), ((int)(((byte)(214)))));
this.dtmToStartDate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
//
//
//
this.dtmToStartDate.Calendar.Font = new System.Drawing.Font("Tahoma", 8F);
this.dtmToStartDate.Calendar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.dtmToStartDate.Calendar.VisualStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmToStartDate.Calendar.VisualStyleBaseStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmToStartDate.CustomFormat = "dd-MM-yyyy";
this.dtmToStartDate.EmptyAsNull = true;
this.dtmToStartDate.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
this.dtmToStartDate.Location = new System.Drawing.Point(312, 50);
this.dtmToStartDate.Name = "dtmToStartDate";
this.dtmToStartDate.Size = new System.Drawing.Size(128, 18);
this.dtmToStartDate.TabIndex = 7;
this.dtmToStartDate.Tag = null;
this.dtmToStartDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.dtmToStartDate.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown;
this.dtmToStartDate.VisualStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmToStartDate.VisualStyleBaseStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmToStartDate.WrapDateTimeFields = false;
//
// dtmFromStartDate
//
this.dtmFromStartDate.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(177)))), ((int)(((byte)(187)))), ((int)(((byte)(214)))));
this.dtmFromStartDate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
//
//
//
this.dtmFromStartDate.Calendar.Font = new System.Drawing.Font("Tahoma", 8F);
this.dtmFromStartDate.Calendar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.dtmFromStartDate.Calendar.VisualStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmFromStartDate.Calendar.VisualStyleBaseStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmFromStartDate.CustomFormat = "dd-MM-yyyy ";
this.dtmFromStartDate.EmptyAsNull = true;
this.dtmFromStartDate.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
this.dtmFromStartDate.Location = new System.Drawing.Point(106, 50);
this.dtmFromStartDate.Name = "dtmFromStartDate";
this.dtmFromStartDate.Size = new System.Drawing.Size(128, 18);
this.dtmFromStartDate.TabIndex = 5;
this.dtmFromStartDate.Tag = null;
this.dtmFromStartDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.dtmFromStartDate.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown;
this.dtmFromStartDate.VisualStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmFromStartDate.VisualStyleBaseStyle = C1.Win.C1Input.VisualStyle.Office2010Blue;
this.dtmFromStartDate.WrapDateTimeFields = false;
//
// lblToStartDate
//
this.lblToStartDate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblToStartDate.Location = new System.Drawing.Point(236, 50);
this.lblToStartDate.Name = "lblToStartDate";
this.lblToStartDate.Size = new System.Drawing.Size(74, 20);
this.lblToStartDate.TabIndex = 6;
this.lblToStartDate.Text = "To Start Date";
this.lblToStartDate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnSearch
//
this.btnSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnSearch.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnSearch.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSearch.Location = new System.Drawing.Point(682, 47);
this.btnSearch.Name = "btnSearch";
this.btnSearch.Size = new System.Drawing.Size(82, 23);
this.btnSearch.TabIndex = 8;
this.btnSearch.Text = "&Search";
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// lblCCN
//
this.lblCCN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblCCN.ForeColor = System.Drawing.Color.Maroon;
this.lblCCN.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCCN.Location = new System.Drawing.Point(662, 6);
this.lblCCN.Name = "lblCCN";
this.lblCCN.Size = new System.Drawing.Size(30, 20);
this.lblCCN.TabIndex = 17;
this.lblCCN.Text = "CCN";
this.lblCCN.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnSearchBeginWO
//
this.btnSearchBeginWO.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnSearchBeginWO.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSearchBeginWO.Location = new System.Drawing.Point(236, 28);
this.btnSearchBeginWO.Name = "btnSearchBeginWO";
this.btnSearchBeginWO.Size = new System.Drawing.Size(24, 20);
this.btnSearchBeginWO.TabIndex = 4;
this.btnSearchBeginWO.Text = "...";
this.btnSearchBeginWO.Click += new System.EventHandler(this.btnSearchBeginWO_Click);
//
// txtBeginWO
//
this.txtBeginWO.Location = new System.Drawing.Point(106, 28);
this.txtBeginWO.Name = "txtBeginWO";
this.txtBeginWO.Size = new System.Drawing.Size(128, 20);
this.txtBeginWO.TabIndex = 3;
this.txtBeginWO.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtBeginWO_KeyDown);
this.txtBeginWO.Leave += new System.EventHandler(this.txtBeginWO_Leave);
//
// lblMasLoc
//
this.lblMasLoc.ForeColor = System.Drawing.Color.Maroon;
this.lblMasLoc.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblMasLoc.Location = new System.Drawing.Point(4, 6);
this.lblMasLoc.Name = "lblMasLoc";
this.lblMasLoc.Size = new System.Drawing.Size(100, 20);
this.lblMasLoc.TabIndex = 14;
this.lblMasLoc.Text = "Mas. Location";
this.lblMasLoc.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblFromStartDate
//
this.lblFromStartDate.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblFromStartDate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblFromStartDate.Location = new System.Drawing.Point(4, 50);
this.lblFromStartDate.Name = "lblFromStartDate";
this.lblFromStartDate.Size = new System.Drawing.Size(100, 20);
this.lblFromStartDate.TabIndex = 16;
this.lblFromStartDate.Text = "From Start Date";
this.lblFromStartDate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblWO
//
this.lblWO.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblWO.Location = new System.Drawing.Point(4, 28);
this.lblWO.Name = "lblWO";
this.lblWO.Size = new System.Drawing.Size(100, 20);
this.lblWO.TabIndex = 15;
this.lblWO.Text = "Work Order";
this.lblWO.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblMasLocValue
//
this.lblMasLocValue.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblMasLocValue.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblMasLocValue.Location = new System.Drawing.Point(106, 6);
this.lblMasLocValue.Name = "lblMasLocValue";
this.lblMasLocValue.Size = new System.Drawing.Size(128, 20);
this.lblMasLocValue.TabIndex = 18;
this.lblMasLocValue.Text = "MasLoc";
this.lblMasLocValue.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblCCNValue
//
this.lblCCNValue.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblCCNValue.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblCCNValue.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCCNValue.Location = new System.Drawing.Point(694, 6);
this.lblCCNValue.Name = "lblCCNValue";
this.lblCCNValue.Size = new System.Drawing.Size(70, 20);
this.lblCCNValue.TabIndex = 19;
this.lblCCNValue.Text = "CCNValue";
this.lblCCNValue.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// SelectWorkOrders
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(768, 453);
this.Controls.Add(this.lblCCNValue);
this.Controls.Add(this.lblMasLocValue);
this.Controls.Add(this.dtmToStartDate);
this.Controls.Add(this.dtmFromStartDate);
this.Controls.Add(this.txtBeginWO);
this.Controls.Add(this.dgrdData);
this.Controls.Add(this.lblToStartDate);
this.Controls.Add(this.btnSearch);
this.Controls.Add(this.lblCCN);
this.Controls.Add(this.btnSearchBeginWO);
this.Controls.Add(this.lblMasLoc);
this.Controls.Add(this.lblFromStartDate);
this.Controls.Add(this.lblWO);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnSelect);
this.Controls.Add(this.chkSelectAll);
this.KeyPreview = true;
this.Name = "SelectWorkOrders";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Select Component";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.SelectWorkOrders_Load);
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dtmToStartDate)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromStartDate)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void SelectWorkOrders_Load(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".MultiWOIssueMaterial_Load()";
try
{
//Set form security
Security objSecurity = new Security();
this.Name = THIS;
if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
this.Close();
return;
}
//check if the Location and the CCN has data
if (mMasterLocationID <=0 || mCCNID <=0)
{
//MessageBox.Show("Please select the Master Location and CCN id");
PCSMessageBox.Show(ErrorCode.MSG_WOISSUE_MATERIAL_SELECT_MASLOC_AND_CCN, MessageBoxIcon.Warning);
this.Close();
return;
}
//Format DateTime control
dtmFromStartDate.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
dtmToStartDate.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
var workingPeriod = Utilities.Instance.GetWorkingPeriod();
dtmFromStartDate.Value = workingPeriod.FromDate;
dtmToStartDate.Value = Utilities.Instance.GetServerDate();
//store the gridlayout
dtStoreGridLayout = FormControlComponents.StoreGridLayout(dgrdData);
//Display the data on form
lblMasLocValue.Text = mMasterLocCode;
lblCCNValue.Text = mCCNCode;
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Display the detail data after searching into the grid
/// //set layout for the grid
/// </summary>
/// <param name="pdtbData"></param>
private void LoadDataDetail(DataSet pdtbData)
{
//load this data into the grid
dgrdData.DataSource = pdtbData.Tables[0];
//Restore the gridLayout
FormControlComponents.RestoreGridLayout(dgrdData, dtStoreGridLayout);
//HACK: added by Tuan TQ. Lock columns
for(int i =0; i < dgrdData.Splits[0].DisplayColumns.Count; i++)
{
dgrdData.Splits[0].DisplayColumns[i].Locked = true;
}
dgrdData.Splits[0].DisplayColumns[SELECTED_COL].Locked = false;
//End hack
//set the column to be check box
//Align center for date
dgrdData.Splits[0].DisplayColumns[PRO_WorkOrderDetailTable.STARTDATE_FLD].Style.HorizontalAlignment = AlignHorzEnum.Center;
dgrdData.Splits[0].DisplayColumns[PRO_WorkOrderDetailTable.DUEDATE_FLD].Style.HorizontalAlignment = AlignHorzEnum.Center;
//align right for Quantity
dgrdData.Splits[0].DisplayColumns[PRO_WorkOrderDetailTable.ORDERQUANTITY_FLD].Style.HorizontalAlignment = AlignHorzEnum.Far;
dgrdData.Splits[0].DisplayColumns[PRO_WorkOrderDetailTable.TABLE_NAME + PRO_WorkOrderDetailTable.LINE_FLD].Style.HorizontalAlignment = AlignHorzEnum.Far;
//Align center for the Selected Column
dgrdData.Splits[0].DisplayColumns[SELECTED_COL].Style.HorizontalAlignment = AlignHorzEnum.Center;
//Set format for the Quantity
dgrdData.Columns[PRO_WorkOrderDetailTable.ORDERQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
dgrdData.Columns[PRO_WorkOrderDetailTable.STARTDATE_FLD].NumberFormat = Constants.DATETIME_FORMAT_HOUR;
dgrdData.Columns[PRO_WorkOrderDetailTable.DUEDATE_FLD].NumberFormat = Constants.DATETIME_FORMAT_HOUR;
//set the selected to be the check box
dgrdData.Columns[SELECTED_COL].ValueItems.Presentation = PresentationEnum.CheckBox;
}
public void btnSearch_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnSearch_Click()";
try
{
DateTime dtmFromDate = DateTime.MinValue, dtmToDate = DateTime.MinValue;
if (dtmFromStartDate.Value != DBNull.Value && dtmFromStartDate.Text != String.Empty)
{
DateTime dtmDate = (DateTime)dtmFromStartDate.Value;
dtmFromDate = new DateTime(dtmDate.Year, dtmDate.Month, dtmDate.Day, dtmDate.Hour, dtmDate.Minute, 0);
}
if (dtmToStartDate.Value != DBNull.Value && dtmToStartDate.Text != String.Empty)
{
DateTime dtmDate = (DateTime)dtmToStartDate.Value;
dtmToDate = new DateTime(dtmDate.Year, dtmDate.Month, dtmDate.Day, dtmDate.Hour, dtmDate.Minute, 0);
}
string strCondition = (new UtilsBO()).GetConditionByRecord(SystemProperty.UserName, REMAIN_COMPONENT_FOR_ISSUE_VIEW);
dtbData = objSelectWorkOrdersBO.SearchWorkOrderToIssueMaterial(strCondition, mMasterLocationID, mToLocationID, intWorkOrderMasterID, dtmFromDate, dtmToDate);
if (dtbData != null && dtbData.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in dtbData.Tables[0].Rows)
{
dr["SELECTED"] = "False";
}
}
LoadDataDetail(dtbData);
chkSelectAll.Checked = false;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Search for specific WORK Order
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSearchBeginWO_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnSearchBeginWO_Click()";
try
{
DataRowView drwResult = null;
//search for master location id
Hashtable hashCondition = new Hashtable();
hashCondition.Add(PRO_WorkOrderMasterTable.MASTERLOCATIONID_FLD, mMasterLocationID);
//HACK: added by Tuan TQ. 19 Jan, 2006. Apply To Location for issuing
hashCondition.Add(MST_LocationTable.LOCATIONID_FLD, mToLocationID);
//End Hack
drwResult = FormControlComponents.OpenSearchForm(REMAIN_WO_FOR_ISSUE_VIEW, PRO_WorkOrderMasterTable.WORKORDERNO_FLD,txtBeginWO.Text.Trim(), hashCondition,true);
if (drwResult != null)
{
intWorkOrderMasterID = int.Parse(drwResult[PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD].ToString());
txtBeginWO.Text = drwResult[PRO_WorkOrderMasterTable.WORKORDERNO_FLD].ToString();
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.No;
this.Close();
}
private void txtBeginWO_KeyDown(object sender, KeyEventArgs e)
{
const string METHOD_NAME = THIS + ".txtBeginWO_KeyDown";
try
{
if (e.KeyCode == Keys.F4)
{
if (btnSearchBeginWO.Enabled)
{
btnSearchBeginWO_Click(null,null);
}
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtBeginWO_Leave(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".txtBeginWO_Leave";
try
{
FormControlComponents.OnLeaveControl(sender, e);
if (!btnSearchBeginWO.Enabled || !txtBeginWO.Modified)
{
return;
}
txtBeginWO.Text = txtBeginWO.Text.Trim();
if (txtBeginWO.Text == String.Empty)
{
intWorkOrderMasterID = 0;
return;
}
UtilsBO objUtilsBO = new UtilsBO();
intWorkOrderMasterID = 0;
//search for master location id
Hashtable hashCondition = new Hashtable();
hashCondition.Add(PRO_WorkOrderMasterTable.MASTERLOCATIONID_FLD,mMasterLocationID);
DataTable dtResult = objUtilsBO.GetRows(REMAIN_WO_FOR_ISSUE_VIEW, PRO_WorkOrderMasterTable.WORKORDERNO_FLD, txtBeginWO.Text, hashCondition);
if (dtResult.Rows.Count == 0)
{
txtBeginWO.Text = String.Empty;
btnSearchBeginWO_Click(null,null);
}
else
{
if (dtResult.Rows.Count > 1)
{
btnSearchBeginWO_Click(null,null);
}
else
{
intWorkOrderMasterID = int.Parse(dtResult.Rows[0][PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD].ToString());
txtBeginWO.Text = dtResult.Rows[0][PRO_WorkOrderMasterTable.WORKORDERNO_FLD].ToString();
}
}
if (intWorkOrderMasterID <=0 )
{
txtBeginWO.Text = String.Empty;
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnSelect_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnSelect_Click";
try
{
this.Cursor = Cursors.WaitCursor;
MultiWOIssueMaterialBO boWOIssue = new MultiWOIssueMaterialBO();
mReturnResult = boWOIssue.GetDetailData(0);
mReturnResult.Tables[0].Columns.Add(HASBIN);
mReturnResult.Tables[0].Columns.Add(ITM_ProductTable.LOTCONTROL_FLD);
mReturnResult.Tables[0].Columns[PRO_IssueMaterialDetailTable.LINE_FLD].AutoIncrement = true;
mReturnResult.Tables[0].Columns[PRO_IssueMaterialDetailTable.LINE_FLD].AutoIncrementSeed = 1;
mReturnResult.Tables[0].Columns[PRO_IssueMaterialDetailTable.LINE_FLD].AutoIncrementStep = 1;
mReturnResult = objSelectWorkOrdersBO.GetSelectedRecords(dtbData.Tables[0].TableName, mReturnResult);
if(mReturnResult.Tables[0].Rows.Count == 0)
{
PCSMessageBox.Show(ErrorCode.MSG_WOISSUE_MATERIAL_SELECT_ATLEAST_ONE_WOLINE, MessageBoxIcon.Warning);
this.Cursor = Cursors.Default;
return;
}
else
{
this.Cursor = Cursors.Default;
this.DialogResult = DialogResult.OK;
this.Close();
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
finally
{
this.Cursor = Cursors.Default;
}
}
private void dgrdData_AfterColUpdate(object sender, ColEventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdData_AfterColUpdate()";
try
{
if(e.Column.DataColumn.DataField == SELECTED_COL)
{
string strExpression = "(" + PRO_WorkOrderDetailTable.WORKORDERMASTERID_FLD + "=" + dgrdData[dgrdData.Row, PRO_WorkOrderDetailTable.WORKORDERMASTERID_FLD].ToString()
+ " AND " + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + "=" + dgrdData[dgrdData.Row, PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD].ToString()
+ " AND " + PRO_WorkOrderDetailTable.TABLE_NAME + PRO_WorkOrderDetailTable.LINE_FLD + "=" + dgrdData[dgrdData.Row, PRO_WorkOrderDetailTable.TABLE_NAME + PRO_WorkOrderDetailTable.LINE_FLD].ToString()
+ " AND " + MST_LocationTable.LOCATIONID_FLD + "=" + dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD].ToString()
+ " AND " + MST_BINTable.BINID_FLD + "=" + dgrdData[dgrdData.Row, MST_BINTable.BINID_FLD].ToString()
+ " AND " + ITM_ProductTable.PRODUCTID_FLD + "=" + dgrdData[dgrdData.Row, ITM_ProductTable.PRODUCTID_FLD].ToString() + ")";
if(dgrdData[dgrdData.Row, SELECTED_COL].Equals(DBNull.Value)
|| dgrdData[dgrdData.Row, SELECTED_COL].ToString().Trim() == string.Empty)
{
chkSelectAll.Checked = false;
sbCondition.Replace(strExpression + "|", string.Empty);
return;
}
if(!bool.Parse(dgrdData[dgrdData.Row, SELECTED_COL].ToString()))
{
chkSelectAll.Checked = false;
sbCondition.Replace(strExpression + "|", string.Empty);
return;
}
int nViewCount = dtbData.Tables[0].DefaultView.Count;
string strFilter = dtbData.Tables[0].DefaultView.RowFilter;
if (strFilter == string.Empty)
strFilter = SELECTED_COL + "=1";
else
strFilter += " AND " + SELECTED_COL + "=1";
int nSelectedCount = dtbData.Tables[0].Select(strFilter).Length + 1;
chkSelectAll.Checked = nViewCount == nSelectedCount;
sbCondition.Append(strExpression).Append(" OR ");
int i = 0;
UtilsBO objUtilBO = new UtilsBO();
int iProductId = 0;
int iWorkOrderMasterID = 0;
int iWorkOrderDetailID=0;
int iComponentID=0;
bool b = false;
if (dgrdData[dgrdData.Row, "ProductID"] != DBNull.Value)
{
iProductId = Convert.ToInt32(dgrdData[dgrdData.Row, "ProductID"]);
}
if (dgrdData[dgrdData.Row, "WorkOrderMasterID"] != DBNull.Value)
{
iWorkOrderMasterID = Convert.ToInt32(dgrdData[dgrdData.Row, "WorkOrderMasterID"]);
}
if (dgrdData[dgrdData.Row, "WorkOrderDetailID"] != DBNull.Value)
{
iWorkOrderDetailID = Convert.ToInt32(dgrdData[dgrdData.Row, "WorkOrderDetailID"]);
}
if (dgrdData[dgrdData.Row, "ComponentID"] != DBNull.Value)
{
iComponentID = Convert.ToInt32(dgrdData[dgrdData.Row, "ComponentID"]);
}
if (dgrdData[dgrdData.Row, "SELECTED"] != DBNull.Value)
{
b = Convert.ToBoolean(dgrdData[dgrdData.Row, "SELECTED"]);
}
//string strFilter = ((DataTable)dgrdData.DataSource).DefaultView.RowFilter;
objUtilBO.UpdateSelectedRow(dtbData.Tables[0].TableName,"", b, iProductId,iWorkOrderMasterID,iWorkOrderDetailID,iComponentID);
//LoadDataDetail(dtbData);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void chkSelectAll_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".chkSelectAll_Click()";
try
{
string strFilter = ((DataTable)dgrdData.DataSource).DefaultView.RowFilter;
var boUtils = new UtilsBO();
dtbData = boUtils.UpdateSelected(dtbData.Tables[0].TableName, strFilter, chkSelectAll.Checked);
LoadDataDetail(dtbData);
dtbData.Tables[0].DefaultView.RowFilter = strFilter;
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Classes: AnonymousPipeServerStream
** AnonymousPipeClientStream
** NamedPipeServerStream
** NamedPipeClientStream
**
** Purpose: pipe stream classes.
**
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace System.IO.Pipes {
/// <summary>
/// Anonymous pipe server stream
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class AnonymousPipeServerStream : PipeStream {
private SafePipeHandle m_clientHandle;
private bool m_clientHandleExposed;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public AnonymousPipeServerStream()
: this(PipeDirection.Out, HandleInheritability.None, 0, null) { }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public AnonymousPipeServerStream(PipeDirection direction)
: this(direction, HandleInheritability.None, 0) { }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability)
: this(direction, inheritability, 0) { }
// bufferSize is used as a suggestion; specify 0 to let OS decide
// This constructor instantiates the PipeSecurity using just the inheritability flag
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
: base(direction, bufferSize) {
if (direction == PipeDirection.InOut) {
throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeUnidirectional));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
}
UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
Create(direction, secAttrs, bufferSize);
}
// bufferSize is used as a suggestion; specify 0 to let OS decide
// pipeSecurity of null is default security descriptor
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
: base(direction, bufferSize) {
if (direction == PipeDirection.InOut) {
throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeUnidirectional));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
}
Object pinningHandle;
UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out pinningHandle);
try {
Create(direction, secAttrs, bufferSize);
}
finally {
if (pinningHandle != null) {
GCHandle pinHandle = (GCHandle)pinningHandle;
pinHandle.Free();
}
}
}
~AnonymousPipeServerStream() {
Dispose(false);
}
// Create an AnonymousPipeServerStream from two existing pipe handles.
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeServerStream(PipeDirection direction, SafePipeHandle serverSafePipeHandle, SafePipeHandle clientSafePipeHandle)
: base(direction, 0) {
if (direction == PipeDirection.InOut) {
throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeUnidirectional));
}
if (serverSafePipeHandle == null) {
throw new ArgumentNullException("serverSafePipeHandle");
}
if (clientSafePipeHandle == null) {
throw new ArgumentNullException("clientSafePipeHandle");
}
if (serverSafePipeHandle.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.Argument_InvalidHandle), "serverSafePipeHandle");
}
if (clientSafePipeHandle.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.Argument_InvalidHandle), "clientSafePipeHandle");
}
// Check that these handles are in fact a handles to a pipe.
if (UnsafeNativeMethods.GetFileType(serverSafePipeHandle) != UnsafeNativeMethods.FILE_TYPE_PIPE) {
throw new IOException(SR.GetString(SR.IO_IO_InvalidPipeHandle));
}
if (UnsafeNativeMethods.GetFileType(clientSafePipeHandle) != UnsafeNativeMethods.FILE_TYPE_PIPE) {
throw new IOException(SR.GetString(SR.IO_IO_InvalidPipeHandle));
}
InitializeHandle(serverSafePipeHandle, true, false);
m_clientHandle = clientSafePipeHandle;
m_clientHandleExposed = true;
State = PipeState.Connected;
}
// This method should exist until we add a first class way of passing handles between parent and child
// processes. For now, people do it via command line arguments.
[System.Security.SecurityCritical]
[SuppressMessage("Microsoft.Reliability","CA2001:AvoidCallingProblematicMethods", MessageId="System.Runtime.InteropServices.SafeHandle.DangerousGetHandle", Justification="By design")]
public String GetClientHandleAsString() {
m_clientHandleExposed = true;
return m_clientHandle.DangerousGetHandle().ToString();
}
public SafePipeHandle ClientSafePipeHandle {
[System.Security.SecurityCritical]
get {
m_clientHandleExposed = true;
return m_clientHandle;
}
}
// This method is an annoying one but it has to exist at least until we make passing handles between
// processes first class. We need this because once the child handle is inherited, the OS considers
// the parent and child's handles to be different. Therefore, if a child closes its handle, our
// Read/Write methods won't throw because the OS will think that there is still a child handle around
// that can still Write/Read to/from the other end of the pipe.
//
// Ideally, we would want the Process class to close this handle after it has been inherited. See
// the pipe spec future features section for more information.
//
// Right now, this is the best signal to set the anonymous pipe as connected; if this is called, we
// know the client has been passed the handle and so the connection is live.
[System.Security.SecurityCritical]
public void DisposeLocalCopyOfClientHandle() {
if (m_clientHandle != null && !m_clientHandle.IsClosed) {
m_clientHandle.Dispose();
}
}
[System.Security.SecurityCritical]
protected override void Dispose(bool disposing) {
try {
// We should dispose of the client handle if it was not exposed.
if (!m_clientHandleExposed && m_clientHandle != null && !m_clientHandle.IsClosed) {
m_clientHandle.Dispose();
}
}
finally {
base.Dispose(disposing);
}
}
// Creates the anonymous pipe.
[System.Security.SecurityCritical]
private void Create(PipeDirection direction, UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs, int bufferSize) {
Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut");
Debug.Assert(bufferSize >= 0, "bufferSize is negative");
bool bSuccess;
SafePipeHandle serverHandle;
SafePipeHandle newServerHandle;
// Create the two pipe handles that make up the anonymous pipe.
if (direction == PipeDirection.In) {
bSuccess = UnsafeNativeMethods.CreatePipe(out serverHandle, out m_clientHandle, secAttrs, bufferSize);
}
else {
bSuccess = UnsafeNativeMethods.CreatePipe(out m_clientHandle, out serverHandle, secAttrs, bufferSize);
}
if (!bSuccess) {
__Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
}
// Duplicate the server handle to make it not inheritable. Note: We need to do this so that the child
// process doesn't end up getting another copy of the server handle. If it were to get a copy, the
// OS wouldn't be able to inform the child that the server has closed its handle because it will see
// that there is still one server handle that is open.
bSuccess = UnsafeNativeMethods.DuplicateHandle(UnsafeNativeMethods.GetCurrentProcess(), serverHandle, UnsafeNativeMethods.GetCurrentProcess(),
out newServerHandle, 0, false, UnsafeNativeMethods.DUPLICATE_SAME_ACCESS);
if (!bSuccess) {
__Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
}
// Close the inheritable server handle.
serverHandle.Dispose();
InitializeHandle(newServerHandle, false, false);
State = PipeState.Connected;
}
// Anonymous pipes do not support message mode so there is no need to use the base version that P/Invokes here.
public override PipeTransmissionMode TransmissionMode {
[System.Security.SecurityCritical]
get {
return PipeTransmissionMode.Byte;
}
}
public override PipeTransmissionMode ReadMode {
[System.Security.SecurityCritical]
set {
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.ArgumentOutOfRange_TransmissionModeByteOrMsg));
}
if (value == PipeTransmissionMode.Message) {
throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeMessagesNotSupported));
}
}
}
}
/// <summary>
/// Anonymous pipe client. Use this to open the client end of an anonymous pipes created with AnonymousPipeServerStream.
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class AnonymousPipeClientStream : PipeStream {
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Naming","CA1720:IdentifiersShouldNotContainTypeNames", MessageId="string", Justification="By design")]
public AnonymousPipeClientStream(String pipeHandleAsString)
: this(PipeDirection.In, pipeHandleAsString) { }
[System.Security.SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SuppressMessage("Microsoft.Naming","CA1720:IdentifiersShouldNotContainTypeNames", MessageId="string", Justification="By design")]
public AnonymousPipeClientStream(PipeDirection direction, String pipeHandleAsString)
: base(direction, 0) {
if (direction == PipeDirection.InOut) {
throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeUnidirectional));
}
if (pipeHandleAsString == null) {
throw new ArgumentNullException("pipeHandleAsString");
}
// Initialize SafePipeHandle from String and check if it's valid. First see if it's parseable
long result = 0;
bool parseable = long.TryParse(pipeHandleAsString, out result);
if (!parseable) {
throw new ArgumentException(SR.GetString(SR.Argument_InvalidHandle), "pipeHandleAsString");
}
// next check whether the handle is invalid
SafePipeHandle safePipeHandle = new SafePipeHandle((IntPtr)result, true);
if (safePipeHandle.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.Argument_InvalidHandle), "pipeHandleAsString");
}
Init(direction, safePipeHandle);
}
[System.Security.SecurityCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public AnonymousPipeClientStream(PipeDirection direction, SafePipeHandle safePipeHandle)
: base(direction, 0) {
if (direction == PipeDirection.InOut) {
throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeUnidirectional));
}
if (safePipeHandle == null) {
throw new ArgumentNullException("safePipeHandle");
}
if (safePipeHandle.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.Argument_InvalidHandle), "safePipeHandle");
}
Init(direction, safePipeHandle);
}
[System.Security.SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void Init(PipeDirection direction, SafePipeHandle safePipeHandle) {
Debug.Assert(direction != PipeDirection.InOut, "anonymous pipes are unidirectional, caller should have verified before calling Init");
Debug.Assert(safePipeHandle != null && !safePipeHandle.IsInvalid, "safePipeHandle must be valid");
// Check that this handle is infact a handle to a pipe.
if (UnsafeNativeMethods.GetFileType(safePipeHandle) != UnsafeNativeMethods.FILE_TYPE_PIPE) {
throw new IOException(SR.GetString(SR.IO_IO_InvalidPipeHandle));
}
InitializeHandle(safePipeHandle, true, false);
State = PipeState.Connected;
}
~AnonymousPipeClientStream() {
Dispose(false);
}
// Anonymous pipes do not support message readmode so there is no need to use the base version
// which P/Invokes (and sometimes fails).
public override PipeTransmissionMode TransmissionMode {
[System.Security.SecurityCritical]
get {
return PipeTransmissionMode.Byte;
}
}
public override PipeTransmissionMode ReadMode {
[System.Security.SecurityCritical]
set {
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.ArgumentOutOfRange_TransmissionModeByteOrMsg));
}
if (value == PipeTransmissionMode.Message) {
throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeMessagesNotSupported));
}
}
}
}
// Users will use this delegate to specify a method to call while impersonating the client
// (see NamedPipeServerStream.RunAsClient).
public delegate void PipeStreamImpersonationWorker();
/// <summary>
/// Named pipe server
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class NamedPipeServerStream : PipeStream {
// Use the maximum number of server instances that the system resources allow
public const int MaxAllowedServerInstances = -1;
[SecurityCritical]
private unsafe static readonly IOCompletionCallback WaitForConnectionCallback =
new IOCompletionCallback(NamedPipeServerStream.AsyncWaitForConnectionCallback);
[System.Security.SecurityCritical]
static NamedPipeServerStream()
{
}
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName)
: this(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, null,
HandleInheritability.None, (PipeAccessRights)0) { }
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction)
: this(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, null,
HandleInheritability.None, (PipeAccessRights)0) { }
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances)
: this(pipeName, direction, maxNumberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None,
0, 0, null, HandleInheritability.None, (PipeAccessRights)0) { }
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, PipeOptions.None, 0, 0,
null, HandleInheritability.None, (PipeAccessRights)0) { }
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, 0, 0,
null, HandleInheritability.None, (PipeAccessRights)0) { }
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize,
null, HandleInheritability.None, (PipeAccessRights)0) { }
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
PipeSecurity pipeSecurity)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize,
pipeSecurity, HandleInheritability.None, (PipeAccessRights)0) { }
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
PipeSecurity pipeSecurity, HandleInheritability inheritability)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize,
pipeSecurity, inheritability, (PipeAccessRights)0) { }
/// <summary>
/// Full named pipe server constructor
/// </summary>
/// <param name="pipeName">Pipe name</param>
/// <param name="direction">Pipe direction: In, Out or InOut (duplex).
/// Win32 note: this gets OR'd into dwOpenMode to CreateNamedPipe
/// </param>
/// <param name="maxNumberOfServerInstances">Maximum number of server instances. Specify a fixed value between
/// 1 and 254, or use NamedPipeServerStream.MaxAllowedServerInstances to use the maximum amount allowed by
/// system resources.</param>
/// <param name="transmissionMode">Byte mode or message mode.
/// Win32 note: this gets used for dwPipeMode. CreateNamedPipe allows you to specify PIPE_TYPE_BYTE/MESSAGE
/// and PIPE_READMODE_BYTE/MESSAGE independently, but this sets type and readmode to match.
/// </param>
/// <param name="options">PipeOption enum: None, Asynchronous, or Writethrough
/// Win32 note: this gets passed in with dwOpenMode to CreateNamedPipe. Asynchronous corresponds to
/// FILE_FLAG_OVERLAPPED option. PipeOptions enum doesn't expose FIRST_PIPE_INSTANCE option because
/// this sets that automatically based on the number of instances specified.
/// </param>
/// <param name="inBufferSize">Incoming buffer size, 0 or higher.
/// Note: this size is always advisory; OS uses a suggestion.
/// </param>
/// <param name="outBufferSize">Outgoing buffer size, 0 or higher (see above)</param>
/// <param name="pipeSecurity">PipeSecurity, or null for default security descriptor</param>
/// <param name="inheritability">Whether handle is inheritable</param>
/// <param name="additionalAccessRights">Combination (logical OR) of PipeAccessRights.TakeOwnership,
/// PipeAccessRights.AccessSystemSecurity, and PipeAccessRights.ChangePermissions</param>
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
: base(direction, transmissionMode, outBufferSize) {
if (pipeName == null) {
throw new ArgumentNullException("pipeName");
}
if (pipeName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_NeedNonemptyPipeName));
}
if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0) {
throw new ArgumentOutOfRangeException("options", SR.GetString(SR.ArgumentOutOfRange_OptionsInvalid));
}
if (inBufferSize < 0) {
throw new ArgumentOutOfRangeException("inBufferSize", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
}
// win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited)
// through the MaxAllowedServerInstances constant. This is consistent e.g. with -1 as infinite timeout, etc
if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances)) {
throw new ArgumentOutOfRangeException("maxNumberOfServerInstances", SR.GetString(SR.ArgumentOutOfRange_MaxNumServerInstances));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
}
// ChangePermissions, TakeOwnership, and AccessSystemSecurity are only legal values user may provide;
// internally this is set to 0 if not provided. This handles both cases.
if ((additionalAccessRights & ~(PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership |
PipeAccessRights.AccessSystemSecurity)) != 0) {
throw new ArgumentOutOfRangeException("additionalAccessRights", SR.GetString(SR.ArgumentOutOfRange_AdditionalAccessLimited));
}
// Named Pipe Servers require Windows NT
if (Environment.OSVersion.Platform == PlatformID.Win32Windows) {
throw new PlatformNotSupportedException(SR.GetString(SR.PlatformNotSupported_NamedPipeServers));
}
string normalizedPipePath = Path.GetFullPath(@"\\.\pipe\" + pipeName);
// Make sure the pipe name isn't one of our reserved names for anonymous pipes.
if (String.Compare(normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase) == 0) {
throw new ArgumentOutOfRangeException("pipeName", SR.GetString(SR.ArgumentOutOfRange_AnonymousReserved));
}
Object pinningHandle = null;
UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out pinningHandle);
try {
Create(normalizedPipePath, direction, maxNumberOfServerInstances, transmissionMode,
options, inBufferSize, outBufferSize, additionalAccessRights, secAttrs);
}
finally {
if (pinningHandle != null) {
GCHandle pinHandle = (GCHandle)pinningHandle;
pinHandle.Free();
}
}
}
// Create a NamedPipeServerStream from an existing server pipe handle.
[System.Security.SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle)
: base(direction, PipeTransmissionMode.Byte, 0) {
if (safePipeHandle == null) {
throw new ArgumentNullException("safePipeHandle");
}
if (safePipeHandle.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.Argument_InvalidHandle), "safePipeHandle");
}
// Check that this handle is infact a handle to a pipe.
if (UnsafeNativeMethods.GetFileType(safePipeHandle) != UnsafeNativeMethods.FILE_TYPE_PIPE) {
throw new IOException(SR.GetString(SR.IO_IO_InvalidPipeHandle));
}
InitializeHandle(safePipeHandle, true, isAsync);
if (isConnected) {
State = PipeState.Connected;
}
}
~NamedPipeServerStream() {
Dispose(false);
}
[System.Security.SecurityCritical]
private void Create(String fullPipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
PipeAccessRights rights, UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs) {
Debug.Assert(fullPipeName != null && fullPipeName.Length != 0, "fullPipeName is null or empty");
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
int openMode = ((int)direction) |
(maxNumberOfServerInstances == 1 ? UnsafeNativeMethods.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
(int)options |
(int)rights;
// We automatically set the ReadMode to match the TransmissionMode.
int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;
// Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
if (maxNumberOfServerInstances == MaxAllowedServerInstances) {
maxNumberOfServerInstances = 255;
}
SafePipeHandle handle = UnsafeNativeMethods.CreateNamedPipe(fullPipeName, openMode, pipeModes,
maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, secAttrs);
if (handle.IsInvalid) {
__Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
}
InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
}
// This will wait until the client calls Connect(). If we return from this method, we guarantee that
// the client has returned from its Connect call. The client may have done so before this method
// was called (but not before this server is been created, or, if we were servicing another client,
// not before we called Disconnect), in which case, there may be some buffer already in the pipe waiting
// for us to read. See NamedPipeClientStream.Connect for more information.
[System.Security.SecurityCritical]
[SuppressMessage("Microsoft.Security","CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Security model of pipes: demand at creation but no subsequent demands")]
public void WaitForConnection() {
CheckConnectOperationsServer();
if (IsAsync) {
IAsyncResult result = BeginWaitForConnection(null, null);
EndWaitForConnection(result);
}
else {
if (!UnsafeNativeMethods.ConnectNamedPipe(InternalHandle, UnsafeNativeMethods.NULL)) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != UnsafeNativeMethods.ERROR_PIPE_CONNECTED) {
__Error.WinIOError(errorCode, String.Empty);
}
// pipe already connected
if (errorCode == UnsafeNativeMethods.ERROR_PIPE_CONNECTED && State == PipeState.Connected) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeAlreadyConnected));
}
// If we reach here then a connection has been established. This can happen if a client
// connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe.
// In this situation, there is still a good connection between client and server, even though
// ConnectNamedPipe returns zero.
}
State = PipeState.Connected;
}
}
// Async version of WaitForConnection. See the comments above for more info.
[System.Security.SecurityCritical]
[HostProtection(ExternalThreading = true)]
public unsafe IAsyncResult BeginWaitForConnection(AsyncCallback callback, Object state) {
CheckConnectOperationsServer();
if (!IsAsync) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeNotAsync));
}
// Create and store async stream class library specific data in the
// async result
PipeAsyncResult asyncResult = new PipeAsyncResult();
asyncResult._handle = InternalHandle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
// Create wait handle and store in async result
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
// Create a managed overlapped class
// We will set the file offsets later
Overlapped overlapped = new Overlapped(0, 0, IntPtr.Zero, asyncResult);
// Pack the Overlapped class, and store it in the async result
NativeOverlapped* intOverlapped = overlapped.Pack(WaitForConnectionCallback, null);
asyncResult._overlapped = intOverlapped;
if (!UnsafeNativeMethods.ConnectNamedPipe(InternalHandle, intOverlapped)) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == UnsafeNativeMethods.ERROR_IO_PENDING)
return asyncResult;
// WaitForConnectionCallback will not be called becasue we completed synchronously.
// Either the pipe is already connected, or there was an error. Unpin and free the overlapped again.
Overlapped.Free(intOverlapped);
asyncResult._overlapped = null;
// Did the client already connect to us?
if (errorCode == UnsafeNativeMethods.ERROR_PIPE_CONNECTED) {
if (State == PipeState.Connected) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeAlreadyConnected));
}
asyncResult.CallUserCallback();
return asyncResult;
}
__Error.WinIOError(errorCode, String.Empty);
}
// will set state to Connected when EndWait is called
return asyncResult;
}
// Async version of WaitForConnection. See comments for WaitForConnection for more info.
[System.Security.SecurityCritical]
public unsafe void EndWaitForConnection(IAsyncResult asyncResult) {
CheckConnectOperationsServer();
if (asyncResult == null) {
throw new ArgumentNullException("asyncResult");
}
if (!IsAsync) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeNotAsync));
}
PipeAsyncResult afsar = asyncResult as PipeAsyncResult;
if (afsar == null) {
__Error.WrongAsyncResult();
}
// Ensure we can't get into any ----s by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice. --
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0)) {
__Error.EndWaitForConnectionCalledTwice();
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null) {
// We must block to ensure that ConnectionIOCallback has completed,
// and we should close the WaitHandle in here. AsyncFSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
try {
wh.WaitOne();
Debug.Assert(afsar._isComplete == true, "NamedPipeServerStream::EndWaitForConnection - AsyncFSCallback didn't set _isComplete to true!");
}
finally {
wh.Close();
}
}
// We should have freed the overlapped and set it to null either in the Begin
// method (if ConnectNamedPipe completed synchronously) or in AsyncWaitForConnectionCallback.
// If it is not nulled out, we should not be past the above wait:
Debug.Assert(afsar._overlapped == null);
// Now check for any error during the read.
if (afsar._errorCode != 0) {
__Error.WinIOError(afsar._errorCode, String.Empty);
}
// Success
State = PipeState.Connected;
}
[System.Security.SecurityCritical]
public void Disconnect() {
CheckDisconnectOperations();
// Disconnect the pipe.
if (!UnsafeNativeMethods.DisconnectNamedPipe(InternalHandle)) {
__Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
}
State = PipeState.Disconnected;
}
// This method calls a delegate while impersonating the client. Note that we will not have
// access to the client's security token until it has written at least once to the pipe
// (and has set its impersonationLevel argument appropriately).
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker) {
CheckWriteOperations();
ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle);
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, execHelper);
// now handle win32 impersonate/revert specific errors by throwing corresponding exceptions
if (execHelper.m_impersonateErrorCode != 0) {
WinIOError(execHelper.m_impersonateErrorCode);
}
else if (execHelper.m_revertImpersonateErrorCode != 0) {
WinIOError(execHelper.m_revertImpersonateErrorCode);
}
}
// the following are needed for CER
private static RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(ImpersonateAndTryCode);
private static RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(RevertImpersonationOnBackout);
[System.Security.SecurityCritical]
private static void ImpersonateAndTryCode(Object helper) {
ExecuteHelper execHelper = (ExecuteHelper)helper;
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally {
if (UnsafeNativeMethods.ImpersonateNamedPipeClient(execHelper.m_handle)) {
execHelper.m_mustRevert = true;
}
else {
execHelper.m_impersonateErrorCode = Marshal.GetLastWin32Error();
}
}
if (execHelper.m_mustRevert) { // impersonate passed so run user code
execHelper.m_userCode();
}
}
[System.Security.SecurityCritical]
[PrePrepareMethod]
private static void RevertImpersonationOnBackout(Object helper, bool exceptionThrown) {
ExecuteHelper execHelper = (ExecuteHelper)helper;
if (execHelper.m_mustRevert) {
if (!UnsafeNativeMethods.RevertToSelf()) {
execHelper.m_revertImpersonateErrorCode = Marshal.GetLastWin32Error();
}
}
}
internal class ExecuteHelper {
internal PipeStreamImpersonationWorker m_userCode;
internal SafePipeHandle m_handle;
internal bool m_mustRevert;
internal int m_impersonateErrorCode;
internal int m_revertImpersonateErrorCode;
[System.Security.SecurityCritical]
internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle handle) {
m_userCode = userCode;
m_handle = handle;
}
}
// Gets the username of the connected client. Not that we will not have access to the client's
// username until it has written at least once to the pipe (and has set its impersonationLevel
// argument appropriately).
[System.Security.SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
public String GetImpersonationUserName() {
CheckWriteOperations();
StringBuilder userName = new StringBuilder(UnsafeNativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1);
if (!UnsafeNativeMethods.GetNamedPipeHandleState(InternalHandle, UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL,
UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL, userName, userName.Capacity)) {
WinIOError(Marshal.GetLastWin32Error());
}
return userName.ToString();
}
// Callback to be called by the OS when completing the async WaitForConnection operation.
[System.Security.SecurityCritical]
unsafe private static void AsyncWaitForConnectionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) {
// Unpack overlapped
Overlapped overlapped = Overlapped.Unpack(pOverlapped);
// Extract async result from overlapped
PipeAsyncResult asyncResult = (PipeAsyncResult)overlapped.AsyncResult;
// Free the pinned overlapped:
Debug.Assert(asyncResult._overlapped == pOverlapped);
Overlapped.Free(pOverlapped);
asyncResult._overlapped = null;
// Special case for when the client has already connected to us.
if (errorCode == UnsafeNativeMethods.ERROR_PIPE_CONNECTED) {
errorCode = 0;
}
asyncResult._errorCode = (int)errorCode;
// Call the user-provided callback. It can and often should
// call EndWaitForConnection. There's no reason to use an async
// delegate here - we're already on a threadpool thread.
// IAsyncResult's completedSynchronously property must return
// false here, saying the user callback was called on another thread.
asyncResult._completedSynchronously = false;
asyncResult._isComplete = true;
// The OS does not signal this event. We must do it ourselves.
ManualResetEvent wh = asyncResult._waitHandle;
if (wh != null) {
Debug.Assert(!wh.SafeWaitHandle.IsClosed, "ManualResetEvent already closed!");
bool r = wh.Set();
Debug.Assert(r, "ManualResetEvent::Set failed!");
if (!r) {
__Error.WinIOError();
}
}
AsyncCallback userCallback = asyncResult._userCallback;
if (userCallback != null) {
userCallback(asyncResult);
}
}
// Server can only connect from Disconnected state
[System.Security.SecurityCritical]
[SuppressMessage("Microsoft.Security","CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Consistent with security model")]
private void CheckConnectOperationsServer() {
// we're not checking whether already connected; this allows us to throw IOException
// "pipe is being closed" if other side is closing (as does win32) or no-op if
// already connected
if (InternalHandle == null) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeHandleNotSet));
}
// object disposed
if (State == PipeState.Closed) {
__Error.PipeNotOpen();
}
if (InternalHandle.IsClosed) {
__Error.PipeNotOpen();
}
// IOException
if (State == PipeState.Broken) {
throw new IOException(SR.GetString(SR.IO_IO_PipeBroken));
}
}
// Server is allowed to disconnect from connected and broken states
[System.Security.SecurityCritical]
private void CheckDisconnectOperations() {
// invalid operation
if (State== PipeState.WaitingToConnect) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeNotYetConnected));
}
if (State == PipeState.Disconnected) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeAlreadyDisconnected));
}
if (InternalHandle == null) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeHandleNotSet));
}
// object disposed
if (State == PipeState.Closed) {
__Error.PipeNotOpen();
}
if (InternalHandle.IsClosed) {
__Error.PipeNotOpen();
}
}
}
// Named pipe client. Use this to open the client end of a named pipes created with
// NamedPipeServerStream.
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class NamedPipeClientStream : PipeStream {
private string m_normalizedPipePath;
private TokenImpersonationLevel m_impersonationLevel;
private PipeOptions m_pipeOptions;
private HandleInheritability m_inheritability;
private int m_access;
// Creates a named pipe client using default server (same machine, or "."), and PipeDirection.InOut
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public NamedPipeClientStream(String pipeName)
: this(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public NamedPipeClientStream(String serverName, String pipeName)
: this(serverName, pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction)
: this(serverName, pipeName, direction, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction,
PipeOptions options)
: this(serverName, pipeName, direction, options, TokenImpersonationLevel.None, HandleInheritability.None) { }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction,
PipeOptions options, TokenImpersonationLevel impersonationLevel)
: this(serverName, pipeName, direction, options, impersonationLevel, HandleInheritability.None) { }
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction,
PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
: base(direction, 0) {
if (pipeName == null) {
throw new ArgumentNullException("pipeName");
}
if (serverName == null) {
throw new ArgumentNullException("serverName", SR.GetString(SR.ArgumentNull_ServerName));
}
if (pipeName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_NeedNonemptyPipeName));
}
if (serverName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_EmptyServerName));
}
if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0) {
throw new ArgumentOutOfRangeException("options", SR.GetString(SR.ArgumentOutOfRange_OptionsInvalid));
}
if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation) {
throw new ArgumentOutOfRangeException("impersonationLevel", SR.GetString(SR.ArgumentOutOfRange_ImpersonationInvalid));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
}
m_normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (String.Compare(m_normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase) == 0) {
throw new ArgumentOutOfRangeException("pipeName", SR.GetString(SR.ArgumentOutOfRange_AnonymousReserved));
}
m_inheritability = inheritability;
m_impersonationLevel = impersonationLevel;
m_pipeOptions = options;
if ((PipeDirection.In & direction) != 0) {
m_access |= UnsafeNativeMethods.GENERIC_READ;
}
if ((PipeDirection.Out & direction) != 0) {
m_access |= UnsafeNativeMethods.GENERIC_WRITE;
}
}
// This constructor is for advanced users that want to specify their PipeAccessRights explcitly. It can be used
// to open pipes with, for example, WritePermissions access in the case that they want to play with the pipe's
// ACL.
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[SecuritySafeCritical]
public NamedPipeClientStream(String serverName, String pipeName, PipeAccessRights desiredAccessRights,
PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
: base(DirectionFromRights(desiredAccessRights), 0) {
if (pipeName == null) {
throw new ArgumentNullException("pipeName");
}
if (serverName == null) {
throw new ArgumentNullException("serverName", SR.GetString(SR.ArgumentNull_ServerName));
}
if (pipeName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_NeedNonemptyPipeName));
}
if (serverName.Length == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_EmptyServerName));
}
if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0) {
throw new ArgumentOutOfRangeException("options", SR.GetString(SR.ArgumentOutOfRange_OptionsInvalid));
}
if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation) {
throw new ArgumentOutOfRangeException("impersonationLevel", SR.GetString(SR.ArgumentOutOfRange_ImpersonationInvalid));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
}
if ((desiredAccessRights & ~(PipeAccessRights.FullControl | PipeAccessRights.AccessSystemSecurity)) != 0) {
throw new ArgumentOutOfRangeException("desiredAccessRights", SR.GetString(SR.ArgumentOutOfRange_InvalidPipeAccessRights));
}
m_normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (String.Compare(m_normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase) == 0) {
throw new ArgumentOutOfRangeException("pipeName", SR.GetString(SR.ArgumentOutOfRange_AnonymousReserved));
}
m_inheritability = inheritability;
m_impersonationLevel = impersonationLevel;
m_pipeOptions = options;
m_access = (int)desiredAccessRights;
}
// Helper method for the constructor above. The PipeStream protected constructor takes in a PipeDirection so we need
// to convert the access rights to a direction. Usually, PipeDirection.In/Out maps to GENERIC_READ/WRITE but in the
// other direction, READ/WRITE_DATA is sufficient.
private static PipeDirection DirectionFromRights(PipeAccessRights rights) {
PipeDirection direction = 0;
if ((rights & PipeAccessRights.ReadData) != 0) {
direction |= PipeDirection.In;
}
if ((rights & PipeAccessRights.WriteData) != 0) {
direction |= PipeDirection.Out;
}
return direction;
}
// Create a NamedPipeClientStream from an existing server pipe handle.
[System.Security.SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected,
SafePipeHandle safePipeHandle)
: base(direction, 0) {
if (safePipeHandle == null) {
throw new ArgumentNullException("safePipeHandle");
}
if (safePipeHandle.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.Argument_InvalidHandle), "safePipeHandle");
}
// Check that this handle is infact a handle to a pipe.
if (UnsafeNativeMethods.GetFileType(safePipeHandle) != UnsafeNativeMethods.FILE_TYPE_PIPE) {
throw new IOException(SR.GetString(SR.IO_IO_InvalidPipeHandle));
}
InitializeHandle(safePipeHandle, true, isAsync);
if (isConnected) {
State = PipeState.Connected;
}
}
~NamedPipeClientStream() {
Dispose(false);
}
// See below
public void Connect() {
Connect(Timeout.Infinite);
}
// Waits for a pipe instance to become available. This method may return before WaitForConnection is called
// on the server end, but WaitForConnection will not return until we have returned. Any data writen to the
// pipe by us after we have connected but before the server has called WaitForConnection will be available
// to the server after it calls WaitForConnection.
[System.Security.SecurityCritical]
public void Connect(int timeout) {
CheckConnectOperationsClient();
if (timeout < 0 && timeout != Timeout.Infinite) {
throw new ArgumentOutOfRangeException("timeout", SR.GetString(SR.ArgumentOutOfRange_InvalidTimeout));
}
UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(m_inheritability);
int _pipeFlags = (int)m_pipeOptions;
if (m_impersonationLevel != TokenImpersonationLevel.None) {
_pipeFlags |= UnsafeNativeMethods.SECURITY_SQOS_PRESENT;
_pipeFlags |= (((int)m_impersonationLevel - 1) << 16);
}
// This is the main connection loop. It will loop until the timeout expires. Most of the
// time, we will be waiting in the WaitNamedPipe win32 blocking function; however, there are
// cases when we will need to loop: 1) The server is not created (WaitNamedPipe returns
// straight away in such cases), and 2) when another client connects to our server in between
// our WaitNamedPipe and CreateFile calls.
int startTime = Environment.TickCount;
int elapsed = 0;
do {
// Wait for pipe to become free (this will block unless the pipe does not exist).
if (!UnsafeNativeMethods.WaitNamedPipe(m_normalizedPipePath, timeout - elapsed)) {
int errorCode = Marshal.GetLastWin32Error();
// Server is not yet created so let's keep looping.
if (errorCode == UnsafeNativeMethods.ERROR_FILE_NOT_FOUND) {
continue;
}
// The timeout has expired.
if (errorCode == UnsafeNativeMethods.ERROR_SUCCESS) {
break;
}
__Error.WinIOError(errorCode, String.Empty);
}
// Pipe server should be free. Let's try to connect to it.
SafePipeHandle handle = UnsafeNativeMethods.CreateNamedPipeClient(m_normalizedPipePath,
m_access, // read and write access
0, // sharing: none
secAttrs, // security attributes
FileMode.Open, // open existing
_pipeFlags, // impersonation flags
UnsafeNativeMethods.NULL); // template file: null
if (handle.IsInvalid) {
int errorCode = Marshal.GetLastWin32Error();
// Handle the possible race condition of someone else connecting to the server
// between our calls to WaitNamedPipe & CreateFile.
if (errorCode == UnsafeNativeMethods.ERROR_PIPE_BUSY) {
continue;
}
__Error.WinIOError(errorCode, String.Empty);
}
// Success!
InitializeHandle(handle, false, (m_pipeOptions & PipeOptions.Asynchronous) != 0);
State = PipeState.Connected;
return;
}
while (timeout == Timeout.Infinite || (elapsed = unchecked(Environment.TickCount - startTime)) < timeout);
// BUGBUG: SerialPort does not use unchecked arithmetic when calculating elapsed times. This is needed
// because Environment.TickCount can overflow (though only every 49.7 days).
throw new TimeoutException();
}
public int NumberOfServerInstances {
[System.Security.SecurityCritical]
[SuppressMessage("Microsoft.Security","CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Security model of pipes: demand at creation but no subsequent demands")]
get {
CheckPipePropertyOperations();
// NOTE: MSDN says that GetNamedPipeHandleState requires that the pipe handle has
// GENERIC_READ access, but we don't check for that because sometimes it works without
// GERERIC_READ access. [Edit: Seems like CreateFile slaps on a READ_ATTRIBUTES
// access request before calling NTCreateFile, so all NamedPipeClientStreams can read
// this if they are created (on WinXP SP2 at least)]
int numInstances;
if (!UnsafeNativeMethods.GetNamedPipeHandleState(InternalHandle, UnsafeNativeMethods.NULL, out numInstances,
UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL, 0)) {
WinIOError(Marshal.GetLastWin32Error());
}
return numInstances;
}
}
// override because named pipe clients can't get/set properties when waiting to connect
// or broken
[System.Security.SecurityCritical]
protected override internal void CheckPipePropertyOperations() {
base.CheckPipePropertyOperations();
// Invalid operation
if (State == PipeState.WaitingToConnect) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeNotYetConnected));
}
// IOException
if (State == PipeState.Broken) {
throw new IOException(SR.GetString(SR.IO_IO_PipeBroken));
}
}
// named client is allowed to connect from broken
private void CheckConnectOperationsClient() {
if (State == PipeState.Connected) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_PipeAlreadyConnected));
}
if (State == PipeState.Closed) {
__Error.PipeNotOpen();
}
}
}
unsafe internal sealed class PipeAsyncResult : IAsyncResult {
internal AsyncCallback _userCallback; // User code callback
internal Object _userStateObject;
internal ManualResetEvent _waitHandle;
[SecurityCritical]
internal SafePipeHandle _handle;
[SecurityCritical]
internal NativeOverlapped* _overlapped;
internal int _EndXxxCalled; // Whether we've called EndXxx already.
internal int _errorCode;
internal bool _isComplete; // Value for IsCompleted property
internal bool _completedSynchronously; // Which thread called callback
public Object AsyncState {
get {
return _userStateObject;
}
}
public bool IsCompleted {
get {
return _isComplete;
}
}
public WaitHandle AsyncWaitHandle {
[System.Security.SecurityCritical]
get {
if (_waitHandle == null) {
ManualResetEvent mre = new ManualResetEvent(false);
if (_overlapped != null && _overlapped->EventHandle != IntPtr.Zero) {
mre.SafeWaitHandle = new SafeWaitHandle(_overlapped->EventHandle, true);
}
if (_isComplete) {
mre.Set();
}
_waitHandle = mre;
}
return _waitHandle;
}
}
public bool CompletedSynchronously {
get {
return _completedSynchronously;
}
}
private void CallUserCallbackWorker(Object callbackState) {
_isComplete = true;
if (_waitHandle != null) {
_waitHandle.Set();
}
_userCallback(this);
}
internal void CallUserCallback() {
if (_userCallback != null) {
_completedSynchronously = false;
ThreadPool.QueueUserWorkItem(new WaitCallback(CallUserCallbackWorker));
}
else {
_isComplete = true;
if (_waitHandle != null) {
_waitHandle.Set();
}
}
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
namespace System.Data.Odbc
{
public sealed class OdbcCommandBuilder : DbCommandBuilder
{
public OdbcCommandBuilder() : base()
{
GC.SuppressFinalize(this);
}
public OdbcCommandBuilder(OdbcDataAdapter adapter) : this()
{
DataAdapter = adapter;
}
public new OdbcDataAdapter DataAdapter
{
get
{
return (base.DataAdapter as OdbcDataAdapter);
}
set
{
base.DataAdapter = value;
}
}
private void OdbcRowUpdatingHandler(object sender, OdbcRowUpdatingEventArgs ruevent)
{
RowUpdatingHandler(ruevent);
}
public new OdbcCommand GetInsertCommand()
{
return (OdbcCommand)base.GetInsertCommand();
}
public new OdbcCommand GetInsertCommand(bool useColumnsForParameterNames)
{
return (OdbcCommand)base.GetInsertCommand(useColumnsForParameterNames);
}
public new OdbcCommand GetUpdateCommand()
{
return (OdbcCommand)base.GetUpdateCommand();
}
public new OdbcCommand GetUpdateCommand(bool useColumnsForParameterNames)
{
return (OdbcCommand)base.GetUpdateCommand(useColumnsForParameterNames);
}
public new OdbcCommand GetDeleteCommand()
{
return (OdbcCommand)base.GetDeleteCommand();
}
public new OdbcCommand GetDeleteCommand(bool useColumnsForParameterNames)
{
return (OdbcCommand)base.GetDeleteCommand(useColumnsForParameterNames);
}
protected override string GetParameterName(int parameterOrdinal)
{
return "p" + parameterOrdinal.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
protected override string GetParameterName(string parameterName)
{
return parameterName;
}
protected override string GetParameterPlaceholder(int parameterOrdinal)
{
return "?";
}
protected override void ApplyParameterInfo(DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause)
{
OdbcParameter p = (OdbcParameter)parameter;
object valueType = datarow[SchemaTableColumn.ProviderType];
p.OdbcType = (OdbcType)valueType;
object bvalue = datarow[SchemaTableColumn.NumericPrecision];
if (DBNull.Value != bvalue)
{
byte bval = (byte)(short)bvalue;
p.PrecisionInternal = ((0xff != bval) ? bval : (byte)0);
}
bvalue = datarow[SchemaTableColumn.NumericScale];
if (DBNull.Value != bvalue)
{
byte bval = (byte)(short)bvalue;
p.ScaleInternal = ((0xff != bval) ? bval : (byte)0);
}
}
public static void DeriveParameters(OdbcCommand command)
{
// MDAC 65927
if (null == command)
{
throw ADP.ArgumentNull(nameof(command));
}
switch (command.CommandType)
{
case System.Data.CommandType.Text:
throw ADP.DeriveParametersNotSupported(command);
case System.Data.CommandType.StoredProcedure:
break;
case System.Data.CommandType.TableDirect:
// CommandType.TableDirect - do nothing, parameters are not supported
throw ADP.DeriveParametersNotSupported(command);
default:
throw ADP.InvalidCommandType(command.CommandType);
}
if (string.IsNullOrEmpty(command.CommandText))
{
throw ADP.CommandTextRequired(ADP.DeriveParameters);
}
OdbcConnection connection = command.Connection;
if (null == connection)
{
throw ADP.ConnectionRequired(ADP.DeriveParameters);
}
ConnectionState state = connection.State;
if (ConnectionState.Open != state)
{
throw ADP.OpenConnectionRequired(ADP.DeriveParameters, state);
}
OdbcParameter[] list = DeriveParametersFromStoredProcedure(connection, command);
OdbcParameterCollection parameters = command.Parameters;
parameters.Clear();
int count = list.Length;
if (0 < count)
{
for (int i = 0; i < list.Length; ++i)
{
parameters.Add(list[i]);
}
}
}
// DeriveParametersFromStoredProcedure (
// OdbcConnection connection,
// OdbcCommand command);
//
// Uses SQLProcedureColumns to create an array of OdbcParameters
//
private static OdbcParameter[] DeriveParametersFromStoredProcedure(OdbcConnection connection, OdbcCommand command)
{
List<OdbcParameter> rParams = new List<OdbcParameter>();
// following call ensures that the command has a statement handle allocated
CMDWrapper cmdWrapper = command.GetStatementHandle();
OdbcStatementHandle hstmt = cmdWrapper.StatementHandle;
int cColsAffected;
// maps an enforced 4-part qualified string as follows
// parts[0] = null - ignored but removal would be a run-time breaking change from V1.0
// parts[1] = CatalogName (optional, may be null)
// parts[2] = SchemaName (optional, may be null)
// parts[3] = ProcedureName
//
string quote = connection.QuoteChar(ADP.DeriveParameters);
string[] parts = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quote, quote, '.', 4, true, SR.ODBC_ODBCCommandText, false);
if (null == parts[3])
{ // match Everett behavior, if the commandtext is nothing but whitespace set the command text to the whitespace
parts[3] = command.CommandText;
}
// note: native odbc appears to ignore all but the procedure name
ODBC32.RetCode retcode = hstmt.ProcedureColumns(parts[1], parts[2], parts[3], null);
// Note: the driver does not return an error if the given stored procedure does not exist
// therefore we cannot handle that case and just return not parameters.
if (ODBC32.RetCode.SUCCESS != retcode)
{
connection.HandleError(hstmt, retcode);
}
using (OdbcDataReader reader = new OdbcDataReader(command, cmdWrapper, CommandBehavior.Default))
{
reader.FirstResult();
cColsAffected = reader.FieldCount;
// go through the returned rows and filter out relevant parameter data
//
while (reader.Read())
{
// devnote: column types are specified in the ODBC Programmer's Reference
// COLUMN_TYPE Smallint 16bit
// COLUMN_SIZE Integer 32bit
// DECIMAL_DIGITS Smallint 16bit
// NUM_PREC_RADIX Smallint 16bit
OdbcParameter parameter = new OdbcParameter();
parameter.ParameterName = reader.GetString(ODBC32.COLUMN_NAME - 1);
switch ((ODBC32.SQL_PARAM)reader.GetInt16(ODBC32.COLUMN_TYPE - 1))
{
case ODBC32.SQL_PARAM.INPUT:
parameter.Direction = ParameterDirection.Input;
break;
case ODBC32.SQL_PARAM.OUTPUT:
parameter.Direction = ParameterDirection.Output;
break;
case ODBC32.SQL_PARAM.INPUT_OUTPUT:
parameter.Direction = ParameterDirection.InputOutput;
break;
case ODBC32.SQL_PARAM.RETURN_VALUE:
parameter.Direction = ParameterDirection.ReturnValue;
break;
default:
Debug.Assert(false, "Unexpected Parametertype while DeriveParamters");
break;
}
parameter.OdbcType = TypeMap.FromSqlType((ODBC32.SQL_TYPE)reader.GetInt16(ODBC32.DATA_TYPE - 1))._odbcType;
parameter.Size = (int)reader.GetInt32(ODBC32.COLUMN_SIZE - 1);
switch (parameter.OdbcType)
{
case OdbcType.Decimal:
case OdbcType.Numeric:
parameter.ScaleInternal = (byte)reader.GetInt16(ODBC32.DECIMAL_DIGITS - 1);
parameter.PrecisionInternal = (byte)reader.GetInt16(ODBC32.NUM_PREC_RADIX - 1);
break;
}
rParams.Add(parameter);
}
}
retcode = hstmt.CloseCursor();
return rParams.ToArray();
}
public override string QuoteIdentifier(string unquotedIdentifier)
{
return QuoteIdentifier(unquotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */);
}
public string QuoteIdentifier(string unquotedIdentifier, OdbcConnection connection)
{
ADP.CheckArgumentNull(unquotedIdentifier, nameof(unquotedIdentifier));
// if the user has specificed a prefix use the user specified prefix and suffix
// otherwise get them from the provider
string quotePrefix = QuotePrefix;
string quoteSuffix = QuoteSuffix;
if (string.IsNullOrEmpty(quotePrefix))
{
if (connection == null)
{
// Use the adapter's connection if QuoteIdentifier was called from
// DbCommandBuilder instance (which does not have an overload that gets connection object)
connection = DataAdapter?.SelectCommand?.Connection;
if (connection == null)
{
throw ADP.QuotePrefixNotSet(ADP.QuoteIdentifier);
}
}
quotePrefix = connection.QuoteChar(ADP.QuoteIdentifier);
quoteSuffix = quotePrefix;
}
// by the ODBC spec "If the data source does not support quoted identifiers, a blank is returned."
// So if a blank is returned the string is returned unchanged. Otherwise the returned string is used
// to quote the string
if (!string.IsNullOrEmpty(quotePrefix) && quotePrefix != " ")
{
return ADP.BuildQuotedString(quotePrefix, quoteSuffix, unquotedIdentifier);
}
else
{
return unquotedIdentifier;
}
}
protected override void SetRowUpdatingHandler(DbDataAdapter adapter)
{
Debug.Assert(adapter is OdbcDataAdapter, "!OdbcDataAdapter");
if (adapter == base.DataAdapter)
{ // removal case
((OdbcDataAdapter)adapter).RowUpdating -= OdbcRowUpdatingHandler;
}
else
{ // adding case
((OdbcDataAdapter)adapter).RowUpdating += OdbcRowUpdatingHandler;
}
}
public override string UnquoteIdentifier(string quotedIdentifier)
{
return UnquoteIdentifier(quotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */);
}
public string UnquoteIdentifier(string quotedIdentifier, OdbcConnection connection)
{
ADP.CheckArgumentNull(quotedIdentifier, nameof(quotedIdentifier));
// if the user has specificed a prefix use the user specified prefix and suffix
// otherwise get them from the provider
string quotePrefix = QuotePrefix;
string quoteSuffix = QuoteSuffix;
if (string.IsNullOrEmpty(quotePrefix))
{
if (connection == null)
{
// Use the adapter's connection if UnquoteIdentifier was called from
// DbCommandBuilder instance (which does not have an overload that gets connection object)
connection = DataAdapter?.SelectCommand?.Connection;
if (connection == null)
{
throw ADP.QuotePrefixNotSet(ADP.UnquoteIdentifier);
}
}
quotePrefix = connection.QuoteChar(ADP.UnquoteIdentifier);
quoteSuffix = quotePrefix;
}
string unquotedIdentifier;
// by the ODBC spec "If the data source does not support quoted identifiers, a blank is returned."
// So if a blank is returned the string is returned unchanged. Otherwise the returned string is used
// to unquote the string
if (!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " ")
{
// ignoring the return value because it is acceptable for the quotedString to not be quoted in this
// context.
ADP.RemoveStringQuotes(quotePrefix, quoteSuffix, quotedIdentifier, out unquotedIdentifier);
}
else
{
unquotedIdentifier = quotedIdentifier;
}
return unquotedIdentifier;
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Threading;
namespace Orleans.Timers.Internal
{
public interface ITimerManager
{
Task<bool> Delay(TimeSpan timeSpan, CancellationToken cancellationToken = default(CancellationToken));
}
internal class TimerManagerImpl : ITimerManager
{
public Task<bool> Delay(TimeSpan timeSpan, CancellationToken cancellationToken = default(CancellationToken)) => TimerManager.Delay(timeSpan, cancellationToken);
}
internal static class TimerManager
{
public static Task<bool> Delay(TimeSpan timeSpan, CancellationToken cancellationToken = default(CancellationToken)) => DelayUntil(DateTime.UtcNow + timeSpan, cancellationToken);
public static Task<bool> DelayUntil(DateTime dueTime, CancellationToken cancellationToken = default(CancellationToken))
{
var result = new DelayTimer(dueTime, cancellationToken);
TimerManager<DelayTimer>.Register(result);
return result.Completion;
}
private sealed class DelayTimer : ITimerCallback, ILinkedListElement<DelayTimer>
{
private readonly TaskCompletionSource<bool> completion =
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
public DelayTimer(DateTime dueTime, CancellationToken cancellationToken)
{
this.DueTime = dueTime;
this.CancellationToken = cancellationToken;
}
public Task<bool> Completion => this.completion.Task;
public DateTime DueTime { get; }
public CancellationToken CancellationToken { get; }
public void OnTimeout() => this.completion.TrySetResult(true);
public void OnCanceled() => this.completion.TrySetResult(false);
DelayTimer ILinkedListElement<DelayTimer>.Next { get; set; }
}
}
/// <summary>
/// Manages timers of a specified type, firing them after they expire.
/// </summary>
/// <typeparam name="T">The timer type.</typeparam>
internal static class TimerManager<T> where T : class, ITimerCallback, ILinkedListElement<T>
{
/// <summary>
/// The maximum number of times a queue can be denied servicing before servicing is mandatory.
/// </summary>
private const int MAX_STARVATION = 2;
/// <summary>
/// The number of milliseconds between timer servicing ticks.
/// </summary>
private const int TIMER_TICK_MILLISECONDS = 50;
/// <summary>
/// Lock protecting <see cref="allQueues"/>.
/// </summary>
// ReSharper disable once StaticMemberInGenericType
private static readonly object AllQueuesLock = new object();
#pragma warning disable IDE0052 // Remove unread private members
private static readonly Timer QueueChecker;
#pragma warning restore IDE0052 // Remove unread private members
/// <summary>
/// Collection of all thread-local timer queues.
/// </summary>
private static ThreadLocalQueue[] allQueues = new ThreadLocalQueue[16];
/// <summary>
/// The queue for the current thread.
/// </summary>
[ThreadStatic]
private static ThreadLocalQueue threadLocalQueue;
static TimerManager()
{
var timerPeriod = TimeSpan.FromMilliseconds(TIMER_TICK_MILLISECONDS);
QueueChecker = new Timer(_ => CheckQueues(), null, timerPeriod, timerPeriod);
}
/// <summary>
/// Registers a timer.
/// </summary>
public static void Register(T timer)
{
ExpiredTimers expired = null;
var queue = EnsureCurrentThreadHasQueue();
try
{
queue.Lock.Get();
queue.AddTail(timer);
if (queue.StarvationCount >= MAX_STARVATION)
{
// If the queue is too starved, service it now.
expired = new ExpiredTimers();
CheckQueueInLock(queue, DateTime.UtcNow, expired);
Interlocked.Exchange(ref queue.StarvationCount, 0);
}
}
finally
{
queue.Lock.TryRelease();
// Fire expired timers outside of lock.
expired?.FireTimers();
}
}
private static void CheckQueues()
{
var expired = new ExpiredTimers();
var now = DateTime.UtcNow;
try
{
foreach (var queue in allQueues)
{
if (queue == null)
{
continue;
}
if (!queue.Lock.TryGet())
{
// Check for starvation.
if (Interlocked.Increment(ref queue.StarvationCount) > MAX_STARVATION)
{
// If the queue starved, block until the lock can be acquired.
queue.Lock.Get();
Interlocked.Exchange(ref queue.StarvationCount, 0);
}
else
{
// Move on to the next queue.
continue;
}
}
try
{
CheckQueueInLock(queue, now, expired);
}
finally
{
queue.Lock.TryRelease();
}
}
}
finally
{
// Expire timers outside of the loop and outside of any lock.
expired.FireTimers();
}
}
private static void CheckQueueInLock(ThreadLocalQueue queue, DateTime now, ExpiredTimers expired)
{
var previous = default(T);
for (var current = queue.Head; current != null; current = current.Next)
{
if (current.CancellationToken.IsCancellationRequested || current.DueTime < now)
{
// Dequeue and add to expired list for later execution.
queue.Remove(previous, current);
expired.AddTail(current);
}
else
{
// If the current item wasn't removed, update previous.
previous = current;
}
}
}
/// <summary>
/// Returns the queue for the current thread, creating and registering one if it does not yet exist.
/// </summary>
/// <returns>The current thread's <see cref="ThreadLocalQueue"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ThreadLocalQueue EnsureCurrentThreadHasQueue()
{
return threadLocalQueue ?? (threadLocalQueue = InitializeThreadLocalQueue());
ThreadLocalQueue InitializeThreadLocalQueue()
{
var threadLocal = new ThreadLocalQueue();
while (true)
{
lock (AllQueuesLock)
{
var queues = Volatile.Read(ref allQueues);
// Find a spot in the existing array to register this thread.
for (var i = 0; i < queues.Length; i++)
{
if (Volatile.Read(ref queues[i]) == null)
{
Volatile.Write(ref queues[i], threadLocal);
return threadLocal;
}
}
// The existing array is full, so copy all values to a new, larger array and register this thread.
var newQueues = new ThreadLocalQueue[queues.Length * 2];
Array.Copy(queues, newQueues, queues.Length);
newQueues[queues.Length] = threadLocal;
Volatile.Write(ref allQueues, newQueues);
return threadLocal;
}
}
}
}
/// <summary>
/// Holds per-thread timer data.
/// </summary>
private sealed class ThreadLocalQueue : ILinkedList<T>
{
public readonly RecursiveInterlockedExchangeLock Lock = new RecursiveInterlockedExchangeLock();
/// <summary>
/// The number of times that this queue has been starved since it was last serviced.
/// </summary>
public int StarvationCount;
public T Head { get; set; }
public T Tail { get; set; }
}
/// <summary>
/// Holds timers that have expired and should be fired.
/// </summary>
private sealed class ExpiredTimers : ILinkedList<T>
{
public T Head { get; set; }
public T Tail { get; set; }
public void FireTimers()
{
var current = this.Head;
while (current != null)
{
try
{
if (current.CancellationToken.IsCancellationRequested)
{
current.OnCanceled();
}
else
{
current.OnTimeout();
}
}
catch
{
// Ignore any exceptions during firing.
}
current = current.Next;
}
}
}
}
internal interface ITimerCallback
{
/// <summary>
/// The UTC time when this timer is due.
/// </summary>
DateTime DueTime { get; }
CancellationToken CancellationToken { get; }
void OnTimeout();
void OnCanceled();
}
/// <summary>
/// Represents a linked list.
/// </summary>
/// <typeparam name="T">The element type.</typeparam>
internal interface ILinkedList<T> where T : ILinkedListElement<T>
{
/// <summary>
/// Gets or sets the first element in the list.
/// This value must never be accessed or modified by user code.
/// </summary>
T Head { get; set; }
/// <summary>
/// Gets or sets the last element in the list.
/// This value must never be accessed or modified by user code.
/// </summary>
T Tail { get; set; }
}
/// <summary>
/// Represents an element in a linked list.
/// </summary>
/// <typeparam name="TSelf">Self-type. The type implementing this interface.</typeparam>
internal interface ILinkedListElement<TSelf> where TSelf : ILinkedListElement<TSelf>
{
/// <summary>
/// The next element in the list.
/// This value must never be accessed or modified by user code.
/// </summary>
TSelf Next { get; set; }
}
internal static class LinkedList
{
/// <summary>
/// Appends an item to the tail of a linked list.
/// </summary>
/// <param name="list">The linked list.</param>
/// <param name="element">The element to append.</param>
public static void AddTail<TList, TElement>(this TList list, TElement element)
where TList : class, ILinkedList<TElement> where TElement : class, ILinkedListElement<TElement>
{
// If this is the first element, update the head.
if (list.Head is null) list.Head = element;
// If this is not the first element, update the current tail.
var prevTail = list.Tail;
if (!(prevTail is null)) prevTail.Next = element;
// Update the tail.
list.Tail = element;
}
/// <summary>
/// Removes an item from a linked list.
/// </summary>
/// <param name="list">The linked list.</param>
/// <param name="previous">The element before <paramref name="current"/>.</param>
/// <param name="current">The element to remove.</param>
public static void Remove<TList, TElement>(this TList list, TElement previous, TElement current)
where TList : class, ILinkedList<TElement> where TElement : class, ILinkedListElement<TElement>
{
var next = current.Next;
// If not removing the first element, point the previous element at the next element.
if (!(previous is null)) previous.Next = next;
// If removing the first element, point the tail at the next element.
if (ReferenceEquals(list.Head, current))
{
list.Head = next ?? previous;
}
// If removing the last element, point the tail at the previous element.
if (ReferenceEquals(list.Tail, current))
{
list.Tail = previous;
}
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics.Contracts;
using Tests;
using CodeUnderTest;
using Xunit;
namespace ManualInheritanceChain
{
public class TestClass : DisableAssertUI
{
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestBasePositive()
{
new BaseOfChain().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel1Positive()
{
new Level1().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive1()
{
new Level3().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive2()
{
new Level3().Test("foo");
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive3()
{
bool result = new Level3().TestIsNonEmpty("foo");
Assert.True(result);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive4()
{
bool result = new Level3().TestIsNonEmpty("");
Assert.False(result);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Positive1()
{
new Level4().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Positive2()
{
new Level4().Test("foo");
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestBaseNegative()
{
try
{
new BaseOfChain().Test(0);
}
catch (ArgumentException a)
{
Assert.Equal("Precondition failed: x > 0: x must be positive\r\nParameter name: x must be positive", a.Message);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel1Negative()
{
try
{
new Level1().CallTest(0);
}
catch (ArgumentException a)
{
Assert.Equal("Precondition failed: x > 0: x must be positive\r\nParameter name: x must be positive", a.Message);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Negative1()
{
try
{
new Level3().CallTest(0);
}
catch (ArgumentException a)
{
Assert.Equal("Precondition failed: x > 0: x must be positive\r\nParameter name: x must be positive", a.Message);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Negative2()
{
try
{
new Level3().Test(null);
}
catch (ArgumentException a)
{
Assert.Equal("Precondition failed: s != null", a.Message);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Negative3()
{
try
{
new Level3().TestIsNonEmpty(null);
}
catch (TestRewriterMethods.PreconditionException p)
{
Assert.Equal("s != null", p.Condition);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Negative1()
{
try
{
new Level4().CallTest(0);
}
catch (ArgumentException a)
{
Assert.Equal("Precondition failed: x > 0: x must be positive\r\nParameter name: x must be positive", a.Message);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Negative2()
{
try
{
new Level4().CallTest(null);
}
catch (ArgumentException a)
{
Assert.Equal("Precondition failed: s != null", a.Message);
return;
}
throw new Exception();
}
}
}
namespace ManualInheritanceChainWithHelpers
{
public class TestClass : DisableAssertUI
{
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestBasePositive()
{
new ManualInheritanceChain.BaseOfChain().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel1Positive1()
{
new Level1().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel1Positive2()
{
new Level1().TestDouble(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive1()
{
new Level3().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive2()
{
new Level3().Test("foo");
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive3()
{
bool result = new Level3().TestIsNonEmpty("foo");
Assert.True(result);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive4()
{
bool result = new Level3().TestIsNonEmpty("");
Assert.False(result);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Positive5()
{
new Level3().TestDouble(0);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Positive1()
{
new Level4().Test(1);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Positive2()
{
new Level4().Test("foo");
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Positive3()
{
new Level4().TestDouble(0);
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestBaseNegative()
{
try
{
new ManualInheritanceChain.BaseOfChain().Test(0);
}
catch (ArgumentException a)
{
Assert.Equal("Precondition failed: x > 0: x must be positive\r\nParameter name: x must be positive", a.Message);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel1Negative1()
{
try
{
new Level1().Test(0);
}
catch (ArgumentException a)
{
Assert.Equal("x must be positive", a.ParamName);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel1Negative2()
{
try
{
new Level1().TestDouble(double.NaN);
}
catch (ArgumentOutOfRangeException a)
{
Assert.Equal("d", a.ParamName);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Negative1()
{
try
{
new Level3().Test(0);
}
catch (ArgumentException a)
{
Assert.Equal("x must be positive", a.ParamName);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Negative2()
{
try
{
new Level3().Test(null);
}
catch (ArgumentException a)
{
Assert.Equal("s", a.ParamName);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Negative3()
{
try
{
new Level3().TestIsNonEmpty(null);
}
catch (TestRewriterMethods.PreconditionException p)
{
Assert.Equal("s != null", p.Condition);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel3Negative4()
{
try
{
new Level3().TestDouble(Double.NaN);
}
catch (ArgumentOutOfRangeException p)
{
Assert.Equal("d", p.ParamName);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Negative1()
{
try
{
new Level4().Test(0);
}
catch (ArgumentException a)
{
Assert.Equal("x must be positive", a.ParamName);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Negative2()
{
try
{
new Level4().Test(null);
}
catch (ArgumentNullException a)
{
Assert.Equal("s", a.ParamName);
return;
}
throw new Exception();
}
[Fact, Trait("Category", "Runtime"), Trait("Category", "V4.0"), Trait("Category", "CoreTest"), Trait("Category", "Short")]
public void TestLevel4Negative3()
{
try
{
new Level4().TestDouble(Double.NaN);
}
catch (ArgumentOutOfRangeException p)
{
Assert.Equal("d", p.ParamName);
return;
}
throw new Exception();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace BinaryTree
{
public class BinaryTree<T> : ICollection<T> where T : IComparable<T>
{
private ITraversalStrategy<T> _traversalStrategy;
private BinaryTreeNode<T> _head;
public BinaryTree(ITraversalStrategy<T> traversalStrategy)
{
_traversalStrategy = traversalStrategy ?? throw new ArgumentNullException(nameof(traversalStrategy));
}
public BinaryTree(IEnumerable<T> collection)
{
AddRange(collection);
}
public BinaryTree(int capacity)
{
if (capacity <= 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity should be more then zero.");
}
IsFixedSize = true;
Capacity = capacity;
}
public BinaryTree()
{
}
public BinaryTreeNode<T> Head => _head;
public ITraversalStrategy<T> TraversalStrategy
{
get => _traversalStrategy ?? (_traversalStrategy = new InOrderTraversal<T>());
set => _traversalStrategy = value ?? throw new ArgumentNullException(nameof(value));
}
public int Count { get; private set; }
public int Capacity { get; }
public bool IsReadOnly => false;
public bool IsFixedSize { get; }
public void Add(T value)
{
if (IsFixedSize && Count >= Capacity)
{
throw new NotSupportedException($"The BinaryTree has a fixed size. Can not add more than {Capacity} items");
}
if (_head == null)
{
_head = new BinaryTreeNode<T>(value);
}
else
{
AddTo(_head, value);
}
Count++;
}
public void AddRange(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
while (enumerator.MoveNext())
{
Add(enumerator.Current);
}
}
}
public bool Contains(T value)
{
return FindWithParent(value, out var _) != null;
}
public bool Remove(T value)
{
var current = FindWithParent(value, out var parent);
if (current == null)
{
return false;
}
Count--;
if (current.Right == null)
{
if (parent == null)
{
_head = current.Left;
}
else
{
var result = parent.CompareTo(current.Value);
if (result > 0)
{
parent.Left = current.Left;
}
else if (result < 0)
{
parent.Right = current.Left;
}
}
}
else if (current.Right.Left == null)
{
current.Right.Left = current.Left;
if (parent == null)
{
_head = current.Right;
}
else
{
var result = parent.CompareTo(current.Value);
if (result > 0)
{
parent.Left = current.Right;
}
else if (result < 0)
{
parent.Right = current.Right;
}
}
}
else
{
var leftMost = current.Right.Left;
var leftMostParent = current.Right;
while (leftMost.Left != null)
{
leftMostParent = leftMost;
leftMost = leftMost.Left;
}
leftMostParent.Left = leftMost.Right;
leftMost.Left = current.Left;
leftMost.Right = current.Right;
if (parent == null)
{
_head = leftMost;
}
else
{
var result = parent.CompareTo(current.Value);
if (result > 0)
{
parent.Left = leftMost;
}
else if (result < 0)
{
parent.Right = leftMost;
}
}
}
return true;
}
public void Clear()
{
_head = null;
Count = 0;
}
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException("Non zero lower bound");
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException();
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException();
}
var items = TraversalStrategy.Traversal(_head);
while (items.MoveNext())
{
array[arrayIndex++] = items.Current;
}
}
[Obsolete]
public void SetTraversalStrategy(ITraversalStrategy<T> traversalStrategy)
{
_traversalStrategy = traversalStrategy ?? throw new ArgumentNullException(nameof(traversalStrategy));
}
private static void AddTo(BinaryTreeNode<T> node, T value)
{
if (value.CompareTo(node.Value) < 0)
{
if (node.Left == null)
{
node.Left = new BinaryTreeNode<T>(value);
}
else
{
AddTo(node.Left, value);
}
}
else
{
if (node.Right == null)
{
node.Right = new BinaryTreeNode<T>(value);
}
else
{
AddTo(node.Right, value);
}
}
}
private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
var current = _head;
parent = null;
while (current != null)
{
var result = current.CompareTo(value);
if (result > 0)
{
parent = current;
current = current.Left;
}
else if (result < 0)
{
parent = current;
current = current.Right;
}
else
{
break;
}
}
return current;
}
public IEnumerator<T> GetEnumerator()
{
return TraversalStrategy.Traversal(_head);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Runtime {
/// <summary>
/// Used as the value for the ScriptingRuntimeHelpers.GetDelegate method caching system
/// </summary>
public sealed class DelegateInfo {
#if FEATURE_LCG
private const int TargetIndex = 0;
private const int CallSiteIndex = 1;
private const int ConvertSiteIndex = 2;
private static readonly object TargetPlaceHolder = new object();
private static readonly object CallSitePlaceHolder = new object();
private static readonly object ConvertSitePlaceHolder = new object();
// to enable:
// function x() { }
// someClass.someEvent += delegateType(x)
// someClass.someEvent -= delegateType(x)
//
// We need to avoid re-creating the closure because the delegates won't
// compare equal when removing the delegate if they have different closure
// instances. Therefore we use a weak hashtable to get back the
// original closure. The closures also need to be held via a weak refererence to avoid
// creating a circular reference from the constants target back to the
// target. This is fine because as long as the delegate is referenced
// the object array will stay alive. Once the delegate is gone it's not
// wired up anywhere and -= will never be used again.
//
// Note that the closure content depends on the signature of the delegate. So a single dynamic object
// might need multiple closures if it is converted to delegates of different signatures.
private WeakDictionary<object, WeakReference> _closureMap = new WeakDictionary<object, WeakReference>();
private readonly Type _returnType;
private readonly Type[] _parameterTypes;
private readonly MethodInfo _method;
private readonly InvokeBinder _invokeBinder;
private readonly ConvertBinder _convertBinder;
public DelegateInfo(LanguageContext context, Type returnType, Type[] parameters) {
Assert.NotNull(returnType);
Assert.NotNullItems(parameters);
_returnType = returnType;
_parameterTypes = parameters;
PerfTrack.NoteEvent(PerfTrack.Categories.DelegateCreate, ToString());
if (_returnType != typeof(void)) {
_convertBinder = context.CreateConvertBinder(_returnType, true);
}
_invokeBinder = context.CreateInvokeBinder(new CallInfo(_parameterTypes.Length));
Type[] delegateParams = new Type[1 + _parameterTypes.Length];
delegateParams[0] = typeof(object[]);
for (int i = 0; i < _parameterTypes.Length; i++) {
delegateParams[1 + i] = _parameterTypes[i];
}
EmitClrCallStub(returnType, delegateParams, out _method);
}
public Delegate CreateDelegate(Type delegateType, object dynamicObject) {
Assert.NotNull(delegateType, dynamicObject);
object[] closure;
lock (_closureMap) {
if (!_closureMap.TryGetValue(dynamicObject, out WeakReference weakClosure) || (closure = (object[])weakClosure.Target) == null) {
closure = new[] { TargetPlaceHolder, CallSitePlaceHolder, ConvertSitePlaceHolder };
_closureMap[dynamicObject] = new WeakReference(closure);
Type[] siteTypes = MakeSiteSignature(_parameterTypes);
CallSite callSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(siteTypes), _invokeBinder);
CallSite convertSite = null;
if (_returnType != typeof(void)) {
convertSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(typeof(object), _returnType), _convertBinder);
}
closure[TargetIndex] = dynamicObject;
closure[CallSiteIndex] = callSite;
closure[ConvertSiteIndex] = convertSite;
}
}
return _method.CreateDelegate(delegateType, closure);
}
private void EmitClrCallStub(Type returnType, Type[] parameterTypes, out MethodInfo method) {
// Create the method with a special name so the langauge compiler knows that method's stack frame is not visible
DynamicILGen cg = Snippets.Shared.CreateDynamicMethod("_Scripting_", returnType, parameterTypes, false);
EmitClrCallStub(cg);
method = cg.Finish();
}
/// <summary>
/// Generates stub to receive the CLR call and then call the dynamic language code.
/// </summary>
private void EmitClrCallStub(ILGen cg) {
List<ReturnFixer> fixers = new List<ReturnFixer>(0);
// Create strongly typed return type from the site.
// This will, among other things, generate tighter code.
Type[] siteTypes = MakeSiteSignature(_parameterTypes);
CallSite callSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(siteTypes), _invokeBinder);
Type siteType = callSite.GetType();
Type convertSiteType = null;
if (_returnType != typeof(void)) {
CallSite convertSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(typeof(object), _returnType), _convertBinder);
convertSiteType = convertSite.GetType();
}
FieldInfo convertTarget = null;
if (_returnType != typeof(void)) {
// load up the conversion logic on the stack
LocalBuilder convertSiteLocal = cg.DeclareLocal(convertSiteType);
EmitConstantGet(cg, ConvertSiteIndex, convertSiteType);
cg.Emit(OpCodes.Dup);
cg.Emit(OpCodes.Stloc, convertSiteLocal);
convertTarget = convertSiteType.GetDeclaredField("Target");
cg.EmitFieldGet(convertTarget);
cg.Emit(OpCodes.Ldloc, convertSiteLocal);
}
// load up the invoke logic on the stack
LocalBuilder site = cg.DeclareLocal(siteType);
EmitConstantGet(cg, CallSiteIndex, siteType);
cg.Emit(OpCodes.Dup);
cg.Emit(OpCodes.Stloc, site);
FieldInfo target = siteType.GetDeclaredField("Target");
cg.EmitFieldGet(target);
cg.Emit(OpCodes.Ldloc, site);
EmitConstantGet(cg, TargetIndex, typeof(object));
for (int i = 0; i < _parameterTypes.Length; i++) {
if (_parameterTypes[i].IsByRef) {
ReturnFixer rf = ReturnFixer.EmitArgument(cg, i + 1, _parameterTypes[i]);
if (rf != null) fixers.Add(rf);
} else {
cg.EmitLoadArg(i + 1);
}
}
// emit the invoke for the call
cg.EmitCall(target.FieldType, "Invoke");
// emit the invoke for the convert
if (_returnType == typeof(void)) {
cg.Emit(OpCodes.Pop);
} else {
cg.EmitCall(convertTarget.FieldType, "Invoke");
}
// fixup any references
foreach (ReturnFixer rf in fixers) {
rf.FixReturn(cg);
}
cg.Emit(OpCodes.Ret);
}
private static void EmitConstantGet(ILGen il, int index, Type type) {
il.Emit(OpCodes.Ldarg_0);
il.EmitInt(index);
il.Emit(OpCodes.Ldelem_Ref);
if (type != typeof(object)) {
il.Emit(OpCodes.Castclass, type);
}
}
private static Type[] MakeSiteSignature(Type[] parameterTypes) {
Type[] sig = new Type[parameterTypes.Length + 2];
// target object
sig[0] = typeof(object);
// arguments
for (int i = 0; i < parameterTypes.Length; i++) {
if (parameterTypes[i].IsByRef) {
sig[i + 1] = typeof(object);
} else {
sig[i + 1] = parameterTypes[i];
}
}
// return type
sig[sig.Length - 1] = typeof(object);
return sig;
}
#else
private static Type[] MakeSiteSignature(ParameterInfo[] parameterInfos) {
Type[] sig = new Type[parameterInfos.Length + 2];
// target object
sig[0] = typeof(object);
// arguments
for (int i = 0; i < parameterInfos.Length; i++) {
if (parameterInfos[i].ParameterType.IsByRef) {
sig[i + 1] = typeof(object);
} else {
sig[i + 1] = parameterInfos[i].ParameterType;
}
}
// return type
sig[sig.Length - 1] = typeof(object);
return sig;
}
internal static Delegate CreateDelegateForDynamicObject(LanguageContext context, object dynamicObject, Type delegateType, MethodInfo invoke) {
PerfTrack.NoteEvent(PerfTrack.Categories.DelegateCreate, delegateType.ToString());
Type returnType = invoke.ReturnType;
ParameterInfo[] parameterInfos = invoke.GetParameters();
var parameters = new List<ParameterExpression>();
for (int i = 0; i < parameterInfos.Length; i++) {
parameters.Add(Expression.Parameter(parameterInfos[i].ParameterType, "p" + i));
}
InvokeBinder invokeBinder = context.CreateInvokeBinder(new CallInfo(parameterInfos.Length));
ConvertBinder convertBinder = (returnType != typeof(void)) ? context.CreateConvertBinder(returnType, explicitCast: true) : null;
CallSite invokeSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(MakeSiteSignature(parameterInfos)), invokeBinder);
Type invokeSiteType = invokeSite.GetType();
Type convertSiteType;
CallSite convertSite;
if (convertBinder != null) {
convertSite = CallSite.Create(DynamicSiteHelpers.MakeCallSiteDelegate(typeof(object), returnType), convertBinder);
convertSiteType = convertSite.GetType();
} else {
convertSiteType = null;
convertSite = null;
}
var locals = new List<ParameterExpression>();
ParameterExpression invokeSiteVar = Expression.Parameter(invokeSiteType, "site");
ParameterExpression convertSiteVar = null;
var args = new List<Expression>();
args.Add(invokeSiteVar);
args.Add(Expression.Constant(dynamicObject));
int strongBoxVarsStart = locals.Count;
for (int i = 0; i < parameterInfos.Length; i++) {
if (parameterInfos[i].ParameterType.IsByRef) {
var argType = parameterInfos[i].ParameterType;
Type elementType = argType.GetElementType();
Type concreteType = typeof(StrongBox<>).MakeGenericType(elementType);
var strongBox = Expression.Parameter(concreteType, "box" + i);
locals.Add(strongBox);
args.Add(
Expression.Assign(
strongBox,
Expression.New(
concreteType.GetConstructor(new Type[] { elementType }),
parameters[i]
)
)
);
} else {
args.Add(parameters[i]);
}
}
int strongBoxVarsEnd = locals.Count;
Expression invocation = Expression.Invoke(
Expression.Field(
Expression.Assign(
invokeSiteVar,
Expression.Convert(Expression.Constant(invokeSite), invokeSiteType)
),
invokeSiteType.GetDeclaredField("Target")
),
args
);
if (convertBinder != null) {
convertSiteVar = Expression.Parameter(convertSiteType, "convertSite");
invocation = Expression.Invoke(
Expression.Field(
Expression.Assign(
convertSiteVar,
Expression.Convert(Expression.Constant(convertSite), convertSiteType)
),
convertSiteType.GetDeclaredField("Target")
),
convertSiteVar,
invocation
);
}
locals.Add(invokeSiteVar);
if (convertSiteVar != null) {
locals.Add(convertSiteVar);
}
Expression body;
// copy back from StrongBox.Value
if (strongBoxVarsEnd > strongBoxVarsStart) {
var block = new Expression[1 + strongBoxVarsEnd - strongBoxVarsStart + 1];
var resultVar = Expression.Parameter(invocation.Type, "result");
locals.Add(resultVar);
int b = 0;
int l = strongBoxVarsStart;
// values of strong boxes are initialized in invocation expression:
block[b++] = Expression.Assign(resultVar, invocation);
for (int i = 0; i < parameterInfos.Length; i++) {
if (parameterInfos[i].ParameterType.IsByRef) {
var local = locals[l++];
block[b++] = Expression.Assign(
parameters[i],
Expression.Field(local, local.Type.GetDeclaredField("Value"))
);
}
}
block[b++] = resultVar;
Debug.Assert(l == strongBoxVarsEnd);
Debug.Assert(b == block.Length);
body = Expression.Block(locals, block);
} else {
body = Expression.Block(locals, invocation);
}
var lambda = Expression.Lambda(delegateType, body, "_Scripting_", parameters);
return lambda.Compile();
}
#endif
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using System.IO;
using System.Diagnostics;
using FluentAssertions;
using System.Collections.Generic;
using System.Linq;
namespace CK.Text.Tests
{
[TestFixture]
public class StringAndStringBuilderExtensionTests
{
[Test]
public void concat_method_uses_StringBuilder_AppendStrings_inside()
{
var strings = new string[] { "A", "Hello", "B", "World", null, "End" };
var s = strings.Concatenate( "|+|" );
s.Should().Be( "A|+|Hello|+|B|+|World|+||+|End" );
}
[Test]
public void StringBuilder_AppendStrings_method_does_not_skip_null_entries()
{
var strings = new string[] { "A", "Hello", "B", "World", null, "End" };
var b = new StringBuilder();
b.AppendStrings( strings, "|+|" );
b.ToString().Should().Be( "A|+|Hello|+|B|+|World|+||+|End" );
}
[Test]
public void appending_multiple_strings_with_a_repeat_count()
{
new StringBuilder().Append( "A", 1 ).ToString().Should().Be( "A" );
new StringBuilder().Append( "AB", 2 ).ToString().Should().Be( "ABAB" );
new StringBuilder().Append( "|-|", 10 ).ToString().Should().Be( "|-||-||-||-||-||-||-||-||-||-|" );
}
[Test]
public void appends_multiple_strings_silently_ignores_0_or_negative_RepeatCount()
{
new StringBuilder().Append( "A", 0 ).ToString().Should().BeEmpty();
new StringBuilder().Append( "A", -1 ).ToString().Should().BeEmpty();
}
[Test]
public void appends_multiple_strings_silently_ignores_null_or_empty_string_to_repeat()
{
new StringBuilder().Append( "", 20 ).ToString().Should().BeEmpty();
new StringBuilder().Append( (string)null, 20 ).ToString().Should().BeEmpty();
}
[TestCase( '0', 0 )]
[TestCase( '1', 1 )]
[TestCase( '9', 9 )]
[TestCase( 'a', 10 )]
[TestCase( 'e', 14 )]
[TestCase( 'f', 15 )]
[TestCase( 'A', 10 )]
[TestCase( 'C', 12 )]
[TestCase( 'F', 15 )]
[TestCase( 'm', -1 )]
[TestCase( '\t', -1 )]
[TestCase( '\u0000', -1 )]
[TestCase( 'Z', -1 )]
public void HexDigitValue_extension_method_on_character( char c, int expected )
{
c.HexDigitValue().Should().Be( expected );
}
[Test]
public void appending_multi_lines_with_a_prefix_with_null_or_empty_or_one_line()
{
{
StringBuilder b = new StringBuilder();
string text = @"One line.";
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( @"|One line." );
}
{
StringBuilder b = new StringBuilder();
string text = @"";
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( @"|" );
}
{
StringBuilder b = new StringBuilder();
string text = null;
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( @"|" );
}
{
StringBuilder b = new StringBuilder();
string text = @"One line.";
string t = b.AppendMultiLine( "|", text, false ).ToString();
t.Should().Be( @"One line." );
}
{
StringBuilder b = new StringBuilder();
string text = @"";
string t = b.AppendMultiLine( "|", text, false ).ToString();;
t.Should().Be( @"" );
}
{
StringBuilder b = new StringBuilder();
string text = null;
string t = b.AppendMultiLine( "|", text, false ).ToString();
t.Should().Be( @"" );
}
}
[Test]
public void appending_multi_lines_to_empty_lines()
{
{
StringBuilder b = new StringBuilder();
string text = Environment.NewLine;
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( "|" );
}
{
StringBuilder b = new StringBuilder();
string text = Environment.NewLine + Environment.NewLine;
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( "|" + Environment.NewLine + "|" );
}
{
StringBuilder b = new StringBuilder();
string text = Environment.NewLine + Environment.NewLine + Environment.NewLine;
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( "|" + Environment.NewLine + "|" + Environment.NewLine + "|" );
}
{
StringBuilder b = new StringBuilder();
string text = Environment.NewLine + Environment.NewLine + Environment.NewLine + "a";
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( "|" + Environment.NewLine + "|" + Environment.NewLine + "|" + Environment.NewLine + "|a" );
}
}
[Test]
public void appending_multi_lines_with_a_prefix()
{
{
StringBuilder b = new StringBuilder();
string text = @"First line.
Second line.
Indented.
Also indented.
Last line.";
// Here, normalizing the source embedded string is to support
// git clone with LF in files instead of CRLF.
// Our (slow) AppendMultiLine normalizes the end of lines to Environment.NewLine.
string t = b.AppendMultiLine( "|", text, true ).ToString();
t.Should().Be( @"|First line.
|Second line.
| Indented.
|
| Also indented.
|Last line.".NormalizeEOL() );
}
{
StringBuilder b = new StringBuilder();
string text = @"First line.
Second line.
Indented.
Also indented.
Last line.";
string t = b.AppendMultiLine( "|", text, false ).ToString();
t.Should().Be( @"First line.
|Second line.
| Indented.
|
| Also indented.
|Last line.".NormalizeEOL() );
}
}
[Test]
public void appending_multi_lines_with_prefixLastEmptyLine()
{
string text = @"First line.
Second line.
";
{
StringBuilder b = new StringBuilder();
string t = b.AppendMultiLine( "|", text, true, prefixLastEmptyLine: false ).ToString();
t.Should().Be( @"|First line.
|Second line.
|
|".NormalizeEOL() );
}
{
StringBuilder b = new StringBuilder();
string t = b.AppendMultiLine( "|", text, true, prefixLastEmptyLine: true ).ToString();
t.Should().Be( @"|First line.
|Second line.
|
|
|".NormalizeEOL() );
}
}
// With VSTest adapter, this test fails.... meaning that
// the String.Join is LESS efficient than the home made new StringBuilder().AppendStrings solution (this occurs in Release as well as in Debug).
// This is hard to believe. So I don't believe :).
// This test is temporarily disabled and this should be investigated.
//[Test]
//public void our_Concatenate_to_string_must_use_String_Join_since_it_is_faster()
//{
// Assume.That( false, "This test should be investigated. We suspect an impact of VSTest adpater on the result." );
// static string ConcatenateCandidate( IEnumerable<string> @this, string separator = ", " )
// {
// return new StringBuilder().AppendStrings( @this, separator ).ToString();
// }
// string text = File.ReadAllText( Path.Combine( TestHelper.SolutionFolder, "Tests/CK.Text.Tests/StringAndStringBuilderExtensionTests.cs" ) )
// .NormalizeEOLToLF();
// var lines = text.Split( '\n' );
// var words = text.Split( ' ', '\n' );
// var rJoinLines = MicroBenchmark.MeasureTime( () => String.Join( ", ", lines ) );
// var rJoinWords = MicroBenchmark.MeasureTime( () => String.Join( ", ", words ) );
// var rConcatLines = MicroBenchmark.MeasureTime( () => ConcatenateCandidate( lines ) );
// var rConcatWords = MicroBenchmark.MeasureTime( () => ConcatenateCandidate( words ) );
// rJoinLines.IsSignificantlyBetterThan( rConcatLines ).Should().BeTrue();
// rJoinWords.IsSignificantlyBetterThan( rConcatWords ).Should().BeTrue();
// var smallSet = lines.Take( 20 ).ToArray();
// var rConcatSmall = MicroBenchmark.MeasureTime( () => ConcatenateCandidate( smallSet ) );
// var rJoinSmall = MicroBenchmark.MeasureTime( () => String.Join( ", ", smallSet ) );
// rJoinSmall.IsSignificantlyBetterThan( rConcatSmall ).Should().BeTrue();
//}
// [Test]
// public void our_appending_multi_lines_is_better_than_naive_implementation_in_release_but_not_in_debug()
// {
// string text = File.ReadAllText( Path.Combine( TestHelper.SolutionFolder, "Tests/CK.Text.Tests/StringAndStringBuilderExtensionTests.cs" ) );
// text = text.NormalizeEOL();
// TestPerf( text, 10 );
// TestPerf( "Small text may behave differently", 100 );
// TestPerf( "Small text may"+Environment.NewLine + "behave differently" +Environment.NewLine, 100 );
// }
// void TestPerf( string text, int count )
// {
// GC.Collect();
// Stopwatch w = new Stopwatch();
// string[] results = new string[2000];
// long naive = PrefixWithNaiveReplace( w, text, results );
// string aNaive = results[0];
// long better = PrefixWithOurExtension( w, text, results );
// results[0].Should().Be( aNaive );
// for( int i = 0; i < count; ++i )
// {
// naive += PrefixWithNaiveReplace( w, text, results );
// better += PrefixWithOurExtension( w, text, results );
// }
// double factor = (double)better / naive;
// Console.WriteLine( $"Naive:{naive}, Extension:{better}. Factor: {factor}" );
//#if DEBUG
// factor.Should().BeGreaterThan( 1 );
//#else
// factor.Should().BeLessThan( 1 );
//#endif
// }
// static readonly string prefix = "-!-";
// long PrefixWithNaiveReplace( Stopwatch w, string f, string[] results )
// {
// GC.Collect();
// w.Restart();
// for( int i = 0; i < results.Length; ++i )
// {
// results[i] = f.Replace( Environment.NewLine, Environment.NewLine + prefix );
// }
// w.Stop();
// return w.ElapsedTicks;
// }
// long PrefixWithOurExtension( Stopwatch w, string f, string[] results )
// {
// GC.Collect();
// w.Restart();
// StringBuilder b = new StringBuilder();
// for( int i = 0; i < results.Length; ++i )
// {
// // We must use the prefixLastEmptyLine to match the way the naive implementation works.
// results[i] = b.AppendMultiLine( prefix, f, false, prefixLastEmptyLine: true ).ToString();
// b.Clear();
// }
// w.Stop();
// return w.ElapsedTicks;
// }
[TestCase( null, "" )]
[TestCase( "", "" )]
[TestCase( "A", "A" )]
[TestCase( @"A""b", @"A\""b" )]
[TestCase( "A$\r\nB\t", @"A$\r\nB\t" )]
[TestCase( "\r\n\t\\", @"\r\n\t\\" )]
[TestCase( "A\0B", @"A\u0000B" )]
public void StringBuilder_AppendJSONEscaped( string text, string json )
{
var b = new StringBuilder();
b.AppendJSONEscaped( text );
b.ToString().Should().Be( json );
}
public void StringBuilder_AppendJSONEscaped_substring()
{
var b = new StringBuilder();
b.AppendJSONEscaped( "AB\rCD", 2, 1 );
b.Invoking( sut => sut.AppendJSONEscaped( null, 0, 1 ) ).Should().Throw<ArgumentNullException>();
b.AppendJSONEscaped( "A\t\n\0BCD", 1, 3 );
b.ToString().Should().Be( @"\r\t\n\u0000" );
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using Common;
using Internal;
using System.Collections.Generic;
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object lockObject = new object();
private Timer lazyWriterTimer;
private readonly Queue<AsyncContinuation> flushAllContinuations = new Queue<AsyncContinuation>();
private readonly object continuationQueueLock = new object();
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
this.Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
this.RequestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
this.TimeToSleepBetweenBatches = 50;
this.BatchSize = 100;
this.WrappedTarget = wrappedTarget;
this.QueueLimit = queueLimit;
this.OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(50)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get { return this.RequestQueue.OnOverflow; }
set { this.RequestQueue.OnOverflow = value; }
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get { return this.RequestQueue.RequestLimit; }
set { this.RequestQueue.RequestLimit = value; }
}
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
internal AsyncRequestQueue RequestQueue { get; private set; }
/// <summary>
/// Waits for the lazy writer thread to finish writing messages.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
bool queueWasEmpty = false;
lock (this.continuationQueueLock)
{
this.flushAllContinuations.Enqueue(asyncContinuation);
if (TimeToSleepBetweenBatches <= 0 && this.flushAllContinuations.Count == 1)
queueWasEmpty = RequestQueue.RequestCount == 0;
}
if (queueWasEmpty)
StartLazyWriterTimer(); // Will schedule new timer-worker-thread, after waiting for the current to have completed its last batch
}
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
this.RequestQueue.Clear();
InternalLogger.Trace("AsyncWrapper '{0}': start timer", Name);
this.lazyWriterTimer = new Timer(this.ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
this.StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
this.StopLazyWriterThread();
if (this.RequestQueue.RequestCount > 0)
{
ProcessPendingEvents(null);
}
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
if (this.TimeToSleepBetweenBatches <= 0)
{
InternalLogger.Trace("AsyncWrapper '{0}': Throttled timer scheduled", this.Name);
this.lazyWriterTimer.Change(1, Timeout.Infinite);
}
else
{
this.lazyWriterTimer.Change(this.TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
}
/// <summary>
/// Attempts to start an instant timer-worker-thread which can write
/// queued log messages.
/// </summary>
/// <returns>Returns true when scheduled a timer-worker-thread</returns>
protected virtual bool StartInstantWriterTimer()
{
bool lockTaken = false;
try
{
lockTaken = Monitor.TryEnter(this.lockObject);
if (lockTaken)
{
// Lock taken means no timer-worker-thread is active, schedule now
if (this.lazyWriterTimer != null)
{
if (this.TimeToSleepBetweenBatches <= 0)
{
// Not optimal to shedule timer-worker-thread while holding lock,
// as the newly scheduled timer-worker-thread will hammer into the lockObject
this.lazyWriterTimer.Change(0, Timeout.Infinite);
return true;
}
}
}
return false;
}
finally
{
// If not able to take lock, then it means timer-worker-thread is already active,
// and timer-worker-thread will check RequestQueue after leaving lockObject
if (lockTaken)
Monitor.Exit(this.lockObject);
}
}
/// <summary>
/// Stops the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
this.lazyWriterTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.lazyWriterTimer = null;
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.MergeEventProperties(logEvent.LogEvent);
this.PrecalculateVolatileLayouts(logEvent.LogEvent);
bool queueWasEmpty = this.RequestQueue.Enqueue(logEvent);
if (queueWasEmpty && TimeToSleepBetweenBatches <= 0)
StartInstantWriterTimer();
}
/// <summary>
/// Write to queue without locking <see cref="Target.SyncRoot"/>
/// </summary>
/// <param name="logEvent"></param>
protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent)
{
try
{
this.Write(logEvent);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
private static readonly AsyncContinuation[] noFlushNullContinuationArray = new AsyncContinuation[] { null };
private void ProcessPendingEvents(object state)
{
bool? wroteFullBatchSize = false;
AsyncContinuation[] continuations;
bool lockTaken = false;
try
{
if (TimeToSleepBetweenBatches <= 0)
{
Monitor.Enter(this.lockObject);
lockTaken = true;
}
lock (this.continuationQueueLock)
{
continuations = this.flushAllContinuations.Count > 0
? this.flushAllContinuations.ToArray()
: noFlushNullContinuationArray;
this.flushAllContinuations.Clear();
}
if (this.WrappedTarget == null)
{
InternalLogger.Error("AsyncWrapper '{0}': WrappedTarget is NULL", this.Name);
return;
}
for (int x = 0; x < continuations.Length; x++)
{
var continuation = continuations[x];
int count = this.BatchSize;
if (continuation != null)
{
count = -1; // Dequeue all
}
AsyncLogEventInfo[] logEventInfos = this.RequestQueue.DequeueBatch(count);
if (logEventInfos.Length == 0)
wroteFullBatchSize = null; // Nothing to write
else if (logEventInfos.Length == BatchSize)
wroteFullBatchSize = true;
if (InternalLogger.IsTraceEnabled || continuation != null)
InternalLogger.Trace("AsyncWrapper '{0}': Flushing {1} events.", this.Name, logEventInfos.Length);
if (continuation != null)
{
// write all events, then flush, then call the continuation
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => this.WrappedTarget.Flush(continuation));
}
else
{
// just write all events
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos);
}
}
}
catch (Exception exception)
{
wroteFullBatchSize = false; // Something went wrong, lets throttle retry
InternalLogger.Error(exception, "AsyncWrapper '{0}': Error in lazy writer timer procedure.", this.Name);
if (exception.MustBeRethrown())
{
throw;
}
}
finally
{
if (TimeToSleepBetweenBatches <= 0 && wroteFullBatchSize == true)
this.StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up)
if (lockTaken)
Monitor.Exit(this.lockObject);
if (TimeToSleepBetweenBatches <= 0)
{
// If queue was not empty, then more might have arrived while writing the first batch
// Uses throttled timer here, so we can process in batches (faster)
if (wroteFullBatchSize.HasValue && !wroteFullBatchSize.Value)
this.StartLazyWriterTimer(); // Queue was not empty, more might have come (Skip expensive RequestQueue-check)
else if (!wroteFullBatchSize.HasValue)
{
if (this.RequestQueue.RequestCount > 0)
this.StartLazyWriterTimer(); // Queue was checked as empty, but now we have more
else
{
lock (this.continuationQueueLock)
if (this.flushAllContinuations.Count > 0)
this.StartLazyWriterTimer(); // Flush queue was checked as empty, but now we have more
}
}
}
else
{
this.StartLazyWriterTimer();
}
}
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Windows.Forms;
using SpiffLib;
namespace m
{
/// <summary>
/// Summary description for TemplatePanel.
/// </summary>
public class TemplatePanel : System.Windows.Forms.UserControl
{
private System.Windows.Forms.ComboBox comboDocs;
private m.FlowPanel flowPanel;
private System.Windows.Forms.ToolBar toolBar;
protected internal System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.ToolBarButton toolBarButtonNew;
private System.Windows.Forms.ToolBarButton toolBarButtonOpen;
private System.Windows.Forms.ToolBarButton toolBarButtonSave;
private System.Windows.Forms.ContextMenu contextMenuTiles;
private System.Windows.Forms.MenuItem menuItemDeleteTile;
private System.Windows.Forms.MenuItem menuItemTileBackground;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.ToolBarButton toolBarButtonClose;
private System.Windows.Forms.ContextMenu contextMenuToolbar;
private System.Windows.Forms.MenuItem menuItemAddTemplates;
private System.Windows.Forms.MenuItem menuItemEditTerrain;
private System.Windows.Forms.ToolBarButton toolBarButtonMisc;
private System.Windows.Forms.ToolBarButton toolBarButtonSeparator;
private System.Windows.Forms.ContextMenu contextMenuSave;
private System.Windows.Forms.MenuItem menuItemSaveAs;
private System.Windows.Forms.MenuItem menuItemSaveAll;
private System.Windows.Forms.MenuItem menuItemSave;
private System.Windows.Forms.MenuItem menuItemProperties;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItemTemplProperties;
private System.Windows.Forms.MenuItem menuItemImportBitmap;
private System.Windows.Forms.MenuItem menuItemExportBitmap;
private System.Windows.Forms.MenuItem menuItemScaleDown;
private System.Windows.Forms.MenuItem menuItemSavePalette;
private System.Windows.Forms.MenuItem menuItemQuantizeOnly;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.ToolTip toolTip;
TemplateDoc m_tmpdActive = null;
public TemplatePanel()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
if (Globals.IsKit()) {
Controls.Remove(toolBar);
toolBar.Visible = false;
}
// Easier than creating a resource file?
System.Reflection.Assembly ass = typeof(TemplatePanel).Module.Assembly;
Stream stm = ass.GetManifestResourceStream("m.toolstrip.bmp");
imageList1.Images.AddStrip(new Bitmap(stm));
// We want to know about changes to template docs
TemplateDocTemplate doctTemplate = (TemplateDocTemplate)DocManager.FindDocTemplate(typeof(TemplateDoc));
if (doctTemplate != null) {
doctTemplate.DocActive += new TemplateDocTemplate.DocActiveHandler(TemplateDocTemplate_DocActive);
doctTemplate.DocAdded += new TemplateDocTemplate.DocAddedHandler(TemplateDocTemplate_DocAdded);
doctTemplate.DocRemoved += new TemplateDocTemplate.DocRemovedHandler(TemplateDocTemplate_DocRemoved);
doctTemplate.TemplatesAdded += new TemplateDocTemplate.TemplatesAddedHandler(TemplateDocTemplate_TemplatesAdded);
doctTemplate.TemplatesRemoved += new TemplateDocTemplate.TemplatesRemovedHandler(TemplateDocTemplate_TemplatesRemoved);
doctTemplate.TemplateChanged += new TemplateDocTemplate.TemplateChangedHandler(TemplateDocTemplate_TemplateChanged);
}
// We want to know when the active level doc changes
LevelDocTemplate doctLevel = (LevelDocTemplate)DocManager.FindDocTemplate(typeof(LevelDoc));
if (doctLevel != null)
doctLevel.DocActive += new TemplateDocTemplate.DocActiveHandler(LevelDocTemplate_DocActive);
}
void LevelDocTemplate_DocActive(Document doc) {
LevelDoc lvld = (LevelDoc)doc;
if (lvld != null)
SetActiveDoc(lvld.GetTemplateDoc());
}
void TemplateDocTemplate_DocActive(Document doc) {
SetActiveDoc((TemplateDoc)doc);
}
void SetActiveDoc(TemplateDoc tmpd) {
if (tmpd == m_tmpdActive)
return;
if (tmpd == null) {
flowPanel.Controls.Clear();
} else {
ComboItem ciFound = null;
for (int nIndex = 0; nIndex < comboDocs.Items.Count; nIndex++) {
ComboItem ci = (ComboItem)comboDocs.Items[nIndex];
if (ci.m_tmpd == tmpd) {
ciFound = ci;
comboDocs.SelectedIndex = nIndex;
break;
}
}
if (ciFound != null)
FillPanel(ciFound.m_alsPictureBoxes);
}
m_tmpdActive = tmpd;
}
void FillPanel(ArrayList alsPictureBoxes) {
flowPanel.SuspendLayout();
flowPanel.Controls.Clear();
flowPanel.Controls.AddRange((Control[])alsPictureBoxes.ToArray(typeof(Control)));
flowPanel.ResumeLayout();
flowPanel.RefreshScrollbar();
}
PictureBox CreatePictureBox(TemplateDoc tmpd, Size sizTile, IMapItem mi) {
PictureBox picb = new PictureBox();
picb.Image = Misc.TraceEdges(mi.GetBitmap(sizTile, tmpd), 1, Color.Azure);
picb.SizeMode = PictureBoxSizeMode.AutoSize;
picb.Tag = (Object)mi;
picb.MouseDown += new MouseEventHandler(PictureBox_MouseDown);
return picb;
}
public class ComboItem {
public TemplateDoc m_tmpd;
public ArrayList m_alsPictureBoxes;
public ComboItem(TemplateDoc tmpd) {
m_tmpd = tmpd;
m_alsPictureBoxes = new ArrayList();
}
public override string ToString() {
return m_tmpd.GetName();
}
}
void TemplateDocTemplate_DocAdded(Document doc) {
TemplateDoc tmpd = (TemplateDoc)doc;
tmpd.ModifiedChanged += new TemplateDoc.ModifiedChangedHandler(TemplateDoc_ModifiedChanged);
tmpd.NameChanged += new TemplateDoc.NameChangedHandler(TemplateDoc_NameChanged);
ComboItem ci = new ComboItem(tmpd);
comboDocs.SelectedIndex = comboDocs.Items.Add(ci);
Template[] atmpl = tmpd.GetTemplates();
ArrayList alsNames = new ArrayList();
foreach (Template tmpl in atmpl)
alsNames.Add(tmpl.Name);
toolTip.RemoveAll();
TemplateDocTemplate_TemplatesAdded(tmpd, (string[])alsNames.ToArray(typeof(string)));
}
void TemplateDocTemplate_DocRemoved(Document doc) {
TemplateDoc tmpd = (TemplateDoc)doc;
tmpd.ModifiedChanged -= new TemplateDoc.ModifiedChangedHandler(TemplateDoc_ModifiedChanged);
tmpd.NameChanged -= new TemplateDoc.NameChangedHandler(TemplateDoc_NameChanged);
ComboItem ci = FindComboItem((TemplateDoc)doc);
if (ci != null)
comboDocs.Items.Remove(ci);
toolTip.RemoveAll();
}
int FindComboIndex(TemplateDoc tmpd) {
for (int nIndex = 0; nIndex < comboDocs.Items.Count; nIndex++) {
ComboItem ci = (ComboItem)comboDocs.Items[nIndex];
if (ci.m_tmpd == tmpd)
return nIndex;
}
return -1;
}
ComboItem FindComboItem(TemplateDoc tmpd) {
int nIndex = FindComboIndex(tmpd);
if (nIndex == -1)
return null;
return (ComboItem)comboDocs.Items[nIndex];
}
void TemplateDocTemplate_TemplatesAdded(TemplateDoc tmpd, string[] astrNames) {
ComboItem ci = FindComboItem(tmpd);
foreach (string strName in astrNames) {
PictureBox picb = CreatePictureBox(tmpd, tmpd.TileSize, new Tile(tmpd, strName, 0, 0));
ci.m_alsPictureBoxes.Add(picb);
toolTip.SetToolTip(picb, strName);
}
if (tmpd == m_tmpdActive)
FillPanel(ci.m_alsPictureBoxes);
}
void TemplateDocTemplate_TemplatesRemoved(TemplateDoc tmpd, string[] astrNames) {
ComboItem ci = FindComboItem(tmpd);
foreach (string strName in astrNames) {
foreach (PictureBox picb in ci.m_alsPictureBoxes) {
Tile tile = (Tile)picb.Tag;
if (strName == tile.Name) {
ci.m_alsPictureBoxes.Remove(picb);
break;
}
}
}
if (tmpd == m_tmpdActive)
FillPanel(ci.m_alsPictureBoxes);
}
void TemplateDocTemplate_TemplateChanged(TemplateDoc tmpd, string strProperty, string strName, string strParam) {
ComboItem ci = FindComboItem(tmpd);
foreach (PictureBox picb in ci.m_alsPictureBoxes) {
Tile tile = (Tile)picb.Tag;
if (tile.Name == strName) {
Template tmpl = tmpd.FindTemplate(strProperty == "Name" ? strParam : strName);
picb.Image = Misc.TraceEdges(tmpl.Bitmap, 1, Color.Azure);
break;
}
}
if (tmpd == m_tmpdActive)
FillPanel(ci.m_alsPictureBoxes);
}
void TemplateDoc_ModifiedChanged(Document doc, bool fModified) {
comboDocs.Invalidate();
}
void TemplateDoc_NameChanged(Document doc) {
comboDocs.Invalidate();
}
private void comboDocs_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) {
if (e.Index < 0 || e.Index >= comboDocs.Items.Count)
return;
ComboItem ci = (ComboItem)comboDocs.Items[e.Index];
string strName = ci.ToString() + (ci.m_tmpd.IsModified() ? "*" : "");
e.DrawBackground();
e.Graphics.DrawString(strName, e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y);
e.DrawFocusRectangle();
}
private void comboDocs_SelectedIndexChanged(object sender, System.EventArgs e) {
ComboItem ci = (ComboItem)comboDocs.Items[comboDocs.SelectedIndex];
DocManager.SetActiveDocument(typeof(TemplateDoc), ci.m_tmpd);
}
private void PictureBox_MouseDown(Object sender, MouseEventArgs e) {
Control ctlSelected = (Control)sender;
if (!Globals.IsKit()) {
if (e.Button == MouseButtons.Right) {
contextMenuTiles.Show(ctlSelected, new Point(e.X, e.Y));
return;
}
}
Tile tile = (Tile)((PictureBox)sender).Tag;
Globals.PropertyGrid.SelectedObject = tile.GetTemplate(m_tmpdActive);
// Start drag drop
LevelData ldat = new LevelData();
IMapItem mi = (IMapItem)ctlSelected.Tag;
ldat.ami = new IMapItem[] { mi };
Size sizTile = m_tmpdActive.TileSize;
ldat.txMouse = e.X / (double)sizTile.Width;
ldat.tyMouse = e.Y / (double)sizTile.Height;
ldat.Grid.Width = mi.Grid.Width;
ldat.Grid.Height = mi.Grid.Height;
DoDragDrop(ldat, DragDropEffects.Copy);
}
private void AddTemplates() {
// Get tile filename(s)
OpenFileDialog frmOpen = new OpenFileDialog();
frmOpen.Multiselect = true;
frmOpen.Filter = "Image Files (*.*)|*.*";
frmOpen.Title = "Add Templates";
if (frmOpen.ShowDialog() == DialogResult.Cancel)
return;
// Load them up. If there is no template doc yet, make a new one
if (m_tmpdActive == null)
DocManager.NewDocument(typeof(TemplateDoc), null);
m_tmpdActive.AddTemplates(frmOpen.FileNames);
}
private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) {
switch (toolBar.Buttons.IndexOf(e.Button)) {
case 0:
DocManager.NewDocument(typeof(TemplateDoc), null);
break;
case 1:
DocManager.OpenDocument(typeof(TemplateDoc));
break;
case 2:
if (m_tmpdActive != null)
m_tmpdActive.Save();
break;
case 3:
AddTemplates();
//Rectangle rc = toolBar.Buttons[toolBar.Buttons.IndexOf(e.Button)].Rectangle;
//contextMenuToolbar.Show(toolBar, new Point(rc.X, rc.Y + rc.Height));
break;
case 4:
// Separator
break;
case 5:
if (m_tmpdActive == null)
return;
m_tmpdActive.Close();
break;
}
}
private void menuItemSave_Click(object sender, System.EventArgs e) {
if (m_tmpdActive != null)
m_tmpdActive.Save();
}
private void menuItemSaveAs_Click(object sender, System.EventArgs e) {
if (m_tmpdActive != null)
m_tmpdActive.SaveAs(null);
}
private void menuItemSaveAll_Click(object sender, System.EventArgs e) {
DocManager.SaveAllModified(typeof(TemplateDoc));
}
private void menuItemAddTemplates_Click(object sender, System.EventArgs e) {
AddTemplates();
}
private void menuItemEditTerrain_Click(object sender, System.EventArgs e) {
if (m_tmpdActive == null)
return;
Form frmEditTerrain = new EditTerrainForm(m_tmpdActive);
frmEditTerrain.ShowDialog();
}
private IMapItem GetMapItem(Object sender) {
ContextMenu contextMenu = (ContextMenu)((MenuItem)sender).Parent;
return (IMapItem)((PictureBox)contextMenu.SourceControl).Tag;
}
private void menuItemImportBitmap_Click(object sender, System.EventArgs e) {
Tile tile = GetMapItem(sender) as Tile;
if (tile == null)
return;
Template tmpl = tile.GetTemplate(m_tmpdActive);
OpenFileDialog frmOpen = new OpenFileDialog();
frmOpen.FileName = tmpl.ImportPath;
if (frmOpen.ShowDialog() == DialogResult.Cancel)
return;
tmpl.Import(frmOpen.FileName);
}
private void menuItemExportBitmap_Click(object sender, System.EventArgs e) {
Tile tile = GetMapItem(sender) as Tile;
if (tile == null)
return;
Template tmpl = tile.GetTemplate(m_tmpdActive);
SaveFileDialog frmSave = new SaveFileDialog();
frmSave.DefaultExt = "png";
frmSave.Filter = "Png Files (*.png)|*.png";
frmSave.Title = "Save Template Bitmap As";
if (tmpl.ImportPath != null) {
frmSave.FileName = tmpl.ImportPath;
} else {
frmSave.FileName = tmpl.Name;
}
if (frmSave.ShowDialog() == DialogResult.Cancel)
return;
tmpl.Bitmap.Save(frmSave.FileName, ImageFormat.Png);
}
private void menuItemProperties_Click(object sender, System.EventArgs e) {
Globals.PropertyGrid.SelectedObject = m_tmpdActive;
}
private void menuItemDeleteTile_Click(object sender, System.EventArgs e) {
Tile tile = GetMapItem(sender) as Tile;
if (tile == null)
return;
if (MessageBox.Show("Are you sure?", "Delete Tile", MessageBoxButtons.YesNo) == DialogResult.Yes)
m_tmpdActive.RemoveTemplates(new Template[] { tile.GetTemplate(m_tmpdActive) });
}
private void menuItemTileBackground_Click(object sender, System.EventArgs e) {
Tile tile = GetMapItem(sender) as Tile;
if (tile == null)
return;
m_tmpdActive.SetBackgroundTemplate(tile.GetTemplate(m_tmpdActive));
}
private void menuItemTemplProperties_Click(object sender, System.EventArgs e) {
Tile tile = GetMapItem(sender) as Tile;
if (tile == null)
return;
Globals.PropertyGrid.SelectedObject = tile.GetTemplate(m_tmpdActive);
}
private void menuItemScaleDown_Click(object sender, System.EventArgs e) {
// If no template doc active, bail
if (m_tmpdActive == null)
return;
// Make sure 24 x 24 (could actually allow any sort of conversion...)
if (m_tmpdActive.TileSize.Width != 24 && m_tmpdActive.TileSize.Height != 24) {
MessageBox.Show(DocManager.GetFrameParent(), "The current template collection must be 24 x 24 tile size");
return;
}
// Get busy
TemplateDoc tmpdDst = TemplateTools.CloneTemplateDoc(m_tmpdActive);
TemplateTools.ScaleTemplates(tmpdDst, new Size(16, 16));
TemplateTools.QuantizeTemplates(tmpdDst, null, 0, 0, 0);
DocManager.SetActiveDocument(typeof(TemplateDoc), tmpdDst);
}
private void menuItemQuantizeOnly_Click(object sender, System.EventArgs e) {
if (m_tmpdActive == null)
return;
TemplateDoc tmpdDst = TemplateTools.CloneTemplateDoc(m_tmpdActive);
TemplateTools.QuantizeTemplates(tmpdDst, null, 0, 0, 0);
DocManager.SetActiveDocument(typeof(TemplateDoc), tmpdDst);
}
private void menuItemSavePalette_Click(object sender, System.EventArgs e) {
if (m_tmpdActive == null)
return;
Palette pal = m_tmpdActive.GetPalette();
if (pal == null) {
MessageBox.Show(DocManager.GetFrameParent(), "No palette on this template collection. You need to create one!");
return;
}
pal.SaveDialog();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.comboDocs = new System.Windows.Forms.ComboBox();
this.flowPanel = new m.FlowPanel();
this.toolBar = new System.Windows.Forms.ToolBar();
this.toolBarButtonNew = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonOpen = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonSave = new System.Windows.Forms.ToolBarButton();
this.contextMenuSave = new System.Windows.Forms.ContextMenu();
this.menuItemSave = new System.Windows.Forms.MenuItem();
this.menuItemSaveAs = new System.Windows.Forms.MenuItem();
this.menuItemSaveAll = new System.Windows.Forms.MenuItem();
this.toolBarButtonMisc = new System.Windows.Forms.ToolBarButton();
this.contextMenuToolbar = new System.Windows.Forms.ContextMenu();
this.menuItemAddTemplates = new System.Windows.Forms.MenuItem();
this.menuItemEditTerrain = new System.Windows.Forms.MenuItem();
this.menuItemScaleDown = new System.Windows.Forms.MenuItem();
this.menuItemQuantizeOnly = new System.Windows.Forms.MenuItem();
this.menuItemSavePalette = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItemProperties = new System.Windows.Forms.MenuItem();
this.toolBarButtonSeparator = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonClose = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.contextMenuTiles = new System.Windows.Forms.ContextMenu();
this.menuItemImportBitmap = new System.Windows.Forms.MenuItem();
this.menuItemExportBitmap = new System.Windows.Forms.MenuItem();
this.menuItemDeleteTile = new System.Windows.Forms.MenuItem();
this.menuItemTileBackground = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItemTemplProperties = new System.Windows.Forms.MenuItem();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// comboDocs
//
this.comboDocs.Dock = System.Windows.Forms.DockStyle.Top;
this.comboDocs.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.comboDocs.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboDocs.Location = new System.Drawing.Point(0, 24);
this.comboDocs.Name = "comboDocs";
this.comboDocs.Size = new System.Drawing.Size(168, 21);
this.comboDocs.TabIndex = 0;
this.comboDocs.SelectedIndexChanged += new System.EventHandler(this.comboDocs_SelectedIndexChanged);
this.comboDocs.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboDocs_DrawItem);
//
// flowPanel
//
this.flowPanel.AutoScroll = true;
this.flowPanel.BackColor = System.Drawing.Color.Black;
this.flowPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowPanel.Location = new System.Drawing.Point(0, 45);
this.flowPanel.Name = "flowPanel";
this.flowPanel.Size = new System.Drawing.Size(168, 403);
this.flowPanel.TabIndex = 1;
//
// toolBar
//
this.toolBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.toolBarButtonNew,
this.toolBarButtonOpen,
this.toolBarButtonSave,
this.toolBarButtonMisc,
this.toolBarButtonSeparator,
this.toolBarButtonClose});
this.toolBar.ButtonSize = new System.Drawing.Size(16, 16);
this.toolBar.DropDownArrows = true;
this.toolBar.ImageList = this.imageList1;
this.toolBar.Name = "toolBar";
this.toolBar.ShowToolTips = true;
this.toolBar.Size = new System.Drawing.Size(168, 24);
this.toolBar.TabIndex = 2;
this.toolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar_ButtonClick);
//
// toolBarButtonNew
//
this.toolBarButtonNew.ImageIndex = 0;
this.toolBarButtonNew.ToolTipText = "New Template Collection";
//
// toolBarButtonOpen
//
this.toolBarButtonOpen.ImageIndex = 1;
this.toolBarButtonOpen.ToolTipText = "Open Template Collection";
//
// toolBarButtonSave
//
this.toolBarButtonSave.DropDownMenu = this.contextMenuSave;
this.toolBarButtonSave.ImageIndex = 2;
this.toolBarButtonSave.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
this.toolBarButtonSave.ToolTipText = "Save Template Collection";
//
// contextMenuSave
//
this.contextMenuSave.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemSave,
this.menuItemSaveAs,
this.menuItemSaveAll});
//
// menuItemSave
//
this.menuItemSave.Index = 0;
this.menuItemSave.Text = "Save";
this.menuItemSave.Click += new System.EventHandler(this.menuItemSave_Click);
//
// menuItemSaveAs
//
this.menuItemSaveAs.Index = 1;
this.menuItemSaveAs.Text = "Save As...";
this.menuItemSaveAs.Click += new System.EventHandler(this.menuItemSaveAs_Click);
//
// menuItemSaveAll
//
this.menuItemSaveAll.Index = 2;
this.menuItemSaveAll.Text = "Save All";
this.menuItemSaveAll.Click += new System.EventHandler(this.menuItemSaveAll_Click);
//
// toolBarButtonMisc
//
this.toolBarButtonMisc.DropDownMenu = this.contextMenuToolbar;
this.toolBarButtonMisc.ImageIndex = 4;
this.toolBarButtonMisc.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
this.toolBarButtonMisc.ToolTipText = "Add Templates and other tools";
//
// contextMenuToolbar
//
this.contextMenuToolbar.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemAddTemplates,
this.menuItemEditTerrain,
this.menuItemScaleDown,
this.menuItemQuantizeOnly,
this.menuItemSavePalette,
this.menuItem1,
this.menuItemProperties});
//
// menuItemAddTemplates
//
this.menuItemAddTemplates.Index = 0;
this.menuItemAddTemplates.Text = "Add Templates...";
this.menuItemAddTemplates.Click += new System.EventHandler(this.menuItemAddTemplates_Click);
//
// menuItemEditTerrain
//
this.menuItemEditTerrain.Index = 1;
this.menuItemEditTerrain.Text = "Edit Terrain...";
this.menuItemEditTerrain.Click += new System.EventHandler(this.menuItemEditTerrain_Click);
//
// menuItemScaleDown
//
this.menuItemScaleDown.Index = 2;
this.menuItemScaleDown.Text = "Scale && Quantize...";
this.menuItemScaleDown.Click += new System.EventHandler(this.menuItemScaleDown_Click);
//
// menuItemQuantizeOnly
//
this.menuItemQuantizeOnly.Index = 3;
this.menuItemQuantizeOnly.Text = "Quantize Only...";
this.menuItemQuantizeOnly.Click += new System.EventHandler(this.menuItemQuantizeOnly_Click);
//
// menuItemSavePalette
//
this.menuItemSavePalette.Index = 4;
this.menuItemSavePalette.Text = "Save Palette...";
this.menuItemSavePalette.Click += new System.EventHandler(this.menuItemSavePalette_Click);
//
// menuItem1
//
this.menuItem1.Index = 5;
this.menuItem1.Text = "-";
//
// menuItemProperties
//
this.menuItemProperties.Index = 6;
this.menuItemProperties.Text = "Properties";
this.menuItemProperties.Click += new System.EventHandler(this.menuItemProperties_Click);
//
// toolBarButtonSeparator
//
this.toolBarButtonSeparator.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// toolBarButtonClose
//
this.toolBarButtonClose.ImageIndex = 5;
this.toolBarButtonClose.ToolTipText = "Close Template Collection";
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 15);
this.imageList1.TransparentColor = System.Drawing.Color.Magenta;
//
// contextMenuTiles
//
this.contextMenuTiles.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemImportBitmap,
this.menuItemExportBitmap,
this.menuItemDeleteTile,
this.menuItemTileBackground,
this.menuItem2,
this.menuItemTemplProperties});
//
// menuItemImportBitmap
//
this.menuItemImportBitmap.Index = 0;
this.menuItemImportBitmap.Text = "Import Bitmap...";
this.menuItemImportBitmap.Click += new System.EventHandler(this.menuItemImportBitmap_Click);
//
// menuItemExportBitmap
//
this.menuItemExportBitmap.Index = 1;
this.menuItemExportBitmap.Text = "Export Bitmap...";
this.menuItemExportBitmap.Click += new System.EventHandler(this.menuItemExportBitmap_Click);
//
// menuItemDeleteTile
//
this.menuItemDeleteTile.Index = 2;
this.menuItemDeleteTile.Text = "Remove";
this.menuItemDeleteTile.Click += new System.EventHandler(this.menuItemDeleteTile_Click);
//
// menuItemTileBackground
//
this.menuItemTileBackground.Index = 3;
this.menuItemTileBackground.Text = "Background";
this.menuItemTileBackground.Click += new System.EventHandler(this.menuItemTileBackground_Click);
//
// menuItem2
//
this.menuItem2.Index = 4;
this.menuItem2.Text = "-";
//
// menuItemTemplProperties
//
this.menuItemTemplProperties.Index = 5;
this.menuItemTemplProperties.Text = "Properties";
this.menuItemTemplProperties.Click += new System.EventHandler(this.menuItemTemplProperties_Click);
//
// TemplatePanel
//
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.flowPanel,
this.comboDocs,
this.toolBar});
this.ForeColor = System.Drawing.SystemColors.Control;
this.Name = "TemplatePanel";
this.Size = new System.Drawing.Size(168, 448);
this.ResumeLayout(false);
}
#endregion
}
}
| |
namespace Gu.Persist.Core.Tests.Repositories
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using NUnit.Framework;
public abstract partial class RepositoryTests
{
[TestCaseSource(nameof(TestCases))]
public void Read(TestCase testCase)
{
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
var dummy = new DummySerializable(1);
this.Save(file, dummy);
var read = testCase.Read<DummySerializable>(repository, file);
Assert.AreEqual(dummy.Value, read.Value);
Assert.AreNotSame(dummy, read);
}
[TestCaseSource(nameof(TestCases))]
public void ReadManagesSingleton(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, dummy);
var read1 = testCase.Read<DummySerializable>(repository, file);
var read2 = testCase.Read<DummySerializable>(repository, file);
if (repository is ISingletonRepository)
{
Assert.AreSame(read1, read2);
}
else
{
Assert.AreNotSame(read1, read2);
}
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenFileExists(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, dummy);
var read = testCase.ReadOrCreate<DummySerializable>(repository, file, () => throw new AssertionException("Should not get here."));
Assert.AreEqual(dummy.Value, read.Value);
Assert.AreNotSame(dummy, read);
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenFileDoesNotExists(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
var read = testCase.ReadOrCreate(repository, file, () => dummy);
Assert.AreSame(dummy, read);
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenFileExistsManagesSingleton(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, dummy);
var read1 = testCase.ReadOrCreate<DummySerializable>(repository, file, () => throw new AssertionException("Should not get here."));
var read2 = testCase.ReadOrCreate<DummySerializable>(repository, file, () => throw new AssertionException("Should not get here."));
if (repository is ISingletonRepository)
{
Assert.AreSame(read1, read2);
}
else
{
Assert.AreNotSame(read1, read2);
}
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenFileDoesNotExistsManagesSingleton(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
var read1 = testCase.ReadOrCreate(repository, file, () => dummy);
var read2 = testCase.ReadOrCreate(repository, file, () => dummy);
if (repository is ISingletonRepository)
{
Assert.AreSame(read1, read2);
}
else
{
Assert.AreNotSame(read1, read2);
}
}
[TestCaseSource(nameof(TestCases))]
public void IsNotDirtyAfterRead(TestCase testCase)
{
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, new DummySerializable(1));
if (repository.Settings.IsTrackingDirty)
{
var read = testCase.Read<DummySerializable>(repository, file);
Assert.AreEqual(false, testCase.IsDirty(repository, file, read));
read.Value++;
Assert.AreEqual(true, testCase.IsDirty(repository, file, read));
testCase.Save(repository, file, read);
Assert.AreEqual(false, testCase.IsDirty(repository, file, read));
}
else
{
var exception = Assert.Throws<InvalidOperationException>(() => repository.IsDirty(new DummySerializable(1)));
Assert.AreEqual("This repository is not tracking dirty.", exception.Message);
}
}
[TestCaseSource(nameof(TestCases))]
public void IsNotDirtyAfterReadOrCreateWhenFileExists(TestCase testCase)
{
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, new DummySerializable(1));
if (repository.Settings.IsTrackingDirty)
{
var read = testCase.ReadOrCreate<DummySerializable>(repository, file, () => throw new AssertionException("Should not get here."));
Assert.AreEqual(false, testCase.IsDirty(repository, file, read));
read.Value++;
Assert.AreEqual(true, testCase.IsDirty(repository, file, read));
testCase.Save(repository, file, read);
Assert.AreEqual(false, testCase.IsDirty(repository, file, read));
}
else
{
var exception = Assert.Throws<InvalidOperationException>(() => repository.IsDirty(new DummySerializable(1)));
Assert.AreEqual("This repository is not tracking dirty.", exception.Message);
}
}
[TestCaseSource(nameof(TestCases))]
public void IsNotDirtyAfterReadOrCreateWhenFileDoesNotExists(TestCase testCase)
{
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
if (repository.Settings.IsTrackingDirty)
{
var read = testCase.ReadOrCreate(repository, file, () => new DummySerializable(1));
Assert.AreEqual(false, testCase.IsDirty(repository, file, read));
read.Value++;
Assert.AreEqual(true, testCase.IsDirty(repository, file, read));
testCase.Save(repository, file, read);
Assert.AreEqual(false, testCase.IsDirty(repository, file, read));
}
else
{
var exception = Assert.Throws<InvalidOperationException>(() => repository.IsDirty(new DummySerializable(1)));
Assert.AreEqual("This repository is not tracking dirty.", exception.Message);
}
}
[TestCaseSource(nameof(TestCases))]
public void ReadWhenNoMigration(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, dummy);
var migration = new NoMigration();
var read = testCase.Read<DummySerializable>(repository, file, migration);
Assert.AreEqual(1, read.Value);
Assert.AreEqual(true, migration.WasCalled);
}
[TestCaseSource(nameof(TestCases))]
public void ReadWhenIdentityMigration(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, dummy);
var migration = new IdentityMigration();
var read = testCase.Read<DummySerializable>(repository, file, migration);
Assert.AreEqual(1, read.Value);
Assert.AreEqual(true, migration.WasCalled);
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenNoMigrationWhenFileExists(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, dummy);
var read = testCase.ReadOrCreate<DummySerializable>(repository, file, () => throw new AssertionException("Should not get here."), new NoMigration());
Assert.AreEqual(1, read.Value);
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenIdentityMigrationWhenFileExists(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
this.Save(file, dummy);
var migration = new IdentityMigration();
var read = testCase.ReadOrCreate<DummySerializable>(repository, file, () => throw new AssertionException("Should not get here."), migration);
Assert.AreEqual(1, read.Value);
Assert.AreEqual(true, migration.WasCalled);
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenNoMigrationWhenFileDoesNotExists(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
var read = testCase.ReadOrCreate(repository, file, () => dummy, new NoMigration());
Assert.AreSame(dummy, read);
}
[TestCaseSource(nameof(TestCases))]
public void ReadOrCreateWhenIdentityMigrationWhenFileDoesNotExists(TestCase testCase)
{
var dummy = new DummySerializable(1);
var repository = this.CreateRepository();
var file = testCase.File<DummySerializable>(repository);
var read = testCase.ReadOrCreate(repository, file, () => dummy, new IdentityMigration());
Assert.AreSame(dummy, read);
}
private class NoMigration : Migration
{
#pragma warning disable SA1401 // Fields should be private
internal bool WasCalled;
#pragma warning restore SA1401 // Fields should be private
public override bool TryUpdate(Stream stream, [NotNullWhen(true)] out Stream? updated)
{
this.WasCalled = true;
updated = null;
return false;
}
}
private class IdentityMigration : Migration
{
#pragma warning disable SA1401 // Fields should be private
internal bool WasCalled;
#pragma warning restore SA1401 // Fields should be private
public override bool TryUpdate(Stream stream, out Stream updated)
{
this.WasCalled = true;
updated = PooledMemoryStream.Borrow();
stream.CopyTo(updated);
updated.Position = 0;
return 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.
namespace MS.Utility
{
using MS.Win32;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
/// <summary>
/// A <see cref="SafeHandle"/> type representing DPI_AWARENESS_CONTEXT values
/// </summary>
/// <remarks>
/// A <see cref="SafeHandle"/> for a pseudo-handle would normally be an overkill. In this instance,
/// it is not quite so. DPI_AWARENESS_CONTEXT handles require extra work to compare, require special
/// work to extract the DPI information from, and need to be converted into an integral form (for e.g.,
/// an enumeration) before it can be transmitted effectively to the renderer. All of this work requires
/// some sort of encapsulation and abstraction. It is easier to do this if the native pseudo-handles are
/// converted into an appropriate class instance from the start.
/// </remarks>
internal partial class DpiAwarenessContextHandle : SafeHandle, IEquatable<IntPtr>, IEquatable<DpiAwarenessContextHandle>, IEquatable<DpiAwarenessContextValue>
{
static DpiAwarenessContextHandle()
{
WellKnownContextValues = new Dictionary<DpiAwarenessContextValue, IntPtr>
{
{ DpiAwarenessContextValue.Unaware, new IntPtr((int)DpiAwarenessContextValue.Unaware) },
{ DpiAwarenessContextValue.SystemAware, new IntPtr((int)DpiAwarenessContextValue.SystemAware) },
{ DpiAwarenessContextValue.PerMonitorAware, new IntPtr((int)DpiAwarenessContextValue.PerMonitorAware) },
{ DpiAwarenessContextValue.PerMonitorAwareVersion2, new IntPtr((int)DpiAwarenessContextValue.PerMonitorAwareVersion2) },
};
DPI_AWARENESS_CONTEXT_UNAWARE =
new DpiAwarenessContextHandle(WellKnownContextValues[DpiAwarenessContextValue.Unaware]);
DPI_AWARENESS_CONTEXT_SYSTEM_AWARE =
new DpiAwarenessContextHandle(WellKnownContextValues[DpiAwarenessContextValue.SystemAware]);
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE =
new DpiAwarenessContextHandle(WellKnownContextValues[DpiAwarenessContextValue.PerMonitorAware]);
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 =
new DpiAwarenessContextHandle(WellKnownContextValues[DpiAwarenessContextValue.PerMonitorAwareVersion2]);
}
/// <summary>
/// Initializes a new instance of the <see cref="DpiAwarenessContextHandle"/> class.
/// </summary>
internal DpiAwarenessContextHandle()
: base(IntPtr.Zero, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DpiAwarenessContextHandle"/> class.
/// </summary>
/// <param name="dpiAwarenessContextValue">Enumeration value equivalent to DPI_AWARENESS_CONTEXT handle value</param>
internal DpiAwarenessContextHandle(DpiAwarenessContextValue dpiAwarenessContextValue)
: base(WellKnownContextValues[dpiAwarenessContextValue], false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DpiAwarenessContextHandle"/> class.
/// </summary>
/// <param name="dpiContext">Handle to DPI Awareness context</param>
internal DpiAwarenessContextHandle(IntPtr dpiContext)
: base(dpiContext, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DpiAwarenessContextHandle"/> class.
/// </summary>
/// <param name="invalidHandleValue">The value of an invalid handle</param>
/// <param name="ownsHandle">Set to true to reliably let SafeHandle release the handle
/// during the finalization phase; otherwise, set to false (not recommended).</param>
/// <remarks>
/// Always set ownsHandle = false. This ensures that the handle will
/// never be attempted to be released, which is just what we need since
/// this is a pseudo-handle.
/// </remarks>
protected DpiAwarenessContextHandle(IntPtr invalidHandleValue, bool ownsHandle)
: base(invalidHandleValue, false)
{
}
/// <inheritdoc/>
public override bool IsInvalid
{
get
{
// This is a pseudo-handle. Always
// returning true will ensure that
// critical-finalization will be avoided
return true;
}
}
/// <summary>
/// Gets DPI_AWARENESS_CONTEST_UNAWARE
/// </summary>
internal static DpiAwarenessContextHandle DPI_AWARENESS_CONTEXT_UNAWARE { get; }
/// <summary>
/// Gets DPI_AWARENESS_CONTEXT_SYSTEM_AWARE
/// </summary>
internal static DpiAwarenessContextHandle DPI_AWARENESS_CONTEXT_SYSTEM_AWARE { get; }
/// <summary>
/// Gets DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE
/// </summary>
internal static DpiAwarenessContextHandle DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE { get; }
/// <summary>
/// Gets DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
/// </summary>
internal static DpiAwarenessContextHandle DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 { get; }
/// <summary>
/// Gets map of well-known DPI awareness context handles
/// </summary>
private static Dictionary<DpiAwarenessContextValue, IntPtr> WellKnownContextValues { get; }
/// <summary>
/// Conversion to DpiAwarenessContextValue
/// </summary>
/// <param name="dpiAwarenessContextHandle">Handle being converted</param>
public static explicit operator DpiAwarenessContextValue(DpiAwarenessContextHandle dpiAwarenessContextHandle)
{
foreach (DpiAwarenessContextValue dpiContextValue in Enum.GetValues(typeof(DpiAwarenessContextValue)))
{
if (dpiContextValue != DpiAwarenessContextValue.Invalid)
{
if (dpiAwarenessContextHandle.Equals(dpiContextValue))
{
return dpiContextValue;
}
}
}
return DpiAwarenessContextValue.Invalid;
}
/// <summary>
/// Equality comparison
/// </summary>
/// <param name="dpiContextHandle">DPI context being compared against</param>
/// <returns>True if equivalent to the other DPI context, otherwise False</returns>
public bool Equals(DpiAwarenessContextHandle dpiContextHandle)
{
return SafeNativeMethods.AreDpiAwarenessContextsEqual(this.DangerousGetHandle(), dpiContextHandle.DangerousGetHandle());
}
/// <summary>
/// Equality comparison
/// </summary>
/// <param name="dpiContext">DPI Context being compared against</param>
/// <returns>True if equivalent to the other DPI context, otherwise False</returns>
public bool Equals(IntPtr dpiContext)
{
return DpiUtil.AreDpiAwarenessContextsEqual(this.DangerousGetHandle(), dpiContext);
}
/// <summary>
/// Equality comparison
/// </summary>
/// <param name="dpiContextEnumValue">DPI context enumeration value being compared against</param>
/// <returns>True if equivalent to the DPI context enum value, otherwise False</returns>
public bool Equals(DpiAwarenessContextValue dpiContextEnumValue)
{
return this.Equals(WellKnownContextValues[dpiContextEnumValue]);
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj is IntPtr)
{
return this.Equals((IntPtr)obj);
}
else if (obj is DpiAwarenessContextHandle)
{
return this.Equals((DpiAwarenessContextHandle)obj);
}
else if (obj is DpiAwarenessContextValue)
{
return this.Equals((DpiAwarenessContextValue)obj);
}
else
{
return base.Equals(obj);
}
}
/// <inheritdoc/>
public override int GetHashCode()
{
return ((DpiAwarenessContextValue)this).GetHashCode();
}
/// <inheritdoc />
protected override bool ReleaseHandle()
{
// Nothing to release - just return true
// This will never get called
// because the handle is marked as invalid
// as soon as it is created
return true;
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using Rotorz.Games.EditorExtensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Serialization;
namespace Rotorz.Tile.Editor
{
/// <summary>
/// Project wide settings.
/// </summary>
public sealed class ProjectSettings : ScriptableObject, ISerializationCallbackReceiver
{
#region Singleton
private static string ProjectSettingsAssetPath {
get { return PackageUtility.GetDataAssetPath("@rotorz/unity3d-tile-system", null, "ProjectSettings.asset"); }
}
private static ProjectSettings s_Instance;
/// <summary>
/// Gets the <see cref="ProjectSettings"/> instance.
/// </summary>
/// <remarks>
/// <para>The <see cref="ProjectSettings"/> asset is automatically created if it
/// does not already exist.</para>
/// <para>This asset is located inside at the following path in your project
/// "Assets/Rotorz/User Data/Tile System/Project Settings.asset".</para>
/// </remarks>
public static ProjectSettings Instance {
get {
if (s_Instance == null) {
SetupInstance();
}
return s_Instance;
}
}
private static void SetupInstance()
{
s_Instance = LoadAsset();
if (s_Instance == null) {
s_Instance = CreateAsset();
}
}
private static ProjectSettings LoadAsset()
{
return AssetDatabase.LoadAssetAtPath(ProjectSettingsAssetPath, typeof(ProjectSettings)) as ProjectSettings;
}
private static ProjectSettings CreateAsset()
{
// Do not proceed if the project settings asset file already exists!
string absoluteFilePath = Path.Combine(Directory.GetCurrentDirectory(), ProjectSettingsAssetPath);
if (File.Exists(absoluteFilePath)) {
// It looks like the project settings asset may already exist.
Debug.LogError(string.Format("Cannot create project settings asset because file already exists: '{0}'\nTry to reimport <color=red>TileSystem.Editor.dll</color> by right-clicking it in the <color=red>Project</color> window and then selecting <color=red>Reimport</color>.", ProjectSettingsAssetPath));
return null;
}
var instance = CreateInstance<ProjectSettings>();
AssetDatabase.CreateAsset(instance, ProjectSettingsAssetPath);
AssetDatabase.Refresh();
return instance;
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="ProjectSettings"/> class.
/// </summary>
public ProjectSettings()
{
this.InitializeFlagLabels();
}
#region ISerializationCallbackReceiver Members
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
this.categoryMap.Clear();
foreach (var info in this.categories) {
// Automatically fix newly added category identifiers.
if (info.Id == 0 || this.categoryMap.ContainsKey(info.Id)) {
info.Id = this.NextUniqueId();
}
// Sanitize category labels.
info.Label = CategoryLabelUtility.SanitizeCategoryLabel(info.Label);
this.categoryMap[info.Id] = info;
}
// Category 0 is not allowed!
if (this.categoryMap.ContainsKey(0)) {
this.DeleteCategory(0);
}
++this.CategoryRevisionCounter;
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
}
#endregion
#region Brush Creator
[SerializeField, FormerlySerializedAs("_brushesFolderRelativePath")]
private string brushesFolderRelativePath;
/// <summary>
/// Gets or sets path of the folder where new brushes and tilesets are created
/// relative to the 'Assets' folder. This must be a sub-folder somewhere inside
/// 'Assets'.
/// </summary>
/// <example>
/// <para>Reset to the default path:</para>
/// <code language="csharp"><![CDATA[
/// var projectSettings = ProjectSettings.Instance;
/// projectSettings.BrushesFolderAssetPath = "Plugins/PackageData/@rotorz/unity3d-tile-system/Brushes";
/// EditorUtility.SetDirty(projectSettings);
/// ]]></code>
/// </example>
/// <exception cref="System.ArgumentNullException">
/// If <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If <paramref name="value"/> is an invalid path.
/// </exception>
/// <seealso cref="BrushUtility.GetBrushAssetPath()"/>
public string BrushesFolderRelativePath {
get {
if (!string.IsNullOrEmpty(this.brushesFolderRelativePath)) {
try {
return SanitizeBrushesFolderRelativePath(this.brushesFolderRelativePath);
}
catch (Exception ex) {
Debug.LogError("Path to brushes folder was invalid (see below); reverting to default.");
Debug.LogException(ex);
}
}
// Assume the default path for creating brushes and tilesets.
this.brushesFolderRelativePath = GetDefaultBrushesFolderRelativePath();
EditorUtility.SetDirty(this);
return this.brushesFolderRelativePath;
}
set {
this.brushesFolderRelativePath = SanitizeBrushesFolderRelativePath(value);
}
}
private static string GetDefaultBrushesFolderRelativePath()
{
return AssetPathUtility.ConvertToAssetsRelativePath(PackageUtility.ResolveDataAssetPath("@rotorz/unity3d-tile-system", "Brushes"));
}
private static string SanitizeBrushesFolderRelativePath(string value)
{
if (value == null) {
throw new ArgumentNullException("value");
}
if (value.Contains("/../") || value.StartsWith("../")) {
throw new ArgumentException("Path contains invalid characters.", "value");
}
// Remove trailing slash for consistency.
return value.TrimEnd('/');
}
#endregion
#region Tileset Creator
[SerializeField, FormerlySerializedAs("_expandTilesetCreatorSection")]
private bool expandTilesetCreatorSection;
[SerializeField, FormerlySerializedAs("_opaqueTilesetMaterialTemplate")]
private Material opaqueTilesetMaterialTemplate;
[SerializeField, FormerlySerializedAs("_transparentTilesetMaterialTemplate")]
private Material transparentTilesetMaterialTemplate;
/// <summary>
/// Gets or sets a value indicating whether the "Tileset Creator" section of the
/// project settings inspector is expanded.
/// </summary>
public bool ExpandTilesetCreatorSection {
get { return this.expandTilesetCreatorSection; }
set { this.expandTilesetCreatorSection = value; }
}
/// <summary>
/// Gets or sets the material that will be used as a template when new opaque
/// tileset materials are created. A value of <c>null</c> specifies that the
/// default is to be assumed.
/// </summary>
public Material OpaqueTilesetMaterialTemplate {
get { return this.opaqueTilesetMaterialTemplate; }
set {
if (this.opaqueTilesetMaterialTemplate == value) {
return;
}
this.opaqueTilesetMaterialTemplate = value;
EditorUtility.SetDirty(this);
}
}
/// <summary>
/// Gets or sets the material that will be used as a template when new transparent
/// tileset materials are created. A value of <c>null</c> specifies that the
/// default is to be assumed.
/// </summary>
public Material TransparentTilesetMaterialTemplate {
get { return this.transparentTilesetMaterialTemplate; }
set {
if (this.transparentTilesetMaterialTemplate == value) {
return;
}
this.transparentTilesetMaterialTemplate = value;
EditorUtility.SetDirty(this);
}
}
#endregion
#region Brush Categories
/// <summary>
/// The value of this counter increments when category changes are detected.
/// </summary>
public int CategoryRevisionCounter { get; private set; }
[SerializeField, FormerlySerializedAs("_expandBrushCategoriesSection")]
private bool expandBrushCategoriesSection;
[SerializeField, FormerlySerializedAs("_showCategoryIds")]
private bool showCategoryIds;
[SerializeField, FormerlySerializedAs("_categories")]
private List<BrushCategoryInfo> categories = new List<BrushCategoryInfo>();
[SerializeField, FormerlySerializedAs("_nextCategoryId")]
private int nextCategoryId = 1;
[NonSerialized]
private Dictionary<int, BrushCategoryInfo> categoryMap = new Dictionary<int, BrushCategoryInfo>();
/// <summary>
/// Gets or sets a value indicating whether the "Brush Categories" section of the
/// project settings inspector is expanded.
/// </summary>
public bool ExpandBrushCategoriesSection {
get { return this.expandBrushCategoriesSection; }
set { this.expandBrushCategoriesSection = value; }
}
/// <summary>
/// Gets or sets whether category identifiers are shown in the inspector.
/// </summary>
internal bool ShowCategoryIds {
get { return this.showCategoryIds; }
set { this.showCategoryIds = value; }
}
internal BrushCategoryInfo[] Categories {
get { return this.categories.ToArray(); }
}
/// <summary>
/// Gets the collection of brush category ids.
/// </summary>
public int[] CategoryIds {
get { return this.categories.Select(info => info.Id).ToArray(); }
}
/// <summary>
/// Gets the collection of brush category labels.
/// </summary>
public string[] CategoryLabels {
get { return this.categories.Select(info => info.Label).ToArray(); }
}
private int NextUniqueId()
{
while (++this.nextCategoryId < int.MaxValue) {
if (!this.categoryMap.ContainsKey(this.nextCategoryId)) {
return this.nextCategoryId;
}
}
// Ran out of unique id's REALLY?!
// Okay... start from zero again.
this.nextCategoryId = 0;
while (++this.nextCategoryId < int.MaxValue) {
if (!this.categoryMap.ContainsKey(this.nextCategoryId)) {
return this.nextCategoryId;
}
}
// User is crazy having so many categories!
throw new InvalidOperationException("Cannot allocate new category id.");
}
/// <summary>
/// Adds a new brush category.
/// </summary>
/// <param name="label">Label for category.</param>
/// <returns>
/// The unique category identifier.
/// </returns>
/// <exception cref="System.ArgumentNullException">
/// If <paramref name="label"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If <paramref name="label"/> is an empty string.
/// </exception>
/// <seealso cref="SetCategoryLabel(int, string)"/>
public int AddCategory(string label)
{
if (label == null) {
throw new ArgumentNullException("label");
}
if (label == "") {
throw new ArgumentException("Was empty.", "label");
}
Undo.RecordObject(this, TileLang.ParticularText("Action", "Add Category"));
var info = new BrushCategoryInfo(this.NextUniqueId(), label);
this.categories.Add(info);
EditorUtility.SetDirty(this);
this.categoryMap[info.Id] = info;
++this.CategoryRevisionCounter;
return info.Id;
}
/// <summary>
/// Sets label of a specific category.
/// </summary>
/// <param name="id">Identifies the category.</param>
/// <param name="label">The new category label.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If <paramref name="id"/> is zero or a negative value.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If <paramref name="label"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If <paramref name="label"/> is an empty string.
/// </exception>
/// <seealso cref="AddCategory(string)"/>
public void SetCategoryLabel(int id, string label)
{
if (id <= 0) {
throw new ArgumentOutOfRangeException("id", id, (string)null);
}
if (label == null) {
throw new ArgumentNullException("label");
}
if (label == "") {
throw new ArgumentException("Was empty.", "label");
}
Undo.RecordObject(this, TileLang.ParticularText("Action", "Set Category Label"));
BrushCategoryInfo info;
if (!this.categoryMap.TryGetValue(id, out info)) {
info = new BrushCategoryInfo(id);
this.categories.Add(info);
this.categoryMap[id] = info;
}
info.Label = label;
EditorUtility.SetDirty(this);
++this.CategoryRevisionCounter;
}
/// <summary>
/// Deletes an unwanted brush category.
/// </summary>
/// <param name="id">Identifies the category.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If <paramref name="id"/> is zero or a negative value.
/// </exception>
public void DeleteCategory(int id)
{
if (id <= 0) {
throw new ArgumentOutOfRangeException("id", id, (string)null);
}
int index = this.categories.FindIndex(info => info.Id == id);
if (index != -1) {
Undo.RecordObject(this, TileLang.ParticularText("Action", "Delete Category"));
this.categories.RemoveAt(index);
EditorUtility.SetDirty(this);
this.categoryMap.Remove(id);
++this.CategoryRevisionCounter;
}
}
/// <summary>
/// Gets label of a specific category.
/// </summary>
/// <param name="id">Identifies the category.</param>
/// <returns>
/// The category label.
/// </returns>
public string GetCategoryLabel(int id)
{
if (id == 0) {
return TileLang.ParticularText("Status", "Uncategorized");
}
BrushCategoryInfo info;
if (this.categoryMap.TryGetValue(id, out info)) {
return info.Label ?? "";
}
else {
return TileLang.ParticularText("Status", "(Unknown Category)");
}
}
/// <summary>
/// Sorts brush categories by label either ascending or descending.
/// </summary>
/// <param name="ascending">A value of <c>true</c> indicates that categories
/// should be sorted in ascending order; otherwise, categories will be sorted
/// in descending order.</param>
public void SortCategoriesByLabel(bool ascending)
{
Undo.RecordObject(this, TileLang.ParticularText("Action", "Sort Categories"));
var comparer = Comparer<string>.Default;
if (ascending) {
this.categories.Sort((a, b) => comparer.Compare(a.Label, b.Label));
}
else {
this.categories.Sort((a, b) => comparer.Compare(b.Label, a.Label));
}
EditorUtility.SetDirty(this);
}
#endregion
#region Flag Labels
[SerializeField, FormerlySerializedAs("_flagLabels")]
private string[] flagLabels;
private void InitializeFlagLabels()
{
// Initialize flag labels array with empty strings.
this.flagLabels = new string[16];
for (int i = 0; i < 16; ++i) {
this.flagLabels[i] = "";
}
}
/// <summary>
/// Gets or sets the collection of labels for the 16 general purpose brush flags.
/// </summary>
/// <exception cref="System.ArgumentNullException">
/// If <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If <paramref name="value"/> does not contain 16 strings.
/// </exception>
public string[] FlagLabels {
get { return this.flagLabels.ToArray(); }
set {
if (value == null) {
throw new ArgumentNullException("value");
}
if (value.Length != 16) {
throw new ArgumentException("Must contain 16 flag labels.", "value");
}
Undo.RecordObject(this, TileLang.ParticularText("Action", "Update Flag Labels"));
for (int i = 0; i < value.Length; ++i) {
string newLabel = value[i];
this.flagLabels[i] = newLabel != null ? newLabel.Trim() : "";
}
EditorUtility.SetDirty(this);
}
}
#endregion
/// <summary>
/// Collapses all expandable sections in project settings inspector.
/// </summary>
public void CollapseAllSections()
{
this.ExpandTilesetCreatorSection = false;
this.ExpandBrushCategoriesSection = false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Represents an Azure Batch JobManager task.
/// </summary>
/// <remarks>
/// Batch will retry tasks when a recovery operation is triggered on a compute node. Examples of recovery operations
/// include (but are not limited to) when an unhealthy compute node is rebooted or a compute node disappeared due to
/// host failure. Retries due to recovery operations are independent of and are not counted against the <see cref="TaskConstraints.MaxTaskRetryCount"
/// />. Even if the <see cref="TaskConstraints.MaxTaskRetryCount" /> is 0, an internal retry due to a recovery operation
/// may occur. Because of this, all tasks should be idempotent. This means tasks need to tolerate being interrupted and
/// restarted without causing any corruption or duplicate data. The best practice for long running tasks is to use some
/// form of checkpointing.
/// </remarks>
public partial class JobManagerTask : ITransportObjectProvider<Models.JobManagerTask>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<bool?> AllowLowPriorityNodeProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty;
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<TaskContainerSettings> ContainerSettingsProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<bool?> KillJobOnCompletionProperty;
public readonly PropertyAccessor<IList<OutputFile>> OutputFilesProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<bool?> RunExclusiveProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AllowLowPriorityNodeProperty = this.CreatePropertyAccessor<bool?>(nameof(AllowLowPriorityNode), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>(nameof(AuthenticationTokenSettings), BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor<string>(nameof(CommandLine), BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor<TaskContainerSettings>(nameof(ContainerSettings), BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.KillJobOnCompletionProperty = this.CreatePropertyAccessor<bool?>(nameof(KillJobOnCompletion), BindingAccess.Read | BindingAccess.Write);
this.OutputFilesProperty = this.CreatePropertyAccessor<IList<OutputFile>>(nameof(OutputFiles), BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>(nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write);
this.RunExclusiveProperty = this.CreatePropertyAccessor<bool?>(nameof(RunExclusive), BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>(nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.JobManagerTask protocolObject) : base(BindingState.Bound)
{
this.AllowLowPriorityNodeProperty = this.CreatePropertyAccessor(
protocolObject.AllowLowPriorityNode,
nameof(AllowLowPriorityNode),
BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o)),
nameof(AuthenticationTokenSettings),
BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
nameof(CommandLine),
BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
nameof(Constraints),
BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerSettings, o => new TaskContainerSettings(o).Freeze()),
nameof(ContainerSettings),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings),
nameof(EnvironmentSettings),
BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read | BindingAccess.Write);
this.KillJobOnCompletionProperty = this.CreatePropertyAccessor(
protocolObject.KillJobOnCompletion,
nameof(KillJobOnCompletion),
BindingAccess.Read | BindingAccess.Write);
this.OutputFilesProperty = this.CreatePropertyAccessor(
OutputFile.ConvertFromProtocolCollection(protocolObject.OutputFiles),
nameof(OutputFiles),
BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles),
nameof(ResourceFiles),
BindingAccess.Read | BindingAccess.Write);
this.RunExclusiveProperty = this.CreatePropertyAccessor(
protocolObject.RunExclusive,
nameof(RunExclusive),
BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o)),
nameof(UserIdentity),
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JobManagerTask"/> class.
/// </summary>
/// <param name='id'>The id of the task.</param>
/// <param name='commandLine'>The command line of the task.</param>
public JobManagerTask(
string id,
string commandLine)
{
this.propertyContainer = new PropertyContainer();
this.Id = id;
this.CommandLine = commandLine;
}
internal JobManagerTask(Models.JobManagerTask protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region JobManagerTask
/// <summary>
/// Gets or sets whether the Job Manager task may run on a low-priority compute node. If omitted, the default is
/// true.
/// </summary>
public bool? AllowLowPriorityNode
{
get { return this.propertyContainer.AllowLowPriorityNodeProperty.Value; }
set { this.propertyContainer.AllowLowPriorityNodeProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running
/// the command line.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the settings for an authentication token that the task can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with an authentication token which can be used to
/// authenticate Batch service operations without requiring an account access key. The token is provided via the
/// AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token
/// depend on the settings. For example, a task can request job permissions in order to add other tasks to the job,
/// or check the status of the job or of other tasks.
/// </remarks>
public AuthenticationTokenSettings AuthenticationTokenSettings
{
get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; }
set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. If the command line
/// refers to file paths, it should use a relative path (relative to the task working directory), or use the Batch
/// provided environment variables (https://docs.microsoft.com/en-us/azure/batch/batch-compute-node-environment-variables).
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets or sets the execution constraints for this JobManager task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the settings for the container under which the task runs.
/// </summary>
/// <remarks>
/// If the pool that will run this task has <see cref="VirtualMachineConfiguration.ContainerConfiguration"/> set,
/// this must be set as well. If the pool that will run this task doesn't have <see cref="VirtualMachineConfiguration.ContainerConfiguration"/>
/// set, this must not be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR
/// (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables
/// are mapped into the container, and the task command line is executed in the container. Files produced in the
/// container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file
/// APIs will not be able to access them.
/// </remarks>
public TaskContainerSettings ContainerSettings
{
get { return this.propertyContainer.ContainerSettingsProperty.Value; }
set { this.propertyContainer.ContainerSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name of the JobManager task.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets a set of environment settings for the JobManager task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets a value that indicates whether to terminate all tasks in the job and complete the job when the job
/// manager task completes.
/// </summary>
public bool? KillJobOnCompletion
{
get { return this.propertyContainer.KillJobOnCompletionProperty.Value; }
set { this.propertyContainer.KillJobOnCompletionProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will upload from the compute node after running the command
/// line.
/// </summary>
public IList<OutputFile> OutputFiles
{
get { return this.propertyContainer.OutputFilesProperty.Value; }
set
{
this.propertyContainer.OutputFilesProperty.Value = ConcurrentChangeTrackedModifiableList<OutputFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
/// <remarks>
/// There is a maximum size for the list of resource files. When the max size is exceeded, the request will fail
/// and the response error code will be RequestEntityTooLarge. If this occurs, the collection of resource files must
/// be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers.
/// </remarks>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the Job Manager task requires exclusive use of the compute node where it runs.
/// </summary>
public bool? RunExclusive
{
get { return this.propertyContainer.RunExclusiveProperty.Value; }
set { this.propertyContainer.RunExclusiveProperty.Value = value; }
}
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to the task.
/// </remarks>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
#endregion // JobManagerTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobManagerTask ITransportObjectProvider<Models.JobManagerTask>.GetTransportObject()
{
Models.JobManagerTask result = new Models.JobManagerTask()
{
AllowLowPriorityNode = this.AllowLowPriorityNode,
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()),
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
ContainerSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerSettings, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
Id = this.Id,
KillJobOnCompletion = this.KillJobOnCompletion,
OutputFiles = UtilitiesInternal.ConvertToProtocolCollection(this.OutputFiles),
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
RunExclusive = this.RunExclusive,
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
namespace Microsoft.AspNetCore.Components.Forms
{
/// <summary>
/// A base class for form input components. This base class automatically
/// integrates with an <see cref="Forms.EditContext"/>, which must be supplied
/// as a cascading parameter.
/// </summary>
public abstract class InputBase<TValue> : ComponentBase, IDisposable
{
private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
private bool _hasInitializedParameters;
private bool _previousParsingAttemptFailed;
private ValidationMessageStore? _parsingValidationMessages;
private Type? _nullableUnderlyingType;
[CascadingParameter] private EditContext? CascadedEditContext { get; set; }
/// <summary>
/// Gets or sets a collection of additional attributes that will be applied to the created element.
/// </summary>
[Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; }
/// <summary>
/// Gets or sets the value of the input. This should be used with two-way binding.
/// </summary>
/// <example>
/// @bind-Value="model.PropertyName"
/// </example>
[Parameter]
public TValue? Value { get; set; }
/// <summary>
/// Gets or sets a callback that updates the bound value.
/// </summary>
[Parameter] public EventCallback<TValue> ValueChanged { get; set; }
/// <summary>
/// Gets or sets an expression that identifies the bound value.
/// </summary>
[Parameter] public Expression<Func<TValue>>? ValueExpression { get; set; }
/// <summary>
/// Gets or sets the display name for this field.
/// <para>This value is used when generating error messages when the input value fails to parse correctly.</para>
/// </summary>
[Parameter] public string? DisplayName { get; set; }
/// <summary>
/// Gets the associated <see cref="Forms.EditContext"/>.
/// This property is uninitialized if the input does not have a parent <see cref="EditForm"/>.
/// </summary>
protected EditContext EditContext { get; set; } = default!;
/// <summary>
/// Gets the <see cref="FieldIdentifier"/> for the bound value.
/// </summary>
protected internal FieldIdentifier FieldIdentifier { get; set; }
/// <summary>
/// Gets or sets the current value of the input.
/// </summary>
protected TValue? CurrentValue
{
get => Value;
set
{
var hasChanged = !EqualityComparer<TValue>.Default.Equals(value, Value);
if (hasChanged)
{
Value = value;
_ = ValueChanged.InvokeAsync(Value);
EditContext?.NotifyFieldChanged(FieldIdentifier);
}
}
}
/// <summary>
/// Gets or sets the current value of the input, represented as a string.
/// </summary>
protected string? CurrentValueAsString
{
get => FormatValueAsString(CurrentValue);
set
{
_parsingValidationMessages?.Clear();
bool parsingFailed;
if (_nullableUnderlyingType != null && string.IsNullOrEmpty(value))
{
// Assume if it's a nullable type, null/empty inputs should correspond to default(T)
// Then all subclasses get nullable support almost automatically (they just have to
// not reject Nullable<T> based on the type itself).
parsingFailed = false;
CurrentValue = default!;
}
else if (TryParseValueFromString(value, out var parsedValue, out var validationErrorMessage))
{
parsingFailed = false;
CurrentValue = parsedValue!;
}
else
{
parsingFailed = true;
// EditContext may be null if the input is not a child component of EditForm.
if (EditContext is not null)
{
_parsingValidationMessages ??= new ValidationMessageStore(EditContext);
_parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage);
// Since we're not writing to CurrentValue, we'll need to notify about modification from here
EditContext.NotifyFieldChanged(FieldIdentifier);
}
}
// We can skip the validation notification if we were previously valid and still are
if (parsingFailed || _previousParsingAttemptFailed)
{
EditContext?.NotifyValidationStateChanged();
_previousParsingAttemptFailed = parsingFailed;
}
}
}
/// <summary>
/// Constructs an instance of <see cref="InputBase{TValue}"/>.
/// </summary>
protected InputBase()
{
_validationStateChangedHandler = OnValidateStateChanged;
}
/// <summary>
/// Formats the value as a string. Derived classes can override this to determine the formating used for <see cref="CurrentValueAsString"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <returns>A string representation of the value.</returns>
protected virtual string? FormatValueAsString(TValue? value)
=> value?.ToString();
/// <summary>
/// Parses a string to create an instance of <typeparamref name="TValue"/>. Derived classes can override this to change how
/// <see cref="CurrentValueAsString"/> interprets incoming values.
/// </summary>
/// <param name="value">The string value to be parsed.</param>
/// <param name="result">An instance of <typeparamref name="TValue"/>.</param>
/// <param name="validationErrorMessage">If the value could not be parsed, provides a validation error message.</param>
/// <returns>True if the value could be parsed; otherwise false.</returns>
protected abstract bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage);
/// <summary>
/// Gets a CSS class string that combines the <c>class</c> attribute and and a string indicating
/// the status of the field being edited (a combination of "modified", "valid", and "invalid").
/// Derived components should typically use this value for the primary HTML element's 'class' attribute.
/// </summary>
protected string CssClass
{
get
{
var fieldClass = EditContext?.FieldCssClass(FieldIdentifier) ?? string.Empty;
return AttributeUtilities.CombineClassNames(AdditionalAttributes, fieldClass);
}
}
/// <inheritdoc />
public override Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (!_hasInitializedParameters)
{
// This is the first run
// Could put this logic in OnInit, but its nice to avoid forcing people who override OnInit to call base.OnInit()
if (ValueExpression == null)
{
throw new InvalidOperationException($"{GetType()} requires a value for the 'ValueExpression' " +
$"parameter. Normally this is provided automatically when using 'bind-Value'.");
}
FieldIdentifier = FieldIdentifier.Create(ValueExpression);
if (CascadedEditContext != null)
{
EditContext = CascadedEditContext;
EditContext.OnValidationStateChanged += _validationStateChangedHandler;
}
_nullableUnderlyingType = Nullable.GetUnderlyingType(typeof(TValue));
_hasInitializedParameters = true;
}
else if (CascadedEditContext != EditContext)
{
// Not the first run
// We don't support changing EditContext because it's messy to be clearing up state and event
// handlers for the previous one, and there's no strong use case. If a strong use case
// emerges, we can consider changing this.
throw new InvalidOperationException($"{GetType()} does not support changing the " +
$"{nameof(Forms.EditContext)} dynamically.");
}
UpdateAdditionalValidationAttributes();
// For derived components, retain the usual lifecycle with OnInit/OnParametersSet/etc.
return base.SetParametersAsync(ParameterView.Empty);
}
private void OnValidateStateChanged(object? sender, ValidationStateChangedEventArgs eventArgs)
{
UpdateAdditionalValidationAttributes();
StateHasChanged();
}
private void UpdateAdditionalValidationAttributes()
{
if (EditContext is null)
{
return;
}
var hasAriaInvalidAttribute = AdditionalAttributes != null && AdditionalAttributes.ContainsKey("aria-invalid");
if (EditContext.GetValidationMessages(FieldIdentifier).Any())
{
if (hasAriaInvalidAttribute)
{
// Do not overwrite the attribute value
return;
}
if (ConvertToDictionary(AdditionalAttributes, out var additionalAttributes))
{
AdditionalAttributes = additionalAttributes;
}
// To make the `Input` components accessible by default
// we will automatically render the `aria-invalid` attribute when the validation fails
// value must be "true" see https://www.w3.org/TR/wai-aria-1.1/#aria-invalid
additionalAttributes["aria-invalid"] = "true";
}
else if (hasAriaInvalidAttribute)
{
// No validation errors. Need to remove `aria-invalid` if it was rendered already
if (AdditionalAttributes!.Count == 1)
{
// Only aria-invalid argument is present which we don't need any more
AdditionalAttributes = null;
}
else
{
if (ConvertToDictionary(AdditionalAttributes, out var additionalAttributes))
{
AdditionalAttributes = additionalAttributes;
}
additionalAttributes.Remove("aria-invalid");
}
}
}
/// <summary>
/// Returns a dictionary with the same values as the specified <paramref name="source"/>.
/// </summary>
/// <returns>true, if a new dictrionary with copied values was created. false - otherwise.</returns>
private bool ConvertToDictionary(IReadOnlyDictionary<string, object>? source, out Dictionary<string, object> result)
{
var newDictionaryCreated = true;
if (source == null)
{
result = new Dictionary<string, object>();
}
else if (source is Dictionary<string, object> currentDictionary)
{
result = currentDictionary;
newDictionaryCreated = false;
}
else
{
result = new Dictionary<string, object>();
foreach (var item in source)
{
result.Add(item.Key, item.Value);
}
}
return newDictionaryCreated;
}
/// <inheritdoc/>
protected virtual void Dispose(bool disposing)
{
}
void IDisposable.Dispose()
{
// When initialization in the SetParametersAsync method fails, the EditContext property can remain equal to null
if (EditContext is not null)
{
EditContext.OnValidationStateChanged -= _validationStateChangedHandler;
}
Dispose(disposing: 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 OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
////////////////////////////////////////////////////////////////
// Module
//
////////////////////////////////////////////////////////////////
[TestModule(Name = "Name Table", Desc = "Test for Get and Add methods")]
public partial class CNameTableTestModule : CTestModule
{
//Accessors
private string _TestData = null;
public string TestData
{
get
{
return _TestData;
}
}
public override int Init(object objParam)
{
int ret = base.Init(objParam);
_TestData = Path.Combine(FilePathUtil.GetTestDataPath(), @"XmlReader");
// Create global usage test files
string strFile = String.Empty;
NameTable_TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC);
return ret;
}
public override int Terminate(object objParam)
{
return base.Terminate(objParam);
}
}
////////////////////////////////////////////////////////////////
// TestCase TCBase
//
////////////////////////////////////////////////////////////////
public partial class TCBase : CTestCase
{
public enum ENAMETABLE_VER
{
VERIFY_WITH_GETSTR,
VERIFY_WITH_GETCHAR,
VERIFY_WITH_ADDSTR,
VERIFY_WITH_ADDCHAR,
};
private ENAMETABLE_VER _eNTVer;
public ENAMETABLE_VER NameTableVer
{
get { return _eNTVer; }
set { _eNTVer = value; }
}
public static string WRONG_EXCEPTION = "Catching Wrong Exception";
protected static string BigStr = new String('Z', (1 << 20) - 1);
protected XmlReader DataReader;
public override int Init(object objParam)
{
if (GetDescription() == "VerifyWGetString")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETSTR;
}
else if (GetDescription() == "VerifyWGetChar")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETCHAR;
}
else if (GetDescription() == "VerifyWAddString")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDSTR;
}
else if (GetDescription() == "VerifyWAddChar")
{
NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDCHAR;
}
else
throw (new Exception());
int ival = base.Init(objParam);
ReloadSource();
if (TEST_PASS == ival)
{
while (DataReader.Read() == true) ;
}
return ival;
}
protected void ReloadSource()
{
if (DataReader != null)
{
DataReader.Dispose();
}
string strFile = NameTable_TestFiles.GetTestFileName(EREADER_TYPE.GENERIC);
DataReader = XmlReader.Create(FilePathUtil.getStream(strFile), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore });//new XmlTextReader(strFile);
}
public void VerifyNameTable(object objActual, string str, char[] ach, int offset, int length)
{
VerifyNameTableGet(objActual, str, ach, offset, length);
VerifyNameTableAdd(objActual, str, ach, offset, length);
}
public void VerifyNameTableGet(object objActual, string str, char[] ach, int offset, int length)
{
object objExpected = null;
if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETSTR)
{
objExpected = DataReader.NameTable.Get(str);
CError.WriteLine("VerifyNameTableWGetStr");
CError.Compare(objActual, objExpected, "VerifyNameTableWGetStr");
}
else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETCHAR)
{
objExpected = DataReader.NameTable.Get(ach, offset, length);
CError.WriteLine("VerifyNameTableWGetChar");
CError.Compare(objActual, objExpected, "VerifyNameTableWGetChar");
}
}
public void VerifyNameTableAdd(object objActual, string str, char[] ach, int offset, int length)
{
object objExpected = null;
if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDSTR)
{
objExpected = DataReader.NameTable.Add(ach, offset, length);
CError.WriteLine("VerifyNameTableWAddStr");
CError.Compare(objActual, objExpected, "VerifyNameTableWAddStr");
}
else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDCHAR)
{
objExpected = DataReader.NameTable.Add(str);
CError.WriteLine("VerifyNameTableWAddChar");
CError.Compare(objActual, objExpected, "VerifyNameTableWAddChar");
}
}
}
////////////////////////////////////////////////////////////////
// TestCase TCRecord NameTable.Get
//
////////////////////////////////////////////////////////////////
//[TestCase(Name="NameTable(Get) VerifyWGetChar", Desc="VerifyWGetChar")]
//[TestCase(Name="NameTable(Get) VerifyWGetString", Desc="VerifyWGetString")]
//[TestCase(Name="NameTable(Get) VerifyWAddString", Desc="VerifyWAddString")]
//[TestCase(Name="NameTable(Get) VerifyWAddChar", Desc="VerifyWAddChar")]
public partial class TCRecordNameTableGet : TCBase
{
public static char[] chInv = { 'U', 'n', 'a', 't', 'o', 'm', 'i', 'z', 'e', 'd' };
public static char[] chVal = { 'P', 'L', 'A', 'Y' };
public static char[] chValW1EndExtra = { 'P', 'L', 'A', 'Y', 'Y' };
public static char[] chValW1FrExtra = { 'P', 'P', 'L', 'A', 'Y' };
public static char[] chValW1Fr1EndExtra = { 'P', 'P', 'L', 'A', 'Y', 'Y' };
public static char[] chValWEndExtras = { 'P', 'L', 'A', 'Y', 'Y', 'Y' };
public static char[] chValWFrExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y' };
public static char[] chValWFrEndExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y', 'Y', 'Y' };
public static string[] strPerVal =
{
"PLYA", "PALY", "PAYL", "PYLA", "PYAL",
"LPAY", "LPYA", "LAPY", "LAYP", "LYPA", "LYAP",
"ALPY", "ALYP", "APLY", "APYL", "AYLP", "AYPL",
"YLPA", "YLAP", "YPLA", "YPAL", "YALP", "YAPL",
};
public static string[] strPerValCase =
{
"pLAY", "plAY", "plaY", "play",
"plAY", "plaY",
"pLaY", "pLay",
"pLAy",
"PlAY", "PlaY", "Play",
"PLaY",
"PLAy"
};
public static string strInv = "Unatomized";
public static string strVal = "PLAY";
[Variation("GetUnAutomized", Pri = 0)]
public int Variation_1()
{
object objActual = DataReader.NameTable.Get(strInv);
object objActual1 = DataReader.NameTable.Get(strInv);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual1, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTableGet(objActual, strInv, chInv, 0, chInv.Length);
return TEST_PASS;
}
[Variation("Get Atomized String", Pri = 0)]
public int Variation_2()
{
object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length);
object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chVal, 0, chVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with end padded", Pri = 0)]
public int Variation_3()
{
object objActual = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front and end padded", Pri = 0)]
public int Variation_4()
{
object objActual = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front padded", Pri = 0)]
public int Variation_5()
{
object objActual = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with end multi-padded", Pri = 0)]
public int Variation_6()
{
object objActual = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front and end multi-padded", Pri = 0)]
public int Variation_7()
{
object objActual = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length);
return TEST_PASS;
}
[Variation("Get Atomized String with front multi-padded", Pri = 0)]
public int Variation_8()
{
object objActual = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length);
object objActual1 = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length);
return TEST_PASS;
}
[Variation("Get Invalid permutation of valid string", Pri = 0)]
public int Variation_9()
{
for (int i = 0; i < strPerVal.Length; i++)
{
char[] ach = strPerVal[i].ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual1, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTableGet(objActual, strPerVal[i], ach, 0, ach.Length);
}
return TEST_PASS;
}
[Variation("Get Valid Super String")]
public int Variation_10()
{
string filename = null;
NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE);
XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename));
while (rDataReader.Read() == true) ;
XmlNameTable nt = rDataReader.NameTable;
object objTest1 = nt.Get(BigStr + "Z");
object objTest2 = nt.Get(BigStr + "X");
object objTest3 = nt.Get(BigStr + "Y");
if (objTest1 != null)
{
throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is not null");
}
if (objTest2 == null)
{
throw new CTestException(CTestBase.TEST_FAIL, "objTest2 is null");
}
if (objTest3 == null)
{
throw new CTestException(CTestBase.TEST_FAIL, "objTest3 is null");
}
if ((objTest1 == objTest2) || (objTest1 == objTest3) || (objTest2 == objTest3))
throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is equal to objTest2, or objTest3");
return TEST_PASS;
}
[Variation("Get invalid Super String")]
public int Variation_11()
{
int size = (1 << 24);
string str = "";
char[] ach = str.ToCharArray();
bool fRetry = false;
for (; ;)
{
try
{
str = new String('Z', size);
ach = str.ToCharArray();
}
catch (OutOfMemoryException exc)
{
size >>= 1;
CError.WriteLine(exc + " : " + exc.Message + " Retry with " + size);
fRetry = true;
}
if (size < (1 << 30))
{
fRetry = true;
}
if (fRetry)
{
CError.WriteLine("Tested size == " + size);
if (str == null)
CError.WriteLine("string is null");
break;
}
}
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTableGet(objActual, str, ach, 0, ach.Length);
return TEST_PASS;
}
[Variation("Get empty string, valid offset and length = 0", Pri = 0)]
public int Variation_12()
{
string str = String.Empty;
char[] ach = str.ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, 0);
object objActual2 = DataReader.NameTable.Get(str);
CError.Compare(objActual, objActual1, "Char with StringEmpty");
CError.Compare(String.Empty, objActual1, "Char with StringEmpty");
CError.Compare(String.Empty, objActual2, "StringEmpty");
VerifyNameTable(objActual, str, ach, 0, 0);
return TEST_PASS;
}
[Variation("Get empty string, valid offset and length = 1", Pri = 0)]
public int Variation_13()
{
char[] ach = new char[] { };
try
{
object objActual = DataReader.NameTable.Get(ach, 0, 1);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get null char[], valid offset and length = 0", Pri = 0)]
public int Variation_14()
{
char[] ach = null;
object objActual = DataReader.NameTable.Add(ach, 0, 0);
CError.Compare(String.Empty, objActual, "Char with null");
return TEST_PASS;
}
[Variation("Get null string", Pri = 0)]
public int Variation_15()
{
string str = null;
try
{
object objActual = DataReader.NameTable.Get(str);
}
catch (ArgumentNullException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get null char[], valid offset and length = 1", Pri = 0)]
public int Variation_16()
{
char[] ach = null;
try
{
object objActual = DataReader.NameTable.Add(ach, 0, 1);
}
catch (NullReferenceException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid length, length = 0", Pri = 0)]
public int Variation_17()
{
object objActual = DataReader.NameTable.Get(chVal, 0, 0);
object objActual1 = DataReader.NameTable.Get(chVal, 0, 0);
CError.WriteLine("Here " + chVal.ToString());
CError.WriteLine("Here2 " + DataReader.NameTable.Get(chVal, 0, 0));
if (DataReader.NameTable.Get(chVal, 0, 0) == String.Empty)
CError.WriteLine("here");
if (DataReader.NameTable.Get(chVal, 0, 0) == null)
CError.WriteLine("null");
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, String.Empty, chVal, 0, 0);
return TEST_PASS;
}
[Variation("Get valid string, invalid length, length = Length+1", Pri = 0)]
public int Variation_18()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length + 1);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid length, length = max_int", Pri = 0)]
public int Variation_19()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, 0, Int32.MaxValue);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid length, length = -1", Pri = 0)]
public int Variation_20()
{
object objActual = DataReader.NameTable.Get(chVal, 0, -1);
CError.WriteLine("HERE " + objActual);
return TEST_PASS;
}
[Variation("Get valid string, invalid offset > Length", Pri = 0)]
public int Variation_21()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, chVal.Length + 1, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset = max_int", Pri = 0)]
public int Variation_22()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, Int32.MaxValue, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset = Length", Pri = 0)]
public int Variation_23()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, chVal.Length, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset -1", Pri = 0)]
public int Variation_24()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, -1, chVal.Length);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Get valid string, invalid offset and length", Pri = 0)]
public int Variation_25()
{
try
{
object objActual = DataReader.NameTable.Get(chVal, -1, -1);
}
catch (IndexOutOfRangeException exc)
{
CError.WriteLine(exc + " : " + exc.Message);
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
}
////////////////////////////////////////////////////////////////
// TestCase TCRecord NameTable.Add
//
////////////////////////////////////////////////////////////////
//[TestCase(Name="NameTable(Add) VerifyWGetString", Desc="VerifyWGetString")]
//[TestCase(Name="NameTable(Add) VerifyWGetChar", Desc="VerifyWGetChar")]
//[TestCase(Name="NameTable(Add) VerifyWAddString", Desc="VerifyWAddString")]
//[TestCase(Name="NameTable(Add) VerifyWAddChar", Desc="VerifyWAddChar")]
public partial class TCRecordNameTableAdd : TCBase
{
public static char[] chVal = { 'F', 'O', 'O' };
public static char[] chValW1EndExtra = { 'F', 'O', 'O', 'O' };
public static char[] chValW1FrExtra = { 'F', 'F', 'O', 'O', 'O' };
public static char[] chValW1Fr1EndExtra = { 'F', 'F', 'O', 'O', 'O' };
public static char[] chValWEndExtras = { 'F', 'O', 'O', 'O', 'O', 'O' };
public static char[] chValWFrExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O' };
public static char[] chValWFrEndExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O', 'O', 'O' };
public static string[] strPerVal =
{
"OFO", "OOF"
};
public static string[] strPerValCase =
{
"fOO", "foO", "foo",
"FoO", "Foo",
"FOo"
};
public static string strVal = "FOO";
public static string strWhitespaceVal = "WITH WHITESPACE";
public static string strAlphaNumVal = "WITH1Number";
public static string strSignVal = "+SIGN-";
[Variation("Add a new atomized string (padded with chars at the end), valid offset and length = str_length", Pri = 0)]
public int Variation_1()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length);
if (objActual == objActual1)
CError.WriteLine(objActual + " and ", objActual1);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with chars at both front and end), valid offset and length = str_length", Pri = 0)]
public int Variation_2()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrExtras, 6, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with chars at the front), valid offset and length = str_length", Pri = 0)]
public int Variation_3()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded a char at the end), valid offset and length = str_length", Pri = 0)]
public int Variation_4()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with a char at both front and end), valid offset and length = str_length", Pri = 0)]
public int Variation_5()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Add a new atomized string (padded with a char at the front), valid offset and length = str_length", Pri = 0)]
public int Variation_6()
{
ReloadSource();
object objActual = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length);
object objActual1 = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length);
return TEST_PASS;
}
[Variation("Add new string between 1M - 2M in size, valid offset and length")]
public int Variation_7()
{
char[] chTest = BigStr.ToCharArray();
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objActual2, CurVariation.Desc);
VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add an existing atomized string (with Max string for test: 1-2M), valid offset and valid length")]
public int Variation_8()
{
////////////////////////////
// Add strings again and verify
string filename = null;
NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE);
XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename));
while (rDataReader.Read() == true) ;
XmlNameTable nt = rDataReader.NameTable;
string strTest = BigStr + "X";
char[] chTest = strTest.ToCharArray();
Object objActual1 = nt.Add(chTest, 0, chTest.Length);
Object objActual2 = nt.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objActual2, "Comparing objActual1 and objActual2");
CError.Compare(objActual1, nt.Get(chTest, 0, chTest.Length), "Comparing objActual1 and GetCharArray");
CError.Compare(objActual1, nt.Get(strTest), "Comparing objActual1 and GetString");
CError.Compare(objActual1, nt.Add(strTest), "Comparing objActual1 and AddString");
NameTable_TestFiles.RemoveDataReader(EREADER_TYPE.BIG_ELEMENT_SIZE);
return TEST_PASS;
}
[Variation("Add new string, and do Get with a combination of the same string in different order", Pri = 0)]
public int Variation_9()
{
ReloadSource();
// Add string
Object objAdded = DataReader.NameTable.Add(strVal);
// Look for permutations of strings, should be null.
for (int i = 0; i < strPerVal.Length; i++)
{
char[] ach = strPerVal[i].ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
}
return TEST_PASS;
}
[Variation("Add new string, and Add a combination of the same string in different case, all are different objects", Pri = 0)]
public int Variation_10()
{
ReloadSource();
// Add string
Object objAdded = DataReader.NameTable.Add(strVal);
// Look for permutations of strings, should be null.
for (int i = 0; i < strPerValCase.Length; i++)
{
char[] ach = strPerValCase[i].ToCharArray();
object objActual = DataReader.NameTable.Add(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Add(ach, 0, ach.Length);
CError.Compare(objActual, objActual1, CurVariation.Desc);
VerifyNameTable(objActual1, strPerValCase[i], ach, 0, ach.Length);
if (objAdded == objActual)
{
throw new Exception("\n Object are the same for " + strVal + " and " + strPerValCase[i]);
}
}
return TEST_PASS;
}
[Variation("Add 1M new string, and do Get with the last char different than the original string", Pri = 0)]
public int Variation_11()
{
object objAdded = DataReader.NameTable.Add(BigStr + "M");
object objActual = DataReader.NameTable.Get(BigStr + "D");
CError.Compare(objActual, null, CurVariation.Desc);
return TEST_PASS;
}
[Variation("Add new alpha numeric, valid offset, valid length", Pri = 0)]
public int Variation_12()
{
ReloadSource();
char[] chTest = strAlphaNumVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objAdded, CurVariation.Desc);
VerifyNameTable(objAdded, strAlphaNumVal, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new alpha numeric, valid offset, length= 0", Pri = 0)]
public int Variation_13()
{
ReloadSource();
char[] chTest = strAlphaNumVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, 0);
object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length);
object objActual2 = DataReader.NameTable.Get(strVal);
CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail");
CError.Compare(objActual1, objActual2, "Both Get should fail");
return TEST_PASS;
}
[Variation("Add new with whitespace, valid offset, valid length", Pri = 0)]
public int Variation_14()
{
ReloadSource();
char[] chTest = strWhitespaceVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objAdded, CurVariation.Desc);
VerifyNameTable(objAdded, strWhitespaceVal, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new with sign characters, valid offset, valid length", Pri = 0)]
public int Variation_15()
{
ReloadSource();
char[] chTest = strSignVal.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objAdded, CurVariation.Desc);
VerifyNameTable(objAdded, strSignVal, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new string between 1M - 2M in size, valid offset and length", Pri = 0)]
public int Variation_16()
{
ReloadSource();
char[] chTest = BigStr.ToCharArray();
object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length);
CError.Compare(objActual1, objActual2, CurVariation.Desc);
VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length);
return TEST_PASS;
}
[Variation("Add new string, get object using permutations of upper & lowecase, should be null", Pri = 0)]
public int Variation_17()
{
ReloadSource();
// Add string
Object objAdded = DataReader.NameTable.Add(strVal);
// Look for permutations of strings, should be null.
for (int i = 0; i < strPerValCase.Length; i++)
{
char[] ach = strPerValCase[i].ToCharArray();
object objActual = DataReader.NameTable.Get(ach, 0, ach.Length);
object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length);
CError.Compare(objActual, null, CurVariation.Desc);
CError.Compare(objActual, objActual1, CurVariation.Desc);
}
return TEST_PASS;
}
[Variation("Add an empty atomized string, valid offset and length = 0", Pri = 0)]
public int Variation_18()
{
ReloadSource();
string strEmpty = String.Empty;
object objAdded = DataReader.NameTable.Add(strEmpty);
object objAdded1 = DataReader.NameTable.Add(strEmpty.ToCharArray(), 0, strEmpty.Length);
object objActual1 = DataReader.NameTable.Get(strEmpty.ToCharArray(), 0, strEmpty.Length);
object objActual2 = DataReader.NameTable.Get(strEmpty);
CError.WriteLine("String " + DataReader.NameTable.Get(strEmpty));
CError.WriteLine("String " + objAdded1 + " String2 " + objAdded1);
if (objAdded != objAdded1)
CError.WriteLine("HERE");
CError.Compare(objActual1, objActual2, CurVariation.Desc);
VerifyNameTable(objActual1, strEmpty, strEmpty.ToCharArray(), 0, 0);
return TEST_PASS;
}
[Variation("Add an empty atomized string (array char only), valid offset and length = 1", Pri = 0)]
public int Variation_19()
{
try
{
char[] chTest = String.Empty.ToCharArray();
object objAdded = DataReader.NameTable.Add(chTest, 0, 1);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a NULL atomized string, valid offset and length = 0", Pri = 0)]
public int Variation_20()
{
object objAdded = DataReader.NameTable.Add(null, 0, 0);
VerifyNameTable(objAdded, String.Empty, (String.Empty).ToCharArray(), 0, 0);
return TEST_PASS;
}
[Variation("Add a NULL atomized string, valid offset and length = 1", Pri = 0)]
public int Variation_21()
{
try
{
object objAdded = DataReader.NameTable.Add(null, 0, 1);
}
catch (NullReferenceException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid offset and length = 0", Pri = 0)]
public int Variation_22()
{
ReloadSource();
object objAdded = DataReader.NameTable.Add(chVal, 0, 0);
object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length);
object objActual2 = DataReader.NameTable.Get(strVal);
CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail");
CError.Compare(objActual1, objActual2, "Both Get should fail");
return TEST_PASS;
}
[Variation("Add a valid atomized string, valid offset and length > valid_length", Pri = 0)]
public int Variation_23()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, 0, chVal.Length * 2);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid offset and length = max_int", Pri = 0)]
public int Variation_24()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, 0, Int32.MaxValue);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid offset and length = - 1", Pri = 0)]
public int Variation_25()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, 0, -1);
}
catch (ArgumentOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset > str_length", Pri = 0)]
public int Variation_26()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, chVal.Length * 2, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset = max_int", Pri = 0)]
public int Variation_27()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, Int32.MaxValue, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset = str_length", Pri = 0)]
public int Variation_28()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, chVal.Length, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, valid length and offset = - 1", Pri = 0)]
public int Variation_29()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, -1, chVal.Length);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Add a valid atomized string, with both invalid offset and length", Pri = 0)]
public int Variation_30()
{
try
{
object objAdded = DataReader.NameTable.Add(chVal, -1, -1);
}
catch (IndexOutOfRangeException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
}
}
| |
// Camera Path 3
// Available on the Unity Asset Store
// Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com/camera-path/
// For support contact email@jasperstocker.com
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using System;
using UnityEngine;
#if UNITY_EDITOR
using System.Text;
using System.Xml;
#endif
public class CameraPathAnimator : MonoBehaviour
{
public float minimumCameraSpeed = 0.01f;
public enum animationModes
{
once,
loop,
reverse,
reverseLoop,
pingPong
}
public enum orientationModes
{
custom,//rotations will be decided by defining orientations along the curve
target,//camera will always face a defined transform
mouselook,//camera will have a mouse free look
followpath,//camera will use the path to determine where to face - maintaining world up as up
reverseFollowpath,//camera will use the path to determine where to face, looking back on the path
followTransform,//move the object to the nearest point on the path and look at target
twoDimentions,
fixedOrientation,
none
}
public Transform orientationTarget;
[SerializeField]
private CameraPath _cameraPath;
//do you want this path to automatically animate at the start of your scene
public bool playOnStart = true;
//the actual transform you want to animate
public Transform animationObject = null;
//a link to the camera component
private Camera animationObjectCamera = null;
//is the transform you are animating a camera?
private bool _isCamera = true;
private bool _playing = false;
public animationModes animationMode = animationModes.once;
public orientationModes orientationMode = orientationModes.custom;
private float pingPongDirection = 1;
public Vector3 fixedOrientaion = Vector3.forward;
public bool normalised = true;
//the time used in the editor to preview the path animation
public float editorPercentage = 0;
//the time the path animation should last for
[SerializeField]
private float _pathTime = 10;
//the time the path animation should last for
[SerializeField]
private float _pathSpeed = 10;
private float _percentage = 0;
private float _lastPercentage = 0;
public float nearestOffset = 0;
private float delayTime = 0;
//the sensitivity of the mouse in mouselook
public float sensitivity = 5.0f;
//the minimum the mouse can move down
public float minX = -90.0f;
//the maximum the mouse can move up
public float maxX = 90.0f;
private float rotationX = 0;
private float rotationY = 0;
public bool showPreview = true;
public GameObject editorPreview = null;
public bool showScenePreview = true;
private bool _animateSceneObjectInEditor = false;
public Vector3 animatedObjectStartPosition;
public Quaternion animatedObjectStartRotation;
//Events
public delegate void AnimationStartedEventHandler();
public delegate void AnimationPausedEventHandler();
public delegate void AnimationStoppedEventHandler();
public delegate void AnimationFinishedEventHandler();
public delegate void AnimationLoopedEventHandler();
public delegate void AnimationPingPongEventHandler();
public delegate void AnimationPointReachedEventHandler();
public delegate void AnimationCustomEventHandler(string eventName);
public delegate void AnimationPointReachedWithNumberEventHandler(int pointNumber);
/// <summary>
/// Broadcast when the Animation has begun
/// </summary>
public event AnimationStartedEventHandler AnimationStartedEvent;
/// <summary>
/// Broadcast when the animation is paused
/// </summary>
public event AnimationPausedEventHandler AnimationPausedEvent;
/// <summary>
/// Broadcast when the animation is stopped
/// </summary>
public event AnimationStoppedEventHandler AnimationStoppedEvent;
/// <summary>
/// Broadcast when the animation is complete
/// </summary>
public event AnimationFinishedEventHandler AnimationFinishedEvent;
/// <summary>
/// Broadcast when the animation has reached the end of the loop and begins the animation again
/// </summary>
public event AnimationLoopedEventHandler AnimationLoopedEvent;
/// <summary>
/// Broadcast when the end of a path animation is reached and the animation ping pongs back
/// </summary>
public event AnimationPingPongEventHandler AnimationPingPongEvent;
/// <summary>
/// Broadcast when a point is reached
/// </summary>
public event AnimationPointReachedEventHandler AnimationPointReachedEvent;
/// <summary>
/// Broadcast when a point is reached sending the point number index with it
/// </summary>
public event AnimationPointReachedWithNumberEventHandler AnimationPointReachedWithNumberEvent;
/// <summary>
/// Broadcast when a user defined event is fired sending the event name as a string
/// </summary>
public event AnimationCustomEventHandler AnimationCustomEvent;
//PUBLIC METHODS
//Script based controls - hook up your scripts to these to control your
/// <summary>
/// Gets or sets the path speed.
/// </summary>
/// <value>
/// The path speed.
/// </value>
public float pathSpeed
{
get
{
return _pathSpeed;
}
set
{
if(_cameraPath.speedList.listEnabled)
Debug.LogWarning("Path Speed in Animator component is ignored and overridden by Camera Path speed points.");
_pathSpeed = Mathf.Max(value, minimumCameraSpeed);
}
}
/// <summary>
/// Retreive the current time of the path animation
/// </summary>
public float currentTime
{
get { return _pathTime * _percentage; }
}
/// <summary>
/// Play the path. If path has finished do not play it.
/// </summary>
public void Play()
{
_playing = true;
if (!isReversed)
{
if(_percentage == 0)
{
if (AnimationStartedEvent != null) AnimationStartedEvent();
cameraPath.eventList.OnAnimationStart(0);
}
}
else
{
if(_percentage == 1)
{
if (AnimationStartedEvent != null) AnimationStartedEvent();
cameraPath.eventList.OnAnimationStart(1);
}
}
_lastPercentage = _percentage;
}
/// <summary>
/// Stop and reset the animation back to the beginning
/// </summary>
public void Stop()
{
_playing = false;
_percentage = 0;
if (AnimationStoppedEvent != null) AnimationStoppedEvent();
}
/// <summary>
/// Pause the animation where it is
/// </summary>
public void Pause()
{
_playing = false;
if (AnimationPausedEvent != null) AnimationPausedEvent();
}
/// <summary>
/// set the time of the animtion
/// </summary>
/// <param name="value">Seek Percent 0-1</param>
public void Seek(float value)
{
_percentage = Mathf.Clamp01(value);
_lastPercentage = _percentage;
//thanks kelnishi!
UpdateAnimationTime(false);
UpdatePointReached();
bool p = _playing;
_playing = true;
UpdateAnimation();
_playing = p;
}
/// <summary>
/// Is the animation playing
/// </summary>
public bool isPlaying
{
get { return _playing; }
}
/// <summary>
/// Current percent of animation
/// </summary>
public float percentage
{
get { return _percentage; }
}
/// <summary>
/// Is the animation ping pong direction forward
/// </summary>
public bool pingPongGoingForward
{
get { return pingPongDirection == 1; }
}
/// <summary>
/// Reverse the animation
/// </summary>
public void Reverse()
{
switch (animationMode)
{
case animationModes.once:
animationMode = animationModes.reverse;
break;
case animationModes.reverse:
animationMode = animationModes.once;
break;
case animationModes.pingPong:
pingPongDirection = pingPongDirection == -1 ? 1 : -1;
break;
case animationModes.loop:
animationMode = animationModes.reverseLoop;
break;
case animationModes.reverseLoop:
animationMode = animationModes.loop;
break;
}
}
/// <summary>
/// A link to the Camera Path component
/// </summary>
public CameraPath cameraPath
{
get
{
if (!_cameraPath)
_cameraPath = GetComponent<CameraPath>();
return _cameraPath;
}
}
/// <summary>
/// Retrieve the animation orientation at a percent based on the animation mode
/// </summary>
/// <param name="percent">Path Percent 0-1</param>
/// <param name="ignoreNormalisation">Should the percetage be normalised</param>
/// <returns>A rotation</returns>
public Quaternion GetAnimatedOrientation(float percent, bool ignoreNormalisation)
{
Quaternion output = Quaternion.identity;
Vector3 currentPosition, forward;
switch (orientationMode)
{
case orientationModes.custom:
output = cameraPath.GetPathRotation(percent, ignoreNormalisation);
break;
case orientationModes.target:
currentPosition = cameraPath.GetPathPosition(percent);
if(orientationTarget != null)
forward = orientationTarget.transform.position - currentPosition;
else
forward = Vector3.forward;
output = Quaternion.LookRotation(forward);
break;
case orientationModes.followpath:
output = Quaternion.LookRotation(cameraPath.GetPathDirection(percent));
output *= Quaternion.Euler(transform.forward * -cameraPath.GetPathTilt(percent));
break;
case orientationModes.reverseFollowpath:
output = Quaternion.LookRotation(-cameraPath.GetPathDirection(percent));
output *= Quaternion.Euler(transform.forward * -cameraPath.GetPathTilt(percent));
break;
case orientationModes.mouselook:
if(!Application.isPlaying)
{
output = Quaternion.LookRotation(cameraPath.GetPathDirection(percent));
output *= Quaternion.Euler(transform.forward * -cameraPath.GetPathTilt(percent));
}
else
{
output = GetMouseLook();
}
break;
case orientationModes.followTransform:
if(orientationTarget == null)
return Quaternion.identity;
float nearestPerc = cameraPath.GetNearestPoint(orientationTarget.position);
nearestPerc = Mathf.Clamp01(nearestPerc + nearestOffset);
currentPosition = cameraPath.GetPathPosition(nearestPerc);
forward = orientationTarget.transform.position - currentPosition;
output = Quaternion.LookRotation(forward);
break;
case orientationModes.twoDimentions:
output = Quaternion.LookRotation(Vector3.forward);
break;
case orientationModes.fixedOrientation:
output = Quaternion.LookRotation(fixedOrientaion);
break;
case orientationModes.none:
output = animationObject.rotation;
break;
}
output *= transform.rotation;
return output;
}
//MONOBEHAVIOURS
private void Awake()
{
if(animationObject == null)
_isCamera = false;
else
{
animationObjectCamera = animationObject.GetComponentInChildren<Camera>();
_isCamera = animationObjectCamera != null;
}
Camera[] cams = Camera.allCameras;
if (cams.Length == 0)
{
Debug.LogWarning("Warning: There are no cameras in the scene");
_isCamera = false;
}
if (!isReversed)
{
_percentage = 0;
}
else
{
_percentage = 1;
}
Vector3 initalRotation = cameraPath.GetPathRotation(0,false).eulerAngles;
rotationX = initalRotation.y;
rotationY = initalRotation.x;
}
private void OnEnable()
{
cameraPath.eventList.CameraPathEventPoint += OnCustomEvent;
cameraPath.delayList.CameraPathDelayEvent += OnDelayEvent;
if (animationObject != null)
animationObjectCamera = animationObject.GetComponentInChildren<Camera>();
}
private void Start()
{
if (playOnStart)
Play();
if(Application.isPlaying && orientationTarget==null && (orientationMode==orientationModes.followTransform || orientationMode == orientationModes.target))
Debug.LogWarning("There has not been an orientation target specified in the Animation component of Camera Path.",transform);
}
private void Update()
{
if (!isCamera)
{
if (_playing)
{
UpdateAnimationTime();
UpdateAnimation();
UpdatePointReached();
}
else
{
if (_cameraPath.nextPath != null && _percentage >= 1)
{
PlayNextAnimation();
}
}
}
}
private void LateUpdate()
{
if (isCamera)
{
if (_playing)
{
UpdateAnimationTime();
UpdateAnimation();
UpdatePointReached();
}
else
{
if (_cameraPath.nextPath != null && _percentage >= 1)
{
PlayNextAnimation();
}
}
}
}
private void OnDisable()
{
CleanUp();
}
private void OnDestroy()
{
CleanUp();
}
//PRIVATE METHODS
private void PlayNextAnimation()
{
if (_cameraPath.nextPath != null)
{
_cameraPath.nextPath.GetComponent<CameraPathAnimator>().Play();
_percentage = 0;
Stop();
}
}
void UpdateAnimation()
{
if (animationObject == null)
{
Debug.LogError("There is no animation object specified in the Camera Path Animator component. Nothing to animate.\nYou can find this component in the main camera path game object called "+gameObject.name+".");
Stop();
return;
}
if (!_playing)
return;
if(cameraPath.speedList.listEnabled)
_pathTime = _cameraPath.pathLength / Mathf.Max(cameraPath.GetPathSpeed(_percentage), minimumCameraSpeed);
else
_pathTime = _cameraPath.pathLength / Mathf.Max(_pathSpeed * cameraPath.GetPathEase(_percentage), minimumCameraSpeed);
animationObject.position = cameraPath.GetPathPosition(_percentage);
if(orientationMode != orientationModes.none)
animationObject.rotation = GetAnimatedOrientation(_percentage,false);
if(isCamera && _cameraPath.fovList.listEnabled)
{
if(orientationMode != orientationModes.twoDimentions)
animationObjectCamera.fieldOfView = _cameraPath.GetPathFOV(_percentage);
else
animationObjectCamera.orthographicSize = _cameraPath.GetPathFOV(_percentage);
}
CheckEvents();
}
private void UpdatePointReached()
{
if(_percentage == _lastPercentage)//no movement
return;
if (Mathf.Abs(percentage - _lastPercentage) > 0.999f)
{
_lastPercentage = percentage;//probable loop
return;
}
for (int i = 0; i < cameraPath.realNumberOfPoints; i++)
{
CameraPathControlPoint point = cameraPath[i];
bool eventBetweenAnimationDelta = (point.percentage >= _lastPercentage && point.percentage <= percentage) || (point.percentage >= percentage && point.percentage <= _lastPercentage);
if (eventBetweenAnimationDelta)
{
if (AnimationPointReachedEvent != null) AnimationPointReachedEvent();
if (AnimationPointReachedWithNumberEvent != null) AnimationPointReachedWithNumberEvent(i);
}
}
_lastPercentage = percentage;
}
private void UpdateAnimationTime()
{
UpdateAnimationTime(true);
}
private void UpdateAnimationTime(bool advance)
{
if(orientationMode == orientationModes.followTransform)
return;
if(delayTime > 0)
{
delayTime += -Time.deltaTime;
return;
}
if(advance)
{
switch(animationMode)
{
case animationModes.once:
if(_percentage >= 1)
{
_playing = false;
if(AnimationFinishedEvent != null) AnimationFinishedEvent();
}
else
{
_percentage += Time.deltaTime * (1.0f / _pathTime);
}
break;
case animationModes.loop:
if(_percentage >= 1)
{
_percentage = 0;
_lastPercentage = 0;
if(AnimationLoopedEvent != null) AnimationLoopedEvent();
}
_percentage += Time.deltaTime * (1.0f / _pathTime);
break;
case animationModes.reverseLoop:
if(_percentage <= 0)
{
_percentage = 1;
_lastPercentage = 1;
if(AnimationLoopedEvent != null) AnimationLoopedEvent();
}
_percentage += -Time.deltaTime * (1.0f / _pathTime);
break;
case animationModes.reverse:
if(_percentage <= 0.0f)
{
_percentage = 0.0f;
_playing = false;
if(AnimationFinishedEvent != null) AnimationFinishedEvent();
}
else
{
_percentage += -Time.deltaTime * (1.0f / _pathTime);
}
break;
case animationModes.pingPong:
float timeStep = Time.deltaTime * (1.0f / _pathTime);
_percentage += timeStep * pingPongDirection;
if(_percentage >= 1)
{
_percentage = 1.0f - timeStep;
_lastPercentage = 1;
pingPongDirection = -1;
if(AnimationPingPongEvent != null) AnimationPingPongEvent();
}
if(_percentage <= 0)
{
_percentage = timeStep;
_lastPercentage = 0;
pingPongDirection = 1;
if(AnimationPingPongEvent != null) AnimationPingPongEvent();
}
break;
}
}
_percentage = Mathf.Clamp01(_percentage);
}
private Quaternion GetMouseLook()
{
if (animationObject == null)
return Quaternion.identity;
rotationX += Input.GetAxis("Mouse X") * sensitivity;
rotationY += -Input.GetAxis("Mouse Y") * sensitivity;
rotationY = Mathf.Clamp(rotationY, minX, maxX);
return Quaternion.Euler(new Vector3(rotationY, rotationX, 0));
}
private void CheckEvents()
{
cameraPath.CheckEvents(_percentage);
}
private bool isReversed
{
get { return (animationMode == animationModes.reverse || animationMode == animationModes.reverseLoop || pingPongDirection < 0); }
}
public bool isCamera
{
get
{
if (animationObject == null)
_isCamera = false;
else
{
_isCamera = animationObjectCamera != null;
}
return _isCamera;
}
}
public bool animateSceneObjectInEditor
{
get {return _animateSceneObjectInEditor;}
set
{
if (value != _animateSceneObjectInEditor)
{
_animateSceneObjectInEditor = value;
if (animationObject != null)
{
if (_animateSceneObjectInEditor)
{
animatedObjectStartPosition = animationObject.transform.position;
animatedObjectStartRotation = animationObject.transform.rotation;
}
else
{
animationObject.transform.position = animatedObjectStartPosition;
animationObject.transform.rotation = animatedObjectStartRotation;
}
}
}
_animateSceneObjectInEditor = value;
}
}
private void CleanUp()
{
cameraPath.eventList.CameraPathEventPoint += OnCustomEvent;
cameraPath.delayList.CameraPathDelayEvent += OnDelayEvent;
}
private void OnDelayEvent(float time)
{
if(time > 0)
delayTime = time;//start delay timer
else
Pause();//indeffinite delay
}
private void OnCustomEvent(string eventName)
{
if(AnimationCustomEvent != null)
AnimationCustomEvent(eventName);
}
#if UNITY_EDITOR
/// <summary>
/// Convert this camera path into an xml string for export
/// </summary>
/// <returns>A generated XML string</returns>
public string ToXML()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<animator>");
sb.AppendLine("<animationObject>" + ((animationObject != null) ? animationObject.name : "null") + "</animationObject>");
sb.AppendLine("<orientationTarget>" + ((orientationTarget != null) ? orientationTarget.name : "null") + "</orientationTarget>");
sb.AppendLine("<animateSceneObjectInEditor>" + _animateSceneObjectInEditor + "</animateSceneObjectInEditor>");
sb.AppendLine("<playOnStart>" + playOnStart + "</playOnStart>");
sb.AppendLine("<animationMode>" + animationMode + "</animationMode>");
sb.AppendLine("<orientationMode>" + orientationMode + "</orientationMode>");
sb.AppendLine("<normalised>" + normalised + "</normalised>");
sb.AppendLine("<pathSpeed>" + _pathSpeed + "</pathSpeed>");
sb.AppendLine("</animator>");
return sb.ToString();
}
/// <summary>
/// Import XML data into this camera path overwriting the current data
/// </summary>
/// <param name="XMLPath">An XML file path</param>
public void FromXML(XmlNode xml)
{
if(xml == null)
return;
GameObject animationObjectGO = GameObject.Find(xml["animationObject"].FirstChild.Value);
if(animationObjectGO != null)
animationObject = animationObjectGO.transform;
GameObject orientationTargetGO = GameObject.Find(xml["orientationTarget"].FirstChild.Value);
if (orientationTargetGO != null)
orientationTarget = orientationTargetGO.transform;
_animateSceneObjectInEditor = bool.Parse(xml["animateSceneObjectInEditor"].FirstChild.Value);
playOnStart = bool.Parse(xml["playOnStart"].FirstChild.Value);
animationMode = (animationModes)Enum.Parse(typeof(animationModes), xml["animationMode"].FirstChild.Value);
orientationMode = (orientationModes)Enum.Parse(typeof(orientationModes), xml["orientationMode"].FirstChild.Value);
normalised = bool.Parse(xml["normalised"].FirstChild.Value);
_pathSpeed = float.Parse(xml["pathSpeed"].FirstChild.Value);
}
#endif
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Build.Collections;
using Microsoft.Build.Shared;
using Microsoft.Build.Execution;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Collections
{
/// <summary>
/// Tests for MSBuildNameIgnoreCaseComparer
/// </summary>
public class MSBuildNameIgnoreCaseComparer_Tests
{
/// <summary>
/// Verify default comparer works on the whole string
/// </summary>
[Fact]
public void DefaultEquals()
{
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals("FOO", "foo"));
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals("FOO", " FOO"));
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals("FOOA", "FOOB"));
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals("AFOO", "BFOO"));
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals("FOO", "FOO "));
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals("a", "b"));
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals("", ""));
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals("x", null));
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals(null, "x"));
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals((string)null, (string)null));
}
/// <summary>
/// Compare real expressions
/// </summary>
[Fact]
public void MatchProperty()
{
MSBuildNameIgnoreCaseComparer comparer = MSBuildNameIgnoreCaseComparer.Default;
PropertyDictionary<ProjectPropertyInstance> dictionary = new PropertyDictionary<ProjectPropertyInstance>(comparer);
ProjectPropertyInstance p = ProjectPropertyInstance.Create("foo", "bar");
dictionary.Set(p);
string s = "$(foo)";
ProjectPropertyInstance value = dictionary.GetProperty(s, 2, 4);
Assert.True(Object.ReferenceEquals(p, value)); // "Should have returned the same object as was inserted"
Assert.Equal(MSBuildNameIgnoreCaseComparer.Default.GetHashCode("foo"), comparer.GetHashCode(s, 2, 3));
}
/// <summary>
/// Null
/// </summary>
[Fact]
public void Null1()
{
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals("x", null));
}
/// <summary>
/// Null
/// </summary>
[Fact]
public void Null2()
{
Assert.False(MSBuildNameIgnoreCaseComparer.Default.Equals(null, "x"));
}
/// <summary>
/// Invalid start
/// </summary>
[Fact]
public void InvalidValue2()
{
Assert.Throws<InternalErrorException>(() =>
{
MSBuildNameIgnoreCaseComparer.Default.Equals("x", "y", -1, 0);
}
);
}
/// <summary>
/// Invalid small end
/// </summary>
[Fact]
public void InvalidValue4()
{
Assert.Throws<InternalErrorException>(() =>
{
MSBuildNameIgnoreCaseComparer.Default.Equals("x", "y", 0, -1);
}
);
}
/// <summary>
/// Invalid large end
/// </summary>
[Fact]
public void InvalidValue5()
{
Assert.Throws<InternalErrorException>(() =>
{
MSBuildNameIgnoreCaseComparer.Default.Equals("x", "y", 0, 2);
}
);
}
/// <summary>
/// End past the end of other string
/// </summary>
[Fact]
public void EqualsEndPastEnd1()
{
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals("bbb", "abbbaaa", 1, 3));
}
/// <summary>
/// Same values means one char
/// </summary>
[Fact]
public void EqualsSameStartEnd1()
{
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals("A", "babbbb", 1, 1));
}
/// <summary>
/// Same values means one char
/// </summary>
[Fact]
public void EqualsSameStartEnd2()
{
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals("b", "aabaa", 2, 1));
}
/// <summary>
/// Same values means one char
/// </summary>
[Fact]
public void EqualsSameStartEnd3()
{
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals("a", "ab", 0, 1));
}
/// <summary>
/// Start at 0
/// </summary>
[Fact]
public void EqualsStartZero()
{
Assert.True(MSBuildNameIgnoreCaseComparer.Default.Equals("aab", "aabaa", 0, 3));
}
/// <summary>
/// Default get hash code
/// </summary>
[Fact]
public void DefaultGetHashcode()
{
Assert.True(0 == MSBuildNameIgnoreCaseComparer.Default.GetHashCode((string)null));
MSBuildNameIgnoreCaseComparer.Default.GetHashCode(""); // doesn't throw
Assert.Equal(MSBuildNameIgnoreCaseComparer.Default.GetHashCode("aBc"), MSBuildNameIgnoreCaseComparer.Default.GetHashCode("AbC"));
}
/// <summary>
/// Indexed get hashcode
/// </summary>
[Fact]
public void IndexedGetHashcode1()
{
MSBuildNameIgnoreCaseComparer comparer = MSBuildNameIgnoreCaseComparer.Default;
comparer.GetHashCode(""); // does not crash
Assert.True(0 == comparer.GetHashCode((string)null));
Assert.Equal(comparer.GetHashCode("aBc"), comparer.GetHashCode("AbC"));
Assert.Equal(comparer.GetHashCode("xyz", 0, 1), comparer.GetHashCode("x"));
}
/// <summary>
/// Indexed get hashcode
/// </summary>
[Fact]
public void IndexedGetHashcode2()
{
MSBuildNameIgnoreCaseComparer comparer = MSBuildNameIgnoreCaseComparer.Default;
Assert.Equal(comparer.GetHashCode("xyz", 1, 2), comparer.GetHashCode("YZ"));
}
/// <summary>
/// Indexed get hashcode
/// </summary>
[Fact]
public void IndexedGetHashcode3()
{
MSBuildNameIgnoreCaseComparer comparer = MSBuildNameIgnoreCaseComparer.Default;
Assert.Equal(comparer.GetHashCode("abcd", 0, 3), comparer.GetHashCode("abc"));
}
}
}
| |
// 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 Xunit;
namespace System.Threading.Tests
{
public class EventWaitHandleTests : RemoteExecutorTestBase
{
[Theory]
[InlineData(false, EventResetMode.AutoReset)]
[InlineData(false, EventResetMode.ManualReset)]
[InlineData(true, EventResetMode.AutoReset)]
[InlineData(true, EventResetMode.ManualReset)]
public void Ctor_StateMode(bool initialState, EventResetMode mode)
{
using (var ewh = new EventWaitHandle(initialState, mode))
Assert.Equal(initialState, ewh.WaitOne(0));
}
[Fact]
public void Ctor_InvalidMode()
{
Assert.Throws<ArgumentException>(() => new EventWaitHandle(true, (EventResetMode)12345));
}
[PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix
[Fact]
public void Ctor_InvalidNames()
{
Assert.Throws<ArgumentException>(() => new EventWaitHandle(true, EventResetMode.AutoReset, new string('a', 1000)));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // names aren't supported on Unix
[Fact]
public void Ctor_NamesArentSupported_Unix()
{
Assert.Throws<PlatformNotSupportedException>(() => new EventWaitHandle(false, EventResetMode.AutoReset, "anything"));
bool createdNew;
Assert.Throws<PlatformNotSupportedException>(() => new EventWaitHandle(false, EventResetMode.AutoReset, "anything", out createdNew));
}
[PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix
[Theory]
[InlineData(false, EventResetMode.AutoReset)]
[InlineData(false, EventResetMode.ManualReset)]
[InlineData(true, EventResetMode.AutoReset)]
[InlineData(true, EventResetMode.ManualReset)]
public void Ctor_StateModeNameCreatedNew_Windows(bool initialState, EventResetMode mode)
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (var ewh = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew))
{
Assert.True(createdNew);
using (new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Theory]
[InlineData(EventResetMode.AutoReset)]
[InlineData(EventResetMode.ManualReset)]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows(EventResetMode mode)
{
string name = Guid.NewGuid().ToString("N");
using (Mutex m = new Mutex(false, name))
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new EventWaitHandle(false, mode, name));
}
[Fact]
public void SetReset()
{
using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset))
{
Assert.False(are.WaitOne(0));
are.Set();
Assert.True(are.WaitOne(0));
Assert.False(are.WaitOne(0));
are.Set();
are.Reset();
Assert.False(are.WaitOne(0));
}
using (EventWaitHandle mre = new EventWaitHandle(false, EventResetMode.ManualReset))
{
Assert.False(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
Assert.True(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
mre.Reset();
Assert.False(mre.WaitOne(0));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_Windows()
{
string name = Guid.NewGuid().ToString("N");
EventWaitHandle resultHandle;
Assert.False(EventWaitHandle.TryOpenExisting(name, out resultHandle));
Assert.Null(resultHandle);
using (EventWaitHandle are1 = new EventWaitHandle(false, EventResetMode.AutoReset, name))
{
using (EventWaitHandle are2 = EventWaitHandle.OpenExisting(name))
{
are1.Set();
Assert.True(are2.WaitOne(0));
Assert.False(are1.WaitOne(0));
Assert.False(are2.WaitOne(0));
are2.Set();
Assert.True(are1.WaitOne(0));
Assert.False(are2.WaitOne(0));
Assert.False(are1.WaitOne(0));
}
Assert.True(EventWaitHandle.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_NotSupported_Unix()
{
Assert.Throws<PlatformNotSupportedException>(() => EventWaitHandle.OpenExisting("anything"));
EventWaitHandle ewh;
Assert.Throws<PlatformNotSupportedException>(() => EventWaitHandle.TryOpenExisting("anything", out ewh));
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_InvalidNames_Windows()
{
Assert.Throws<ArgumentNullException>("name", () => EventWaitHandle.OpenExisting(null));
Assert.Throws<ArgumentException>(() => EventWaitHandle.OpenExisting(string.Empty));
Assert.Throws<ArgumentException>(() => EventWaitHandle.OpenExisting(new string('a', 10000)));
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_UnavailableName_Windows()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => EventWaitHandle.OpenExisting(name));
EventWaitHandle ignored;
Assert.False(EventWaitHandle.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Mutex mtx = new Mutex(true, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => EventWaitHandle.OpenExisting(name));
EventWaitHandle ignored;
Assert.False(EventWaitHandle.TryOpenExisting(name, out ignored));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix
[Theory]
[InlineData(EventResetMode.ManualReset)]
[InlineData(EventResetMode.AutoReset)]
public void PingPong(EventResetMode mode)
{
// Create names for the two events
string outboundName = Guid.NewGuid().ToString("N");
string inboundName = Guid.NewGuid().ToString("N");
// Create the two events and the other process with which to synchronize
using (var inbound = new EventWaitHandle(true, mode, inboundName))
using (var outbound = new EventWaitHandle(false, mode, outboundName))
using (var remote = RemoteInvoke(PingPong_OtherProcess, mode.ToString(), outboundName, inboundName))
{
// Repeatedly wait for one event and then set the other
for (int i = 0; i < 10; i++)
{
Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds));
if (mode == EventResetMode.ManualReset)
{
inbound.Reset();
}
outbound.Set();
}
}
}
private static int PingPong_OtherProcess(string modeName, string inboundName, string outboundName)
{
EventResetMode mode = (EventResetMode)Enum.Parse(typeof(EventResetMode), modeName);
// Open the two events
using (var inbound = EventWaitHandle.OpenExisting(inboundName))
using (var outbound = EventWaitHandle.OpenExisting(outboundName))
{
// Repeatedly wait for one event and then set the other
for (int i = 0; i < 10; i++)
{
Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds));
if (mode == EventResetMode.ManualReset)
{
inbound.Reset();
}
outbound.Set();
}
}
return SuccessExitCode;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
public enum ProfileShape : byte
{
Circle = 0,
Square = 1,
IsometricTriangle = 2,
EquilateralTriangle = 3,
RightTriangle = 4,
HalfCircle = 5
}
public enum HollowShape : byte
{
Same = 0,
Circle = 16,
Square = 32,
Triangle = 48
}
public enum PCodeEnum : byte
{
Primitive = 9,
Avatar = 47,
Grass = 95,
NewTree = 111,
ParticleSystem = 143,
Tree = 255
}
public enum Extrusion : byte
{
Straight = 16,
Curve1 = 32,
Curve2 = 48,
Flexible = 128
}
[Serializable]
public class PrimitiveBaseShape
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly byte[] DEFAULT_TEXTURE = new Primitive.TextureEntry(new UUID("89556747-24cb-43ed-920b-47caed15465f")).GetBytes();
private byte[] m_textureEntry;
private ushort _pathBegin;
private byte _pathCurve;
private ushort _pathEnd;
private sbyte _pathRadiusOffset;
private byte _pathRevolutions;
private byte _pathScaleX;
private byte _pathScaleY;
private byte _pathShearX;
private byte _pathShearY;
private sbyte _pathSkew;
private sbyte _pathTaperX;
private sbyte _pathTaperY;
private sbyte _pathTwist;
private sbyte _pathTwistBegin;
private byte _pCode;
private ushort _profileBegin;
private ushort _profileEnd;
private ushort _profileHollow;
private Vector3 _scale;
private byte _state;
private ProfileShape _profileShape;
private HollowShape _hollowShape;
// Sculpted
[XmlIgnore] private UUID _sculptTexture;
[XmlIgnore] private byte _sculptType;
[XmlIgnore] private byte[] _sculptData = Utils.EmptyBytes;
// Flexi
[XmlIgnore] private int _flexiSoftness;
[XmlIgnore] private float _flexiTension;
[XmlIgnore] private float _flexiDrag;
[XmlIgnore] private float _flexiGravity;
[XmlIgnore] private float _flexiWind;
[XmlIgnore] private float _flexiForceX;
[XmlIgnore] private float _flexiForceY;
[XmlIgnore] private float _flexiForceZ;
//Bright n sparkly
[XmlIgnore] private float _lightColorR;
[XmlIgnore] private float _lightColorG;
[XmlIgnore] private float _lightColorB;
[XmlIgnore] private float _lightColorA = 1.0f;
[XmlIgnore] private float _lightRadius;
[XmlIgnore] private float _lightCutoff;
[XmlIgnore] private float _lightFalloff;
[XmlIgnore] private float _lightIntensity = 1.0f;
[XmlIgnore] private bool _flexiEntry;
[XmlIgnore] private bool _lightEntry;
[XmlIgnore] private bool _sculptEntry;
// Light Projection Filter
[XmlIgnore] private bool _projectionEntry;
[XmlIgnore] private UUID _projectionTextureID;
[XmlIgnore] private float _projectionFOV;
[XmlIgnore] private float _projectionFocus;
[XmlIgnore] private float _projectionAmb;
// XML3D Representation
// FIXME: Currently it's just a hack and we will set and get the value of this property
// directly, but correct implementation would be to derive all other fields in setter and
// construct this representation dynamically in getter.
public string XML3D { get; set; }
public byte ProfileCurve
{
get { return (byte)((byte)HollowShape | (byte)ProfileShape); }
set
{
// Handle hollow shape component
byte hollowShapeByte = (byte)(value & 0xf0);
if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
this._hollowShape = HollowShape.Same;
}
else
{
this._hollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
byte profileShapeByte = (byte)(value & 0xf);
if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
this._profileShape = ProfileShape.Square;
}
else
{
this._profileShape = (ProfileShape)profileShapeByte;
}
}
}
/// <summary>
/// Entries to store media textures on each face
/// </summary>
/// Do not change this value directly - always do it through an IMoapModule.
/// Lock before manipulating.
public MediaList Media { get; set; }
public PrimitiveBaseShape()
{
PCode = (byte)PCodeEnum.Primitive;
m_textureEntry = DEFAULT_TEXTURE;
}
/// <summary>
/// Construct a PrimitiveBaseShape object from a OpenMetaverse.Primitive object
/// </summary>
/// <param name="prim"></param>
public PrimitiveBaseShape(Primitive prim)
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Creating from {0}", prim.ID);
PCode = (byte)prim.PrimData.PCode;
State = prim.PrimData.State;
PathBegin = Primitive.PackBeginCut(prim.PrimData.PathBegin);
PathEnd = Primitive.PackEndCut(prim.PrimData.PathEnd);
PathScaleX = Primitive.PackPathScale(prim.PrimData.PathScaleX);
PathScaleY = Primitive.PackPathScale(prim.PrimData.PathScaleY);
PathShearX = (byte)Primitive.PackPathShear(prim.PrimData.PathShearX);
PathShearY = (byte)Primitive.PackPathShear(prim.PrimData.PathShearY);
PathSkew = Primitive.PackPathTwist(prim.PrimData.PathSkew);
ProfileBegin = Primitive.PackBeginCut(prim.PrimData.ProfileBegin);
ProfileEnd = Primitive.PackEndCut(prim.PrimData.ProfileEnd);
Scale = prim.Scale;
PathCurve = (byte)prim.PrimData.PathCurve;
ProfileCurve = (byte)prim.PrimData.ProfileCurve;
ProfileHollow = Primitive.PackProfileHollow(prim.PrimData.ProfileHollow);
PathRadiusOffset = Primitive.PackPathTwist(prim.PrimData.PathRadiusOffset);
PathRevolutions = Primitive.PackPathRevolutions(prim.PrimData.PathRevolutions);
PathTaperX = Primitive.PackPathTaper(prim.PrimData.PathTaperX);
PathTaperY = Primitive.PackPathTaper(prim.PrimData.PathTaperY);
PathTwist = Primitive.PackPathTwist(prim.PrimData.PathTwist);
PathTwistBegin = Primitive.PackPathTwist(prim.PrimData.PathTwistBegin);
m_textureEntry = prim.Textures.GetBytes();
if (prim.Sculpt != null)
{
SculptEntry = (prim.Sculpt.Type != OpenMetaverse.SculptType.None);
SculptData = prim.Sculpt.GetBytes();
SculptTexture = prim.Sculpt.SculptTexture;
SculptType = (byte)prim.Sculpt.Type;
}
else
{
SculptType = (byte)OpenMetaverse.SculptType.None;
}
}
[XmlIgnore]
public Primitive.TextureEntry Textures
{
get
{
// m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
try { return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); }
catch { }
m_log.Warn("[SHAPE]: Failed to decode texture, length=" + ((m_textureEntry != null) ? m_textureEntry.Length : 0));
return new Primitive.TextureEntry(UUID.Zero);
}
set { m_textureEntry = value.GetBytes(); }
}
public byte[] TextureEntry
{
get { return m_textureEntry; }
set
{
if (value == null)
m_textureEntry = new byte[1];
else
m_textureEntry = value;
}
}
public static PrimitiveBaseShape Default
{
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
public static PrimitiveBaseShape Create()
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
return shape;
}
public static PrimitiveBaseShape CreateBox()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Straight;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.HalfCircle;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public void SetScale(float side)
{
_scale = new Vector3(side, side, side);
}
public void SetHeigth(float height)
{
_scale.Z = height;
}
public void SetRadius(float radius)
{
_scale.X = _scale.Y = radius * 2f;
}
// TODO: void returns need to change of course
public virtual void GetMesh()
{
}
public PrimitiveBaseShape Copy()
{
return (PrimitiveBaseShape) MemberwiseClone();
}
public static PrimitiveBaseShape CreateCylinder(float radius, float heigth)
{
PrimitiveBaseShape shape = CreateCylinder();
shape.SetHeigth(heigth);
shape.SetRadius(radius);
return shape;
}
public void SetPathRange(Vector3 pathRange)
{
_pathBegin = Primitive.PackBeginCut(pathRange.X);
_pathEnd = Primitive.PackEndCut(pathRange.Y);
}
public void SetPathRange(float begin, float end)
{
_pathBegin = Primitive.PackBeginCut(begin);
_pathEnd = Primitive.PackEndCut(end);
}
public void SetSculptProperties(byte sculptType, UUID SculptTextureUUID)
{
_sculptType = sculptType;
_sculptTexture = SculptTextureUUID;
}
public void SetProfileRange(Vector3 profileRange)
{
_profileBegin = Primitive.PackBeginCut(profileRange.X);
_profileEnd = Primitive.PackEndCut(profileRange.Y);
}
public void SetProfileRange(float begin, float end)
{
_profileBegin = Primitive.PackBeginCut(begin);
_profileEnd = Primitive.PackEndCut(end);
}
public byte[] ExtraParams
{
get
{
return ExtraParamsToBytes();
}
set
{
ReadInExtraParamsBytes(value);
}
}
public ushort PathBegin {
get {
return _pathBegin;
}
set {
_pathBegin = value;
}
}
public byte PathCurve {
get {
return _pathCurve;
}
set {
_pathCurve = value;
}
}
public ushort PathEnd {
get {
return _pathEnd;
}
set {
_pathEnd = value;
}
}
public sbyte PathRadiusOffset {
get {
return _pathRadiusOffset;
}
set {
_pathRadiusOffset = value;
}
}
public byte PathRevolutions {
get {
return _pathRevolutions;
}
set {
_pathRevolutions = value;
}
}
public byte PathScaleX {
get {
return _pathScaleX;
}
set {
_pathScaleX = value;
}
}
public byte PathScaleY {
get {
return _pathScaleY;
}
set {
_pathScaleY = value;
}
}
public byte PathShearX {
get {
return _pathShearX;
}
set {
_pathShearX = value;
}
}
public byte PathShearY {
get {
return _pathShearY;
}
set {
_pathShearY = value;
}
}
public sbyte PathSkew {
get {
return _pathSkew;
}
set {
_pathSkew = value;
}
}
public sbyte PathTaperX {
get {
return _pathTaperX;
}
set {
_pathTaperX = value;
}
}
public sbyte PathTaperY {
get {
return _pathTaperY;
}
set {
_pathTaperY = value;
}
}
public sbyte PathTwist {
get {
return _pathTwist;
}
set {
_pathTwist = value;
}
}
public sbyte PathTwistBegin {
get {
return _pathTwistBegin;
}
set {
_pathTwistBegin = value;
}
}
public byte PCode {
get {
return _pCode;
}
set {
_pCode = value;
}
}
public ushort ProfileBegin {
get {
return _profileBegin;
}
set {
_profileBegin = value;
}
}
public ushort ProfileEnd {
get {
return _profileEnd;
}
set {
_profileEnd = value;
}
}
public ushort ProfileHollow {
get {
return _profileHollow;
}
set {
_profileHollow = value;
}
}
public Vector3 Scale {
get {
return _scale;
}
set {
_scale = value;
}
}
public byte State {
get {
return _state;
}
set {
_state = value;
}
}
public ProfileShape ProfileShape {
get {
return _profileShape;
}
set {
_profileShape = value;
}
}
public HollowShape HollowShape {
get {
return _hollowShape;
}
set {
_hollowShape = value;
}
}
public UUID SculptTexture {
get {
return _sculptTexture;
}
set {
_sculptTexture = value;
}
}
public byte SculptType
{
get
{
return _sculptType;
}
set
{
_sculptType = value;
}
}
// This is only used at runtime. For sculpties this holds the texture data, and for meshes
// the mesh data.
public byte[] SculptData
{
get
{
return _sculptData;
}
set
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Setting SculptData to data with length {0}", value.Length);
_sculptData = value;
}
}
public int FlexiSoftness
{
get
{
return _flexiSoftness;
}
set
{
_flexiSoftness = value;
}
}
public float FlexiTension {
get {
return _flexiTension;
}
set {
_flexiTension = value;
}
}
public float FlexiDrag {
get {
return _flexiDrag;
}
set {
_flexiDrag = value;
}
}
public float FlexiGravity {
get {
return _flexiGravity;
}
set {
_flexiGravity = value;
}
}
public float FlexiWind {
get {
return _flexiWind;
}
set {
_flexiWind = value;
}
}
public float FlexiForceX {
get {
return _flexiForceX;
}
set {
_flexiForceX = value;
}
}
public float FlexiForceY {
get {
return _flexiForceY;
}
set {
_flexiForceY = value;
}
}
public float FlexiForceZ {
get {
return _flexiForceZ;
}
set {
_flexiForceZ = value;
}
}
public float LightColorR {
get {
return _lightColorR;
}
set {
_lightColorR = value;
}
}
public float LightColorG {
get {
return _lightColorG;
}
set {
_lightColorG = value;
}
}
public float LightColorB {
get {
return _lightColorB;
}
set {
_lightColorB = value;
}
}
public float LightColorA {
get {
return _lightColorA;
}
set {
_lightColorA = value;
}
}
public float LightRadius {
get {
return _lightRadius;
}
set {
_lightRadius = value;
}
}
public float LightCutoff {
get {
return _lightCutoff;
}
set {
_lightCutoff = value;
}
}
public float LightFalloff {
get {
return _lightFalloff;
}
set {
_lightFalloff = value;
}
}
public float LightIntensity {
get {
return _lightIntensity;
}
set {
_lightIntensity = value;
}
}
public bool FlexiEntry {
get {
return _flexiEntry;
}
set {
_flexiEntry = value;
}
}
public bool LightEntry {
get {
return _lightEntry;
}
set {
_lightEntry = value;
}
}
public bool SculptEntry {
get {
return _sculptEntry;
}
set {
_sculptEntry = value;
}
}
public bool ProjectionEntry {
get {
return _projectionEntry;
}
set {
_projectionEntry = value;
}
}
public UUID ProjectionTextureUUID {
get {
return _projectionTextureID;
}
set {
_projectionTextureID = value;
}
}
public float ProjectionFOV {
get {
return _projectionFOV;
}
set {
_projectionFOV = value;
}
}
public float ProjectionFocus {
get {
return _projectionFocus;
}
set {
_projectionFocus = value;
}
}
public float ProjectionAmbiance {
get {
return _projectionAmb;
}
set {
_projectionAmb = value;
}
}
public ulong GetMeshKey(Vector3 size, float lod)
{
ulong hash = 5381;
hash = djb2(hash, this.PathCurve);
hash = djb2(hash, (byte)((byte)this.HollowShape | (byte)this.ProfileShape));
hash = djb2(hash, this.PathBegin);
hash = djb2(hash, this.PathEnd);
hash = djb2(hash, this.PathScaleX);
hash = djb2(hash, this.PathScaleY);
hash = djb2(hash, this.PathShearX);
hash = djb2(hash, this.PathShearY);
hash = djb2(hash, (byte)this.PathTwist);
hash = djb2(hash, (byte)this.PathTwistBegin);
hash = djb2(hash, (byte)this.PathRadiusOffset);
hash = djb2(hash, (byte)this.PathTaperX);
hash = djb2(hash, (byte)this.PathTaperY);
hash = djb2(hash, this.PathRevolutions);
hash = djb2(hash, (byte)this.PathSkew);
hash = djb2(hash, this.ProfileBegin);
hash = djb2(hash, this.ProfileEnd);
hash = djb2(hash, this.ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
byte[] scaleBytes = size.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
// Include LOD in hash, accounting for endianness
byte[] lodBytes = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lodBytes, 0, 4);
}
for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]);
// include sculpt UUID
if (this.SculptEntry)
{
scaleBytes = this.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
}
return hash;
}
private ulong djb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong djb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
public byte[] ExtraParamsToBytes()
{
// m_log.DebugFormat("[EXTRAPARAMS]: Called ExtraParamsToBytes()");
ushort FlexiEP = 0x10;
ushort LightEP = 0x20;
ushort SculptEP = 0x30;
ushort ProjectionEP = 0x40;
int i = 0;
uint TotalBytesLength = 1; // ExtraParamsNum
uint ExtraParamsNum = 0;
if (_flexiEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_lightEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_sculptEntry)
{
ExtraParamsNum++;
TotalBytesLength += 17;// data
TotalBytesLength += 2 + 4; // type
}
if (_projectionEntry)
{
ExtraParamsNum++;
TotalBytesLength += 28;// data
TotalBytesLength += 2 + 4;// type
}
byte[] returnbytes = new byte[TotalBytesLength];
// uint paramlength = ExtraParamsNum;
// Stick in the number of parameters
returnbytes[i++] = (byte)ExtraParamsNum;
if (_flexiEntry)
{
byte[] FlexiData = GetFlexiBytes();
returnbytes[i++] = (byte)(FlexiEP % 256);
returnbytes[i++] = (byte)((FlexiEP >> 8) % 256);
returnbytes[i++] = (byte)(FlexiData.Length % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256);
Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length);
i += FlexiData.Length;
}
if (_lightEntry)
{
byte[] LightData = GetLightBytes();
returnbytes[i++] = (byte)(LightEP % 256);
returnbytes[i++] = (byte)((LightEP >> 8) % 256);
returnbytes[i++] = (byte)(LightData.Length % 256);
returnbytes[i++] = (byte)((LightData.Length >> 8) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 16) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 24) % 256);
Array.Copy(LightData, 0, returnbytes, i, LightData.Length);
i += LightData.Length;
}
if (_sculptEntry)
{
byte[] SculptData = GetSculptBytes();
returnbytes[i++] = (byte)(SculptEP % 256);
returnbytes[i++] = (byte)((SculptEP >> 8) % 256);
returnbytes[i++] = (byte)(SculptData.Length % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256);
Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length);
i += SculptData.Length;
}
if (_projectionEntry)
{
byte[] ProjectionData = GetProjectionBytes();
returnbytes[i++] = (byte)(ProjectionEP % 256);
returnbytes[i++] = (byte)((ProjectionEP >> 8) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 16) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 20) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 24) % 256);
Array.Copy(ProjectionData, 0, returnbytes, i, ProjectionData.Length);
i += ProjectionData.Length;
}
if (!_flexiEntry && !_lightEntry && !_sculptEntry && !_projectionEntry)
{
byte[] returnbyte = new byte[1];
returnbyte[0] = 0;
return returnbyte;
}
return returnbytes;
}
public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
{
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
switch (type)
{
case FlexiEP:
if (!inUse)
{
_flexiEntry = false;
return;
}
ReadFlexiData(data, 0);
break;
case LightEP:
if (!inUse)
{
_lightEntry = false;
return;
}
ReadLightData(data, 0);
break;
case SculptEP:
if (!inUse)
{
_sculptEntry = false;
return;
}
ReadSculptData(data, 0);
break;
case ProjectionEP:
if (!inUse)
{
_projectionEntry = false;
return;
}
ReadProjectionData(data, 0);
break;
}
}
public void ReadInExtraParamsBytes(byte[] data)
{
if (data == null || data.Length == 1)
return;
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
bool lGotFlexi = false;
bool lGotLight = false;
bool lGotSculpt = false;
bool lGotFilter = false;
int i = 0;
byte extraParamCount = 0;
if (data.Length > 0)
{
extraParamCount = data[i++];
}
for (int k = 0; k < extraParamCount; k++)
{
ushort epType = Utils.BytesToUInt16(data, i);
i += 2;
// uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
switch (epType)
{
case FlexiEP:
ReadFlexiData(data, i);
i += 16;
lGotFlexi = true;
break;
case LightEP:
ReadLightData(data, i);
i += 16;
lGotLight = true;
break;
case SculptEP:
ReadSculptData(data, i);
i += 17;
lGotSculpt = true;
break;
case ProjectionEP:
ReadProjectionData(data, i);
i += 28;
lGotFilter = true;
break;
}
}
if (!lGotFlexi)
_flexiEntry = false;
if (!lGotLight)
_lightEntry = false;
if (!lGotSculpt)
_sculptEntry = false;
if (!lGotFilter)
_projectionEntry = false;
}
public void ReadSculptData(byte[] data, int pos)
{
UUID SculptUUID;
byte SculptTypel;
if (data.Length-pos >= 17)
{
_sculptEntry = true;
byte[] SculptTextureUUID = new byte[16];
SculptTypel = data[16 + pos];
Array.Copy(data, pos, SculptTextureUUID,0, 16);
SculptUUID = new UUID(SculptTextureUUID, 0);
}
else
{
_sculptEntry = false;
SculptUUID = UUID.Zero;
SculptTypel = 0x00;
}
if (_sculptEntry)
{
if (_sculptType != (byte)1 && _sculptType != (byte)2 && _sculptType != (byte)3 && _sculptType != (byte)4)
_sculptType = 4;
}
_sculptTexture = SculptUUID;
_sculptType = SculptTypel;
//m_log.Info("[SCULPT]:" + SculptUUID.ToString());
}
public byte[] GetSculptBytes()
{
byte[] data = new byte[17];
_sculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)_sculptType;
return data;
}
public void ReadFlexiData(byte[] data, int pos)
{
if (data.Length-pos >= 16)
{
_flexiEntry = true;
_flexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
_flexiTension = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiDrag = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiGravity = (float)(data[pos++] / 10.0f) - 10.0f;
_flexiWind = (float)data[pos++] / 10.0f;
Vector3 lForce = new Vector3(data, pos);
_flexiForceX = lForce.X;
_flexiForceY = lForce.Y;
_flexiForceZ = lForce.Z;
}
else
{
_flexiEntry = false;
_flexiSoftness = 0;
_flexiTension = 0.0f;
_flexiDrag = 0.0f;
_flexiGravity = 0.0f;
_flexiWind = 0.0f;
_flexiForceX = 0f;
_flexiForceY = 0f;
_flexiForceZ = 0f;
}
}
public byte[] GetFlexiBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((_flexiSoftness & 2) << 6);
data[i + 1] = (byte)((_flexiSoftness & 1) << 7);
data[i++] |= (byte)((byte)(_flexiTension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(_flexiDrag * 10.01f) & 0x7F);
data[i++] = (byte)((_flexiGravity + 10.0f) * 10.01f);
data[i++] = (byte)(_flexiWind * 10.01f);
Vector3 lForce = new Vector3(_flexiForceX, _flexiForceY, _flexiForceZ);
lForce.GetBytes().CopyTo(data, i);
return data;
}
public void ReadLightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
_lightEntry = true;
Color4 lColor = new Color4(data, pos, false);
_lightIntensity = lColor.A;
_lightColorA = 1f;
_lightColorR = lColor.R;
_lightColorG = lColor.G;
_lightColorB = lColor.B;
_lightRadius = Utils.BytesToFloat(data, pos + 4);
_lightCutoff = Utils.BytesToFloat(data, pos + 8);
_lightFalloff = Utils.BytesToFloat(data, pos + 12);
}
else
{
_lightEntry = false;
_lightColorA = 1f;
_lightColorR = 0f;
_lightColorG = 0f;
_lightColorB = 0f;
_lightRadius = 0f;
_lightCutoff = 0f;
_lightFalloff = 0f;
_lightIntensity = 0f;
}
}
public byte[] GetLightBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = new Color4(_lightColorR,_lightColorG,_lightColorB,_lightIntensity);
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_lightRadius).CopyTo(data, 4);
Utils.FloatToBytes(_lightCutoff).CopyTo(data, 8);
Utils.FloatToBytes(_lightFalloff).CopyTo(data, 12);
return data;
}
public void ReadProjectionData(byte[] data, int pos)
{
byte[] ProjectionTextureUUID = new byte[16];
if (data.Length - pos >= 28)
{
_projectionEntry = true;
Array.Copy(data, pos, ProjectionTextureUUID,0, 16);
_projectionTextureID = new UUID(ProjectionTextureUUID, 0);
_projectionFOV = Utils.BytesToFloat(data, pos + 16);
_projectionFocus = Utils.BytesToFloat(data, pos + 20);
_projectionAmb = Utils.BytesToFloat(data, pos + 24);
}
else
{
_projectionEntry = false;
_projectionTextureID = UUID.Zero;
_projectionFOV = 0f;
_projectionFocus = 0f;
_projectionAmb = 0f;
}
}
public byte[] GetProjectionBytes()
{
byte[] data = new byte[28];
_projectionTextureID.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_projectionFOV).CopyTo(data, 16);
Utils.FloatToBytes(_projectionFocus).CopyTo(data, 20);
Utils.FloatToBytes(_projectionAmb).CopyTo(data, 24);
return data;
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <returns></returns>
public Primitive ToOmvPrimitive()
{
// position and rotation defaults here since they are not available in PrimitiveBaseShape
return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f),
new Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
prim.Scale = this.Scale;
prim.Position = position;
prim.Rotation = rotation;
if (this.SculptEntry)
{
prim.Sculpt = new Primitive.SculptData();
prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
prim.Sculpt.SculptTexture = this.SculptTexture;
}
prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f;
prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f;
prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
prim.PrimData.PathTwist = this.PathTwist * 0.01f;
prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
prim.PrimData.profileCurve = this.ProfileCurve;
prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
prim.PrimData.PathSkew = 0.01f * this.PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
if (this.FlexiEntry)
{
prim.Flexible = new Primitive.FlexibleData();
prim.Flexible.Drag = this.FlexiDrag;
prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
prim.Flexible.Gravity = this.FlexiGravity;
prim.Flexible.Softness = this.FlexiSoftness;
prim.Flexible.Tension = this.FlexiTension;
prim.Flexible.Wind = this.FlexiWind;
}
if (this.LightEntry)
{
prim.Light = new Primitive.LightData();
prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
prim.Light.Cutoff = this.LightCutoff;
prim.Light.Falloff = this.LightFalloff;
prim.Light.Intensity = this.LightIntensity;
prim.Light.Radius = this.LightRadius;
}
prim.Textures = this.Textures;
prim.Properties = new Primitive.ObjectProperties();
prim.Properties.Name = "Primitive";
prim.Properties.Description = "";
prim.Properties.CreatorID = UUID.Zero;
prim.Properties.GroupID = UUID.Zero;
prim.Properties.OwnerID = UUID.Zero;
prim.Properties.Permissions = new Permissions();
prim.Properties.SalePrice = 10;
prim.Properties.SaleType = new SaleType();
return prim;
}
/// <summary>
/// Encapsulates a list of media entries.
/// </summary>
/// This class is necessary because we want to replace auto-serialization of MediaEntry with something more
/// OSD like and less vulnerable to change.
public class MediaList : List<MediaEntry>, IXmlSerializable
{
public const string MEDIA_TEXTURE_TYPE = "sl";
public MediaList() : base() {}
public MediaList(IEnumerable<MediaEntry> collection) : base(collection) {}
public MediaList(int capacity) : base(capacity) {}
public XmlSchema GetSchema()
{
return null;
}
public string ToXml()
{
lock (this)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
xtw.WriteStartElement("OSMedia");
xtw.WriteAttributeString("type", MEDIA_TEXTURE_TYPE);
xtw.WriteAttributeString("version", "0.1");
OSDArray meArray = new OSDArray();
foreach (MediaEntry me in this)
{
OSD osd = (null == me ? new OSD() : me.GetOSD());
meArray.Add(osd);
}
xtw.WriteStartElement("OSData");
xtw.WriteRaw(OSDParser.SerializeLLSDXmlString(meArray));
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.Flush();
return sw.ToString();
}
}
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteRaw(ToXml());
}
public static MediaList FromXml(string rawXml)
{
MediaList ml = new MediaList();
ml.ReadXml(rawXml);
return ml;
}
public void ReadXml(string rawXml)
{
using (StringReader sr = new StringReader(rawXml))
{
using (XmlTextReader xtr = new XmlTextReader(sr))
{
xtr.MoveToContent();
string type = xtr.GetAttribute("type");
//m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
if (type != MEDIA_TEXTURE_TYPE)
return;
xtr.ReadStartElement("OSMedia");
OSDArray osdMeArray = (OSDArray)OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
foreach (OSD osdMe in osdMeArray)
{
MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
Add(me);
}
xtr.ReadEndElement();
}
}
}
public void ReadXml(XmlReader reader)
{
if (reader.IsEmptyElement)
return;
ReadXml(reader.ReadInnerXml());
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace System
{
//This class contains only static members and doesn't require serialization.
using System;
using System.Runtime.CompilerServices;
[Clarity.ExportStub("System_Math.cpp")]
public static class Math
{
// Public Constants
// Summary:
// Represents the ratio of the circumference of a circle to its diameter, specified
// by the constant, p.
public const double PI = 3.14159265358979323846;
// Summary:
// Represents the natural logarithmic base, specified by the constant, e
public const double E = 2.7182818284590452354;
// Methods
// Summary:
// Returns the absolute value of an integer number.
//
// Parameters:
// value:
// A number in the range System.Double.MinValue=value=System.Double.MaxValue.
//
// Returns:
// An integer, x, such that 0 = x =System.Integer.MaxValue.
public static int Abs(int val)
{
return (val >= 0) ? val : -val;
}
//
// Summary:
// Returns the larger of two integer numbers.
//
// Parameters:
// val1:
// The first of two integert numbers to compare.
//
// val2:
// The second of two integer numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is larger.
public static int Max(int val1, int val2)
{
return (val1 >= val2) ? val1 : val2;
}
//
// Summary:
// Returns the smaller of two integer numbers.
//
// Parameters:
// val1:
// The first of two integer numbers to compare.
//
// val2:
// The second of two integer numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is smaller.
public static int Min(int val1, int val2)
{
return (val1 <= val2) ? val1 : val2;
}
// Summary:
// Returns the absolute value of a double-precision floating-point number.
//
// Parameters:
// value:
// A number in the range System.Double.MinValue=value=System.Double.MaxValue.
//
// Returns:
// A double-precision floating-point number, x, such that 0 = x =System.Double.MaxValue.
public static double Abs(double val)
{
return (val >= 0) ? val : -val;
}
//
// Summary:
// Returns the angle whose cosine is the specified number.
//
// Parameters:
// d:
// A number representing a cosine, where -1 =d= 1.
//
// Returns:
// An angle, ?, measured in radians, such that 0 =?=p -or- System.Double.NaN
// if d < -1 or d > 1.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Acos(double d);
//
// Summary:
// Returns the angle whose sine is the specified number.
//
// Parameters:
// d:
// A number representing a sine, where -1 =d= 1.
//
// Returns:
// An angle, ?, measured in radians, such that -p/2 =?=p/2 -or- System.Double.NaN
// if d < -1 or d > 1.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Asin(double d);
//
// Summary:
// Returns the angle whose tangent is the specified number.
//
// Parameters:
// d:
// A number representing a tangent.
//
// Returns:
// An angle, ?, measured in radians, such that -p/2 =?=p/2. -or- System.Double.NaN
// if d equals System.Double.NaN, -p/2 rounded to double precision (-1.5707963267949)
// if d equals System.Double.NegativeInfinity, or p/2 rounded to double precision
// (1.5707963267949) if d equals System.Double.PositiveInfinity.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan(double d);
//
// Summary:
// Returns the angle whose tangent is the quotient of two specified numbers.
//
// Parameters:
// y:
// The y coordinate of a point.
//
// x:
// The x coordinate of a point.
//
// Returns:
// An angle, ?, measured in radians, such that -p=?=p, and tan(?) = y / x, where
// (x, y) is a point in the Cartesian plane. Observe the following: For (x,
// y) in quadrant 1, 0 < ? < p/2. For (x, y) in quadrant 2, p/2 < ?=p. For
// (x, y) in quadrant 3, -p < ? < -p/2. For (x, y) in quadrant 4, -p/2 < ?
// < 0. For points on the boundaries of the quadrants, the return value is
// the following: If y is 0 and x is not negative, ? = 0. If y is 0 and x is
// negative, ? = p. If y is positive and x is 0, ? = p/2. If y is negative
// and x is 0, ? = -p/2.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan2(double y, double x); //
// Summary:
// Returns the smallest integer greater than or equal to the specified double-precision
// floating-point number.
//
// Parameters:
// a:
// A double-precision floating-point number.
//
// Returns:
// The smallest integer greater than or equal to a. If a is equal to System.Double.NaN,
// System.Double.NegativeInfinity, or System.Double.PositiveInfinity, that value
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Ceiling(double d); //
// Summary:
// Returns the cosine of the specified angle.
//
// Parameters:
// d:
// An angle, measured in radians.
//
// Returns:
// The cosine of d.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cos(double a);
//
// Summary:
// Returns the hyperbolic cosine of the specified angle.
//
// Parameters:
// value:
// An angle, measured in radians.
//
// Returns:
// The hyperbolic cosine of value. If value is equal to System.Double.NegativeInfinity
// or System.Double.PositiveInfinity, System.Double.PositiveInfinity is returned.
// If value is equal to System.Double.NaN, System.Double.NaN is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cosh(double a);
//
// Summary:
// Returns the remainder resulting from the division of a specified number by
// another specified number.
//
// Parameters:
// x:
// A dividend.
//
// y:
// A divisor.
//
// Returns:
// A number equal to x - (y Q), where Q is the quotient of x / y rounded to
// the nearest integer (if x / y falls halfway between two integers, the even
// integer is returned). If x - (y Q) is zero, the value +0 is returned if
// x is positive, or -0 if x is negative. If y = 0, System.Double.NaN (Not-A-Number)
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double IEEERemainder(double x, double y);
//
// Summary:
// Returns e raised to the specified power.
//
// Parameters:
// d:
// A number specifying a power.
//
// Returns:
// The number e raised to the power d. If d equals System.Double.NaN or System.Double.PositiveInfinity,
// that value is returned. If d equals System.Double.NegativeInfinity, 0 is
// returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Exp(double d);
//
// Summary:
// Returns the largest integer less than or equal to the specified double-precision
// floating-point number.
//
// Parameters:
// d:
// A double-precision floating-point number.
//
// Returns:
// The largest integer less than or equal to d. If d is equal to System.Double.NaN,
// System.Double.NegativeInfinity, or System.Double.PositiveInfinity, that value
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Floor(double d);
//
// Summary:
// Returns the natural (base e) logarithm of a specified number.
//
// Parameters:
// d:
// A number whose logarithm is to be found.
//
// Returns:
// Sign of d Returns Positive The natural logarithm of d; that is, ln d, or
// log ed Zero System.Double.NegativeInfinity Negative System.Double.NaN If
// d is equal to System.Double.NaN, returns System.Double.NaN. If d is equal
// to System.Double.PositiveInfinity, returns System.Double.PositiveInfinity.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log(double d);
//
// Summary:
// Returns the base 10 logarithm of a specified number.
//
// Parameters:
// d:
// A number whose logarithm is to be found.
//
// Returns:
// Sign of d Returns Positive The base 10 log of d; that is, log 10d. Zero System.Double.NegativeInfinity
// Negative System.Double.NaN If d is equal to System.Double.NaN, this method
// returns System.Double.NaN. If d is equal to System.Double.PositiveInfinity,
// this method returns System.Double.PositiveInfinity.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log10(double d);
//
// Summary:
// Returns the larger of two double-precision floating-point numbers.
//
// Parameters:
// val1:
// The first of two double-precision floating-point numbers to compare.
//
// val2:
// The second of two double-precision floating-point numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is larger. If val1, val2, or both val1
// and val2 are equal to System.Double.NaN, System.Double.NaN is returned.
public static double Max(double x, double y)
{
return (x >= y) ? x : y;
}
//
// Summary:
// Returns the smaller of two double-precision floating-point numbers.
//
// Parameters:
// val1:
// The first of two double-precision floating-point numbers to compare.
//
// val2:
// The second of two double-precision floating-point numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is smaller. If val1, val2, or both val1
// and val2 are equal to System.Double.NaN, System.Double.NaN is returned.
public static double Min(double x, double y)
{
return (x <= y) ? x : y;
}
//
// Summary:
// Returns a specified number raised to the specified power.
//
// Parameters:
// x:
// A double-precision floating-point number to be raised to a power.
//
// y:
// A double-precision floating-point number that specifies a power.
//
// Returns:
// The number x raised to the power y.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Pow(double x, double y); //
// Summary:
// Rounds a double-precision floating-point value to the nearest integer.
//
// Parameters:
// a:
// A double-precision floating-point number to be rounded.
//
// Returns:
// The integer nearest a. If the fractional component of a is halfway between
// two integers, one of which is even and the other odd, then the even number
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Round(double d); //
//
// Summary:
// Returns a value indicating the sign of a double-precision floating-point
// number.
//
// Parameters:
// value:
// A signed number.
//
// Returns:
// A number indicating the sign of value. Number Description -1 value is less
// than zero. 0 value is equal to zero. 1 value is greater than zero.
//
// Exceptions:
// System.ArithmeticException:
// value is equal to System.Double.NaN.
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int Sign(double value);
// Summary:
// Returns the sine of the specified angle.
//
// Parameters:
// a:
// An angle, measured in radians.
//
// Returns:
// The sine of a. If a is equal to System.Double.NaN, System.Double.NegativeInfinity,
// or System.Double.PositiveInfinity, this method returns System.Double.NaN.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sin(double a);
//
// Summary:
// Returns the hyperbolic sine of the specified angle.
//
// Parameters:
// value:
// An angle, measured in radians.
//
// Returns:
// The hyperbolic sine of value. If value is equal to System.Double.NegativeInfinity,
// System.Double.PositiveInfinity, or System.Double.NaN, this method returns
// a System.Double equal to value.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sinh(double value);
//
// Summary:
// Returns the square root of a specified number.
//
// Parameters:
// d:
// A number.
//
// Returns:
// Value of d Returns Zero, or positive The positive square root of d. Negative
// System.Double.NaN If d is equal to System.Double.NaN or System.Double.PositiveInfinity,
// that value is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sqrt(double d);
//
// Summary:
// Returns the tangent of the specified angle.
//
// Parameters:
// a:
// An angle, measured in radians.
//
// Returns:
// The tangent of a. If a is equal to System.Double.NaN, System.Double.NegativeInfinity,
// or System.Double.PositiveInfinity, this method returns System.Double.NaN.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tan(double a);
//
// Summary:
// Returns the hyperbolic tangent of the specified angle.
//
// Parameters:
// value:
// An angle, measured in radians.
//
// Returns:
// The hyperbolic tangent of value. If value is equal to System.Double.NegativeInfinity,
// this method returns -1. If value is equal to System.Double.PositiveInfinity,
// this method returns 1. If value is equal to System.Double.NaN, this method
// returns System.Double.NaN.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tanh(double value);
//
// Summary:
// Calculates the integral part of a specified double-precision floating-point
// number.
//
// Parameters:
// d:
// A number to truncate.
//
// Returns:
// The integral part of d; that is, the number that remains after any fractional
// digits have been discarded.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Truncate(double d);
}
}
| |
// 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.DataLake.Store
{
using Azure;
using Management;
using DataLake;
using Rest;
using Rest.Azure;
using 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>
/// Creates an Azure Data Lake Store filesystem client.
/// </summary>
public partial class DataLakeStoreFileSystemManagementClient : ServiceClient<DataLakeStoreFileSystemManagementClient>, IDataLakeStoreFileSystemManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
internal string BaseUri {get; set;}
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public string AdlsFileSystemDnsSuffix { 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 IFileSystemOperations.
/// </summary>
public virtual IFileSystemOperations FileSystem { get; private set; }
/// <summary>
/// Initializes a new instance of the DataLakeStoreFileSystemManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeStoreFileSystemManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreFileSystemManagementClient 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 DataLakeStoreFileSystemManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeStoreFileSystemManagementClient 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>
internal DataLakeStoreFileSystemManagementClient(ServiceClientCredentials credentials, params System.Net.Http.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 DataLakeStoreFileSystemManagementClient 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>
internal DataLakeStoreFileSystemManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
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()
{
FileSystem = new FileSystemOperations(this);
BaseUri = "https://{accountName}.{adlsFileSystemDnsSuffix}";
ApiVersion = "2016-11-01";
AdlsFileSystemDnsSuffix = "azuredatalakestore.net";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.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 System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.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 System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<AdlsRemoteException>("exception"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<AdlsRemoteException>("exception"));
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="MathUtils.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
// This source is subject to the Microsoft Limited Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/limitedpermissivelicense.mspx
// This file is based on the 3D Tools for Windows Presentation Foundation
// project. For more information, see:
// http://CodePlex.com/Wiki/View.aspx?ProjectName=3DTools
//---------------------------------------------------------------------------
namespace Wpf3DTools
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
/// <summary>
/// A helper class for common math operations.
/// </summary>
public static class MathUtils
{
/// <summary>
/// The zero matrix definition
/// </summary>
public static readonly Matrix3D ZeroMatrix = new Matrix3D(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
/// <summary>
/// The X axis definition
/// </summary>
public static readonly Vector3D XAxis = new Vector3D(1, 0, 0);
/// <summary>
/// The Y axis definition
/// </summary>
public static readonly Vector3D YAxis = new Vector3D(0, 1, 0);
/// <summary>
/// The Z axis definition
/// </summary>
public static readonly Vector3D ZAxis = new Vector3D(0, 0, 1);
/// <summary>
/// Get the aspect ratio
/// </summary>
/// <param name="size">The image or window extent.</param>
/// <returns>Returns the aspect ratio.</returns>
public static double GetAspectRatio(Size size)
{
return size.Width / size.Height;
}
/// <summary>
/// Convert degrees to radians
/// </summary>
/// <param name="degrees">The angle in degrees.</param>
/// <returns>Returns the angle in radians.</returns>
public static double DegreesToRadians(double degrees)
{
return degrees * (Math.PI / 180.0);
}
/// <summary>
/// Computes the effective view matrix for the given camera.
/// </summary>
/// <param name="camera">The perspective, orthogonal or matrix camera.</param>
/// <returns>A Matrix3D containing the View.</returns>
public static Matrix3D GetViewMatrix(Camera camera)
{
if (camera == null)
{
throw new ArgumentNullException("camera");
}
ProjectionCamera projectionCamera = camera as ProjectionCamera;
if (projectionCamera != null)
{
return GetViewMatrix(projectionCamera);
}
MatrixCamera matrixCamera = camera as MatrixCamera;
if (matrixCamera != null)
{
return matrixCamera.ViewMatrix;
}
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported camera type '{0}'.", camera.GetType().FullName), "camera");
}
/// <summary>
/// Computes the effective projection matrix for the given camera.
/// </summary>
/// <param name="camera">The perspective, orthogonal or matrix camera.</param>
/// <param name="aspectRatio">The aspect ratio of the image or window.</param>
/// <returns>A Matrix3D containing the Projection matrix.</returns>
public static Matrix3D GetProjectionMatrix(Camera camera, double aspectRatio)
{
if (camera == null)
{
throw new ArgumentNullException("camera");
}
PerspectiveCamera perspectiveCamera = camera as PerspectiveCamera;
if (perspectiveCamera != null)
{
return GetProjectionMatrix(perspectiveCamera, aspectRatio);
}
OrthographicCamera orthographicCamera = camera as OrthographicCamera;
if (orthographicCamera != null)
{
return GetProjectionMatrix(orthographicCamera, aspectRatio);
}
MatrixCamera matrixCamera = camera as MatrixCamera;
if (matrixCamera != null)
{
return matrixCamera.ProjectionMatrix;
}
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported camera type '{0}'.", camera.GetType().FullName), "camera");
}
/// <summary>
/// Computes the transform from world space to the Viewport3DVisual's inner 2D space.
/// This method can fail if Camera.Transform is non-invertible in which case the camera clip
/// planes will be coincident and nothing will render. In this case success will be false.
/// </summary>
/// <param name="visual">The input visual.</param>
/// <param name="success">Whether the call succeeded.</param>
/// <returns>A Matrix3D containing the world-to-viewport transform.</returns>
public static Matrix3D TryWorldToViewportTransform(Viewport3DVisual visual, out bool success)
{
success = false;
Matrix3D result = TryWorldToCameraTransform(visual, out success);
if (null == visual)
{
return ZeroMatrix;
}
if (success)
{
result.Append(GetProjectionMatrix(visual.Camera, MathUtils.GetAspectRatio(visual.Viewport.Size)));
result.Append(GetHomogeneousToViewportTransform(visual.Viewport));
success = true;
}
return result;
}
/// <summary>
/// Computes the transform from world space to camera space
/// This method can fail if Camera.Transform is non-invertible, in which case the camera clip
/// planes will be coincident and nothing will render. In this case success will be false.
/// </summary>
/// <param name="visual">The input visual.</param>
/// <param name="success">Whether the call succeeded.</param>
/// <returns>A Matrix3D containing the world-to-camera transform.</returns>
public static Matrix3D TryWorldToCameraTransform(Viewport3DVisual visual, out bool success)
{
success = false;
Matrix3D result = Matrix3D.Identity;
if (null == visual)
{
return ZeroMatrix;
}
Camera camera = visual.Camera;
if (null == camera)
{
return ZeroMatrix;
}
Rect viewport = visual.Viewport;
if (viewport == Rect.Empty)
{
return ZeroMatrix;
}
Transform3D cameraTransform = camera.Transform;
if (cameraTransform != null)
{
Matrix3D m = cameraTransform.Value;
if (!m.HasInverse)
{
return ZeroMatrix;
}
m.Invert();
result.Append(m);
}
result.Append(GetViewMatrix(camera));
success = true;
return result;
}
/// <summary>
/// Computes the transform from the inner space of the given Visual3D to the 2D space of
/// the Viewport3DVisual which contains it. The result will contain the transform of the
/// given visual. This method can fail if Camera.Transform is non-invertible in which
/// case the camera clip planes will be coincident and nothing will render. In this case
/// success will be false.
/// </summary>
/// <param name="visual">The visual.</param>
/// <param name="viewport">The viewport.</param>
/// <param name="success">Set true if successful</param>
/// <returns>A Matrix3D.</returns>
public static Matrix3D TryTransformTo2DAncestor(DependencyObject visual, out Viewport3DVisual viewport, out bool success)
{
Matrix3D to2D = GetWorldTransformationMatrix(visual, out viewport);
to2D.Append(MathUtils.TryWorldToViewportTransform(viewport, out success));
if (!success)
{
return ZeroMatrix;
}
return to2D;
}
/// <summary>
/// Computes the transform from the inner space of the given Visual3D to the camera
/// coordinate space. The result will contain the transform of the given visual.
/// This method can fail if Camera.Transform is non-invertible in which case the
/// camera clip planes will be coincident and nothing will render. In this case success
/// will be false.
/// </summary>
/// <param name="visual">The visual.</param>
/// <param name="viewport">The viewport.</param>
/// <param name="success">Set true if successful.</param>
/// <returns>A Matrix3D containing.</returns>
public static Matrix3D TryTransformToCameraSpace(DependencyObject visual, out Viewport3DVisual viewport, out bool success)
{
Matrix3D toViewSpace = GetWorldTransformationMatrix(visual, out viewport);
toViewSpace.Append(MathUtils.TryWorldToCameraTransform(viewport, out success));
if (!success)
{
return ZeroMatrix;
}
return toViewSpace;
}
/// <summary>
/// Transforms the axis-aligned bounding box 'bounds' by 'transform'
/// </summary>
/// <param name="bounds">The AABB to transform</param>
/// <param name="transform">The transform to apply</param>
/// <returns>Transformed AABB</returns>
public static Rect3D TransformBounds(Rect3D bounds, Matrix3D transform)
{
double x1 = bounds.X;
double y1 = bounds.Y;
double z1 = bounds.Z;
double x2 = bounds.X + bounds.SizeX;
double y2 = bounds.Y + bounds.SizeY;
double z2 = bounds.Z + bounds.SizeZ;
Point3D[] points = new Point3D[]
{
new Point3D(x1, y1, z1),
new Point3D(x1, y1, z2),
new Point3D(x1, y2, z1),
new Point3D(x1, y2, z2),
new Point3D(x2, y1, z1),
new Point3D(x2, y1, z2),
new Point3D(x2, y2, z1),
new Point3D(x2, y2, z2),
};
transform.Transform(points);
// reuse the 1 and 2 variables to stand for smallest and largest
Point3D p = points[0];
x1 = x2 = p.X;
y1 = y2 = p.Y;
z1 = z2 = p.Z;
for (int i = 1; i < points.Length; i++)
{
p = points[i];
x1 = Math.Min(x1, p.X);
y1 = Math.Min(y1, p.Y);
z1 = Math.Min(z1, p.Z);
x2 = Math.Max(x2, p.X);
y2 = Math.Max(y2, p.Y);
z2 = Math.Max(z2, p.Z);
}
return new Rect3D(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1);
}
/// <summary>
/// Normalizes vector if |vector| > 0.
/// This normalization is slightly different from Vector3D.Normalize. Here we just divide
/// by the length but Vector3D.Normalize tries to avoid overflow when finding the length.
/// </summary>
/// <param name="vector">The vector to normalize</param>
/// <returns>'true' if vector was normalized</returns>
public static bool TryNormalize(ref Vector3D vector)
{
double length = vector.Length;
if (length != 0)
{
vector /= length;
return true;
}
return false;
}
/// <summary>
/// Computes the center of 'box'
/// </summary>
/// <param name="box">The rectangle we want the center of.</param>
/// <returns>The center point</returns>
public static Point3D GetCenter(Rect3D box)
{
return new Point3D(box.X + (box.SizeX / 2), box.Y + (box.SizeY / 2), box.Z + (box.SizeZ / 2));
}
/// <summary>
/// Get the view matrix from a camera.
/// </summary>
/// <param name="camera">The camera we want the view matrix of.</param>
/// <returns>Returns the view matrix.</returns>
private static Matrix3D GetViewMatrix(ProjectionCamera camera)
{
Debug.Assert(camera != null, "Caller needs to ensure camera is non-null.");
// This math is identical to what you find documented for
// D3DXMatrixLookAtRH with the exception that WPF uses a
// LookDirection vector rather than a LookAt point.
Vector3D axisZ = -camera.LookDirection;
axisZ.Normalize();
Vector3D axisX = Vector3D.CrossProduct(camera.UpDirection, axisZ);
axisX.Normalize();
Vector3D axisY = Vector3D.CrossProduct(axisZ, axisX);
Vector3D position = (Vector3D)camera.Position;
double offsetX = -Vector3D.DotProduct(axisX, position);
double offsetY = -Vector3D.DotProduct(axisY, position);
double offsetZ = -Vector3D.DotProduct(axisZ, position);
return new Matrix3D(
axisX.X,
axisY.X,
axisZ.X,
0,
axisX.Y,
axisY.Y,
axisZ.Y,
0,
axisX.Z,
axisY.Z,
axisZ.Z,
0,
offsetX,
offsetY,
offsetZ,
1);
}
/// <summary>
/// Get the projection matrix from an orthographic camera.
/// </summary>
/// <param name="camera">The camera we want the projection matrix of.</param>
/// <param name="aspectRatio">The aspect ratio of the image or window.</param>
/// <returns>Returns the projection matrix.</returns>
private static Matrix3D GetProjectionMatrix(OrthographicCamera camera, double aspectRatio)
{
Debug.Assert(camera != null, "Caller needs to ensure camera is non-null.");
// This math is identical to what you find documented for
// D3DXMatrixOrthoRH with the exception that in WPF only
// the camera's width is specified. Height is calculated
// from width and the aspect ratio.
double w = camera.Width;
double h = w / aspectRatio;
double zn = camera.NearPlaneDistance;
double zf = camera.FarPlaneDistance;
double m33 = 1 / (zn - zf);
double m43 = zn * m33;
return new Matrix3D(
2 / w,
0,
0,
0,
0,
2 / h,
0,
0,
0,
0,
m33,
0,
0,
0,
m43,
1);
}
/// <summary>
/// Get the projection matrix from a perspective camera.
/// </summary>
/// <param name="camera">The camera we want the projection matrix of.</param>
/// <param name="aspectRatio">The aspect ratio of the image or window.</param>
/// <returns>Returns the projection matrix.</returns>
private static Matrix3D GetProjectionMatrix(PerspectiveCamera camera, double aspectRatio)
{
Debug.Assert(camera != null, "Caller needs to ensure camera is non-null.");
// This math is identical to what you find documented for
// D3DXMatrixPerspectiveFovRH with the exception that in
// WPF the camera's horizontal rather the vertical
// field-of-view is specified.
double horizFoV = MathUtils.DegreesToRadians(camera.FieldOfView);
double zn = camera.NearPlaneDistance;
double zf = camera.FarPlaneDistance;
double scaleX = 1 / Math.Tan(horizFoV / 2);
double scaleY = aspectRatio * scaleX;
double m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf));
double m43 = zn * m33;
return new Matrix3D(
scaleX,
0,
0,
0,
0,
scaleY,
0,
0,
0,
0,
m33,
-1,
0,
0,
m43,
0);
}
/// <summary>
/// Get the 3D to viewport transformation.
/// </summary>
/// <param name="viewport">The viewport rectangle.</param>
/// <returns>Returns the 3D to viewport transform matrix.</returns>
private static Matrix3D GetHomogeneousToViewportTransform(Rect viewport)
{
double scaleX = viewport.Width / 2;
double scaleY = viewport.Height / 2;
double offsetX = viewport.X + scaleX;
double offsetY = viewport.Y + scaleY;
return new Matrix3D(
scaleX,
0,
0,
0,
0,
-scaleY,
0,
0,
0,
0,
1,
0,
offsetX,
offsetY,
0,
1);
}
/// <summary>
/// Gets the object space to world space transformation for the given DependencyObject
/// </summary>
/// <param name="visual">The visual whose world space transform should be found</param>
/// <param name="viewport">The Viewport3DVisual the Visual is contained within</param>
/// <returns>The world space transformation</returns>
private static Matrix3D GetWorldTransformationMatrix(DependencyObject visual, out Viewport3DVisual viewport)
{
Matrix3D worldTransform = Matrix3D.Identity;
viewport = null;
if (!(visual is Visual3D))
{
throw new ArgumentException("Must be of type Visual3D.", "visual");
}
while (visual != null)
{
if (!(visual is ModelVisual3D))
{
break;
}
Transform3D transform = (Transform3D)visual.GetValue(ModelVisual3D.TransformProperty);
if (transform != null)
{
worldTransform.Append(transform.Value);
}
visual = VisualTreeHelper.GetParent(visual);
}
viewport = visual as Viewport3DVisual;
if (viewport == null)
{
if (visual != null)
{
// In WPF 3D v1 the only possible configuration is a chain of
// ModelVisual3Ds leading up to a Viewport3DVisual.
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, "Unsupported type: '{0}'. Expected tree of ModelVisual3Ds leading up to a Viewport3DVisual.", visual.GetType().FullName));
}
return ZeroMatrix;
}
return worldTransform;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Cryptography
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class AesCryptoServiceProvider : System.Security.Cryptography.Aes
{
public AesCryptoServiceProvider() { }
public override int BlockSize { get { throw null; } set { } }
public override int FeedbackSize { get { throw null; } set { } }
public override byte[] IV { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
public sealed partial class CspKeyContainerInfo
{
public CspKeyContainerInfo(System.Security.Cryptography.CspParameters parameters) { }
public bool Accessible { get { throw null; } }
public bool Exportable { get { throw null; } }
public bool HardwareDevice { get { throw null; } }
public string KeyContainerName { get { throw null; } }
public System.Security.Cryptography.KeyNumber KeyNumber { get { throw null; } }
public bool MachineKeyStore { get { throw null; } }
public bool Protected { get { throw null; } }
public string ProviderName { get { throw null; } }
public int ProviderType { get { throw null; } }
public bool RandomlyGenerated { get { throw null; } }
public bool Removable { get { throw null; } }
public string UniqueKeyContainerName { get { throw null; } }
}
public sealed partial class CspParameters
{
public string KeyContainerName;
public int KeyNumber;
public string ProviderName;
public int ProviderType;
public CspParameters() { }
public CspParameters(int dwTypeIn) { }
public CspParameters(int dwTypeIn, string strProviderNameIn) { }
public CspParameters(int dwTypeIn, string strProviderNameIn, string strContainerNameIn) { }
public System.Security.Cryptography.CspProviderFlags Flags { get { throw null; } set { } }
[System.CLSCompliantAttribute(false)]
public System.Security.SecureString KeyPassword { get { throw null; } set { } }
public System.IntPtr ParentWindowHandle { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum CspProviderFlags
{
CreateEphemeralKey = 128,
NoFlags = 0,
NoPrompt = 64,
UseArchivableKey = 16,
UseDefaultKeyContainer = 2,
UseExistingKey = 8,
UseMachineKeyStore = 1,
UseNonExportableKey = 4,
UseUserProtectedKey = 32,
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class DESCryptoServiceProvider : System.Security.Cryptography.DES
{
public DESCryptoServiceProvider() { }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
public sealed partial class DSACryptoServiceProvider : System.Security.Cryptography.DSA, System.Security.Cryptography.ICspAsymmetricAlgorithm
{
public DSACryptoServiceProvider() { }
public DSACryptoServiceProvider(int dwKeySize) { }
public DSACryptoServiceProvider(int dwKeySize, System.Security.Cryptography.CspParameters parameters) { }
public DSACryptoServiceProvider(System.Security.Cryptography.CspParameters parameters) { }
public System.Security.Cryptography.CspKeyContainerInfo CspKeyContainerInfo { get { throw null; } }
public override string KeyExchangeAlgorithm { get { throw null; } }
public override int KeySize { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public bool PersistKeyInCsp { get { throw null; } set { } }
public bool PublicOnly { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public static bool UseMachineKeyStore { get { throw null; } set { } }
public override byte[] CreateSignature(byte[] rgbHash) { throw null; }
protected override void Dispose(bool disposing) { }
public byte[] ExportCspBlob(bool includePrivateParameters) { throw null; }
public override System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters) { throw null; }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public void ImportCspBlob(byte[] keyBlob) { }
public override void ImportParameters(System.Security.Cryptography.DSAParameters parameters) { }
public byte[] SignData(byte[] buffer) { throw null; }
public byte[] SignData(byte[] buffer, int offset, int count) { throw null; }
public byte[] SignData(System.IO.Stream inputStream) { throw null; }
public byte[] SignHash(byte[] rgbHash, string str) { throw null; }
public bool VerifyData(byte[] rgbData, byte[] rgbSignature) { throw null; }
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { throw null; }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; }
}
public partial interface ICspAsymmetricAlgorithm
{
System.Security.Cryptography.CspKeyContainerInfo CspKeyContainerInfo { get; }
byte[] ExportCspBlob(bool includePrivateParameters);
void ImportCspBlob(byte[] rawData);
}
public enum KeyNumber
{
Exchange = 1,
Signature = 2,
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class MD5CryptoServiceProvider : System.Security.Cryptography.MD5
{
public MD5CryptoServiceProvider() { }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected override void HashCore(System.ReadOnlySpan<byte> source) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public partial class PasswordDeriveBytes : System.Security.Cryptography.DeriveBytes
{
public PasswordDeriveBytes(byte[] password, byte[] salt) { }
public PasswordDeriveBytes(byte[] password, byte[] salt, System.Security.Cryptography.CspParameters cspParams) { }
public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations) { }
public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations, System.Security.Cryptography.CspParameters cspParams) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, System.Security.Cryptography.CspParameters cspParams) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations) { }
public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations, System.Security.Cryptography.CspParameters cspParams) { }
public string HashName { get { throw null; } set { } }
public int IterationCount { get { throw null; } set { } }
public byte[] Salt { get { throw null; } set { } }
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
#pragma warning disable 0809
[System.ObsoleteAttribute("Rfc2898DeriveBytes replaces PasswordDeriveBytes for deriving key material from a password and is preferred in new applications.")]
public override byte[] GetBytes(int cb) { throw null; }
#pragma warning restore 0809
public override void Reset() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class RC2CryptoServiceProvider : System.Security.Cryptography.RC2
{
public RC2CryptoServiceProvider() { }
public override int EffectiveKeySize { get { throw null; } set { } }
public bool UseSalt { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class RNGCryptoServiceProvider : System.Security.Cryptography.RandomNumberGenerator
{
public RNGCryptoServiceProvider() { }
public RNGCryptoServiceProvider(byte[] rgb) { }
public RNGCryptoServiceProvider(System.Security.Cryptography.CspParameters cspParams) { }
public RNGCryptoServiceProvider(string str) { }
protected override void Dispose(bool disposing) { }
public override void GetBytes(byte[] data) { }
public override void GetBytes(byte[] data, int offset, int count) { }
public override void GetBytes(System.Span<byte> data) { }
public override void GetNonZeroBytes(byte[] data) { }
public override void GetNonZeroBytes(System.Span<byte> data) { }
}
public sealed partial class RSACryptoServiceProvider : System.Security.Cryptography.RSA, System.Security.Cryptography.ICspAsymmetricAlgorithm
{
public RSACryptoServiceProvider() { }
public RSACryptoServiceProvider(int dwKeySize) { }
public RSACryptoServiceProvider(int dwKeySize, System.Security.Cryptography.CspParameters parameters) { }
public RSACryptoServiceProvider(System.Security.Cryptography.CspParameters parameters) { }
public System.Security.Cryptography.CspKeyContainerInfo CspKeyContainerInfo { get { throw null; } }
public override string KeyExchangeAlgorithm { get { throw null; } }
public override int KeySize { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public bool PersistKeyInCsp { get { throw null; } set { } }
public bool PublicOnly { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public static bool UseMachineKeyStore { get { throw null; } set { } }
public byte[] Decrypt(byte[] rgb, bool fOAEP) { throw null; }
public override byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public override byte[] DecryptValue(byte[] rgb) { throw null; }
protected override void Dispose(bool disposing) { }
public byte[] Encrypt(byte[] rgb, bool fOAEP) { throw null; }
public override byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public override byte[] EncryptValue(byte[] rgb) { throw null; }
public byte[] ExportCspBlob(bool includePrivateParameters) { throw null; }
public override System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters) { throw null; }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public void ImportCspBlob(byte[] keyBlob) { }
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters) { }
public byte[] SignData(byte[] buffer, int offset, int count, object halg) { throw null; }
public byte[] SignData(byte[] buffer, object halg) { throw null; }
public byte[] SignData(System.IO.Stream inputStream, object halg) { throw null; }
public override byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public byte[] SignHash(byte[] rgbHash, string str) { throw null; }
public bool VerifyData(byte[] buffer, object halg, byte[] signature) { throw null; }
public override bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA1CryptoServiceProvider : System.Security.Cryptography.SHA1
{
public SHA1CryptoServiceProvider() { }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected override void HashCore(System.ReadOnlySpan<byte> source) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA256CryptoServiceProvider : System.Security.Cryptography.SHA256
{
public SHA256CryptoServiceProvider() { }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected override void HashCore(System.ReadOnlySpan<byte> source) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA384CryptoServiceProvider : System.Security.Cryptography.SHA384
{
public SHA384CryptoServiceProvider() { }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected override void HashCore(System.ReadOnlySpan<byte> source) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA512CryptoServiceProvider : System.Security.Cryptography.SHA512
{
public SHA512CryptoServiceProvider() { }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected override void HashCore(System.ReadOnlySpan<byte> source) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class TripleDESCryptoServiceProvider : System.Security.Cryptography.TripleDES
{
public TripleDESCryptoServiceProvider() { }
public override int BlockSize { get { throw null; } set { } }
public override int FeedbackSize { get { throw null; } set { } }
public override byte[] IV { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Email Service
///<para>SObject Name: EmailServicesFunction</para>
///<para>Custom Object: False</para>
///</summary>
public class SfEmailServicesFunction : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "EmailServicesFunction"; }
}
///<summary>
/// Service ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Active
/// <para>Name: IsActive</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isActive")]
public bool? IsActive { get; set; }
///<summary>
/// Email Service Name
/// <para>Name: FunctionName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "functionName")]
public string FunctionName { get; set; }
///<summary>
/// Accept Email From
/// <para>Name: AuthorizedSenders</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "authorizedSenders")]
public string AuthorizedSenders { get; set; }
///<summary>
/// Advanced Email Security Settings
/// <para>Name: IsAuthenticationRequired</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isAuthenticationRequired")]
public bool? IsAuthenticationRequired { get; set; }
///<summary>
/// TLS Required
/// <para>Name: IsTlsRequired</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isTlsRequired")]
public bool? IsTlsRequired { get; set; }
///<summary>
/// Accept Attachments
/// <para>Name: AttachmentOption</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "attachmentOption")]
public string AttachmentOption { get; set; }
///<summary>
/// Class ID
/// <para>Name: ApexClassId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "apexClassId")]
public string ApexClassId { get; set; }
///<summary>
/// Over Email Rate Limit Action
/// <para>Name: OverLimitAction</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "overLimitAction")]
public string OverLimitAction { get; set; }
///<summary>
/// Deactivated Email Service Action
/// <para>Name: FunctionInactiveAction</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "functionInactiveAction")]
public string FunctionInactiveAction { get; set; }
///<summary>
/// Deactivated Email Address Action
/// <para>Name: AddressInactiveAction</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "addressInactiveAction")]
public string AddressInactiveAction { get; set; }
///<summary>
/// Unauthenticated Sender Action
/// <para>Name: AuthenticationFailureAction</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "authenticationFailureAction")]
public string AuthenticationFailureAction { get; set; }
///<summary>
/// Unauthorized Sender Action
/// <para>Name: AuthorizationFailureAction</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "authorizationFailureAction")]
public string AuthorizationFailureAction { get; set; }
///<summary>
/// Enable Error Routing
/// <para>Name: IsErrorRoutingEnabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isErrorRoutingEnabled")]
public bool? IsErrorRoutingEnabled { get; set; }
///<summary>
/// Route Error Emails to This Email Address
/// <para>Name: ErrorRoutingAddress</para>
/// <para>SF Type: email</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "errorRoutingAddress")]
public string ErrorRoutingAddress { get; set; }
///<summary>
/// Convert Text Attachments to Binary Attachments
/// <para>Name: IsTextAttachmentsAsBinary</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isTextAttachmentsAsBinary")]
public bool? IsTextAttachmentsAsBinary { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007-2011
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
namespace MatterHackers.Agg.Font
{
public class TypeFace
{
private class Glyph
{
public int horiz_adv_x;
public int unicode;
public string glyphName;
public IVertexSource glyphData = new VertexStorage();
}
private class Panos_1
{
// these are defined in the order in which they are present in the panos-1 attribute.
private enum Family { Any, No_Fit, Latin_Text_and_Display, Latin_Script, Latin_Decorative, Latin_Pictorial };
private enum Serif_Style { Any, No_Fit, Cove, Obtuse_Cove, Square_Cove, Obtuse_Square_Cove, Square, Thin, Bone, Exaggerated, Triangle, Normal_Sans, Obtuse_Sans, Perp_Sans, Flared, Rounded };
private enum Weight { Any, No_Fit, Very_Light_100, Light_200, Thin_300, Book_400_same_as_CSS1_normal, Medium_500, Demi_600, Bold_700_same_as_CSS1_bold, Heavy_800, Black_900, Extra_Black_Nord_900_force_mapping_to_CSS1_100_900_scale };
private enum Proportion { Any, No_Fit, Old_Style, Modern, Even_Width, Expanded, Condensed, Very_Expanded, Very_Condensed, Monospaced };
private enum Contrast { Any, No_Fit, None, Very_Low, Low, Medium_Low, Medium, Medium_High, High, Very_High };
private enum Stroke_Variation { Any, No_Fit, No_Variation, Gradual_Diagonal, Gradual_Transitional, Gradual_Vertical, Gradual_Horizontal, Rapid_Vertical, Rapid_Horizontal, Instant_Horizontal, Instant_Vertical };
private enum Arm_Style { Any, No_Fit, Straight_Arms_Horizontal, Straight_Arms_Wedge, Straight_Arms_Vertical, Straight_Arms_Single_Serif, Straight_Arms_Double_Serif, Non_Straight_Arms_Horizontal, Non_Straight_Arms_Wedge, Non_Straight_Arms_Vertical_90, Non_Straight_Arms_Single_Serif, Non_Straight_Arms_Double_Serif };
private enum Letterform { Any, No_Fit, Normal_Contact, Normal_Weighted, Normal_Boxed, Normal_Flattened, Normal_Rounded, Normal_Off_Center, Normal_Square, Oblique_Contact, Oblique_Weighted, Oblique_Boxed, Oblique_Flattened, Oblique_Rounded, Oblique_Off_Center, Oblique_Square };
private enum Midline { Any, No_Fit, Standard_Trimmed, Standard_Pointed, Standard_Serifed, High_Trimmed, High_Pointed, High_Serifed, Constant_Trimmed, Constant_Pointed, Constant_Serifed, Low_Trimmed, Low_Pointed, Low_Serifed };
private enum XHeight { Any, No_Fit, Constant_Small, Constant_Standard, Constant_Large, Ducking_Small, Ducking_Standard, Ducking_Large };
private Family family;
private Serif_Style serifStyle;
private Weight weight;
private Proportion proportion;
private Contrast contrast;
private Stroke_Variation strokeVariation;
private Arm_Style armStyle;
private Letterform letterform;
private Midline midline;
private XHeight xHeight;
public Panos_1(string SVGPanos1String)
{
int tempInt;
string[] valuesString = SVGPanos1String.Split(' ');
if (int.TryParse(valuesString[0], out tempInt))
family = (Family)tempInt;
if (int.TryParse(valuesString[1], out tempInt))
serifStyle = (Serif_Style)tempInt;
if (int.TryParse(valuesString[2], out tempInt))
weight = (Weight)tempInt;
if (int.TryParse(valuesString[3], out tempInt))
proportion = (Proportion)tempInt;
if (int.TryParse(valuesString[4], out tempInt))
contrast = (Contrast)tempInt;
if (int.TryParse(valuesString[5], out tempInt))
strokeVariation = (Stroke_Variation)tempInt;
if (int.TryParse(valuesString[6], out tempInt))
armStyle = (Arm_Style)tempInt;
if (int.TryParse(valuesString[7], out tempInt))
letterform = (Letterform)tempInt;
if (int.TryParse(valuesString[8], out tempInt))
midline = (Midline)tempInt;
if (int.TryParse(valuesString[0], out tempInt))
xHeight = (XHeight)tempInt;
}
}
Typography.OpenFont.Typeface _ofTypeface;
private string fontId;
private int horiz_adv_x;
private string fontFamily;
private int font_weight;
private string font_stretch;
private int unitsPerEm;
private Panos_1 panose_1;
private int ascent;
public int Ascent { get { return ascent; } }
private int descent;
public int Descent { get { return descent; } }
private int x_height;
public int X_height { get { return x_height; } }
private int cap_height;
public int Cap_height { get { return cap_height; } }
private RectangleInt boundingBox;
public RectangleInt BoundingBox { get { return boundingBox; } }
private int underline_thickness;
public int Underline_thickness { get { return underline_thickness; } }
private int underline_position;
public int Underline_position { get { return underline_position; } }
private string unicode_range;
private Glyph missingGlyph;
private Dictionary<int, Glyph> glyphs = new Dictionary<int, Glyph>(); // a glyph is indexed by the string it represents, usually one character, but sometimes multiple
private Dictionary<char, Dictionary<char, int>> HKerns = new Dictionary<char, Dictionary<char, int>>();
public int UnitsPerEm
{
get
{
return unitsPerEm;
}
}
private static string GetSubString(string source, string start, string end)
{
int startIndex = 0;
return GetSubString(source, start, end, ref startIndex);
}
private static string GetSubString(string source, string start, string end, ref int startIndex)
{
int startPos = source.IndexOf(start, startIndex);
if (startPos >= 0)
{
int endPos = source.IndexOf(end, startPos + start.Length);
int length = endPos - (startPos + start.Length);
startIndex = endPos + end.Length; // advance our start position to the last position used
return source.Substring(startPos + start.Length, length);
}
return null;
}
private static string GetStringValue(string source, string name)
{
string element = GetSubString(source, name + "=\"", "\"");
return element;
}
private static bool GetIntValue(string source, string name, out int outValue, ref int startIndex)
{
string element = GetSubString(source, name + "=\"", "\"", ref startIndex);
if (int.TryParse(element, NumberStyles.Number, null, out outValue))
{
return true;
}
return false;
}
private static bool GetIntValue(string source, string name, out int outValue)
{
int startIndex = 0;
return GetIntValue(source, name, out outValue, ref startIndex);
}
public static TypeFace LoadFrom(string content)
{
var fontUnderConstruction = new TypeFace();
fontUnderConstruction.ReadSVG(content);
return fontUnderConstruction;
}
public void LoadTTF(string filename)
{
using (var fs = new FileStream(filename, FileMode.Open))
{
LoadTTF(fs);
}
}
public bool LoadTTF(Stream stream)
{
var reader = new Typography.OpenFont.OpenFontReader();
_ofTypeface = reader.Read(stream);
if (_ofTypeface != null)
{
this.ascent = _ofTypeface.Ascender;
this.descent = _ofTypeface.Descender;
this.unitsPerEm = _ofTypeface.UnitsPerEm;
this.underline_position = _ofTypeface.UnderlinePosition;
var bounds = _ofTypeface.Bounds;
this.boundingBox = new RectangleInt(bounds.XMin, bounds.YMin, bounds.XMax, bounds.YMax);
return true;
}
return false;
}
public static TypeFace LoadSVG(string filename)
{
var fontUnderConstruction = new TypeFace();
string svgContent = "";
using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = new StreamReader(fileStream))
{
svgContent = reader.ReadToEnd();
}
}
fontUnderConstruction.ReadSVG(svgContent);
return fontUnderConstruction;
}
private Glyph CreateGlyphFromSVGGlyphData(string SVGGlyphData)
{
var newGlyph = new Glyph();
if (!GetIntValue(SVGGlyphData, "horiz-adv-x", out newGlyph.horiz_adv_x))
{
newGlyph.horiz_adv_x = horiz_adv_x;
}
newGlyph.glyphName = GetStringValue(SVGGlyphData, "glyph-name");
string unicodeString = GetStringValue(SVGGlyphData, "unicode");
if (unicodeString != null)
{
if (unicodeString.Length == 1)
{
newGlyph.unicode = (int)unicodeString[0];
}
else
{
if (unicodeString.Split(';').Length > 1 && unicodeString.Split(';')[1].Length > 0)
{
throw new NotImplementedException("We do not currently support glyphs longer than one character. You need to write the search so that it will find them if you want to support this");
}
if (int.TryParse(unicodeString, NumberStyles.Number, null, out newGlyph.unicode) == false)
{
// see if it is a unicode
string hexNumber = GetSubString(unicodeString, "&#x", ";");
int.TryParse(hexNumber, NumberStyles.HexNumber, null, out newGlyph.unicode);
}
}
}
string dString = GetStringValue(SVGGlyphData, "d");
if (dString == null || dString.Length == 0)
{
return newGlyph;
}
if (newGlyph.glyphData is VertexStorage storage)
{
storage.ParseSvgDString(dString);
}
return newGlyph;
}
public void ReadSVG(string svgContent)
{
int startIndex = 0;
string fontElementString = GetSubString(svgContent, "<font", ">", ref startIndex);
fontId = GetStringValue(fontElementString, "id");
GetIntValue(fontElementString, "horiz-adv-x", out horiz_adv_x);
string fontFaceString = GetSubString(svgContent, "<font-face", "/>", ref startIndex);
fontFamily = GetStringValue(fontFaceString, "font-family");
GetIntValue(fontFaceString, "font-weight", out font_weight);
font_stretch = GetStringValue(fontFaceString, "font-stretch");
GetIntValue(fontFaceString, "units-per-em", out unitsPerEm);
panose_1 = new Panos_1(GetStringValue(fontFaceString, "panose-1"));
GetIntValue(fontFaceString, "ascent", out ascent);
GetIntValue(fontFaceString, "descent", out descent);
GetIntValue(fontFaceString, "x-height", out x_height);
GetIntValue(fontFaceString, "cap-height", out cap_height);
String bboxString = GetStringValue(fontFaceString, "bbox");
String[] valuesString = bboxString.Split(' ');
int.TryParse(valuesString[0], out boundingBox.Left);
int.TryParse(valuesString[1], out boundingBox.Bottom);
int.TryParse(valuesString[2], out boundingBox.Right);
int.TryParse(valuesString[3], out boundingBox.Top);
GetIntValue(fontFaceString, "underline-thickness", out underline_thickness);
GetIntValue(fontFaceString, "underline-position", out underline_position);
unicode_range = GetStringValue(fontFaceString, "unicode-range");
string missingGlyphString = GetSubString(svgContent, "<missing-glyph", "/>", ref startIndex);
missingGlyph = CreateGlyphFromSVGGlyphData(missingGlyphString);
string nextGlyphString = GetSubString(svgContent, "<glyph", "/>", ref startIndex);
while (nextGlyphString != null)
{
// get the data and put it in the glyph dictionary
Glyph newGlyph = CreateGlyphFromSVGGlyphData(nextGlyphString);
if (newGlyph.unicode > 0)
{
glyphs.Add(newGlyph.unicode, newGlyph);
}
nextGlyphString = GetSubString(svgContent, "<glyph", "/>", ref startIndex);
}
}
internal IVertexSource GetGlyphForCharacter(char character)
{
if (_ofTypeface != null)
{
// TODO: MAKE SURE THIS IS OFF!!!!!!! It is un-needed and only for debugging
//glyphs.Clear();
}
// TODO: check for multi character glyphs (we don't currently support them in the reader).
return GetGlyph(character)?.glyphData;
}
private Glyph GetGlyph(char character)
{
Glyph glyph;
lock (glyphs)
{
if (!glyphs.TryGetValue(character, out glyph))
{
// if we have a loaded ttf try to create the glyph data
if (_ofTypeface != null)
{
var storage = new VertexStorage();
var translator = new VertexSourceGlyphTranslator(storage);
var glyphIndex = _ofTypeface.GetGlyphIndex(character);
var ttfGlyph = _ofTypeface.GetGlyph(glyphIndex);
//
Typography.OpenFont.IGlyphReaderExtensions.Read(translator, ttfGlyph.GlyphPoints, ttfGlyph.EndPoints);
//
glyph = new Glyph();
glyph.unicode = character;
glyph.horiz_adv_x = _ofTypeface.GetHAdvanceWidthFromGlyphIndex(glyphIndex);
glyphs.Add(character, glyph);
// Wrap glyph data with ClosedLoopGlyphData to ensure all loops are correctly closed
glyph.glyphData = new ClosedLoopGlyphData(storage);
}
}
}
return glyph;
}
/// <summary>
/// Ensure all MoveTo operations are preceded by ClosePolygon commands
/// </summary>
private class ClosedLoopGlyphData : IVertexSource
{
private VertexStorage storage;
public ClosedLoopGlyphData(VertexStorage source)
{
storage = new VertexStorage();
var vertexData = source.Vertices().Where(v => v.command != ShapePath.FlagsAndCommand.FlagNone).ToArray();
var previous = default(VertexData);
for (var i = 0; i < vertexData.Length; i++)
{
var current = vertexData[i];
// All MoveTo operations should be preceded by ClosePolygon
if (i > 0 &&
current.IsMoveTo
&& ShapePath.is_vertex(previous.command))
{
storage.ClosePolygon();
}
// Add original VertexData
storage.Add(current.position.X, current.position.Y, current.command);
// Hold prior item
previous = current;
}
// Ensure closed
storage.ClosePolygon();
}
public void rewind(int pathId = 0)
{
storage.rewind(pathId);
}
public ShapePath.FlagsAndCommand vertex(out double x, out double y)
{
return storage.vertex(out x, out y);
}
public IEnumerable<VertexData> Vertices()
{
return storage.Vertices();
}
}
internal int GetAdvanceForCharacter(char character, char nextCharacterToKernWith)
{
// TODO: check for kerning and adjust
Glyph glyph = GetGlyph(character);
if (glyph != null)
{
return glyph.horiz_adv_x;
}
return 0;
}
internal int GetAdvanceForCharacter(char character)
{
Glyph glyph = GetGlyph(character);
if (glyph != null)
{
return glyph.horiz_adv_x;
}
return 0;
}
public void ShowDebugInfo(Graphics2D graphics2D)
{
Color boundingBoxColor = new Color(0, 0, 0);
var typeFaceNameStyle = new StyledTypeFace(this, 50);
var fontNamePrinter = new TypeFacePrinter(this.fontFamily + " - 50 point", typeFaceNameStyle);
double x = 30 + typeFaceNameStyle.EmSizeInPoints * 1.5;
double y = 40 - typeFaceNameStyle.DescentInPixels;
int width = 150;
var originColor = new Color(0, 0, 0);
var ascentColor = new Color(255, 0, 0);
var descentColor = new Color(255, 0, 0);
var xHeightColor = new Color(12, 25, 200);
var capHeightColor = new Color(12, 25, 200);
var underlineColor = new Color(0, 150, 55);
// the origin
RectangleDouble bounds = typeFaceNameStyle.BoundingBoxInPixels;
graphics2D.Rectangle(x + bounds.Left, y + bounds.Bottom, x + bounds.Right, y + bounds.Top, boundingBoxColor);
graphics2D.Line(x - 10, y, x + width / 2, y, originColor);
double temp = typeFaceNameStyle.AscentInPixels;
graphics2D.Line(x, y + temp, x + width, y + temp, ascentColor);
temp = typeFaceNameStyle.DescentInPixels;
graphics2D.Line(x, y + temp, x + width, y + temp, descentColor);
temp = typeFaceNameStyle.XHeightInPixels;
graphics2D.Line(x, y + temp, x + width, y + temp, xHeightColor);
temp = typeFaceNameStyle.CapHeightInPixels;
graphics2D.Line(x, y + temp, x + width, y + temp, capHeightColor);
temp = typeFaceNameStyle.UnderlinePositionInPixels;
graphics2D.Line(x, y + temp, x + width, y + temp, underlineColor);
Affine textTransform;
textTransform = Affine.NewIdentity();
textTransform *= Affine.NewTranslation(x, y);
var transformedText = new VertexSourceApplyTransform(textTransform);
fontNamePrinter.Render(graphics2D, Color.Black, transformedText);
graphics2D.Render(transformedText, Color.Black);
// render the legend
var legendFont = new StyledTypeFace(this, 12);
var textPos = new Vector2(x + width / 2, y + typeFaceNameStyle.EmSizeInPixels * 1.5);
graphics2D.Render(new TypeFacePrinter("Bounding Box"), textPos, boundingBoxColor);
textPos.Y += legendFont.EmSizeInPixels;
graphics2D.Render(new TypeFacePrinter("Descent"), textPos, descentColor);
textPos.Y += legendFont.EmSizeInPixels;
graphics2D.Render(new TypeFacePrinter("Underline"), textPos, underlineColor);
textPos.Y += legendFont.EmSizeInPixels;
graphics2D.Render(new TypeFacePrinter("Origin"), textPos, originColor);
textPos.Y += legendFont.EmSizeInPixels;
graphics2D.Render(new TypeFacePrinter("X Height"), textPos, xHeightColor);
textPos.Y += legendFont.EmSizeInPixels;
graphics2D.Render(new TypeFacePrinter("CapHeight"), textPos, capHeightColor);
textPos.Y += legendFont.EmSizeInPixels;
graphics2D.Render(new TypeFacePrinter("Ascent"), textPos, ascentColor);
textPos.Y += legendFont.EmSizeInPixels;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using NuGet.Resources;
namespace NuGet
{
public static class FileSystemExtensions
{
public static IEnumerable<string> GetFiles(this IFileSystem fileSystem, string path, string filter)
{
return fileSystem.GetFiles(path, filter, recursive: false);
}
public static void AddFiles(IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir)
{
AddFiles(fileSystem, files, rootDir, preserveFilePath: true);
}
/// <summary>
/// Add the files to the specified FileSystem
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="files">The files to add to FileSystem.</param>
/// <param name="rootDir">The directory of the FileSystem to copy the files to.</param>
/// <param name="preserveFilePath">if set to <c>true</c> preserve full path of the copies files. Otherwise,
/// all files with be copied to the <paramref name="rootDir"/>.</param>
public static void AddFiles(this IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir, bool preserveFilePath)
{
foreach (IPackageFile file in files)
{
string path = Path.Combine(rootDir, preserveFilePath ? file.Path : Path.GetFileName(file.Path));
fileSystem.AddFileWithCheck(path, file.GetStream);
}
}
internal static void DeleteFiles(IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir)
{
// First get all directories that contain files
var directoryLookup = files.ToLookup(p => Path.GetDirectoryName(p.Path));
// Get all directories that this package may have added
var directories = from grouping in directoryLookup
from directory in GetDirectories(grouping.Key)
orderby directory.Length descending
select directory;
// Remove files from every directory
foreach (var directory in directories)
{
var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<IPackageFile>();
string dirPath = Path.Combine(rootDir, directory);
if (!fileSystem.DirectoryExists(dirPath))
{
continue;
}
foreach (var file in directoryFiles)
{
string path = Path.Combine(rootDir, file.Path);
fileSystem.DeleteFileSafe(path, file.GetStream);
}
// If the directory is empty then delete it
if (!fileSystem.GetFilesSafe(dirPath).Any() &&
!fileSystem.GetDirectoriesSafe(dirPath).Any())
{
fileSystem.DeleteDirectorySafe(dirPath, recursive: false);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to log an exception as a warning and move on")]
internal static IEnumerable<string> GetDirectoriesSafe(this IFileSystem fileSystem, string path)
{
try
{
return fileSystem.GetDirectories(path);
}
catch (Exception e)
{
fileSystem.Logger.Log(MessageLevel.Warning, e.Message);
}
return Enumerable.Empty<string>();
}
internal static IEnumerable<string> GetFilesSafe(this IFileSystem fileSystem, string path)
{
return GetFilesSafe(fileSystem, path, "*.*");
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to log an exception as a warning and move on")]
internal static IEnumerable<string> GetFilesSafe(this IFileSystem fileSystem, string path, string filter)
{
try
{
return fileSystem.GetFiles(path, filter);
}
catch (Exception e)
{
fileSystem.Logger.Log(MessageLevel.Warning, e.Message);
}
return Enumerable.Empty<string>();
}
internal static void DeleteDirectorySafe(this IFileSystem fileSystem, string path, bool recursive)
{
DoSafeAction(() => fileSystem.DeleteDirectory(path, recursive), fileSystem.Logger);
}
internal static void DeleteFileSafe(this IFileSystem fileSystem, string path)
{
DoSafeAction(() => fileSystem.DeleteFile(path), fileSystem.Logger);
}
public static bool ContentEqual(IFileSystem fileSystem, string path, Func<Stream> streamFactory)
{
using (Stream stream = streamFactory(),
fileStream = fileSystem.OpenFile(path))
{
return stream.ContentEquals(fileStream);
}
}
public static void DeleteFileSafe(this IFileSystem fileSystem, string path, Func<Stream> streamFactory)
{
// Only delete the file if it exists and the checksum is the same
if (fileSystem.FileExists(path))
{
if (ContentEqual(fileSystem, path, streamFactory))
{
fileSystem.DeleteFileSafe(path);
}
else
{
// This package installed a file that was modified so warn the user
fileSystem.Logger.Log(MessageLevel.Warning, NuGetResources.Warning_FileModified, path);
}
}
}
public static void DeleteFileAndParentDirectoriesIfEmpty(this IFileSystem fileSystem, string filePath)
{
// first delete the file itself
fileSystem.DeleteFileSafe(filePath);
// now delete all parent directories if they are empty
for (string path = Path.GetDirectoryName(filePath); !String.IsNullOrEmpty(path); path = Path.GetDirectoryName(path))
{
if (fileSystem.GetFiles(path, "*.*").Any() || fileSystem.GetDirectories(path).Any())
{
// if this directory is not empty, stop
break;
}
else
{
// otherwise, delete it, and move up to its parent
fileSystem.DeleteDirectorySafe(path, recursive: false);
}
}
}
internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Func<Stream> streamFactory)
{
if (fileSystem.FileExists(path))
{
fileSystem.Logger.Log(MessageLevel.Warning, NuGetResources.Warning_FileAlreadyExists, path);
}
else
{
using (Stream stream = streamFactory())
{
fileSystem.AddFile(path, stream);
}
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The caller is responsible for closing the stream")]
internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Action<Stream> write)
{
if (fileSystem.FileExists(path))
{
fileSystem.Logger.Log(MessageLevel.Warning, NuGetResources.Warning_FileAlreadyExists, path);
}
else
{
fileSystem.AddFile(path, write);
}
}
internal static IEnumerable<string> GetDirectories(string path)
{
foreach (var index in IndexOfAll(path, Path.DirectorySeparatorChar))
{
yield return path.Substring(0, index);
}
yield return path;
}
private static IEnumerable<int> IndexOfAll(string value, char ch)
{
int index = -1;
do
{
index = value.IndexOf(ch, index + 1);
if (index >= 0)
{
yield return index;
}
}
while (index >= 0);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to log an exception as a warning and move on")]
private static void DoSafeAction(Action action, ILogger logger)
{
try
{
Attempt(action);
}
catch (Exception e)
{
logger.Log(MessageLevel.Warning, e.Message);
}
}
private static void Attempt(Action action, int retries = 3, int delayBeforeRetry = 150)
{
while (retries > 0)
{
try
{
action();
break;
}
catch
{
retries--;
if (retries == 0)
{
throw;
}
}
Thread.Sleep(delayBeforeRetry);
}
}
}
}
| |
/*
kowe kudu nginstall mysql connecter ngge .NET disek sak durunge gawe library iki
*/
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace DB
{
public class MySqlDB
{
private MySqlConnection con;
private MySqlCommand cmd;
private MySqlDataAdapter DA;
private DataSet DS = new DataSet();
public Mysql()
{
con = new MySqlConnection("server=localhost;port=3306;uid=root;pwd=;database=laravel");
}
public MySqlConnection Open()
{
if (con.State == ConnectionState.Closed || con.State == ConnectionState.Broken)
{
con.Open();
}
return con;
}
public MySqlConnection Close()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
return con;
}
public void Execute(string query)
{
cmd = new MySqlCommand();
try
{
cmd.Connection = Open();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
catch (MySqlException Ex)
{
throw Ex;
}
finally
{
cmd = null;
}
}
public void Insert(string table, string[,] Field)
{
string query = "";
query = "INSERT INTO " + table + " SET ";
for (int i = 0; i <= Field.GetUpperBound(0); i++)
{
query += MySqlHelper.EscapeString(Field[i, 0])+ "='" + MySqlHelper.EscapeString(Field[i, 0]) + "',";
}
query = query.TrimEnd(',');
Execute(query);
}
public void Delete(string table, string key, string value)
{
string query = "DELETE FROM " + table + " WHERE " + MySqlHelper.EscapeString(key) + "='" + MySqlHelper.EscapeString(value) + "'";
Execute(query);
}
public void Update(string table, string[,] Field, string key, string value)
{
string query = "";
query = "UPDATE " + table + " SET ";
for (int i = 0; i <= Field.GetUpperBound(0); i++)
{
query += MySqlHelper.EscapeString(Field[i, 0]) + "='" + MySqlHelper.EscapeString(Field[i, 0]) + "',";
}
query = query.TrimEnd(',');
query += " WHERE " + MySqlHelper.EscapeString(key) + " ='" + MySqlHelper.EscapeString(value) + "'";
Execute(query);
}
public DataSet DataSet(string query)
{
con.Open();
cmd = con.CreateCommand();
DA = new MySqlDataAdapter(query, con);
DS.Reset();
DA.Fill(DS);
con.Close();
return (DS);
}
public DataTable getDataTable(string query)
{
cmd = new MySqlCommand();
MySqlDataAdapter DA;
try
{
cmd.Connection = Open();
cmd.CommandText = query;
DA = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
DA.Fill(dt);
return dt;
}
catch (MySqlException Ex)
{
throw Ex;
}
finally
{
cmd = null;
}
}
public MySqlDataReader getDataReader(string query)
{
cmd = new MySqlCommand();
try
{
cmd.Connection = Open();
cmd.CommandText = query;
MySqlDataReader DR;
DR = cmd.ExecuteReader();
return DR;
}
catch (MySqlException Ex)
{
throw Ex;
}
finally
{
cmd = null;
}
}
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "C:\\MySqlBackup" + year + "-" + month + "-" + day +
"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysqldump";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup!");
}
}
public void Restore()
{
try
{
//Read file from C:\
string path;
path = "C:\\MySqlBackup.sql";
StreamReader file = new StreamReader(path);
string input = file.ReadToEnd();
file.Close();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysql";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
uid, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.StandardInput.WriteLine(input);
process.StandardInput.Close();
process.WaitForExit();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to Restore!");
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: BCLDebug
**
**
** Purpose: Debugging Macros for use in the Base Class Libraries
**
**
============================================================*/
namespace System
{
////using System.IO;
////using System.Text;
////using System.Runtime.Remoting;
using System.Diagnostics;
////using Microsoft.Win32;
using System.Runtime.CompilerServices;
////using System.Runtime.Versioning;
////using System.Security.Permissions;
////using System.Security;
[Serializable]
internal enum LogLevel
{
Trace = 0,
Status = 20,
Warning = 40,
Error = 50,
Panic = 100,
}
////internal struct SwitchStructure
////{
//// internal String name;
//// internal int value;
////
//// internal SwitchStructure( String n, int v )
//// {
//// name = n;
//// value = v;
//// }
////}
// Only statics, does not need to be marked with the serializable attribute
internal static class BCLDebug
{
//// internal static bool m_registryChecked = false;
//// internal static bool m_loggingNotEnabled = false;
//// internal static bool m_perfWarnings;
//// internal static bool m_correctnessWarnings;
//// internal static bool m_safeHandleStackTraces;
#if _DEBUG
//// internal static bool m_domainUnloadAdded;
#endif
//// internal static PermissionSet m_MakeConsoleErrorLoggingWork;
////
//// static readonly SwitchStructure[] switches =
//// {
//// new SwitchStructure( "NLS" , 0x00000001 ),
//// new SwitchStructure( "SER" , 0x00000002 ),
//// new SwitchStructure( "DYNIL" , 0x00000004 ),
//// new SwitchStructure( "REMOTE" , 0x00000008 ),
//// new SwitchStructure( "BINARY" , 0x00000010 ), //Binary Formatter
//// new SwitchStructure( "SOAP" , 0x00000020 ), // Soap Formatter
//// new SwitchStructure( "REMOTINGCHANNELS", 0x00000040 ),
//// new SwitchStructure( "CACHE" , 0x00000080 ),
//// new SwitchStructure( "RESMGRFILEFORMAT", 0x00000100 ), // .resources files
//// new SwitchStructure( "PERF" , 0x00000200 ),
//// new SwitchStructure( "CORRECTNESS" , 0x00000400 ),
//// new SwitchStructure( "MEMORYFAILPOINT" , 0x00000800 ),
//// };
////
//// static readonly LogLevel[] levelConversions =
//// {
//// LogLevel.Panic ,
//// LogLevel.Error ,
//// LogLevel.Error ,
//// LogLevel.Warning,
//// LogLevel.Warning,
//// LogLevel.Status ,
//// LogLevel.Status ,
//// LogLevel.Trace ,
//// LogLevel.Trace ,
//// LogLevel.Trace ,
//// LogLevel.Trace ,
//// };
#if _DEBUG
internal static void WaitForFinalizers( Object sender, EventArgs e )
{
if(!m_registryChecked)
{
CheckRegistry();
}
if(m_correctnessWarnings)
{
GC.GetTotalMemory( true );
GC.WaitForPendingFinalizers();
}
}
#endif
[Conditional( "_DEBUG" )]
//// [ResourceExposure( ResourceScope.None )]
static public void Assert( bool condition, String message )
{
#if _DEBUG
//// // Speed up debug builds marginally by avoiding the garbage from
//// // concatinating "BCL Assert: " and the message.
//// if(!condition)
//// {
//// System.Diagnostics.Assert.Check( condition, "BCL Assert", message );
//// }
#endif
}
[Conditional( "_LOGGING" )]
//// [ResourceExposure( ResourceScope.None )]
static public void Log( String message )
{
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return;
//// }
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// System.Diagnostics.Log.Trace( message );
//// System.Diagnostics.Log.Trace( Environment.NewLine );
}
[Conditional( "_LOGGING" )]
//// [ResourceExposure( ResourceScope.None )]
static public void Log( String switchName, String message )
{
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return;
//// }
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
//// try
//// {
//// LogSwitch ls = LogSwitch.GetSwitch( switchName );
//// if(ls != null)
//// {
//// System.Diagnostics.Log.Trace( ls, message );
//// System.Diagnostics.Log.Trace( ls, Environment.NewLine );
//// }
//// }
//// catch
//// {
//// System.Diagnostics.Log.Trace( "Exception thrown in logging." + Environment.NewLine );
//// System.Diagnostics.Log.Trace( "Switch was: " + ((switchName == null) ? "<null>" : switchName) + Environment.NewLine );
//// System.Diagnostics.Log.Trace( "Message was: " + ((message == null) ? "<null>" : message) + Environment.NewLine );
//// }
}
//// //
//// // This code gets called during security startup, so we can't go through Marshal to get the values. This is
//// // just a small helper in native code instead of that.
//// //
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private extern static int GetRegistryLoggingValues( out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces );
////
//// private static void CheckRegistry()
//// {
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return;
//// }
////
//// if(m_registryChecked)
//// {
//// return;
//// }
////
//// m_registryChecked = true;
////
//// bool loggingEnabled;
//// bool logToConsole;
//// int logLevel;
//// int facilityValue;
////
//// facilityValue = GetRegistryLoggingValues( out loggingEnabled, out logToConsole, out logLevel, out m_perfWarnings, out m_correctnessWarnings, out m_safeHandleStackTraces );
////
//// // Note we can get into some recursive situations where we call
//// // ourseves recursively through the .cctor. That's why we have the
//// // check for levelConversions == null.
//// if(!loggingEnabled)
//// {
//// m_loggingNotEnabled = true;
//// }
////
//// if(loggingEnabled && levelConversions != null)
//// {
//// try
//// {
//// //The values returned for the logging levels in the registry don't map nicely onto the
//// //values which we support internally (which are an approximation of the ones that
//// //the System.Diagnostics namespace uses) so we have a quick map.
//// Assert( logLevel >= 0 && logLevel <= 10, "logLevel>=0 && logLevel<=10" );
////
//// logLevel = (int)levelConversions[logLevel];
////
//// if(facilityValue > 0)
//// {
//// for(int i = 0; i < switches.Length; i++)
//// {
//// if((switches[i].value & facilityValue) != 0)
//// {
//// LogSwitch L = new LogSwitch( switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch );
//// L.MinimumLevel = (LoggingLevels)logLevel;
//// }
//// }
////
//// System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel;
//// System.Diagnostics.Log.IsConsoleEnabled = logToConsole;
//// }
////
//// }
//// catch
//// {
//// //Silently eat any exceptions.
//// }
//// }
//// }
////
//// internal static bool CheckEnabled( String switchName )
//// {
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return false;
//// }
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// LogSwitch logSwitch = LogSwitch.GetSwitch( switchName );
//// if(logSwitch == null)
//// {
//// return false;
//// }
////
//// return ((int)logSwitch.MinimumLevel <= (int)LogLevel.Trace);
//// }
////
//// private static bool CheckEnabled( String switchName, LogLevel level, out LogSwitch logSwitch )
//// {
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// logSwitch = null;
//// return false;
//// }
////
//// logSwitch = LogSwitch.GetSwitch( switchName );
//// if(logSwitch == null)
//// {
//// return false;
//// }
////
//// return ((int)logSwitch.MinimumLevel <= (int)level);
//// }
[Conditional( "_LOGGING" )]
//// [ResourceExposure( ResourceScope.None )]
public static void Log( String switchName, LogLevel level, params Object[] messages )
{
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return;
//// }
////
//// //Add code to check if logging is enabled in the registry.
//// LogSwitch logSwitch;
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// if(!CheckEnabled( switchName, level, out logSwitch ))
//// {
//// return;
//// }
////
//// StringBuilder sb = new StringBuilder();
////
//// for(int i = 0; i < messages.Length; i++)
//// {
//// String s;
////
//// try
//// {
//// if(messages[i] == null)
//// {
//// s = "<null>";
//// }
//// else
//// {
//// s = messages[i].ToString();
//// }
//// }
//// catch
//// {
//// s = "<unable to convert>";
//// }
////
//// sb.Append( s );
//// }
////
//// System.Diagnostics.Log.LogMessage( (LoggingLevels)((int)level), logSwitch, sb.ToString() );
}
// Note this overload doesn't take a format string. You probably don't
// want this one.
[Conditional( "_LOGGING" )]
//// [ResourceExposure( ResourceScope.None )]
public static void Trace( String switchName, params Object[] messages )
{
//// if(m_loggingNotEnabled)
//// {
//// return;
//// }
////
//// LogSwitch logSwitch;
//// if(!CheckEnabled( switchName, LogLevel.Trace, out logSwitch ))
//// {
//// return;
//// }
////
//// StringBuilder sb = new StringBuilder();
////
//// for(int i = 0; i < messages.Length; i++)
//// {
//// String s;
////
//// try
//// {
//// if(messages[i] == null)
//// {
//// s = "<null>";
//// }
//// else
//// {
//// s = messages[i].ToString();
//// }
//// }
//// catch
//// {
//// s = "<unable to convert>";
//// }
////
//// sb.Append( s );
//// }
////
//// sb.Append( Environment.NewLine );
//// System.Diagnostics.Log.LogMessage( LoggingLevels.TraceLevel0, logSwitch, sb.ToString() );
}
[Conditional( "_LOGGING" )]
//// [ResourceExposure( ResourceScope.None )]
public static void Trace( String switchName, String format, params Object[] messages )
{
//// if(m_loggingNotEnabled)
//// {
//// return;
//// }
////
//// LogSwitch logSwitch;
//// if(!CheckEnabled( switchName, LogLevel.Trace, out logSwitch ))
//// {
//// return;
//// }
////
//// StringBuilder sb = new StringBuilder();
////
//// sb.AppendFormat( format, messages );
//// sb.Append( Environment.NewLine );
////
//// System.Diagnostics.Log.LogMessage( LoggingLevels.TraceLevel0, logSwitch, sb.ToString() );
}
[Conditional( "_LOGGING" )]
//// [ResourceExposure( ResourceScope.None )]
public static void DumpStack( String switchName )
{
//// LogSwitch logSwitch;
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// if(!CheckEnabled( switchName, LogLevel.Trace, out logSwitch ))
//// {
//// return;
//// }
////
//// StackTrace trace = new StackTrace();
////
//// System.Diagnostics.Log.LogMessage( LoggingLevels.TraceLevel0, logSwitch, trace.ToString() );
}
// For logging errors related to the console - we often can't expect to
// write to stdout if it doesn't exist.
[Conditional( "_DEBUG" )]
//// [ResourceExposure( ResourceScope.None )] // Debug-only extra logging code
//// [ResourceConsumption( ResourceScope.Machine, ResourceScope.Machine )]
internal static void ConsoleError( String msg )
{
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return;
//// }
////
//// if(m_MakeConsoleErrorLoggingWork == null)
//// {
//// PermissionSet perms = new PermissionSet();
////
//// perms.AddPermission( new EnvironmentPermission( PermissionState .Unrestricted ) );
//// perms.AddPermission( new FileIOPermission ( FileIOPermissionAccess.AllAccess, Path.GetFullPath( "." ) ) );
////
//// m_MakeConsoleErrorLoggingWork = perms;
//// }
////
//// m_MakeConsoleErrorLoggingWork.Assert();
////
//// using(TextWriter err = File.AppendText( "ConsoleErrors.log" ))
//// {
//// err.WriteLine( msg );
//// }
}
// For perf-related asserts. On a debug build, set the registry key
// BCLPerfWarnings to non-zero.
[Conditional( "_DEBUG" )]
//// [ResourceExposure( ResourceScope.None )]
internal static void Perf( bool expr, String msg )
{
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return;
//// }
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// if(!m_perfWarnings)
//// {
//// return;
//// }
////
//// if(!expr)
//// {
//// Log( "PERF", "BCL Perf Warning: " + msg );
//// }
////
//// System.Diagnostics.Assert.Check( expr, "BCL Perf Warning: Your perf may be less than perfect because...", msg );
}
// For correctness-related asserts. On a debug build, set the registry key
// BCLCorrectnessWarnings to non-zero.
[Conditional( "_DEBUG" )]
//// [ResourceExposure( ResourceScope.None )]
internal static void Correctness( bool expr, String msg )
{
#if _DEBUG
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return;
//// }
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// if(!m_correctnessWarnings)
//// {
//// return;
//// }
////
//// if(!m_domainUnloadAdded)
//// {
//// m_domainUnloadAdded = true;
////
//// AppDomain.CurrentDomain.DomainUnload += new EventHandler( WaitForFinalizers );
//// }
////
//// if(!expr)
//// {
//// Log( "CORRECTNESS", "BCL Correctness Warning: " + msg );
//// }
////
//// System.Diagnostics.Assert.Check( expr, "BCL Correctness Warning: Your program may not work because...", msg );
#endif
}
internal static bool CorrectnessEnabled()
{
#if WIN32
//// if(AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
//// {
//// return false;
//// }
////
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// return m_correctnessWarnings;
return false;
#else
return false;
#endif // WIN32
}
// Whether SafeHandles include a stack trace showing where they
// were allocated. Only useful in checked & debug builds.
internal static bool SafeHandleStackTracesEnabled
{
get
{
#if _DEBUG
//// if(!m_registryChecked)
//// {
//// CheckRegistry();
//// }
////
//// return m_safeHandleStackTraces;
return false;
#else
return false;
#endif
}
}
}
//--//
internal sealed class ASSERT : Exception
{
#region FRIEND
//// private static bool AssertIsFriend( Type[] friends, StackTrace st )
//// {
//// Type typeOfCallee = st.GetFrame( 1 ).GetMethod().DeclaringType;
//// Type typeOfCaller = st.GetFrame( 2 ).GetMethod().DeclaringType;
////
//// bool noFriends = true;
//// foreach(Type friend in friends)
//// {
//// if(typeOfCaller != friend && typeOfCaller != typeOfCallee)
//// {
//// noFriends = false;
//// }
//// }
////
//// if(noFriends)
//// {
//// Assert( false, Environment.GetResourceString( "RtType.InvalidCaller" ), st.ToString() );
//// }
////
//// return true;
//// }
//// [Conditional( "_DEBUG" )]
//// internal static void FRIEND( Type[] friends )
//// {
//// StackTrace st = new StackTrace();
//// AssertIsFriend( friends, st );
//// }
//// [Conditional( "_DEBUG" )]
//// internal static void FRIEND( Type friend )
//// {
//// StackTrace st = new StackTrace();
//// AssertIsFriend( new Type[] { friend }, st );
//// }
//// [Conditional( "_DEBUG" )]
//// internal static void FRIEND( string ns )
//// {
//// StackTrace st = new StackTrace();
////
//// string nsOfCallee = st.GetFrame( 1 ).GetMethod().DeclaringType.Namespace;
//// string nsOfCaller = st.GetFrame( 2 ).GetMethod().DeclaringType.Namespace;
////
//// Assert( nsOfCaller.Equals( nsOfCaller ) || nsOfCaller.Equals( ns ), Environment.GetResourceString( "RtType.InvalidCaller" ), st.ToString() );
//// }
#endregion
#region PRECONDITION
[Conditional( "_DEBUG" )]
internal static void PRECONDITION( bool condition )
{
Assert( condition );
}
[Conditional( "_DEBUG" )]
internal static void PRECONDITION( bool condition, string message )
{
Assert( condition, message );
}
[Conditional( "_DEBUG" )]
internal static void PRECONDITION( bool condition, string message, string detailedMessage )
{
Assert( condition, message, detailedMessage );
}
#endregion
#region POSTCONDITION
[Conditional( "_DEBUG" )]
internal static void POSTCONDITION( bool condition )
{
Assert( condition );
}
[Conditional( "_DEBUG" )]
internal static void POSTCONDITION( bool condition, string message )
{
Assert( condition, message );
}
[Conditional( "_DEBUG" )]
internal static void POSTCONDITION( bool condition, string message, string detailedMessage )
{
Assert( condition, message, detailedMessage );
}
#endregion
#region CONSISTENCY_CHECK
[Conditional( "_DEBUG" )]
internal static void CONSISTENCY_CHECK( bool condition )
{
Assert( condition );
}
[Conditional( "_DEBUG" )]
internal static void CONSISTENCY_CHECK( bool condition, string message )
{
Assert( condition, message );
}
[Conditional( "_DEBUG" )]
internal static void CONSISTENCY_CHECK( bool condition, string message, string detailedMessage )
{
Assert( condition, message, detailedMessage );
}
#endregion
#region SIMPLIFYING_ASSUMPTION
[Conditional( "_DEBUG" )]
internal static void SIMPLIFYING_ASSUMPTION( bool condition )
{
Assert( condition );
}
[Conditional( "_DEBUG" )]
internal static void SIMPLIFYING_ASSUMPTION( bool condition, string message )
{
Assert( condition, message );
}
[Conditional( "_DEBUG" )]
internal static void SIMPLIFYING_ASSUMPTION( bool condition, string message, string detailedMessage )
{
Assert( condition, message, detailedMessage );
}
#endregion
#region UNREACHABLE
[Conditional( "_DEBUG" )]
internal static void UNREACHABLE()
{
Assert();
}
[Conditional( "_DEBUG" )]
internal static void UNREACHABLE( string message )
{
Assert( message );
}
[Conditional( "_DEBUG" )]
internal static void UNREACHABLE( string message, string detailedMessage )
{
Assert( message, detailedMessage );
}
#endregion
#region NOT_IMPLEMENTED
[Conditional( "_DEBUG" )]
internal static void NOT_IMPLEMENTED()
{
Assert();
}
[Conditional( "_DEBUG" )]
internal static void NOT_IMPLEMENTED( string message )
{
Assert( message );
}
[Conditional( "_DEBUG" )]
internal static void NOT_IMPLEMENTED( string message, string detailedMessage )
{
Assert( message, detailedMessage );
}
#endregion
#region Private Asserts - Throw before assert so debugger can inspect
private static void Assert()
{
Assert( false, null, null );
}
private static void Assert( string message )
{
Assert( false, message, null );
}
private static void Assert( bool condition )
{
Assert( condition, null, null );
}
private static void Assert( bool condition, string message )
{
Assert( condition, message, null );
}
private static void Assert( string message, string detailedMessage )
{
Assert( false, message, detailedMessage );
}
private static void Assert( bool condition, string message, string detailedMessage )
{
if(!condition)
{
// Console.WriteLine("ASSERT MESSAGE: " + message + ", " + detailedMessage);
// System.Diagnostics.Debug.Assert(condition, message, detailedMessage);
// throw new ASSERT();
}
}
#endregion
}
internal static class LOGIC
{
internal static bool IMPLIES( bool p, bool q )
{
return !p || q;
}
internal static bool BIJECTION( bool p, bool q )
{
return IMPLIES( p, q ) && IMPLIES( q, p );
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Configuration;
using Microsoft.Win32;
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using Xunit;
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.Build.UnitTests.Evaluation
{
/// <summary>
/// Unit tests for Importing from $(MSBuildExtensionsPath*)
/// </summary>
public class ImportFromMSBuildExtensionsPathTests : IDisposable
{
public void Dispose()
{
ToolsetConfigurationReaderTestHelper.CleanUp();
}
[Fact]
public void ImportFromExtensionsPathFound()
{
CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath", (p, l) => Assert.True(p.Build()));
}
[Fact]
public void ImportFromExtensionsPathNotFound()
{
string extnDir1 = null;
string mainProjectPath = null;
try {
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1());
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistant")));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));
logger.AssertLogContains("MSB4226");
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
}
}
[Fact]
public void ConditionalImportFromExtensionsPathNotFound()
{
string extnTargetsFileContentWithCondition = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FooBar</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\bar\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\bar\extn2.proj')""/>
</Project>
";
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContentWithCondition);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {extnDir1, Path.Combine("tmp", "nonexistant")},
null,
(p, l) => {
Assert.True(p.Build());
l.AssertLogContains("Running FromExtn");
l.AssertLogContains("PropertyFromExtn1: FooBar");
});
}
[Fact]
public void ImportFromExtensionsPathCircularImportError()
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\foo\extn2.proj' />
</Project>
";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn2'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='{0}'/>
</Project>
";
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn2.proj"),
String.Format(extnTargetsFileContent2, mainProjectPath));
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath",
new string[] {extnDir2, Path.Combine("tmp", "nonexistant"), extnDir1},
null,
(p, l) => l.AssertLogContains("MSB4210"));
}
[Fact]
public void ImportFromExtensionsPathWithWildCard()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='Main'>
<Message Text='Running Main'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\foo\*.proj'/>
</Project>";
string extnTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='{0}'>
<Message Text='Running {0}'/>
</Target>
</Project>
";
// Importing should stop at the first extension path where a project file is found
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
String.Format(extnTargetsFileContent, "FromExtn1"));
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"),
String.Format(extnTargetsFileContent, "FromExtn2"));
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {extnDir1, Path.Combine("tmp", "nonexistant"), extnDir2},
null,
(p, l) => {
Console.WriteLine (l.FullLog);
Console.WriteLine ("checking FromExtn1");
Assert.True(p.Build("FromExtn1"));
Console.WriteLine ("checking FromExtn2");
Assert.False(p.Build("FromExtn2"));
Console.WriteLine ("checking logcontains");
l.AssertLogContains(String.Format(MockLogger.GetString("TargetDoesNotExist"), "FromExtn2"));
});
}
[Fact]
public void ImportFromExtensionsPathWithWildCardNothingFound()
{
string extnTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\non-existant\*.proj'/>
</Project>
";
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {Path.Combine("tmp", "nonexistant"), extnDir1},
null, (p, l) => Assert.True(p.Build()));
}
[Fact]
public void ImportFromExtensionsPathInvalidFile()
{
string extnTargetsFileContent = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >";
string extnDir1 = null;
string mainProjectPath = null;
try {
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1,
Path.Combine("tmp", "nonexistant")));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));
logger.AssertLogContains("MSB4025");
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
}
}
[Fact]
public void ImportFromExtensionsPathSearchOrder()
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromFirstFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromSecondFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
// File with the same name available in two different extension paths, but the one from the first
// directory in MSBuildExtensionsPath environment variable should get loaded
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {extnDir2, Path.Combine("tmp", "nonexistant"), extnDir1},
null,
(p, l) => {
Assert.True(p.Build());
l.AssertLogContains("Running FromExtn");
l.AssertLogContains("PropertyFromExtn1: FromSecondFile");
});
}
[Fact]
public void ImportFromExtensionsPathSearchOrder2()
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromFirstFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromSecondFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
// File with the same name available in two different extension paths, but the one from the first
// directory in MSBuildExtensionsPath environment variable should get loaded
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
// MSBuildExtensionsPath* property value has highest priority for the lookups
try {
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", Path.Combine("tmp", "non-existstant"), extnDir1));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
project.SetProperty("MSBuildExtensionsPath", extnDir2);
project.ReevaluateIfNecessary();
Assert.True(project.Build());
logger.AssertLogContains("Running FromExtn");
logger.AssertLogContains("PropertyFromExtn1: FromSecondFile");
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
}
}
[Fact]
public void ImportOrderFromExtensionsPath32()
{
CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath32", (p, l) => Assert.True(p.Build()));
}
[Fact]
public void ImportOrderFromExtensionsPath64()
{
CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath64", (p, l) => Assert.True(p.Build()));
}
// Use MSBuildExtensionsPath, MSBuildExtensionsPath32 and MSBuildExtensionsPath64 in the build
[Fact]
public void ImportFromExtensionsPathAnd32And64()
{
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn{0}' DependsOnTargets='{1}'>
<Message Text='Running FromExtn{0}'/>
</Target>
{2}
</Project>
";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""14.1"">
<toolset toolsVersion=""14.1"">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value=""" + /*v4Folder*/"." + @"""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""{0}"" />
<property name=""MSBuildExtensionsPath32"" value=""{1}"" />
<property name=""MSBuildExtensionsPath64"" value=""{2}"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null, extnDir2 = null, extnDir3 = null;
string mainProjectPath = null;
try {
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
String.Format(extnTargetsFileContentTemplate, String.Empty, "FromExtn2", "<Import Project='$(MSBuildExtensionsPath32)\\bar\\extn2.proj' />"));
extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"),
String.Format(extnTargetsFileContentTemplate, 2, "FromExtn3", "<Import Project='$(MSBuildExtensionsPath64)\\xyz\\extn3.proj' />"));
extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("xyz", "extn3.proj"),
String.Format(extnTargetsFileContentTemplate, 3, String.Empty, String.Empty));
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
var configFilePath = ToolsetConfigurationReaderTestHelper.WriteConfigFile(String.Format(configFileContents, extnDir1, extnDir2, extnDir3));
var reader = GetStandardConfigurationReader();
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn3");
logger.AssertLogContains("Running FromExtn2");
logger.AssertLogContains("Running FromExtn");
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
if (extnDir3 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir3, recursive: true);
}
}
}
// Fall-back path that has a property in it: $(FallbackExpandDir1)
[Fact]
public void ExpandExtensionsPathFallback()
{
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\\foo\\extn.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" />
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""14.1"">
<toolset toolsVersion=""14.1"">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj",
GetMainTargetFileContent());
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = new ProjectCollection(new Dictionary<string, string> {["FallbackExpandDir1"] = extnDir1});
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
var project = projectCollection.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
// Fall-back path that has a property in it: $(FallbackExpandDir1)
[Fact]
public void ExpandExtensionsPathFallbackInErrorMessage()
{
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\\foo\\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" />
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""14.1"">
<toolset toolsVersion=""14.1"">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj",
GetMainTargetFileContent());
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath));
// Expanded $(FallbackExpandDir) will appear in quotes in the log
logger.AssertLogContains("\"" + extnDir1 + "\"");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
// Fall-back search path with custom variable
[Fact]
public void FallbackImportWithIndirectReference()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<VSToolsPath>$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v99</VSToolsPath>
</PropertyGroup>
<Import Project='$(VSToolsPath)\DNX\Microsoft.DNX.Props' Condition=""Exists('$(VSToolsPath)\DNX\Microsoft.DNX.Props')"" />
<Target Name='Main' DependsOnTargets='FromExtn' />
</Project>";
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""14.1"">
<toolset toolsVersion=""14.1"">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
<property name=""VSToolsPath"" value=""$(FallbackExpandDir1)\Microsoft\VisualStudio\v99"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("Microsoft", "VisualStudio", "v99", "DNX", "Microsoft.DNX.Props"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
var project = projectCollection.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
// Fall-back search path on a property that is not defined.
[Fact]
public void FallbackImportWithUndefinedProperty()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='$(UndefinedProperty)\file.props' Condition=""Exists('$(UndefinedProperty)\file.props')"" />
<Target Name='Main' DependsOnTargets='FromExtn' />
</Project>";
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""14.1"">
<toolset toolsVersion=""14.1"">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""UndefinedProperty"" value=""$(FallbackExpandDir1)"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
var project = projectCollection.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
void CreateAndBuildProjectForImportFromExtensionsPath(string extnPathPropertyName, Action<Project, MockLogger> action)
{
string extnDir1 = null, extnDir2 = null, mainProjectPath = null;
try {
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
GetExtensionTargetsFileContent1(extnPathPropertyName));
extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"),
GetExtensionTargetsFileContent2(extnPathPropertyName));
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent(extnPathPropertyName));
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, extnPathPropertyName, new string[] {extnDir1, extnDir2},
null,
action);
} finally {
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
}
}
void CreateAndBuildProjectForImportFromExtensionsPath(string mainProjectPath, string extnPathPropertyName, string[] extnDirs, Action<string[]> setExtensionsPath,
Action<Project, MockLogger> action)
{
try {
var projColln = new ProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader(extnPathPropertyName, extnDirs));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
action(project, logger);
} finally {
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDirs != null)
{
foreach (var extnDir in extnDirs)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir, recursive: true);
}
}
}
}
private ToolsetConfigurationReader WriteConfigFileAndGetReader(string extnPathPropertyName, params string[] extnDirs)
{
string combinedExtnDirs = extnDirs != null ? String.Join(";", extnDirs) : String.Empty;
ToolsetConfigurationReaderTestHelper.WriteConfigFile(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""14.1"">
<toolset toolsVersion=""14.1"">
<property name=""MSBuildToolsPath"" value=""."" />
<property name=""MSBuildBinPath"" value=""."" />
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""" + extnPathPropertyName + @""" value=""" + combinedExtnDirs + @""" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>");
return GetStandardConfigurationReader();
}
string GetNewExtensionsPathAndCreateFile(string extnDirName, string relativeFilePath, string fileContents)
{
var extnDir = Path.Combine(Path.GetTempPath(), extnDirName);
Directory.CreateDirectory(Path.Combine(extnDir, Path.GetDirectoryName(relativeFilePath)));
File.WriteAllText(Path.Combine(extnDir, relativeFilePath), fileContents);
return extnDir;
}
string GetMainTargetFileContent(string extensionsPathPropertyName="MSBuildExtensionsPath")
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='Main' DependsOnTargets='FromExtn'>
<Message Text='PropertyFromExtn1: $(PropertyFromExtn1)'/>
</Target>
<Import Project='$({0})\foo\extn.proj'/>
</Project>";
return String.Format(mainTargetsFileContent, extensionsPathPropertyName);
}
string GetExtensionTargetsFileContent1(string extensionsPathPropertyName="MSBuildExtensionsPath")
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FooBar</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$({0})\bar\extn2.proj'/>
</Project>
";
return String.Format(extnTargetsFileContent1, extensionsPathPropertyName);
}
string GetExtensionTargetsFileContent2(string extensionsPathPropertyName="MSBuildExtensionsPath")
{
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn2>Abc</PropertyFromExtn2>
</PropertyGroup>
<Target Name='FromExtn2'>
<Message Text='Running FromExtn2'/>
</Target>
</Project>
";
return extnTargetsFileContent2;
}
private ToolsetConfigurationReader GetStandardConfigurationReader()
{
return new ToolsetConfigurationReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>(), ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest);
}
}
}
| |
/*
* Copyright 2017 ZXing.Net authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Runtime.InteropServices;
using ZXing.Interop.Common;
namespace ZXing.Interop.Decoding
{
/// <summary>
/// Encapsulates the result of decoding a barcode within an image.
/// </summary>
[ComVisible(true)]
[Guid("6A7AC019-6108-474E-9806-E36F5409EE66")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public sealed class Result : IResult
{
/// <returns>raw text encoded by the barcode, if applicable, otherwise <code>null</code></returns>
public String Text { get; private set; }
/// <returns>raw bytes encoded by the barcode, if applicable, otherwise <code>null</code></returns>
public byte[] RawBytes { get; private set; }
/// <returns>
/// points related to the barcode in the image. These are typically points
/// identifying finder patterns or the corners of the barcode. The exact meaning is
/// specific to the type of barcode that was decoded.
/// </returns>
public ResultPoint[] ResultPoints { get; private set; }
/// <returns>{@link BarcodeFormat} representing the format of the barcode that was decoded</returns>
public Common.BarcodeFormat BarcodeFormat { get; private set; }
/// <returns>
/// {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be
/// <code>null</code>. This contains optional metadata about what was detected about the barcode,
/// like orientation.
/// </returns>
public ResultMetadataItem[] ResultMetadata { get; private set; }
/// <summary>
/// Gets the timestamp.
/// </summary>
public long Timestamp { get; private set; }
/// <summary>
/// how many bits of <see cref="RawBytes"/> are valid; typically 8 times its length
/// </summary>
public int NumBits { get; private set; }
internal Result(ZXing.Result result)
{
if (result != null)
{
Text = result.Text;
RawBytes = result.RawBytes;
ResultPoints = result.ResultPoints.ToInteropResultPoints();
BarcodeFormat = result.BarcodeFormat.ToInterop();
if (result.ResultMetadata != null)
{
ResultMetadata = new ResultMetadataItem[result.ResultMetadata.Count];
var index = 0;
foreach (var item in result.ResultMetadata)
{
ResultMetadata[index] = new ResultMetadataItem {Key = item.Key.ToInterop(), Value = item.Value != null ? item.Value.ToString() : null};
index++;
}
}
Timestamp = result.Timestamp;
NumBits = result.NumBits;
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override String ToString()
{
if (Text == null)
{
return "[" + RawBytes.Length + " bytes]";
}
return Text;
}
}
[ComVisible(true)]
[Guid("E6B8E5FD-E301-416B-9620-BA86FB5EA1B7")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class ResultMetadataItem
{
public ResultMetadataType Key { get; internal set; }
public string Value { get; internal set; }
public override string ToString()
{
return Key + ":" + (Value ?? String.Empty);
}
}
/// <summary>
/// Represents some type of metadata about the result of the decoding that the decoder
/// wishes to communicate back to the caller.
/// </summary>
/// <author>Sean Owen</author>
[ComVisible(true)]
[Guid("7089C95E-18C4-4A67-B0F1-FC1D6D14EDD2")]
public enum ResultMetadataType
{
/// <summary>
/// Unspecified, application-specific metadata. Maps to an unspecified {@link Object}.
/// </summary>
OTHER,
/// <summary>
/// Denotes the likely approximate orientation of the barcode in the image. This value
/// is given as degrees rotated clockwise from the normal, upright orientation.
/// For example a 1D barcode which was found by reading top-to-bottom would be
/// said to have orientation "90". This key maps to an {@link Integer} whose
/// value is in the range [0,360).
/// </summary>
ORIENTATION,
/// <summary>
/// <p>2D barcode formats typically encode text, but allow for a sort of 'byte mode'
/// which is sometimes used to encode binary data. While {@link Result} makes available
/// the complete raw bytes in the barcode for these formats, it does not offer the bytes
/// from the byte segments alone.</p>
/// <p>This maps to a {@link java.util.List} of byte arrays corresponding to the
/// raw bytes in the byte segments in the barcode, in order.</p>
/// </summary>
BYTE_SEGMENTS,
/// <summary>
/// Error correction level used, if applicable. The value type depends on the
/// format, but is typically a String.
/// </summary>
ERROR_CORRECTION_LEVEL,
/// <summary>
/// For some periodicals, indicates the issue number as an {@link Integer}.
/// </summary>
ISSUE_NUMBER,
/// <summary>
/// For some products, indicates the suggested retail price in the barcode as a
/// formatted {@link String}.
/// </summary>
SUGGESTED_PRICE,
/// <summary>
/// For some products, the possible country of manufacture as a {@link String} denoting the
/// ISO country code. Some map to multiple possible countries, like "US/CA".
/// </summary>
POSSIBLE_COUNTRY,
/// <summary>
/// For some products, the extension text
/// </summary>
UPC_EAN_EXTENSION,
/// <summary>
/// If the code format supports structured append and
/// the current scanned code is part of one then the
/// sequence number is given with it.
/// </summary>
STRUCTURED_APPEND_SEQUENCE,
/// <summary>
/// If the code format supports structured append and
/// the current scanned code is part of one then the
/// parity is given with it.
/// </summary>
STRUCTURED_APPEND_PARITY,
/// <summary>
/// PDF417-specific metadata
/// </summary>
PDF417_EXTRA_METADATA,
/// <summary>
/// Aztec-specific metadata
/// </summary>
AZTEC_EXTRA_METADATA
}
internal static class ResultMetadataTypeExtensions
{
public static ResultMetadataType ToInterop(this ZXing.ResultMetadataType metadataType)
{
switch (metadataType)
{
case ZXing.ResultMetadataType.AZTEC_EXTRA_METADATA:
return ResultMetadataType.AZTEC_EXTRA_METADATA;
case ZXing.ResultMetadataType.BYTE_SEGMENTS:
return ResultMetadataType.BYTE_SEGMENTS;
case ZXing.ResultMetadataType.ERROR_CORRECTION_LEVEL:
return ResultMetadataType.ERROR_CORRECTION_LEVEL;
case ZXing.ResultMetadataType.ISSUE_NUMBER:
return ResultMetadataType.ISSUE_NUMBER;
case ZXing.ResultMetadataType.ORIENTATION:
return ResultMetadataType.ORIENTATION;
case ZXing.ResultMetadataType.OTHER:
return ResultMetadataType.OTHER;
case ZXing.ResultMetadataType.PDF417_EXTRA_METADATA:
return ResultMetadataType.PDF417_EXTRA_METADATA;
case ZXing.ResultMetadataType.POSSIBLE_COUNTRY:
return ResultMetadataType.POSSIBLE_COUNTRY;
case ZXing.ResultMetadataType.STRUCTURED_APPEND_PARITY:
return ResultMetadataType.STRUCTURED_APPEND_PARITY;
case ZXing.ResultMetadataType.STRUCTURED_APPEND_SEQUENCE:
return ResultMetadataType.STRUCTURED_APPEND_SEQUENCE;
case ZXing.ResultMetadataType.SUGGESTED_PRICE:
return ResultMetadataType.SUGGESTED_PRICE;
case ZXing.ResultMetadataType.UPC_EAN_EXTENSION:
return ResultMetadataType.UPC_EAN_EXTENSION;
default:
return ResultMetadataType.OTHER;
}
}
}
}
| |
// 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 Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// 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>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Files(AutoRestSwaggerBATFileService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
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>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/nonempty").ToString();
// 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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.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<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>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/verylarge").ToString();
// 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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.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<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>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/empty").ToString();
// 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 (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.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<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;
}
}
}
| |
using UnityEngine;
using System.Collections;
public class NPCBehaviour : NPCMotion
{
public GameObject player;
public GameObject homePoint;
public float alertThreshold = 15.0f;
public float homeProximity = 3.0f;
public GameObject acidSpit;
public float acidSpeed = 50.0f;
public float acidCooldown = 5.0f;
private AIState state = AIState.idle;
private float timeCounter = 5.0f;
private bool slowDownOnce = false;
// Use this for initialization
void Awake ()
{
if(!source)
source = this.gameObject;
if(!player)
{
player = GameObject.Find("Player");
player = player.transform.FindChild("PlayerCharacter").gameObject;
}
if(!homePoint)
{
GameObject[] homes = GameObject.FindGameObjectsWithTag("Home");
if(homes.Length <= 0)
return;
float counter = 9999.0f;
GameObject closestHome = homes[0];
foreach(GameObject home in homes)
{
Vector3 distance = home.transform.position - source.transform.position;
if(Vector3.Magnitude(distance) < counter)
{
closestHome = home;
counter = Vector3.Magnitude(distance);
}
}
homePoint = closestHome;
}
}
// Update is called once per frame
void Update ()
{
//Debug.Log("current state is " + state);
timeCounter += Time.deltaTime;
// TODO - if no homepoint, do something else
Think();
Move();
ManageSpeed();
}
void Think ()
{
switch(state)
{
case NPCMotion.AIState.idle:
ActionsIdle();
break;
case NPCMotion.AIState.alert:
ActionsAlert();
break;
case NPCMotion.AIState.scared:
ActionsScared();
break;
}
}
void ActionsIdle ()
{
Vector3 waypoint = source.transform.position;;
if(homePoint)
{
waypoint = homePoint.transform.position;
waypoint.x += Random.Range(-homeProximity, homeProximity);
waypoint.y += Random.Range(-homeProximity, homeProximity);
//waypoint.z += Random.Range(-homeProximity, homeProximity);
}
else // No home or destroyed home
{
if(slowDownOnce == false)
{
//Debug.Log("slowing down " + Vector3.Magnitude(source.rigidbody.velocity) + " vs " + Vector3.Magnitude(Vector3.zero));
Brakes();
if(Vector3.Magnitude(source.rigidbody.velocity) <= 2.0f)
{
source.rigidbody.drag = 0.05f;
slowDownOnce = true;
}
}
else
{
//Debug.Log("done slowing with velo " + Vector3.Magnitude(source.rigidbody.velocity));
waypoint = source.transform.position;
waypoint.x += Random.Range(-homeProximity * 2.0f, homeProximity * 2.0f);
waypoint.y += Random.Range(-homeProximity * 2.0f, homeProximity * 2.0f);
//waypoint.z += Random.Range(-homeProximity * 2.0f, homeProximity * 2.0f);
}
}
SetWaypoint(waypoint);
// Conditions for change
if(Vector3.Magnitude(player.transform.position - source.transform.position) <= alertThreshold)
{
state = NPCMotion.AIState.alert;
if(Input.GetMouseButton(0) || Input.GetMouseButton(1))
state = NPCMotion.AIState.scared;
}
}
void ActionsAlert ()
{
Vector3 waypoint = source.transform.position;
if(homePoint)
{
Vector3 protectLine = player.transform.position - homePoint.transform.position;
Vector3 factor = protectLine * (homeProximity / Vector3.Magnitude(protectLine));
waypoint = homePoint.transform.position + factor;
}
else
{
if(slowDownOnce == false)
{
//Debug.Log("slowing down " + Vector3.Magnitude(source.rigidbody.velocity) + " vs " + Vector3.Magnitude(Vector3.zero));
Brakes();
if(Vector3.Magnitude(source.rigidbody.velocity) <= 2.0f)
{
source.rigidbody.drag = 0.05f;
slowDownOnce = true;
}
}
else
{
//Debug.Log("done slowing with velo " + Vector3.Magnitude(source.rigidbody.velocity));
waypoint = source.transform.position;
waypoint.x += Random.Range(-homeProximity * 2.0f, homeProximity * 2.0f);
waypoint.y += Random.Range(-homeProximity * 2.0f, homeProximity * 2.0f);
//waypoint.z += Random.Range(-homeProximity * 2.0f, homeProximity * 2.0f);
}
}
SetWaypoint(waypoint);
// Acid attack vs player
if(timeCounter >= acidCooldown)
{
Vector3 towardsPlayer = player.transform.position - source.transform.position;
Ray targetting = new Ray(source.transform.position, towardsPlayer);
Vector3 attackPoint = targetting.GetPoint(Vector3.Magnitude(towardsPlayer) / 10);
RaycastHit hit;
if(Physics.Raycast(source.transform.position, towardsPlayer, out hit))
{
if(hit.transform.root.name == "Player")
{
GameObject attack = Instantiate(acidSpit, attackPoint, Quaternion.identity) as GameObject;
attack.transform.LookAt(player.transform.position);
attack.rigidbody.AddForce(attack.transform.forward * acidSpeed * 5000.0f * Time.deltaTime);
}
}
timeCounter = 0.0f;
}
// Conditions for change
ArmControls playerArmScript = player.transform.parent.gameObject.GetComponent<ArmControls>() as ArmControls;
//if(Vector3.Magnitude(player.transform.position - source.transform.position) <= alertThreshold)
if(Vector3.Magnitude(player.transform.position - source.transform.position) <= playerArmScript.checkArmDistance())
{
if(Input.GetMouseButton(0) || Input.GetMouseButton(1))
state = NPCMotion.AIState.scared;
}
else if(Vector3.Magnitude(player.transform.position - source.transform.position) > alertThreshold)
state = NPCMotion.AIState.idle;
}
void ActionsScared ()
{
// TODO - need to correct the targets
//Vector3 runAway = Vector3.Reflect((player.transform.position - source.transform.position), Vector3.up);
//Vector3 runAway = Vector3.Reflect((player.transform.position), Vector3.up);
Vector3 runAway = source.transform.position - player.transform.position;
Vector3 runAwayPoint = runAway / 10;
runAway = source.transform.position + (runAwayPoint * 10);
SetWaypoint(runAway);
// Conditions for change
if(Vector3.Magnitude(player.transform.position - source.transform.position) >= alertThreshold * 1.5f)
state = NPCMotion.AIState.idle;
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u32 = System.UInt32;
using Pgno = System.UInt32;
namespace System.Data.SQLite
{
using sqlite3_value = Sqlite3.Mem;
using sqlite3_pcache = Sqlite3.PCache1;
public partial class Sqlite3
{
/*
** 2008 August 05
**
** 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 implements that page cache.
*************************************************************************
** 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"
/*
** A complete page cache is an instance of this structure.
*/
public class PCache
{
public PgHdr pDirty, pDirtyTail; /* List of dirty pages in LRU order */
public PgHdr pSynced; /* Last synced page in dirty page list */
public int _nRef; /* Number of referenced pages */
public int nMax; /* Configured cache size */
public int szPage; /* Size of every page in this cache */
public int szExtra; /* Size of extra space for each page */
public bool bPurgeable; /* True if pages are on backing store */
public dxStress xStress; //int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
public object pStress; /* Argument to xStress */
public sqlite3_pcache pCache; /* Pluggable cache module */
public PgHdr pPage1; /* Reference to page 1 */
public int nRef /* Number of referenced pages */
{
get
{
return _nRef;
}
set
{
_nRef = value;
}
}
public void Clear()
{
pDirty = null;
pDirtyTail = null;
pSynced = null;
nRef = 0;
}
};
/*
** Some of the Debug.Assert() macros in this code are too expensive to run
** even during normal debugging. Use them only rarely on long-running
** tests. Enable the expensive asserts using the
** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
//# define expensive_assert(X) Debug.Assert(X)
static void expensive_assert( bool x ) { Debug.Assert( x ); }
#else
//# define expensive_assert(X)
#endif
/********************************** Linked List Management ********************/
#if !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT
/*
** Check that the pCache.pSynced variable is set correctly. If it
** is not, either fail an Debug.Assert or return zero. Otherwise, return
** non-zero. This is only used in debugging builds, as follows:
**
** expensive_assert( pcacheCheckSynced(pCache) );
*/
static int pcacheCheckSynced(PCache pCache){
PgHdr p ;
for(p=pCache.pDirtyTail; p!=pCache.pSynced; p=p.pDirtyPrev){
Debug.Assert( p.nRef !=0|| (p.flags&PGHDR_NEED_SYNC) !=0);
}
return (p==null || p.nRef!=0 || (p.flags&PGHDR_NEED_SYNC)==0)?1:0;
}
#endif //* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
/*
** Remove page pPage from the list of dirty pages.
*/
static void pcacheRemoveFromDirtyList(PgHdr pPage)
{
PCache p = pPage.pCache;
Debug.Assert(pPage.pDirtyNext != null || pPage == p.pDirtyTail);
Debug.Assert(pPage.pDirtyPrev != null || pPage == p.pDirty);
/* Update the PCache1.pSynced variable if necessary. */
if (p.pSynced == pPage)
{
PgHdr pSynced = pPage.pDirtyPrev;
while (pSynced != null && (pSynced.flags & PGHDR_NEED_SYNC) != 0)
{
pSynced = pSynced.pDirtyPrev;
}
p.pSynced = pSynced;
}
if (pPage.pDirtyNext != null)
{
pPage.pDirtyNext.pDirtyPrev = pPage.pDirtyPrev;
}
else
{
Debug.Assert(pPage == p.pDirtyTail);
p.pDirtyTail = pPage.pDirtyPrev;
}
if (pPage.pDirtyPrev != null)
{
pPage.pDirtyPrev.pDirtyNext = pPage.pDirtyNext;
}
else
{
Debug.Assert(pPage == p.pDirty);
p.pDirty = pPage.pDirtyNext;
}
pPage.pDirtyNext = null;
pPage.pDirtyPrev = null;
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
** pPage).
*/
static void pcacheAddToDirtyList(PgHdr pPage)
{
PCache p = pPage.pCache;
Debug.Assert(pPage.pDirtyNext == null && pPage.pDirtyPrev == null && p.pDirty != pPage);
pPage.pDirtyNext = p.pDirty;
if (pPage.pDirtyNext != null)
{
Debug.Assert(pPage.pDirtyNext.pDirtyPrev == null);
pPage.pDirtyNext.pDirtyPrev = pPage;
}
p.pDirty = pPage;
if (null == p.pDirtyTail)
{
p.pDirtyTail = pPage;
}
if (null == p.pSynced && 0 == (pPage.flags & PGHDR_NEED_SYNC))
{
p.pSynced = pPage;
}
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Wrapper around the pluggable caches xUnpin method. If the cache is
** being used for an in-memory database, this function is a no-op.
*/
static void pcacheUnpin(PgHdr p)
{
PCache pCache = p.pCache;
if (pCache.bPurgeable)
{
if (p.pgno == 1)
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin(pCache.pCache, p, false);
}
}
/*************************************************** General Interfaces ******
**
** Initialize and shutdown the page cache subsystem. Neither of these
** functions are threadsafe.
*/
static int sqlite3PcacheInitialize()
{
if (sqlite3GlobalConfig.pcache.xInit == null)
{
/* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
** built-in default page cache is used instead of the application defined
** page cache. */
sqlite3PCacheSetDefault();
}
return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
}
static void sqlite3PcacheShutdown()
{
if (sqlite3GlobalConfig.pcache.xShutdown != null)
{
/* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
}
}
/*
** Return the size in bytes of a PCache object.
*/
static int sqlite3PcacheSize()
{
return 4;
}// sizeof( PCache ); }
/*
** Create a new PCache object. Storage space to hold the object
** has already been allocated and is passed in as the p pointer.
** The caller discovers how much space needs to be allocated by
** calling sqlite3PcacheSize().
*/
static void sqlite3PcacheOpen(
int szPage, /* Size of every page */
int szExtra, /* Extra space associated with each page */
bool bPurgeable, /* True if pages are on backing store */
dxStress xStress,//int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
object pStress, /* Argument to xStress */
PCache p /* Preallocated space for the PCache */
)
{
p.Clear();//memset(p, 0, sizeof(PCache));
p.szPage = szPage;
p.szExtra = szExtra;
p.bPurgeable = bPurgeable;
p.xStress = xStress;
p.pStress = pStress;
p.nMax = 100;
}
/*
** Change the page size for PCache object. The caller must ensure that there
** are no outstanding page references when this function is called.
*/
static void sqlite3PcacheSetPageSize(PCache pCache, int szPage)
{
Debug.Assert(pCache.nRef == 0 && pCache.pDirty == null);
if (pCache.pCache != null)
{
sqlite3GlobalConfig.pcache.xDestroy(ref pCache.pCache);
pCache.pCache = null;
}
pCache.szPage = szPage;
}
/*
** Try to obtain a page from the cache.
*/
static int sqlite3PcacheFetch(
PCache pCache, /* Obtain the page from this cache */
u32 pgno, /* Page number to obtain */
int createFlag, /* If true, create page if it does not exist already */
ref PgHdr ppPage /* Write the page here */
)
{
PgHdr pPage = null;
int eCreate;
Debug.Assert(pCache != null);
Debug.Assert(createFlag == 1 || createFlag == 0);
Debug.Assert(pgno > 0);
/* If the pluggable cache (sqlite3_pcache*) has not been allocated,
** allocate it now.
*/
if (null == pCache.pCache && createFlag != 0)
{
sqlite3_pcache p;
int nByte;
nByte = pCache.szPage + pCache.szExtra + 0;// sizeof( PgHdr );
p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache.bPurgeable);
//if ( null == p )
//{
// return SQLITE_NOMEM;
//}
sqlite3GlobalConfig.pcache.xCachesize(p, pCache.nMax);
pCache.pCache = p;
}
eCreate = createFlag * (1 + ((!pCache.bPurgeable || null == pCache.pDirty) ? 1 : 0));
if (pCache.pCache != null)
{
pPage = sqlite3GlobalConfig.pcache.xFetch(pCache.pCache, pgno, eCreate);
}
if (null == pPage && eCreate == 1)
{
PgHdr pPg;
/* Find a dirty page to write-out and recycle. First try to find a
** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
** cleared), but if that is not possible settle for any other
** unreferenced dirty page.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(pCache) );
#endif
for (pPg = pCache.pSynced;
pPg != null && (pPg.nRef != 0 || (pPg.flags & PGHDR_NEED_SYNC) != 0);
pPg = pPg.pDirtyPrev
)
;
pCache.pSynced = pPg;
if (null == pPg)
{
for (pPg = pCache.pDirtyTail; pPg != null && pPg.nRef != 0; pPg = pPg.pDirtyPrev)
;
}
if (pPg != null)
{
int rc;
#if SQLITE_LOG_CACHE_SPILL
sqlite3_log(SQLITE_FULL,
"spill page %d making room for %d - cache used: %d/%d",
pPg->pgno, pgno,
sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
pCache->nMax);
#endif
rc = pCache.xStress(pCache.pStress, pPg);
if (rc != SQLITE_OK && rc != SQLITE_BUSY)
{
return rc;
}
}
pPage = sqlite3GlobalConfig.pcache.xFetch(pCache.pCache, pgno, 2);
}
if (pPage != null)
{
if (null == pPage.pData)
{
// memset(pPage, 0, sizeof(PgHdr));
pPage.pData = sqlite3Malloc(pCache.szPage);// pPage->pData = (void*)&pPage[1];
//pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage];
//memset(pPage->pExtra, 0, pCache->szExtra);
pPage.pCache = pCache;
pPage.pgno = pgno;
}
Debug.Assert(pPage.pCache == pCache);
Debug.Assert(pPage.pgno == pgno);
//assert(pPage->pData == (void*)&pPage[1]);
//assert(pPage->pExtra == (void*)&((char*)&pPage[1])[pCache->szPage]);
if (0 == pPage.nRef)
{
pCache.nRef++;
}
pPage.nRef++;
if (pgno == 1)
{
pCache.pPage1 = pPage;
}
}
ppPage = pPage;
return (pPage == null && eCreate != 0) ? SQLITE_NOMEM : SQLITE_OK;
}
/*
** Decrement the reference count on a page. If the page is clean and the
** reference count drops to 0, then it is made elible for recycling.
*/
static void sqlite3PcacheRelease(PgHdr p)
{
Debug.Assert(p.nRef > 0);
p.nRef--;
if (p.nRef == 0)
{
PCache pCache = p.pCache;
pCache.nRef--;
if ((p.flags & PGHDR_DIRTY) == 0)
{
pcacheUnpin(p);
}
else
{
/* Move the page to the head of the dirty list. */
pcacheRemoveFromDirtyList(p);
pcacheAddToDirtyList(p);
}
}
}
/*
** Increase the reference count of a supplied page by 1.
*/
static void sqlite3PcacheRef(PgHdr p)
{
Debug.Assert(p.nRef > 0);
p.nRef++;
}
/*
** Drop a page from the cache. There must be exactly one reference to the
** page. This function deletes that reference, so after it returns the
** page pointed to by p is invalid.
*/
static void sqlite3PcacheDrop(PgHdr p)
{
PCache pCache;
Debug.Assert(p.nRef == 1);
if ((p.flags & PGHDR_DIRTY) != 0)
{
pcacheRemoveFromDirtyList(p);
}
pCache = p.pCache;
pCache.nRef--;
if (p.pgno == 1)
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin(pCache.pCache, p, true);
}
/*
** Make sure the page is marked as dirty. If it isn't dirty already,
** make it so.
*/
static void sqlite3PcacheMakeDirty(PgHdr p)
{
p.flags &= ~PGHDR_DONT_WRITE;
Debug.Assert(p.nRef > 0);
if (0 == (p.flags & PGHDR_DIRTY))
{
p.flags |= PGHDR_DIRTY;
pcacheAddToDirtyList(p);
}
}
/*
** Make sure the page is marked as clean. If it isn't clean already,
** make it so.
*/
static void sqlite3PcacheMakeClean(PgHdr p)
{
if ((p.flags & PGHDR_DIRTY) != 0)
{
pcacheRemoveFromDirtyList(p);
p.flags &= ~(PGHDR_DIRTY | PGHDR_NEED_SYNC);
if (p.nRef == 0)
{
pcacheUnpin(p);
}
}
}
/*
** Make every page in the cache clean.
*/
static void sqlite3PcacheCleanAll(PCache pCache)
{
PgHdr p;
while ((p = pCache.pDirty) != null)
{
sqlite3PcacheMakeClean(p);
}
}
/*
** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
*/
static void sqlite3PcacheClearSyncFlags(PCache pCache)
{
PgHdr p;
for (p = pCache.pDirty; p != null; p = p.pDirtyNext)
{
p.flags &= ~PGHDR_NEED_SYNC;
}
pCache.pSynced = pCache.pDirtyTail;
}
/*
** Change the page number of page p to newPgno.
*/
static void sqlite3PcacheMove(PgHdr p, Pgno newPgno)
{
PCache pCache = p.pCache;
Debug.Assert(p.nRef > 0);
Debug.Assert(newPgno > 0);
sqlite3GlobalConfig.pcache.xRekey(pCache.pCache, p, p.pgno, newPgno);
p.pgno = newPgno;
if ((p.flags & PGHDR_DIRTY) != 0 && (p.flags & PGHDR_NEED_SYNC) != 0)
{
pcacheRemoveFromDirtyList(p);
pcacheAddToDirtyList(p);
}
}
/*
** Drop every cache entry whose page number is greater than "pgno". The
** caller must ensure that there are no outstanding references to any pages
** other than page 1 with a page number greater than pgno.
**
** If there is a reference to page 1 and the pgno parameter passed to this
** function is 0, then the data area associated with page 1 is zeroed, but
** the page object is not dropped.
*/
static void sqlite3PcacheTruncate(PCache pCache, u32 pgno)
{
if (pCache.pCache != null)
{
PgHdr p;
PgHdr pNext;
for (p = pCache.pDirty; p != null; p = pNext)
{
pNext = p.pDirtyNext;
/* This routine never gets call with a positive pgno except right
** after sqlite3PcacheCleanAll(). So if there are dirty pages,
** it must be that pgno==0.
*/
Debug.Assert(p.pgno > 0);
if (ALWAYS(p.pgno > pgno))
{
Debug.Assert((p.flags & PGHDR_DIRTY) != 0);
sqlite3PcacheMakeClean(p);
}
}
if (pgno == 0 && pCache.pPage1 != null)
{
// memset( pCache.pPage1.pData, 0, pCache.szPage );
pCache.pPage1.pData = sqlite3Malloc(pCache.szPage);
pgno = 1;
}
sqlite3GlobalConfig.pcache.xTruncate(pCache.pCache, pgno + 1);
}
}
/*
** Close a cache.
*/
static void sqlite3PcacheClose(PCache pCache)
{
if (pCache.pCache != null)
{
sqlite3GlobalConfig.pcache.xDestroy(ref pCache.pCache);
}
}
/*
** Discard the contents of the cache.
*/
static void sqlite3PcacheClear(PCache pCache)
{
sqlite3PcacheTruncate(pCache, 0);
}
/*
** Merge two lists of pages connected by pDirty and in pgno order.
** Do not both fixing the pDirtyPrev pointers.
*/
static PgHdr pcacheMergeDirtyList(PgHdr pA, PgHdr pB)
{
PgHdr result = new PgHdr();
PgHdr pTail = result;
while (pA != null && pB != null)
{
if (pA.pgno < pB.pgno)
{
pTail.pDirty = pA;
pTail = pA;
pA = pA.pDirty;
}
else
{
pTail.pDirty = pB;
pTail = pB;
pB = pB.pDirty;
}
}
if (pA != null)
{
pTail.pDirty = pA;
}
else if (pB != null)
{
pTail.pDirty = pB;
}
else
{
pTail.pDirty = null;
}
return result.pDirty;
}
/*
** Sort the list of pages in accending order by pgno. Pages are
** connected by pDirty pointers. The pDirtyPrev pointers are
** corrupted by this sort.
**
** Since there cannot be more than 2^31 distinct pages in a database,
** there cannot be more than 31 buckets required by the merge sorter.
** One extra bucket is added to catch overflow in case something
** ever changes to make the previous sentence incorrect.
*/
//#define N_SORT_BUCKET 32
const int N_SORT_BUCKET = 32;
static PgHdr pcacheSortDirtyList(PgHdr pIn)
{
PgHdr[] a;
PgHdr p;//a[N_SORT_BUCKET], p;
int i;
a = new PgHdr[N_SORT_BUCKET];//memset(a, 0, sizeof(a));
while (pIn != null)
{
p = pIn;
pIn = p.pDirty;
p.pDirty = null;
for (i = 0; ALWAYS(i < N_SORT_BUCKET - 1); i++)
{
if (a[i] == null)
{
a[i] = p;
break;
}
else
{
p = pcacheMergeDirtyList(a[i], p);
a[i] = null;
}
}
if (NEVER(i == N_SORT_BUCKET - 1))
{
/* To get here, there need to be 2^(N_SORT_BUCKET) elements in
** the input list. But that is impossible.
*/
a[i] = pcacheMergeDirtyList(a[i], p);
}
}
p = a[0];
for (i = 1; i < N_SORT_BUCKET; i++)
{
p = pcacheMergeDirtyList(p, a[i]);
}
return p;
}
/*
** Return a list of all dirty pages in the cache, sorted by page number.
*/
static PgHdr sqlite3PcacheDirtyList(PCache pCache)
{
PgHdr p;
for (p = pCache.pDirty; p != null; p = p.pDirtyNext)
{
p.pDirty = p.pDirtyNext;
}
return pcacheSortDirtyList(pCache.pDirty);
}
/*
** Return the total number of referenced pages held by the cache.
*/
static int sqlite3PcacheRefCount(PCache pCache)
{
return pCache.nRef;
}
/*
** Return the number of references to the page supplied as an argument.
*/
static int sqlite3PcachePageRefcount(PgHdr p)
{
return p.nRef;
}
/*
** Return the total number of pages in the cache.
*/
static int sqlite3PcachePagecount(PCache pCache)
{
int nPage = 0;
if (pCache.pCache != null)
{
nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache.pCache);
}
return nPage;
}
#if SQLITE_TEST
/*
** Get the suggested cache-size value.
*/
static int sqlite3PcacheGetCachesize( PCache pCache )
{
return pCache.nMax;
}
#endif
/*
** Set the suggested cache-size value.
*/
static void sqlite3PcacheSetCachesize(PCache pCache, int mxPage)
{
pCache.nMax = mxPage;
if (pCache.pCache != null)
{
sqlite3GlobalConfig.pcache.xCachesize(pCache.pCache, mxPage);
}
}
#if SQLITE_CHECK_PAGES || (SQLITE_DEBUG)
/*
** For all dirty pages currently in the cache, invoke the specified
** callback. This is only used if the SQLITE_CHECK_PAGES macro is
** defined.
*/
static void sqlite3PcacheIterateDirty( PCache pCache, dxIter xIter )
{
PgHdr pDirty;
for ( pDirty = pCache.pDirty; pDirty != null; pDirty = pDirty.pDirtyNext )
{
xIter( pDirty );
}
}
#endif
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ProjectTracker.Library;
using Csla.Security;
using Csla.Configuration;
using Csla;
namespace PTWin
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
_main = this;
}
private static MainForm _main;
internal static MainForm Instance
{
get { return _main; }
}
private void MainForm_Load(object sender, EventArgs e)
{
if (Csla.ApplicationContext.AuthenticationType == "Windows")
{
AppDomain.CurrentDomain.SetPrincipalPolicy(
System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
ApplyAuthorizationRules();
}
else
{
DoLogin();
}
if (DocumentCount == 0)
DocumentsToolStripDropDownButton.Enabled = false;
// initialize cache of role list
var task = RoleList.CacheListAsync();
}
#region Projects
private void NewProjectToolStripMenuItem_Click(
object sender, EventArgs e)
{
using (StatusBusy busy =
new StatusBusy("Creating project..."))
{
AddWinPart(new ProjectEdit(ProjectTracker.Library.ProjectEdit.NewProject()));
}
}
private void EditProjectToolStripMenuItem_Click(
object sender, EventArgs e)
{
using (ProjectSelect dlg = new ProjectSelect())
{
dlg.Text = "Edit Project";
if (dlg.ShowDialog() == DialogResult.OK)
{
ShowEditProject(dlg.ProjectId);
}
}
}
public void ShowEditProject(int projectId)
{
// see if this project is already loaded
foreach (Control ctl in Panel1.Controls)
{
if (ctl is ProjectEdit)
{
ProjectEdit part = (ProjectEdit)ctl;
if (part.Project.Id.Equals(projectId))
{
// project already loaded so just
// display the existing winpart
ShowWinPart(part);
return;
}
}
}
// the project wasn't already loaded
// so load it and display the new winpart
using (StatusBusy busy = new StatusBusy("Loading project..."))
{
try
{
AddWinPart(new ProjectEdit(ProjectTracker.Library.ProjectEdit.GetProject(projectId)));
}
catch (Csla.DataPortalException ex)
{
MessageBox.Show(ex.BusinessException.ToString(),
"Error loading", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error loading", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}
private async void DeleteProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
ProjectSelect dlg = new ProjectSelect();
dlg.Text = "Delete Project";
if (dlg.ShowDialog() == DialogResult.OK)
{
// get the project id
var projectId = dlg.ProjectId;
if (MessageBox.Show("Are you sure?", "Delete project",
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
using (StatusBusy busy = new StatusBusy("Deleting project..."))
{
try
{
await ProjectTracker.Library.ProjectEdit.DeleteProjectAsync(projectId);
}
catch (Csla.DataPortalException ex)
{
MessageBox.Show(ex.BusinessException.ToString(),
"Error deleting", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error deleting", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}
}
}
#endregion
#region Resources
private void NewResourceToolStripMenuItem_Click(object sender, EventArgs e)
{
using (StatusBusy busy = new StatusBusy("Creating resource..."))
{
AddWinPart(new ResourceEdit(ProjectTracker.Library.ResourceEdit.NewResourceEdit()));
}
}
private void EditResourceToolStripMenuItem_Click(
object sender, EventArgs e)
{
ResourceSelect dlg = new ResourceSelect();
dlg.Text = "Edit Resource";
if (dlg.ShowDialog() == DialogResult.OK)
{
// get the resource id
ShowEditResource(dlg.ResourceId);
}
}
public void ShowEditResource(int resourceId)
{
// see if this resource is already loaded
foreach (Control ctl in Panel1.Controls)
{
if (ctl is ResourceEdit)
{
ResourceEdit part = (ResourceEdit)ctl;
if (part.Resource.Id.Equals(resourceId))
{
// resource already loaded so just
// display the existing winpart
ShowWinPart(part);
return;
}
}
}
// the resource wasn't already loaded
// so load it and display the new winpart
using (StatusBusy busy = new StatusBusy("Loading resource..."))
{
try
{
AddWinPart(new ResourceEdit(ProjectTracker.Library.ResourceEdit.GetResourceEdit(resourceId)));
}
catch (Csla.DataPortalException ex)
{
MessageBox.Show(ex.BusinessException.ToString(),
"Error loading", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error loading", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}
private void DeleteResourceToolStripMenuItem_Click(
object sender, EventArgs e)
{
ResourceSelect dlg = new ResourceSelect();
dlg.Text = "Delete Resource";
if (dlg.ShowDialog() == DialogResult.OK)
{
// get the resource id
int resourceId = dlg.ResourceId;
if (MessageBox.Show("Are you sure?", "Delete resource",
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
using (StatusBusy busy =
new StatusBusy("Deleting resource..."))
{
try
{
ProjectTracker.Library.ResourceEdit.DeleteResourceEdit(resourceId);
}
catch (Csla.DataPortalException ex)
{
MessageBox.Show(ex.BusinessException.ToString(),
"Error deleting", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error deleting", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}
}
}
#endregion
#region Roles
private void EditRolesToolStripMenuItem_Click(
object sender, EventArgs e)
{
// see if this form is already loaded
foreach (Control ctl in Panel1.Controls)
{
if (ctl is RolesEdit)
{
ShowWinPart((WinPart)ctl);
return;
}
}
// it wasn't already loaded, so show it.
AddWinPart(new RolesEdit());
}
#endregion
#region ApplyAuthorizationRules
private void ApplyAuthorizationRules()
{
// Project menu
this.NewProjectToolStripMenuItem.Enabled =
Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectTracker.Library.ProjectEdit));
this.EditProjectToolStripMenuItem.Enabled =
Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ProjectEdit));
if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ProjectEdit)))
this.EditProjectToolStripMenuItem.Text =
"Edit project";
else
this.EditProjectToolStripMenuItem.Text =
"View project";
this.DeleteProjectToolStripMenuItem.Enabled =
Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectTracker.Library.ProjectEdit));
// Resource menu
this.NewResourceToolStripMenuItem.Enabled =
Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectTracker.Library.ResourceEdit));
this.EditResourceToolStripMenuItem.Enabled =
Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ResourceEdit));
if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ResourceEdit)))
this.EditResourceToolStripMenuItem.Text =
"Edit resource";
else
this.EditResourceToolStripMenuItem.Text =
"View resource";
this.DeleteResourceToolStripMenuItem.Enabled =
Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectTracker.Library.ResourceEdit));
// Admin menu
this.EditRolesToolStripMenuItem.Enabled =
Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.Admin.RoleEditBindingList));
}
#endregion
#region Login/Logout
private void LoginToolStripButton_Click(
object sender, EventArgs e)
{
DoLogin();
}
private void DoLogin()
{
ProjectTracker.Library.Security.PTPrincipal.Logout();
if (this.LoginToolStripButton.Text == "Login")
{
LoginForm loginForm = new LoginForm();
loginForm.ShowDialog(this);
}
System.Security.Principal.IPrincipal user =
Csla.ApplicationContext.User;
if (user.Identity.IsAuthenticated)
{
this.LoginToolStripLabel.Text = "Logged in as " +
user.Identity.Name;
this.LoginToolStripButton.Text = "Logout";
}
else
{
this.LoginToolStripLabel.Text = "Not logged in";
this.LoginToolStripButton.Text = "Login";
}
// reset menus, etc.
ApplyAuthorizationRules();
// notify all documents
List<object> tmpList = new List<object>();
foreach (var ctl in Panel1.Controls)
tmpList.Add(ctl);
foreach (var ctl in tmpList)
if (ctl is WinPart)
((WinPart)ctl).OnCurrentPrincipalChanged(this, EventArgs.Empty);
}
#endregion
#region WinPart handling
/// <summary>
/// Add a new WinPart control to the
/// list of available documents and
/// make it the active WinPart.
/// </summary>
/// <param name="part">The WinPart control to add and display.</param>
private void AddWinPart(WinPart part)
{
part.CloseWinPart += new EventHandler(CloseWinPart);
part.BackColor = toolStrip1.BackColor;
Panel1.Controls.Add(part);
this.DocumentsToolStripDropDownButton.Enabled = true;
ShowWinPart(part);
}
/// <summary>
/// Make the specified WinPart the
/// active, displayed control.
/// </summary>
/// <param name="part">The WinPart control to display.</param>
private void ShowWinPart(WinPart part)
{
part.Dock = DockStyle.Fill;
part.Visible = true;
part.BringToFront();
this.Text = "Project Tracker - " + part.ToString();
PopulateDocuments();
}
/// <summary>
/// Populate the Documents dropdown list.
/// </summary>
private void DocumentsToolStripDropDownButton_DropDownOpening(
object sender, EventArgs e)
{
PopulateDocuments();
}
/// <summary>
/// Populate the Documents dropdown list.
/// </summary>
private void PopulateDocuments()
{
ToolStripItemCollection items =
DocumentsToolStripDropDownButton.DropDownItems;
foreach (ToolStripItem item in items)
item.Click -= new EventHandler(DocumentClick);
items.Clear();
foreach (Control ctl in Panel1.Controls)
if (ctl is WinPart)
{
ToolStripItem item = new ToolStripMenuItem();
item.Text = ((WinPart)ctl).ToString();
item.Tag = ctl;
item.Click += new EventHandler(DocumentClick);
items.Add(item);
}
}
/// <summary>
/// Make selected WinPart the active control.
/// </summary>
private void DocumentClick(object sender, EventArgs e)
{
WinPart ctl = (WinPart)((ToolStripItem)sender).Tag;
ShowWinPart(ctl);
}
/// <summary>
/// Gets a count of the number of loaded
/// documents.
/// </summary>
public int DocumentCount
{
get
{
int count = 0;
foreach (Control ctl in Panel1.Controls)
if (ctl is WinPart)
count++;
return count;
}
}
/// <summary>
/// Handles event from WinPart when that
/// WinPart is closing.
/// </summary>
private void CloseWinPart(object sender, EventArgs e)
{
WinPart part = (WinPart)sender;
part.CloseWinPart -= new EventHandler(CloseWinPart);
part.Visible = false;
Panel1.Controls.Remove(part);
part.Dispose();
PopulateDocuments();
if (DocumentCount == 0)
{
this.DocumentsToolStripDropDownButton.Enabled = false;
this.Text = "Project Tracker";
}
else
{
// Find the first WinPart control and set
// the main form's Text property accordingly.
// This works because the first WinPart
// is the active one.
foreach (Control ctl in Panel1.Controls)
{
if (ctl is WinPart)
{
this.Text = "Project Tracker - " + ((WinPart)ctl).ToString();
break;
}
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ProjectTrackingServices.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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);
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Compatibility.dll
// Description: Supports DotSpatial interfaces organized for a MapWindow 4 plugin context.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 1/20/2009 11:44:42 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections.Generic;
using System.Drawing;
using DotSpatial.Data;
using GeoAPI.Geometries;
namespace DotSpatial.Compatibility
{
/// <summary>
/// Layer
/// </summary>
public interface ILayerOld
{
#region Methods
/// <summary>
/// Returns the <c>MapWinGIS.Grid</c> object associated with the layer. If the layer is not a
/// grid layer, "Nothing" will be returned.
/// </summary>
IRaster GetGridObject { get; }
/// <summary>
/// Indicates whether to skip over the layer when saving a project.
/// </summary>
bool SkipOverDuringSave { get; set; }
/// <summary>
/// Adds a label to this layer.
/// </summary>
/// <param name="text">The text of the label.</param>
/// <param name="textColor">The color of the label text.</param>
/// <param name="xPos">X position in projected map units.</param>
/// <param name="yPos">Y position in projected map units.</param>
/// <param name="justification">Text justification. Can be hjCenter, hjLeft or hjRight.</param>
void AddLabel(string text, Color textColor, double xPos, double yPos, HJustification justification);
///The following function was added for plug-in 3.1 version compatibility
/// <summary>
/// Adds an extended label to this layer.
/// </summary>
/// <param name="text">The text of the label.</param>
/// <param name="textColor">The color of the label text.</param>
/// <param name="xPos">X position in projected map units.</param>
/// <param name="yPos">Y position in projected map units.</param>
/// <param name="justification">Text justification. Can be hjCenter, hjLeft or hjRight.</param>
/// <param name="rotation">The rotation angle for the label.</param>
void AddLabelEx(string text, Color textColor, double xPos, double yPos, HJustification justification, double rotation);
/// <summary>
/// Clears all labels for this layer.
/// </summary>
void ClearLabels();
/// <summary>
/// Clears out the list of images to be used by the tkImageList point type.
/// See also UserPointImageListAdd, UserPointImageListItem, UserPointImageListCount,
/// and (on the shape interface) ShapePointImageListID.
/// </summary>
void ClearUDPointImageList();
/// <summary>
/// Sets the font to use for all labels on this layer.
/// </summary>
/// <param name="fontName">Name of the font or font family. Example: "Arial"</param>
/// <param name="fontSize">Size of the font.</param>
void Font(string fontName, int fontSize);
/// <summary>
/// Gets the underlying MapWinGIS object for this layer. The object can be either a
/// <c>MapWinGIS.Shapefile</c> or a <c>MapWinGIS.Image</c>. If the layer is a grid layer the
/// <c>MapWinGIS.Grid</c> object can be retrieved using the <c>GetGridObject</c> method.
/// </summary>
IDataSet GetObject();
/// <summary>
/// Gets a single row in the user defined line stipple. There are 32 rows in a fill stipple
/// (0-31). Each row is defined the same way as a <c>UserLineStipple</c>.
/// </summary>
/// <param name="row">The index of the row to get. Must be between 0 and 31 inclusive.</param>
/// <returns>A single stipple row.</returns>
int GetUserFillStipple(int row);
/// <summary>
/// Hides all vertices in the shapefile. Only applies to line and polygon shapefiles.
/// </summary>
void HideVertices();
/// <summary>
/// Loads the shapefile rendering properties from a .mwsr file whose base fileName matches the shapefile.
/// If the file isn't found, false is returned.
/// Function call is ignored and returns false if the layer is a grid.
/// </summary>
bool LoadShapeLayerProps();
/// <summary>
/// Loads the shapefile rendering properties from the specified fileName.
/// Function call is ignored and returns false if the layer is a grid.
/// </summary>
bool LoadShapeLayerProps(string loadFromFilename);
/// <summary>
/// Moves this layer to a new position in the layer list. The highest position is the topmost layer
/// in the display.
/// </summary>
/// <param name="newPosition">The new position.</param>
/// <param name="targetGroup">The group to put this layer in.</param>
void MoveTo(int newPosition, int targetGroup);
/// <summary>
/// Saves the shapefile rendering properties to a .mwsr file whose base fileName matches the shapefile.
/// Function call is ignored and returns false if the layer is a grid.
/// </summary>
bool SaveShapeLayerProps();
/// <summary>
/// Saves the shapefile rendering properties to the specified fileName.
/// Function call is ignored if the layer is a grid.
/// </summary>
bool SaveShapeLayerProps(string saveToFilename);
/// <summary>
/// Sets a single row in the user defined line stipple. There are 32 rows in a fill stipple
/// (0-31). Each row is defined the same way as a <c>UserLineStipple</c>.
/// </summary>
/// <param name="row">The index of the row to set. Must be between 0 and 31 inclusive.</param>
/// <param name="value">The row value to set in the fill stipple.</param>
void SetUserFillStipple(int row, int value);
/// <summary>
/// Updates the label information file stored for this layer.
/// </summary>
void UpdateLabelInfo();
/// <summary>
/// Adds an image to the list of point images used by the tkImageList point type.
/// See also UserPointImageListItem, UserPointImageListCount, ClearUDPointImageList,
/// and (on the shape interface) ShapePointImageListID.
/// </summary>
/// <param name="newValue">The new image to add.</param>
/// <returns>The index for this image, to be passed to ShapePointImageListID or other functions.</returns>
long UserPointImageListAdd(Image newValue);
/// <summary>
/// Gets the count of images from the list of images to be used by the tkImageList point type.
/// See also UserPointImageListAdd, UserPointImageListItem, ClearUDPointImageList,
/// and (on the shape interface) ShapePointImageListID.
/// </summary>
/// <returns>The count of items in the image list.</returns>
long UserPointImageListCount();
/// <summary>
/// Gets an image from the list of images to be used by the tkImageList point type.
/// See also UserPointImageListAdd, UserPointImageListCount, ClearUDPointImageList,
/// and (on the shape interface) ShapePointImageListID.
/// </summary>
/// <param name="imageIndex">The image index to retrieve.</param>
/// <returns>The index associated with this index; or null/nothing if nonexistant.</returns>
Image UserPointImageListItem(long imageIndex);
/// <summary>
/// Zooms the display to this layer, taking into acount the <c>View.ExtentPad</c>.
/// </summary>
void ZoomTo();
#endregion
#region Properties
/// <summary>
/// Gets or sets the color of this shapefile. Applies only to shapefiles. Setting the color of the
/// shapefile will clear any selected shapes and will also reset each individual shape to the same color.
/// The coloring scheme will also be overriden.
/// </summary>
Color Color { get; set; }
/// <summary>
/// Gets or sets the coloring scheme. The <c>Shapefile</c> and <c>Grid</c> objects each have
/// their own coloring scheme object. It is important to cast the <c>ColoringScheme</c> to the
/// proper type.
/// </summary>
object ColoringScheme { get; set; }
/// <summary>
/// Gets or sets whether or not to draw the fill for a polygon shapefile.
/// </summary>
bool DrawFill { get; set; }
/// <summary>
/// Gets or sets the extents where the layer changes from visible to not visible or vice versa.
///
/// If the map is zoomed beyond these extents, the layer is invisible until the map is zoomed to
/// be within these extents.
/// </summary>
Envelope DynamicVisibilityExtents { get; set; }
/// <summary>
/// Gets or sets whether the layer's coloring scheme is expanded in the legend.
/// </summary>
bool Expanded { get; set; }
/// <summary>
/// Returns the extents of this layer.
/// </summary>
Envelope Extents { get; }
/// <summary>
/// Returns the fileName of this layer. If the layer is memory-based only it may not have a valid fileName.
/// </summary>
string FileName { get; }
/// <summary>
/// Gets or sets the stipple pattern to use for the entire shapefile.
///
/// The valid values for this property are:
/// <list type="bullet">
/// <item>Custom</item>
/// <item>DashDotDash</item>
/// <item>Dashed</item>
/// <item>Dotted</item>
/// <item>None</item>
/// </list>
/// </summary>
Stipple FillStipple { get; set; }
/// <summary>
/// Gets or sets the position of the layer without respect to any group.
/// </summary>
int GlobalPosition { get; set; }
/// <summary>
/// Gets or sets the handle of the group that this layer belongs to.
/// </summary>
int GroupHandle { get; set; }
/// <summary>
/// Gets or sets the position of the layer within a group.
/// </summary>
int GroupPosition { get; set; }
/// <summary>
/// Returns the layer handle of this layer. The DotSpatial automatically sets the <c>LayerHandle</c> for the layer, and it cannot be reset.
/// </summary>
int Handle { get; set; }
/// <summary>
/// Indicates whether to skip over the layer when drawing the legend.
/// </summary>
bool HideFromLegend { get; set; }
/// <summary>
/// Gets or sets the icon to use in the legend for this layer.
/// </summary>
Image Icon { get; set; }
/// <summary>
/// Gets or sets the color that represents transparent in an <c>Image</c> layer.
/// </summary>
Color ImageTransparentColor { get; set; }
///The following label properties were added for plug-in 3.1 version compatibility
/// <summary>
/// Determines the distance from the label point to the text for the label in pixels.
/// </summary>
int LabelsOffset { get; set; }
/// <summary>
/// Determines whether labels are scaled for this layer.
/// </summary>
bool LabelsScale { get; set; }
/// <summary>
/// Determines whether labels are shadowed for this layer.
/// </summary>
bool LabelsShadow { get; set; }
/// <summary>
/// Determines the color of the labels shadows.
/// </summary>
Color LabelsShadowColor { get; set; }
/// <summary>
/// Turns labels on or off for this layer.
/// </summary>
bool LabelsVisible { get; set; }
/// <summary>
/// Returns the type of this layer. Valid values are:
/// <list type="bullet">
/// <item>Grid</item>
/// <item>Image</item>
/// <item>Invalid</item>
/// <item>LineShapefile</item>
/// <item>PointShapefile</item>
/// <item>PolygonShapefile</item>
/// </list>
/// </summary>
LayerType LayerType { get; }
/// <summary>
/// Gets or sets the line or point size. If the <c>PointType</c> is <c>ptUserDefined</c> then the
/// size of the user defined point will be multiplied by the <c>LineOrPointSize</c>. For all other
/// points and for lines, the <c>LineOrPointSize</c> is represented in pixels.
/// </summary>
float LineOrPointSize { get; set; }
///The following was added for plug-in 3.1 version compatibility
/// <summary>
/// Sets the width between lines for multiple-line drawing styles (e.g, doublesolid).
/// </summary>
int LineSeparationFactor { get; set; }
/// <summary>
/// Gets or sets the stipple pattern to use for the entire shapefile.
///
/// The valid values for this property are:
/// <list type="bullet">
/// <item>Custom</item>
/// <item>DashDotDash</item>
/// <item>Dashed</item>
/// <item>Dotted</item>
/// <item>None</item>
/// </list>
/// </summary>
Stipple LineStipple { get; set; }
/// <summary>
/// Returns or sets the projection of this layer.
/// Projections must be / will be in PROJ4 format.
/// If no projection is present, "" will be returned.
/// If an invalid projection is provided, it's not guaranteed to be saved!
/// </summary>
string Projection { get; set; }
/// <summary>
/// Gets or sets the layer name.
/// </summary>
string Name { get; set; }
/// <summary>
/// Gets or sets the outline color for this layer. Only applies to polygon shapefile layers.
/// </summary>
Color OutlineColor { get; set; }
/// <summary>
/// Gets or sets the Point Image Scheme object for a given point layer. To be used from DotSpatial only
/// </summary>
object PointImageScheme { get; set; }
/// <summary>
/// Gets or sets the point type for this shapefile.
///
/// The valid values for this property are:
/// <list type="bullet">
/// <item>ptCircle</item>
/// <item>ptDiamond</item>
/// <item>ptSquare</item>
/// <item>ptTriangleDown</item>
/// <item>ptTriangleLeft</item>
/// <item>ptTriangleRight</item>
/// <item>ptTriangleUp</item>
/// <item>ptUserDefined</item>
/// </list>
/// </summary>
PointType PointType { get; set; }
/// <summary>
/// This property gives access to all shapes in the layer. Only applies to shapefile layers.
/// </summary>
List<IFeature> Shapes { get; }
/// <summary>
/// Gets or sets the tag for this layer. The tag is simply a string that can be used by the
/// programmer to store any information desired.
/// </summary>
string Tag { get; set; }
/// <summary>
/// Specifies whether or not to use <c>DynamicVisibility</c>.
/// </summary>
bool UseDynamicVisibility { get; set; }
/// <summary>
/// Determines whether MapWinGIS ocx will hide labels which collide with already drawn labels or not.
/// </summary>
bool UseLabelCollision { get; set; }
/// <summary>
/// Gets or sets the user defined line stipple. A line stipple is simply a 32-bit integer
/// whose bits define a pattern that can be displayed on the screen. For example, the value
/// 0011 0011 in binary would represent a dashed line ( -- --).
/// </summary>
int UserLineStipple { get; set; }
/// <summary>
/// Gets or sets the user defined point image for this layer. To display the user defined point
/// the layer's <c>PointType</c> must be set to <c>ptUserDefined</c>.
/// </summary>
Image UserPointType { get; set; }
/// <summary>
/// Gets or sets whether to use transparency on an <c>Image</c> layer.
/// </summary>
bool UseTransparentColor { get; set; }
/// <summary>
/// (Doesn't apply to line shapefiles)
/// Indicates whether the vertices of a line or polygon are visible.
/// </summary>
bool VerticesVisible { get; set; }
/// <summary>
/// Gets or sets whether the layer is visible.
/// </summary>
bool Visible { get; set; }
/// <summary>
/// Shows all vertices for the entire shapefile. Applies only to line and polygon shapefiles.
/// </summary>
/// <param name="color">The color to draw vertices with.</param>
/// <param name="vertexSize">The size of each vertex.</param>
void ShowVertices(Color color, int vertexSize);
/// <summary>
/// Returns information about the given layer in a human-readible string.
/// </summary>
string ToString();
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DbConnectionInternal.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.ProviderBase {
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
using SysTx = System.Transactions;
internal abstract class DbConnectionInternal { // V1.1.3300
private static int _objectTypeCount;
internal readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed);
internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
private readonly bool _allowSetConnectionString;
private readonly bool _hidePassword;
private readonly ConnectionState _state;
private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only)
private DbConnectionPoolCounters _performanceCounters; // the performance counters we're supposed to update
private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated
private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool)
private bool _connectionIsDoomed; // true when the connection should no longer be used.
private bool _cannotBePooled; // true when the connection should no longer be pooled.
private bool _isInStasis;
private DateTime _createTime; // when the connection was created.
private SysTx.Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
// _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
// However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
// This field should only be assigned a value at the same time _enlistedTransaction is updated.
// Also, this reference should not be disposed, since we aren't taking ownership of it.
private SysTx.Transaction _enlistedTransactionOriginal;
#if DEBUG
private int _activateCount; // debug only counter to verify activate/deactivates are in [....].
#endif //DEBUG
protected DbConnectionInternal() : this(ConnectionState.Open, true, false) { // V1.1.3300
}
// Constructor for internal connections
internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString) {
_allowSetConnectionString = allowSetConnectionString;
_hidePassword = hidePassword;
_state = state;
}
internal bool AllowSetConnectionString {
get {
return _allowSetConnectionString;
}
}
internal bool CanBePooled {
get {
bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive);
return flag;
}
}
protected internal SysTx.Transaction EnlistedTransaction {
get {
return _enlistedTransaction;
}
set {
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
if (((null == currentEnlistedTransaction) && (null != value))
|| ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) { // WebData 20000024
// Pay attention to the order here:
// 1) defect from any notifications
// 2) replace the transaction
// 3) re-enlist in notifications for the new transaction
// SQLBUDT #230558 we need to use a clone of the transaction
// when we store it, or we'll end up keeping it past the
// duration of the using block of the TransactionScope
SysTx.Transaction valueClone = null;
SysTx.Transaction previousTransactionClone = null;
try {
if (null != value) {
valueClone = value.Clone();
}
// NOTE: rather than take locks around several potential round-
// trips to the server, and/or virtual function calls, we simply
// presume that you aren't doing something illegal from multiple
// threads, and check once we get around to finalizing things
// inside a lock.
lock(this) {
// NOTE: There is still a race condition here, when we are
// called from EnlistTransaction (which cannot re-enlist)
// instead of EnlistDistributedTransaction (which can),
// however this should have been handled by the outer
// connection which checks to ensure that it's OK. The
// only case where we have the race condition is multiple
// concurrent enlist requests to the same connection, which
// is a bit out of line with something we should have to
// support.
// enlisted transaction can be nullified in Dispose call without lock
previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
_enlistedTransactionOriginal = value;
value = valueClone;
valueClone = null; // we've stored it, don't dispose it.
}
}
finally {
// we really need to dispose our clones; they may have
// native resources and GC may not happen soon enough.
// VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
if (null != previousTransactionClone &&
!Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction)) {
previousTransactionClone.Dispose();
}
if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction)) {
valueClone.Dispose();
}
}
// I don't believe that we need to lock to protect the actual
// enlistment in the transaction; it would only protect us
// against multiple concurrent calls to enlist, which really
// isn't supported anyway.
if (null != value) {
if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
int x = value.GetHashCode();
Bid.PoolerTrace("<prov.DbConnectionInternal.set_EnlistedTransaction|RES|CPOOL> %d#, Transaction %d#, Enlisting.\n", ObjectID, x);
}
TransactionOutcomeEnlist(value);
}
}
}
}
/// <summary>
/// Get boolean value that indicates whether the enlisted transaction has been disposed.
/// </summary>
/// <value>
/// True if there is an enlisted transaction, and it has been diposed.
/// False if there is an enlisted transaction that has not been disposed, or if the transaction reference is null.
/// </value>
/// <remarks>
/// This method must be called while holding a lock on the DbConnectionInternal instance.
/// </remarks>
protected bool EnlistedTransactionDisposed
{
get
{
// Until the Transaction.Disposed property is public it is necessary to access a member
// that throws if the object is disposed to determine if in fact the transaction is disposed.
try
{
bool disposed;
SysTx.Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal;
if (currentEnlistedTransactionOriginal != null)
{
disposed = currentEnlistedTransactionOriginal.TransactionInformation == null;
}
else
{
// Don't expect to get here in the general case,
// Since this getter is called by CheckEnlistedTransactionBinding
// after checking for a non-null enlisted transaction (and it does so under lock).
disposed = false;
}
return disposed;
}
catch (ObjectDisposedException)
{
return true;
}
}
}
// Is this connection in stasis, waiting for transaction to end before returning to pool?
internal bool IsTxRootWaitingForTxEnd {
get {
return _isInStasis;
}
}
/// <summary>
/// Get boolean that specifies whether an enlisted transaction can be unbound from
/// the connection when that transaction completes.
/// </summary>
/// <value>
/// True if the enlisted transaction can be unbound on transaction completion; otherwise false.
/// </value>
virtual protected bool UnbindOnTransactionCompletion
{
get
{
return true;
}
}
// Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
virtual protected internal bool IsNonPoolableTransactionRoot {
get {
return false; // if you want to have delegated transactions that are non-poolable, you better override this...
}
}
virtual internal bool IsTransactionRoot {
get {
return false; // if you want to have delegated transactions, you better override this...
}
}
protected internal bool IsConnectionDoomed {
get {
return _connectionIsDoomed;
}
}
internal bool IsEmancipated {
get {
// NOTE: There are race conditions between PrePush, PostPop and this
// property getter -- only use this while this object is locked;
// (DbConnectionPool.Clear and ReclaimEmancipatedObjects
// do this for us)
// Remember how this works (I keep getting confused...)
//
// _pooledCount is incremented when the connection is pushed into the pool
// _pooledCount is decremented when the connection is popped from the pool
// _pooledCount is set to -1 when the connection is not pooled (just in case...)
//
// That means that:
//
// _pooledCount > 1 connection is in the pool multiple times (this is a serious bug...)
// _pooledCount == 1 connection is in the pool
// _pooledCount == 0 connection is out of the pool
// _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections.
// _pooledCount < -1 connection out of the pool multiple times (not sure how this could happen...)
//
// Now, our job is to return TRUE when the connection is out
// of the pool and it's owning object is no longer around to
// return it.
bool value = !IsTxRootWaitingForTxEnd && (_pooledCount < 1) && !_owningObject.IsAlive;
return value;
}
}
internal bool IsInPool {
get {
Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid");
return (_pooledCount == 1);
}
}
internal int ObjectID {
get {
return _objectID;
}
}
protected internal object Owner {
// We use a weak reference to the owning object so we can identify when
// it has been garbage collected without thowing exceptions.
get {
return _owningObject.Target;
}
}
internal DbConnectionPool Pool {
get {
return _connectionPool;
}
}
protected DbConnectionPoolCounters PerformanceCounters {
get {
return _performanceCounters;
}
}
virtual protected bool ReadyToPrepareTransaction {
get {
return true;
}
}
protected internal DbReferenceCollection ReferenceCollection {
get {
return _referenceCollection;
}
}
abstract public string ServerVersion {
get;
}
// this should be abstract but untill it is added to all the providers virtual will have to do [....]
virtual public string ServerVersionNormalized {
get{
throw ADP.NotSupported();
}
}
public bool ShouldHidePassword {
get {
return _hidePassword;
}
}
public ConnectionState State {
get {
return _state;
}
}
abstract protected void Activate(SysTx.Transaction transaction);
internal void ActivateConnection(SysTx.Transaction transaction) {
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
Bid.PoolerTrace("<prov.DbConnectionInternal.ActivateConnection|RES|INFO|CPOOL> %d#, Activating\n", ObjectID);
#if DEBUG
int activateCount = Interlocked.Increment(ref _activateCount);
Debug.Assert(1 == activateCount, "activated multiple times?");
#endif // DEBUG
Activate(transaction);
PerformanceCounters.NumberOfActiveConnections.Increment();
}
internal void AddWeakReference(object value, int tag) {
if (null == _referenceCollection) {
_referenceCollection = CreateReferenceCollection();
if (null == _referenceCollection) {
throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull);
}
}
_referenceCollection.Add(value, tag);
}
abstract public DbTransaction BeginTransaction(IsolationLevel il);
virtual public void ChangeDatabase(string value) {
throw ADP.MethodNotImplemented("ChangeDatabase");
}
internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory) {
// The implementation here is the implementation required for the
// "open" internal connections, since our own private "closed"
// singleton internal connection objects override this method to
// prevent anything funny from happening (like disposing themselves
// or putting them into a connection pool)
//
// Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose
// for cleaning up after DbConnection.Close
// protected override void Deactivate() { // override DbConnectionInternal.Close
// // do derived class connection deactivation for both pooled & non-pooled connections
// }
// public override void Dispose() { // override DbConnectionInternal.Close
// // do derived class cleanup
// base.Dispose();
// }
//
// overriding DbConnection.Close is also possible, but must provider for their own synchronization
// public override void Close() { // override DbConnection.Close
// base.Close();
// // do derived class outer connection for both pooled & non-pooled connections
// // user must do their own synchronization here
// }
//
// if the DbConnectionInternal derived class needs to close the connection it should
// delegate to the DbConnection if one exists or directly call dispose
// DbConnection owningObject = (DbConnection)Owner;
// if (null != owningObject) {
// owningObject.Close(); // force the closed state on the outer object.
// }
// else {
// Dispose();
// }
//
////////////////////////////////////////////////////////////////
// DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING!
////////////////////////////////////////////////////////////////
Debug.Assert(null != owningObject, "null owningObject");
Debug.Assert(null != connectionFactory, "null connectionFactory");
Bid.PoolerTrace("<prov.DbConnectionInternal.CloseConnection|RES|CPOOL> %d# Closing.\n", ObjectID);
// if an exception occurs after the state change but before the try block
// the connection will be stuck in OpenBusy state. The commented out try-catch
// block doesn't really help because a ThreadAbort during the finally block
// would just refert the connection to a bad state.
// Open->Closed: guarantee internal connection is returned to correct pool
if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this)) {
// Lock to prevent race condition with cancellation
lock (this) {
object lockToken = ObtainAdditionalLocksForClose();
try {
PrepareForCloseConnection();
DbConnectionPool connectionPool = Pool;
// Detach from enlisted transactions that are no longer active on close
DetachCurrentTransactionIfEnded();
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
// into the pool.
if (null != connectionPool) {
connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us...
// NOTE: Before we leave the PutObject call, another
// thread may have already popped the connection from
// the pool, so don't expect to be able to verify it.
}
else {
Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up...
PerformanceCounters.HardDisconnectsPerSecond.Increment();
// To prevent an endless recursion, we need to clear
// the owning object before we call dispose so that
// we can't get here a second time... Ordinarily, I
// would call setting the owner to null a hack, but
// this is safe since we're about to dispose the
// object and it won't have an owner after that for
// certain.
_owningObject.Target = null;
if (IsTransactionRoot) {
SetInStasis();
}
else {
PerformanceCounters.NumberOfNonPooledConnections.Decrement();
if (this.GetType() != typeof(System.Data.SqlClient.SqlInternalConnectionSmi))
{
Dispose();
}
}
}
}
finally {
ReleaseAdditionalLocksForClose(lockToken);
// if a ThreadAbort puts us here then its possible the outer connection will not reference
// this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope.
connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
}
}
}
virtual internal void PrepareForReplaceConnection() {
// By default, there is no preperation required
}
virtual protected void PrepareForCloseConnection() {
// By default, there is no preperation required
}
virtual protected object ObtainAdditionalLocksForClose() {
return null; // no additional locks in default implementation
}
virtual protected void ReleaseAdditionalLocksForClose(object lockToken) {
// no additional locks in default implementation
}
virtual protected DbReferenceCollection CreateReferenceCollection() {
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject);
}
abstract protected void Deactivate();
internal void DeactivateConnection() {
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
Bid.PoolerTrace("<prov.DbConnectionInternal.DeactivateConnection|RES|INFO|CPOOL> %d#, Deactivating\n", ObjectID);
#if DEBUG
int activateCount = Interlocked.Decrement(ref _activateCount);
Debug.Assert(0 == activateCount, "activated multiple times?");
#endif // DEBUG
if (PerformanceCounters != null) { // Pool.Clear will DestroyObject that will clean performanceCounters before going here
PerformanceCounters.NumberOfActiveConnections.Decrement();
}
if (!_connectionIsDoomed && Pool.UseLoadBalancing) {
// If we're not already doomed, check the connection's lifetime and
// doom it if it's lifetime has elapsed.
DateTime now = DateTime.UtcNow; // WebData 111116
if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks) {
DoNotPoolThisConnection();
}
}
Deactivate();
}
virtual internal void DelegatedTransactionEnded() {
// Called by System.Transactions when the delegated transaction has
// completed. We need to make closed connections that are in stasis
// available again, or disposed closed/leaked non-pooled connections.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
Bid.Trace("<prov.DbConnectionInternal.DelegatedTransactionEnded|RES|CPOOL> %d#, Delegated Transaction Completed.\n", ObjectID);
if (1 == _pooledCount) {
// When _pooledCount is 1, it indicates a closed, pooled,
// connection so it is ready to put back into the pool for
// general use.
TerminateStasis(true);
Deactivate(); // call it one more time just in case
DbConnectionPool pool = Pool;
if (null == pool) {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool
}
pool.PutObjectFromTransactedPool(this);
}
else if (-1 == _pooledCount && !_owningObject.IsAlive) {
// When _pooledCount is -1 and the owning object no longer exists,
// it indicates a closed (or leaked), non-pooled connection so
// it is safe to dispose.
TerminateStasis(false);
Deactivate(); // call it one more time just in case
// it's a non-pooled connection, we need to dispose of it
// once and for all, or the server will have fits about us
// leaving connections open until the client-side GC kicks
// in.
PerformanceCounters.NumberOfNonPooledConnections.Decrement();
Dispose();
}
// When _pooledCount is 0, the connection is a pooled connection
// that is either open (if the owning object is alive) or leaked (if
// the owning object is not alive) In either case, we can't muck
// with the connection here.
}
public virtual void Dispose()
{
_connectionPool = null;
_performanceCounters = null;
_connectionIsDoomed = true;
_enlistedTransactionOriginal = null; // should not be disposed
// Dispose of the _enlistedTransaction since it is a clone
// of the original reference.
// VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event)
SysTx.Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null);
if (enlistedTransaction != null)
{
enlistedTransaction.Dispose();
}
}
protected internal void DoNotPoolThisConnection() {
_cannotBePooled = true;
Bid.PoolerTrace("<prov.DbConnectionInternal.DoNotPoolThisConnection|RES|INFO|CPOOL> %d#, Marking pooled object as non-poolable so it will be disposed\n", ObjectID);
}
/// <devdoc>Ensure that this connection cannot be put back into the pool.</devdoc>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected internal void DoomThisConnection() {
_connectionIsDoomed = true;
Bid.PoolerTrace("<prov.DbConnectionInternal.DoomThisConnection|RES|INFO|CPOOL> %d#, Dooming\n", ObjectID);
}
abstract public void EnlistTransaction(SysTx.Transaction transaction);
virtual protected internal DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions){
Debug.Assert(outerConnection != null,"outerConnection may not be null.");
DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
Debug.Assert(metaDataFactory != null,"metaDataFactory may not be null.");
return metaDataFactory.GetSchema(outerConnection, collectionName,restrictions);
}
internal void MakeNonPooledObject(object owningObject, DbConnectionPoolCounters performanceCounters) {
// Used by DbConnectionFactory to indicate that this object IS NOT part of
// a connection pool.
_connectionPool = null;
_performanceCounters = performanceCounters;
_owningObject.Target = owningObject;
_pooledCount = -1;
}
internal void MakePooledConnection(DbConnectionPool connectionPool) {
// Used by DbConnectionFactory to indicate that this object IS part of
// a connection pool.
//
_createTime = DateTime.UtcNow; // WebData 111116
_connectionPool = connectionPool;
_performanceCounters = connectionPool.PerformanceCounters;
}
internal void NotifyWeakReference(int message) {
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection) {
referenceCollection.Notify(message);
}
}
internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) {
if (!TryOpenConnection(outerConnection, connectionFactory, null, null)) {
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
/// <devdoc>The default implementation is for the open connection objects, and
/// it simply throws. Our private closed-state connection objects
/// override this and do the correct thing.</devdoc>
// User code should either override DbConnectionInternal.Activate when it comes out of the pool
// or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections
internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) {
throw ADP.ConnectionAlreadyOpen(State);
}
internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) {
throw ADP.MethodNotImplemented("TryReplaceConnection");
}
protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) {
// ?->Connecting: prevent set_ConnectionString during Open
if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) {
DbConnectionInternal openConnection = null;
try {
connectionFactory.PermissionDemand(outerConnection);
if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection)) {
return false;
}
}
catch {
// This should occure for all exceptions, even ADP.UnCatchableExceptions.
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw;
}
if (null == openConnection) {
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection);
}
return true;
}
internal void PrePush(object expectedOwner) {
// Called by DbConnectionPool when we're about to be put into it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null == expectedOwner) {
if (null != _owningObject.Target) {
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner
}
}
else if (_owningObject.Target != expectedOwner) {
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner
}
if (0 != _pooledCount) {
throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time
}
if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
//DbConnection x = (expectedOwner as DbConnection);
Bid.PoolerTrace("<prov.DbConnectionInternal.PrePush|RES|CPOOL> %d#, Preparing to push into pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount);
}
_pooledCount++;
_owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2%
}
internal void PostPop(object newOwner) {
// Called by DbConnectionPool right after it pulls this from it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
Debug.Assert(!IsEmancipated,"pooled object not in pool");
// SQLBUDT #356871 -- When another thread is clearing this pool, it
// will doom all connections in this pool without prejudice which
// causes the following assert to fire, which really mucks up stress
// against checked bits. The assert is benign, so we're commenting
// it out.
//Debug.Assert(CanBePooled, "pooled object is not poolable");
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (null != _owningObject.Target) {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner!
}
_owningObject.Target = newOwner;
_pooledCount--;
if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
//DbConnection x = (newOwner as DbConnection);
Bid.PoolerTrace("<prov.DbConnectionInternal.PostPop|RES|CPOOL> %d#, Preparing to pop from pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount);
}
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null != Pool) {
if (0 != _pooledCount) {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
else if (-1 != _pooledCount) {
throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
internal void RemoveWeakReference(object value) {
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection) {
referenceCollection.Remove(value);
}
}
// Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
// This is a separate method because cleanup can be triggered in multiple ways for a delegated
// transaction.
virtual protected void CleanupTransactionOnCompletion(SysTx.Transaction transaction) {
}
internal void DetachCurrentTransactionIfEnded() {
SysTx.Transaction enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null) {
bool transactionIsDead;
try {
transactionIsDead = (SysTx.TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
}
catch (SysTx.TransactionException) {
// If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
transactionIsDead = true;
}
if (transactionIsDead) {
DetachTransaction(enlistedTransaction, true);
}
}
}
// Detach transaction from connection.
internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) {
Bid.Trace("<prov.DbConnectionInternal.DetachTransaction|RES|CPOOL> %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount);
// potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new
// transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should
// be the exception, not the rule.
lock (this) {
// Detach if detach-on-end behavior, or if outer connection was closed
DbConnection owner = (DbConnection)Owner;
if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner) {
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction)) {
EnlistedTransaction = null;
if (IsTxRootWaitingForTxEnd) {
DelegatedTransactionEnded();
}
}
}
}
}
// Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transaction) {
DetachTransaction(transaction, false);
DbConnectionPool pool = Pool;
if (null != pool) {
pool.TransactionEnded(transaction, this);
}
}
void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) {
SysTx.Transaction transaction = e.Transaction;
Bid.Trace("<prov.DbConnectionInternal.TransactionCompletedEvent|RES|CPOOL> %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount);
CleanupTransactionOnCompletion(transaction);
CleanupConnectionOnTransactionCompletion(transaction);
}
//
[SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode)]
private void TransactionOutcomeEnlist(SysTx.Transaction transaction) {
transaction.TransactionCompleted += new SysTx.TransactionCompletedEventHandler(TransactionCompletedEvent);
}
internal void SetInStasis() {
_isInStasis = true;
Bid.PoolerTrace("<prov.DbConnectionInternal.SetInStasis|RES|CPOOL> %d#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.\n", ObjectID);
PerformanceCounters.NumberOfStasisConnections.Increment();
}
private void TerminateStasis(bool returningToPool) {
if (returningToPool) {
Bid.PoolerTrace("<prov.DbConnectionInternal.TerminateStasis|RES|CPOOL> %d#, Delegated Transaction has ended, connection is closed. Returning to general pool.\n", ObjectID);
}
else {
Bid.PoolerTrace("<prov.DbConnectionInternal.TerminateStasis|RES|CPOOL> %d#, Delegated Transaction has ended, connection is closed/leaked. Disposing.\n", ObjectID);
}
PerformanceCounters.NumberOfStasisConnections.Decrement();
_isInStasis = false;
}
/// <summary>
/// When overridden in a derived class, will check if the underlying connection is still actually alive
/// </summary>
/// <param name="throwOnException">If true an exception will be thrown if the connection is dead instead of returning true\false
/// (this allows the caller to have the real reason that the connection is not alive (e.g. network error, etc))</param>
/// <returns>True if the connection is still alive, otherwise false (If not overridden, then always true)</returns>
internal virtual bool IsConnectionAlive(bool throwOnException = false)
{
return 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.Globalization;
namespace System
{
// The class designed as to keep working set of Uri class as minimal.
// The idea is to stay with static helper methods and strings
internal class DomainNameHelper
{
private DomainNameHelper()
{
}
internal const string Localhost = "localhost";
internal const string Loopback = "loopback";
internal static string ParseCanonicalName(string str, int start, int end, ref bool loopback)
{
string res = null;
for (int i = end - 1; i >= start; --i)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
res = str.Substring(start, end - start).ToLowerInvariant();
break;
}
if (str[i] == ':')
end = i;
}
if (res == null)
{
res = str.Substring(start, end - start);
}
if (res == Localhost || res == Loopback)
{
loopback = true;
return Localhost;
}
return res;
}
//
// IsValid
//
// Determines whether a string is a valid domain name
//
// subdomain -> <label> | <label> "." <subdomain>
//
// Inputs:
// - name as Name to test
// - starting position
// - ending position
//
// Outputs:
// The end position of a valid domain name string, the canonical flag if found so
//
// Returns:
// bool
//
// Remarks: Optimized for speed as a most common case,
// MUST NOT be used unless all input indexes are verified and trusted.
//
internal unsafe static bool IsValid(char* name, ushort pos, ref int returnedEnd, ref bool notCanonical, bool notImplicitFile)
{
char* curPos = name + pos;
char* newPos = curPos;
char* end = name + returnedEnd;
for (; newPos < end; ++newPos)
{
char ch = *newPos;
if (ch > 0x7f) return false; // not ascii
if (ch == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#')))
{
end = newPos;
break;
}
}
if (end == curPos)
{
return false;
}
do
{
// Determines whether a string is a valid domain name label. In keeping
// with RFC 1123, section 2.1, the requirement that the first character
// of a label be alphabetic is dropped. Therefore, Domain names are
// formed as:
//
// <label> -> <alphanum> [<alphanum> | <hyphen> | <underscore>] * 62
//find the dot or hit the end
newPos = curPos;
while (newPos < end)
{
if (*newPos == '.') break;
++newPos;
}
//check the label start/range
if (curPos == newPos || newPos - curPos > 63 || !IsASCIILetterOrDigit(*curPos++, ref notCanonical))
{
return false;
}
//check the label content
while (curPos < newPos)
{
if (!IsValidDomainLabelCharacter(*curPos++, ref notCanonical))
{
return false;
}
}
++curPos;
} while (curPos < end);
returnedEnd = (ushort)(end - name);
return true;
}
//
// Checks if the domain name is valid according to iri
// There are pretty much no restrictions and we effectively return the end of the
// domain name.
//
internal unsafe static bool IsValidByIri(char* name, ushort pos, ref int returnedEnd, ref bool notCanonical, bool notImplicitFile)
{
char* curPos = name + pos;
char* newPos = curPos;
char* end = name + returnedEnd;
int count = 0; // count number of octets in a label;
for (; newPos < end; ++newPos)
{
char ch = *newPos;
if (ch == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#')))
{
end = newPos;
break;
}
}
if (end == curPos)
{
return false;
}
do
{
// Determines whether a string is a valid domain name label. In keeping
// with RFC 1123, section 2.1, the requirement that the first character
// of a label be alphabetic is dropped. Therefore, Domain names are
// formed as:
//
// <label> -> <alphanum> [<alphanum> | <hyphen> | <underscore>] * 62
//find the dot or hit the end
newPos = curPos;
count = 0;
bool labelHasUnicode = false; // if label has unicode we need to add 4 to label count for xn--
while (newPos < end)
{
if ((*newPos == '.') ||
(*newPos == '\u3002') || //IDEOGRAPHIC FULL STOP
(*newPos == '\uFF0E') || //FULLWIDTH FULL STOP
(*newPos == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP
break;
count++;
if (*newPos > 0xFF)
count++; // counts for two octets
if (*newPos >= 0xA0)
labelHasUnicode = true;
++newPos;
}
//check the label start/range
if (curPos == newPos || (labelHasUnicode ? count + 4 : count) > 63 || ((*curPos++ < 0xA0) && !IsASCIILetterOrDigit(*(curPos - 1), ref notCanonical)))
{
return false;
}
//check the label content
while (curPos < newPos)
{
if ((*curPos++ < 0xA0) && !IsValidDomainLabelCharacter(*(curPos - 1), ref notCanonical))
{
return false;
}
}
++curPos;
} while (curPos < end);
returnedEnd = (ushort)(end - name);
return true;
}
internal static string IdnEquivalent(string hostname)
{
bool allAscii = true;
bool atLeastOneValidIdn = false;
unsafe
{
fixed (char* host = hostname)
{
return IdnEquivalent(host, 0, hostname.Length, ref allAscii, ref atLeastOneValidIdn);
}
}
}
//
// Will convert a host name into its idn equivalent + tell you if it had a valid idn label
//
internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn)
{
string bidiStrippedHost = null;
string idnEquivalent = IdnEquivalent(hostname, start, end, ref allAscii, ref bidiStrippedHost);
if (idnEquivalent != null)
{
string strippedHost = (allAscii ? idnEquivalent : bidiStrippedHost);
fixed (char* strippedHostPtr = strippedHost)
{
int length = strippedHost.Length;
int newPos = 0;
int curPos = 0;
bool foundAce = false;
bool checkedAce = false;
bool foundDot = false;
do
{
foundAce = false;
checkedAce = false;
foundDot = false;
//find the dot or hit the end
newPos = curPos;
while (newPos < length)
{
char c = strippedHostPtr[newPos];
if (!checkedAce)
{
checkedAce = true;
if ((newPos + 3 < length) && IsIdnAce(strippedHostPtr, newPos))
{
newPos += 4;
foundAce = true;
continue;
}
}
if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP
(c == '\uFF0E') || //FULLWIDTH FULL STOP
(c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP
{
foundDot = true;
break;
}
++newPos;
}
if (foundAce)
{
// check ace validity
try
{
IdnMapping map = new IdnMapping();
map.GetUnicode(new string(strippedHostPtr, curPos, newPos - curPos));
atLeastOneValidIdn = true;
break;
}
catch (ArgumentException)
{
// not valid ace so treat it as a normal ascii label
}
}
curPos = newPos + (foundDot ? 1 : 0);
} while (curPos < length);
}
}
else
{
atLeastOneValidIdn = false;
}
return idnEquivalent;
}
//
// Will convert a host name into its idn equivalent
//
internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref string bidiStrippedHost)
{
string idn = null;
if (end <= start)
return idn;
// indexes are validated
int newPos = start;
allAscii = true;
while (newPos < end)
{
// check if only ascii chars
// special case since idnmapping will not lowercase if only ascii present
if (hostname[newPos] > '\x7F')
{
allAscii = false;
break;
}
++newPos;
}
if (allAscii)
{
// just lowercase for ascii
string unescapedHostname = new string(hostname, start, end - start);
return ((unescapedHostname != null) ? unescapedHostname.ToLowerInvariant() : null);
}
else
{
IdnMapping map = new IdnMapping();
string asciiForm;
bidiStrippedHost = Uri.StripBidiControlCharacter(hostname, start, end - start);
try
{
asciiForm = map.GetAscii(bidiStrippedHost);
}
catch (ArgumentException)
{
throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn);
}
return asciiForm;
}
}
private unsafe static bool IsIdnAce(string input, int index)
{
if ((input[index] == 'x') &&
(input[index + 1] == 'n') &&
(input[index + 2] == '-') &&
(input[index + 3] == '-'))
return true;
else
return false;
}
private unsafe static bool IsIdnAce(char* input, int index)
{
if ((input[index] == 'x') &&
(input[index + 1] == 'n') &&
(input[index + 2] == '-') &&
(input[index + 3] == '-'))
return true;
else
return false;
}
//
// Will convert a host name into its unicode equivalent expanding any existing idn names present
//
internal unsafe static string UnicodeEquivalent(string idnHost, char* hostname, int start, int end)
{
IdnMapping map = new IdnMapping();
// Test common scenario first for perf
// try to get unicode equivalent
try
{
return map.GetUnicode(idnHost);
}
catch (ArgumentException)
{
}
// Here because something threw in GetUnicode above
// Need to now check individual labels of they had an ace label that was not valid Idn name
// or if there is a label with invalid Idn char.
bool dummy = true;
return UnicodeEquivalent(hostname, start, end, ref dummy, ref dummy);
}
internal unsafe static string UnicodeEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn)
{
IdnMapping map = new IdnMapping();
// hostname already validated
allAscii = true;
atLeastOneValidIdn = false;
string idn = null;
if (end <= start)
return idn;
string unescapedHostname = Uri.StripBidiControlCharacter(hostname, start, (end - start));
string unicodeEqvlHost = null;
int curPos = 0;
int newPos = 0;
int length = unescapedHostname.Length;
bool asciiLabel = true;
bool foundAce = false;
bool checkedAce = false;
bool foundDot = false;
// We run a loop where for every label
// a) if label is ascii and no ace then we lowercase it
// b) if label is ascii and ace and not valid idn then just lowercase it
// c) if label is ascii and ace and is valid idn then get its unicode eqvl
// d) if label is unicode then clean it by running it through idnmapping
do
{
asciiLabel = true;
foundAce = false;
checkedAce = false;
foundDot = false;
//find the dot or hit the end
newPos = curPos;
while (newPos < length)
{
char c = unescapedHostname[newPos];
if (!checkedAce)
{
checkedAce = true;
if ((newPos + 3 < length) && (c == 'x') && IsIdnAce(unescapedHostname, newPos))
foundAce = true;
}
if (asciiLabel && (c > '\x7F'))
{
asciiLabel = false;
allAscii = false;
}
if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP
(c == '\uFF0E') || //FULLWIDTH FULL STOP
(c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP
{
foundDot = true;
break;
}
++newPos;
}
if (!asciiLabel)
{
string asciiForm = unescapedHostname.Substring(curPos, newPos - curPos);
try
{
asciiForm = map.GetAscii(asciiForm);
}
catch (ArgumentException)
{
throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn);
}
unicodeEqvlHost += map.GetUnicode(asciiForm);
if (foundDot)
unicodeEqvlHost += ".";
}
else
{
bool aceValid = false;
if (foundAce)
{
// check ace validity
try
{
unicodeEqvlHost += map.GetUnicode(unescapedHostname.Substring(curPos, newPos - curPos));
if (foundDot)
unicodeEqvlHost += ".";
aceValid = true;
atLeastOneValidIdn = true;
}
catch (ArgumentException)
{
// not valid ace so treat it as a normal ascii label
}
}
if (!aceValid)
{
// for invalid aces we just lowercase the label
unicodeEqvlHost += unescapedHostname.Substring(curPos, newPos - curPos).ToLowerInvariant();
if (foundDot)
unicodeEqvlHost += ".";
}
}
curPos = newPos + (foundDot ? 1 : 0);
} while (curPos < length);
return unicodeEqvlHost;
}
//
// Determines whether a character is a letter or digit according to the
// DNS specification [RFC 1035]. We use our own variant of IsLetterOrDigit
// because the base version returns false positives for non-ANSI characters
//
private static bool IsASCIILetterOrDigit(char character, ref bool notCanonical)
{
if ((character >= 'a' && character <= 'z') || (character >= '0' && character <= '9'))
return true;
if (character >= 'A' && character <= 'Z')
{
notCanonical = true;
return true;
}
return false;
}
//
// Takes into account the additional legal domain name characters '-' and '_'
// Note that '_' char is formally invalid but is historically in use, especially on corpnets
//
private static bool IsValidDomainLabelCharacter(char character, ref bool notCanonical)
{
if ((character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') || (character == '-') || (character == '_'))
return true;
if (character >= 'A' && character <= 'Z')
{
notCanonical = true;
return true;
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
namespace Compute.Tests
{
public class VMScenarioTests : VMTestBase
{
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// GET VM Model View
/// GET VM InstanceView
/// GETVMs in a RG
/// List VMSizes in a RG
/// List VMSizes in an AvailabilitySet
/// Delete RG
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations")]
public void TestVMScenarioOperations()
{
TestVMScenarioOperationsInternal("TestVMScenarioOperations");
}
/// <summary>
/// Covers following Operations for managed disks:
/// Create RG
/// Create Network Resources
/// Create VM with WriteAccelerator enabled OS and Data disk
/// GET VM Model View
/// GET VM InstanceView
/// GETVMs in a RG
/// List VMSizes in a RG
/// List VMSizes in an AvailabilitySet
/// Delete RG
///
/// To record this test case, you need to run it in region which support XMF VMSizeFamily like eastus2.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks")]
public void TestVMScenarioOperations_ManagedDisks()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks", vmSize: VirtualMachineSizeTypes.StandardM64s, hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.PremiumLRS, dataDiskStorageAccountType: StorageAccountTypes.PremiumLRS, writeAcceleratorEnabled: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in region which support local diff disks.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_DiffDisks")]
public void TestVMScenarioOperations_DiffDisks()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_DiffDisks", vmSize: VirtualMachineSizeTypes.StandardDS148V2, hasManagedDisks: true,
hasDiffDisks: true, osDiskStorageAccountType: StorageAccountTypes.StandardLRS);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in region which support Encryption at host
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_EncryptionAtHost")]
public void TestVMScenarioOperations_EncryptionAtHost()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_EncryptionAtHost", vmSize: VirtualMachineSizeTypes.StandardDS1V2, hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.StandardLRS, encryptionAtHostEnabled: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in region which support Encryption at host
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_TrustedLaunch")]
public void TestVMScenarioOperations_TrustedLaunch()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
ImageReference image = new ImageReference(publisher: "MicrosoftWindowsServer", offer: "windowsserver-gen2preview-preview", version: "18363.592.2001092016", sku: "windows10-tvm");
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2euap");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_TrustedLaunch", vmSize: VirtualMachineSizeTypes.StandardD2sV3, hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.StandardSSDLRS, securityType: "TrustedLaunch", imageReference: image, validateListAvailableSize: false);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in region which support DiskEncryptionSet resource for the Disks
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet")]
public void TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
string diskEncryptionSetId = getDefaultDiskEncryptionSetId();
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_DiskEncryptionSet", vmSize: VirtualMachineSizeTypes.StandardA1V2, hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.StandardLRS, diskEncryptionSetId: diskEncryptionSetId);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// TODO: StandardSSD is currently in preview and is available only in a few regions. Once it goes GA, it can be tested in
/// the default test location.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_StandardSSD")]
public void TestVMScenarioOperations_ManagedDisks_StandardSSD()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_StandardSSD", hasManagedDisks: true,
osDiskStorageAccountType: StorageAccountTypes.StandardSSDLRS, dataDiskStorageAccountType: StorageAccountTypes.StandardSSDLRS);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in zone supported regions like eastus2.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_PirImage_Zones")]
public void TestVMScenarioOperations_ManagedDisks_PirImage_Zones()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_PirImage_Zones", hasManagedDisks: true, zones: new List<string> { "1" }, callUpdateVM: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in zone supported regions like eastus2euap.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_ManagedDisks_UltraSSD")]
public void TestVMScenarioOperations_ManagedDisks_UltraSSD()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_ManagedDisks_UltraSSD", hasManagedDisks: true, zones: new List<string> { "1" },
vmSize: VirtualMachineSizeTypes.StandardE16sV3, osDiskStorageAccountType: StorageAccountTypes.PremiumLRS,
dataDiskStorageAccountType: StorageAccountTypes.UltraSSDLRS, callUpdateVM: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
[Fact]
[Trait("Name", "TestVMScenarioOperations_AutomaticPlacementOnDedicatedHostGroup")]
public void TestVMScenarioOperations_AutomaticPlacementOnDedicatedHostGroup()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
// This test was recorded in WestUSValidation, where the platform image typically used for recording is not available.
// Hence the following custom image was used.
//ImageReference imageReference = new ImageReference
//{
// Publisher = "AzureRT.PIRCore.TestWAStage",
// Offer = "TestUbuntuServer",
// Sku = "16.04",
// Version = "latest"
//};
//TestVMScenarioOperationsInternal("TestVMScenarioOperations_AutomaticPlacementOnDedicatedHostGroup",
// hasManagedDisks: true, vmSize: VirtualMachineSizeTypes.StandardD2sV3, isAutomaticPlacementOnDedicatedHostGroupScenario: true,
// imageReference: imageReference, validateListAvailableSize: false);
TestVMScenarioOperationsInternal("TestVMScenarioOperations_AutomaticPlacementOnDedicatedHostGroup",
hasManagedDisks: true, vmSize: VirtualMachineSizeTypes.StandardD2sV3, isAutomaticPlacementOnDedicatedHostGroupScenario: true,
validateListAvailableSize: false);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
/// <summary>
/// To record this test case, you need to run it in zone supported regions like eastus2euap.
/// </summary>
[Fact]
[Trait("Name", "TestVMScenarioOperations_PpgScenario")]
public void TestVMScenarioOperations_PpgScenario()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
TestVMScenarioOperationsInternal("TestVMScenarioOperations_PpgScenario", hasManagedDisks: true, isPpgScenario: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
private void TestVMScenarioOperationsInternal(string methodName, bool hasManagedDisks = false, IList<string> zones = null, string vmSize = "Standard_A1_v2",
string osDiskStorageAccountType = "Standard_LRS", string dataDiskStorageAccountType = "Standard_LRS", bool? writeAcceleratorEnabled = null,
bool hasDiffDisks = false, bool callUpdateVM = false, bool isPpgScenario = false, string diskEncryptionSetId = null, bool? encryptionAtHostEnabled = null,
string securityType = null, bool isAutomaticPlacementOnDedicatedHostGroupScenario = false, ImageReference imageReference = null, bool validateListAvailableSize = true)
{
using (MockContext context = MockContext.Start(this.GetType(), methodName))
{
EnsureClientsInitialized(context);
ImageReference imageRef = imageReference ?? GetPlatformVMImage(useWindowsImage: true);
const string expectedOSName = "Windows Server 2012 R2 Datacenter", expectedOSVersion = "Microsoft Windows NT 6.3.9600.0", expectedComputerName = ComputerName;
// Create resource group
var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string asName = ComputeManagementTestUtilities.GenerateName("as");
string ppgName = null, expectedPpgReferenceId = null;
string dedicatedHostGroupName = null, dedicatedHostName = null, dedicatedHostGroupReferenceId = null, dedicatedHostReferenceId = null;
if (isPpgScenario)
{
ppgName = ComputeManagementTestUtilities.GenerateName("ppgtest");
expectedPpgReferenceId = Helpers.GetProximityPlacementGroupRef(m_subId, rgName, ppgName);
}
if (isAutomaticPlacementOnDedicatedHostGroupScenario)
{
dedicatedHostGroupName = ComputeManagementTestUtilities.GenerateName("dhgtest");
dedicatedHostName = ComputeManagementTestUtilities.GenerateName("dhtest");
dedicatedHostGroupReferenceId = Helpers.GetDedicatedHostGroupRef(m_subId, rgName, dedicatedHostGroupName);
dedicatedHostReferenceId = Helpers.GetDedicatedHostRef(m_subId, rgName, dedicatedHostGroupName, dedicatedHostName);
}
VirtualMachine inputVM;
try
{
if (!hasManagedDisks)
{
CreateStorageAccount(rgName, storageAccountName);
}
CreateVM(rgName, asName, storageAccountName, imageRef, out inputVM, hasManagedDisks: hasManagedDisks,hasDiffDisks: hasDiffDisks, vmSize: vmSize, osDiskStorageAccountType: osDiskStorageAccountType,
dataDiskStorageAccountType: dataDiskStorageAccountType, writeAcceleratorEnabled: writeAcceleratorEnabled, zones: zones, ppgName: ppgName,
diskEncryptionSetId: diskEncryptionSetId, encryptionAtHostEnabled: encryptionAtHostEnabled, securityType: securityType, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId,
dedicatedHostGroupName: dedicatedHostGroupName, dedicatedHostName: dedicatedHostName);
// Instance view is not completely populated just after VM is provisioned. So we wait here for a few minutes to
// allow GA blob to populate.
ComputeManagementTestUtilities.WaitMinutes(5);
var getVMWithInstanceViewResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name, InstanceViewTypes.InstanceView);
Assert.True(getVMWithInstanceViewResponse != null, "VM in Get");
if (diskEncryptionSetId != null)
{
Assert.True(getVMWithInstanceViewResponse.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != null, "OsDisk.ManagedDisk.DiskEncryptionSet is null");
Assert.True(string.Equals(diskEncryptionSetId, getVMWithInstanceViewResponse.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
"OsDisk.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");
Assert.Equal(1, getVMWithInstanceViewResponse.StorageProfile.DataDisks.Count);
Assert.True(getVMWithInstanceViewResponse.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet != null, ".DataDisks.ManagedDisk.DiskEncryptionSet is null");
Assert.True(string.Equals(diskEncryptionSetId, getVMWithInstanceViewResponse.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
"DataDisks.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");
}
ValidateVMInstanceView(inputVM, getVMWithInstanceViewResponse, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion, dedicatedHostReferenceId);
var getVMInstanceViewResponse = m_CrpClient.VirtualMachines.InstanceView(rgName, inputVM.Name);
Assert.True(getVMInstanceViewResponse != null, "VM in InstanceView");
ValidateVMInstanceView(inputVM, getVMInstanceViewResponse, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion, dedicatedHostReferenceId);
bool hasUserDefinedAS = inputVM.AvailabilitySet != null;
string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name);
var listResponse = m_CrpClient.VirtualMachines.List(rgName);
ValidateVM(inputVM, listResponse.FirstOrDefault(x => x.Name == inputVM.Name),
expectedVMReferenceId, hasManagedDisks, hasUserDefinedAS, writeAcceleratorEnabled, hasDiffDisks, expectedPpgReferenceId: expectedPpgReferenceId,
encryptionAtHostEnabled: encryptionAtHostEnabled, expectedDedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId);
if (validateListAvailableSize)
{
var listVMSizesResponse = m_CrpClient.VirtualMachines.ListAvailableSizes(rgName, inputVM.Name);
Helpers.ValidateVirtualMachineSizeListResponse(listVMSizesResponse, hasAZ: zones != null, writeAcceleratorEnabled: writeAcceleratorEnabled,
hasDiffDisks: hasDiffDisks);
listVMSizesResponse = m_CrpClient.AvailabilitySets.ListAvailableSizes(rgName, asName);
Helpers.ValidateVirtualMachineSizeListResponse(listVMSizesResponse, hasAZ: zones != null, writeAcceleratorEnabled: writeAcceleratorEnabled, hasDiffDisks: hasDiffDisks);
}
if(securityType != null && securityType.Equals("TrustedLaunch"))
{
Assert.True(inputVM.SecurityProfile.UefiSettings.VTpmEnabled);
Assert.True(inputVM.SecurityProfile.UefiSettings.SecureBootEnabled);
}
if(isPpgScenario)
{
ProximityPlacementGroup outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(rgName, ppgName);
string expectedAvSetReferenceId = Helpers.GetAvailabilitySetRef(m_subId, rgName, asName);
Assert.Equal(1, outProximityPlacementGroup.VirtualMachines.Count);
Assert.Equal(1, outProximityPlacementGroup.AvailabilitySets.Count);
Assert.Equal(expectedVMReferenceId, outProximityPlacementGroup.VirtualMachines.First().Id, StringComparer.OrdinalIgnoreCase);
Assert.Equal(expectedAvSetReferenceId, outProximityPlacementGroup.AvailabilitySets.First().Id, StringComparer.OrdinalIgnoreCase);
}
if (callUpdateVM)
{
VirtualMachineUpdate updateParams = new VirtualMachineUpdate()
{
Tags = inputVM.Tags
};
string updateKey = "UpdateTag";
updateParams.Tags.Add(updateKey, "UpdateTagValue");
VirtualMachine updateResponse = m_CrpClient.VirtualMachines.Update(rgName, inputVM.Name, updateParams);
Assert.True(updateResponse.Tags.ContainsKey(updateKey));
}
}
finally
{
// Fire and forget. No need to wait for RG deletion completion
try
{
m_ResourcesClient.ResourceGroups.BeginDelete(rgName);
}
catch (Exception e)
{
// Swallow this exception so that the original exception is thrown
Console.WriteLine(e);
}
}
}
}
}
}
| |
// 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.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using Internal.Runtime.Augments;
namespace System.Threading
{
public delegate void TimerCallback(Object state);
//
// TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer to schedule
// all managed timers in the process.
//
// Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire.
// There are roughly two types of timer:
//
// - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because
// the whole point is that the timer only fires if something has gone wrong.
//
// - scheduled background tasks. These typically do fire, but they usually have quite long durations.
// So the impact of spending a few extra cycles to fire these is negligible.
//
// Because of this, we want to choose a data structure with very fast insert and delete times, but we can live
// with linear traversal times when firing timers.
//
// The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion
// and removal, and O(N) traversal when finding expired timers.
//
// Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance.
//
class TimerQueue
{
#region singleton pattern implementation
// The one-and-only TimerQueue for the AppDomain.
static TimerQueue s_queue = new TimerQueue();
public static TimerQueue Instance
{
get { return s_queue; }
}
private TimerQueue()
{
// empty private constructor to ensure we remain a singleton.
}
#endregion
#region interface to native per-AppDomain timer
//
// We need to keep our notion of time synchronized with the calls to SleepEx that drive
// the underlying native timer. In Win8, SleepEx does not count the time the machine spends
// sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time,
// so we will get out of sync with SleepEx if we use that method.
//
// So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent
// in sleep/hibernate mode.
//
private static int TickCount
{
get
{
ulong time100ns;
bool result = Interop.mincore.QueryUnbiasedInterruptTime(out time100ns);
Contract.Assert(result);
// convert to 100ns to milliseconds, and truncate to 32 bits.
return (int)(uint)(time100ns / 10000);
}
}
Delegate m_nativeTimerCallback;
Object m_nativeTimer;
int m_currentNativeTimerStartTicks;
uint m_currentNativeTimerDuration;
private void EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
//
// The CLR VM's timer implementation does not work well for very long-duration timers.
// See kb 950807.
// So we'll limit our native timer duration to a "small" value.
// This may cause us to attempt to fire timers early, but that's ok -
// we'll just see that none of our timers has actually reached its due time,
// and schedule the native timer again.
//
const uint maxPossibleDuration = 0x0fffffff;
uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);
if (m_nativeTimer != null)
{
uint elapsed = (uint)(TickCount - m_currentNativeTimerStartTicks);
if (elapsed >= m_currentNativeTimerDuration)
return; //the timer's about to fire
uint remainingDuration = m_currentNativeTimerDuration - elapsed;
if (actualDuration >= remainingDuration)
return; //the timer will fire earlier than this request
}
#if FEATURE_LEGACYNETCFFAS
// If Pause is underway then do not schedule the timers
// A later update during resume will re-schedule
if (m_pauseTicks != 0)
{
Contract.Assert(!m_isAppDomainTimerScheduled);
Contract.Assert(m_appDomainTimer == null);
return true;
}
#endif //FEATURE_LEGACYNETCFFAS
if (m_nativeTimerCallback == null)
{
Contract.Assert(m_nativeTimer == null);
m_nativeTimerCallback = WinRTInterop.Callbacks.CreateTimerDelegate(new Action(AppDomainTimerCallback));
}
Object previousNativeTimer = m_nativeTimer;
m_nativeTimer = WinRTInterop.Callbacks.CreateTimer(m_nativeTimerCallback, TimeSpan.FromMilliseconds(actualDuration));
if (previousNativeTimer != null)
WinRTInterop.Callbacks.ReleaseTimer(previousNativeTimer, true);
m_currentNativeTimerStartTicks = TickCount;
m_currentNativeTimerDuration = actualDuration;
}
//
// The VM calls this when the native timer fires.
//
internal static void AppDomainTimerCallback()
{
try
{
Instance.FireNextTimers();
}
catch (Exception ex)
{
RuntimeAugments.ReportUnhandledException(ex);
}
}
#endregion
#region Firing timers
//
// The list of timers
//
TimerQueueTimer m_timers;
readonly internal Lock Lock = new Lock();
#if FEATURE_LEGACYNETCFFAS
volatile int m_pauseTicks = 0; // Time when Pause was called
internal void Pause()
{
lock (Lock)
{
// Delete the native timer so that no timers are fired in the Pause zone
if (m_appDomainTimer != null && !m_appDomainTimer.IsInvalid)
{
m_appDomainTimer.Dispose();
m_appDomainTimer = null;
m_isAppDomainTimerScheduled = false;
m_pauseTicks = TickCount;
}
}
}
internal void Resume()
{
//
// Update timers to adjust their due-time to accomodate Pause/Resume
//
lock (Lock)
{
// prevent ThreadAbort while updating state
try { }
finally
{
int pauseTicks = m_pauseTicks;
m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled
int resumedTicks = TickCount;
int pauseDuration = resumedTicks - pauseTicks;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timer.UnsignedInfiniteTimeout);
Contract.Assert(resumedTicks >= timer.m_startTicks);
uint elapsed; // How much of the timer dueTime has already elapsed
// Timers started before the paused event has to be sufficiently delayed to accomodate
// for the Pause time. However, timers started after the Paused event shouldnt be adjusted.
// E.g. ones created by the app in its Activated event should fire when it was designated.
// The Resumed event which is where this routine is executing is after this Activated and hence
// shouldn't delay this timer
if (timer.m_startTicks <= pauseTicks)
elapsed = (uint)(pauseTicks - timer.m_startTicks);
else
elapsed = (uint)(resumedTicks - timer.m_startTicks);
// Handling the corner cases where a Timer was already due by the time Resume is happening,
// We shouldn't delay those timers.
// Example is a timer started in App's Activated event with a very small duration
timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0; ;
timer.m_startTicks = resumedTicks; // re-baseline
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
timer = timer.m_next;
}
if (haveTimerToSchedule)
{
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
}
}
#endif // FEATURE_LEGACYNETCFFAS
//
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
//
private void FireNextTimers()
{
//
// we fire the first timer on this thread; any other timers that might have fired are queued
// to the ThreadPool.
//
TimerQueueTimer timerToFireOnThisThread = null;
Object previousTimer = null;
lock (Lock)
{
// prevent ThreadAbort while updating state
try { }
finally
{
//
// since we got here, that means our previous timer has fired.
//
previousTimer = m_nativeTimer;
m_nativeTimer = null;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
int nowTicks = TickCount;
//
// Sweep through all timers. The ones that have reached their due time
// will fire. We will calculate the next native timer due time from the
// other timers.
//
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timer.UnsignedInfiniteTimeout);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
{
//
// Remember the next timer in case we delete this one
//
TimerQueueTimer nextTimer = timer.m_next;
if (timer.m_period != Timer.UnsignedInfiniteTimeout)
{
timer.m_startTicks = nowTicks;
timer.m_dueTime = timer.m_period;
//
// This is a repeating timer; schedule it to run again.
//
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
}
else
{
//
// Not repeating; remove it from the queue
//
DeleteTimer(timer);
}
//
// If this is the first timer, we'll fire it on this thread. Otherwise, queue it
// to the ThreadPool.
//
if (timerToFireOnThisThread == null)
timerToFireOnThisThread = timer;
else
QueueTimerCompletion(timer);
timer = nextTimer;
}
else
{
//
// This timer hasn't fired yet. Just update the next time the native timer fires.
//
uint remaining = timer.m_dueTime - elapsed;
if (remaining < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = remaining;
}
timer = timer.m_next;
}
}
if (haveTimerToSchedule)
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
//
// Release the previous timer object outside of the lock!
//
if (previousTimer != null)
WinRTInterop.Callbacks.ReleaseTimer(previousTimer, false);
//
// Fire the user timer outside of the lock!
//
if (timerToFireOnThisThread != null)
timerToFireOnThisThread.Fire();
}
private static void QueueTimerCompletion(TimerQueueTimer timer)
{
WaitCallback callback = s_fireQueuedTimerCompletion;
if (callback == null)
s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion);
// Can use "unsafe" variant because we take care of capturing and restoring
// the ExecutionContext.
ThreadPool.UnsafeQueueUserWorkItem(callback, timer);
}
private static WaitCallback s_fireQueuedTimerCompletion;
private static void FireQueuedTimerCompletion(object state)
{
((TimerQueueTimer)state).Fire();
}
#endregion
#region Queue implementation
public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period)
{
if (timer.m_dueTime == Timer.UnsignedInfiniteTimeout)
{
// the timer is not in the list; add it (as the head of the list).
timer.m_next = m_timers;
timer.m_prev = null;
if (timer.m_next != null)
timer.m_next.m_prev = timer;
m_timers = timer;
}
timer.m_dueTime = dueTime;
timer.m_period = (period == 0) ? Timer.UnsignedInfiniteTimeout : period;
timer.m_startTicks = TickCount;
EnsureAppDomainTimerFiresBy(dueTime);
return true;
}
public void DeleteTimer(TimerQueueTimer timer)
{
if (timer.m_dueTime != Timer.UnsignedInfiniteTimeout)
{
if (timer.m_next != null)
timer.m_next.m_prev = timer.m_prev;
if (timer.m_prev != null)
timer.m_prev.m_next = timer.m_next;
if (m_timers == timer)
m_timers = timer.m_next;
timer.m_dueTime = Timer.UnsignedInfiniteTimeout;
timer.m_period = Timer.UnsignedInfiniteTimeout;
timer.m_startTicks = 0;
timer.m_prev = null;
timer.m_next = null;
}
}
#endregion
}
//
// A timer in our TimerQueue.
//
sealed class TimerQueueTimer
{
//
// All fields of this class are protected by a lock on TimerQueue.Instance.
//
// The first four fields are maintained by TimerQueue itself.
//
internal TimerQueueTimer m_next;
internal TimerQueueTimer m_prev;
//
// The time, according to TimerQueue.TickCount, when this timer's current interval started.
//
internal int m_startTicks;
//
// Timer.UnsignedInfiniteTimeout if we are not going to fire. Otherwise, the offset from m_startTime when we will fire.
//
internal uint m_dueTime;
//
// Timer.UnsignedInfiniteTimeout if we are a single-shot timer. Otherwise, the repeat interval.
//
internal uint m_period;
//
// Info about the user's callback
//
readonly TimerCallback m_timerCallback;
readonly Object m_state;
readonly ExecutionContext m_executionContext;
//
// When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only
// after all pending callbacks are complete. We set m_canceled to prevent any callbacks that
// are already queued from running. We track the number of callbacks currently executing in
// m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning
// reaches zero.
//
//int m_callbacksRunning;
volatile bool m_canceled;
//volatile WaitHandle m_notifyWhenNoCallbacksRunning;
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period)
{
m_timerCallback = timerCallback;
m_state = state;
m_dueTime = Timer.UnsignedInfiniteTimeout;
m_period = Timer.UnsignedInfiniteTimeout;
m_executionContext = ExecutionContext.Capture();
//
// After the following statement, the timer may fire. No more manipulation of timer state outside of
// the lock is permitted beyond this point!
//
if (dueTime != Timer.UnsignedInfiniteTimeout)
Change(dueTime, period);
}
internal bool Change(uint dueTime, uint period)
{
bool success;
lock (TimerQueue.Instance.Lock)
{
if (m_canceled)
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
// prevent ThreadAbort while updating state
try { }
finally
{
m_period = period;
if (dueTime == Timer.UnsignedInfiniteTimeout)
{
TimerQueue.Instance.DeleteTimer(this);
success = true;
}
else
{
success = TimerQueue.Instance.UpdateTimer(this, dueTime, period);
}
}
}
return success;
}
public void Close()
{
lock (TimerQueue.Instance.Lock)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (!m_canceled)
{
m_canceled = true;
TimerQueue.Instance.DeleteTimer(this);
}
}
}
}
//public bool Close(WaitHandle toSignal)
//{
// bool success;
// bool shouldSignal = false;
// lock (TimerQueue.Instance.Lock)
// {
// // prevent ThreadAbort while updating state
// try { }
// finally
// {
// if (m_canceled)
// {
// success = false;
// }
// else
// {
// m_canceled = true;
// m_notifyWhenNoCallbacksRunning = toSignal;
// TimerQueue.Instance.DeleteTimer(this);
// if (m_callbacksRunning == 0)
// shouldSignal = true;
// success = true;
// }
// }
// }
// if (shouldSignal)
// SignalNoCallbacksRunning();
// return success;
//}
internal void Fire()
{
bool canceled = false;
//lock (TimerQueue.Instance.Lock)
//{
// // prevent ThreadAbort while updating state
// try { }
// finally
// {
canceled = m_canceled;
// if (!canceled)
// m_callbacksRunning++;
// }
//}
if (canceled)
return;
CallCallback();
//bool shouldSignal = false;
//lock (TimerQueue.Instance.Lock)
//{
// // prevent ThreadAbort while updating state
// try { }
// finally
// {
// m_callbacksRunning--;
// if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null)
// shouldSignal = true;
// }
//}
//if (shouldSignal)
// SignalNoCallbacksRunning();
}
//internal void SignalNoCallbacksRunning()
//{
// SafeHandle handle = m_notifyWhenNoCallbacksRunning.SafeWaitHandle;
// handle.DangerousAddRef();
// Interop.kernel32.SetEvent(handle.DangerousGetHandle());
// handle.DangerousRelease();
//}
internal void CallCallback()
{
ContextCallback callback = s_callCallbackInContext;
if (callback == null)
s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext);
ExecutionContext.Run(m_executionContext, callback, this);
}
private static ContextCallback s_callCallbackInContext;
private static void CallCallbackInContext(object state)
{
TimerQueueTimer t = (TimerQueueTimer)state;
t.m_timerCallback(t.m_state);
}
}
//
// TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer
// if the Timer is collected.
// This is necessary because Timer itself cannot use its finalizer for this purpose. If it did,
// then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize.
// You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this
// via first-class APIs), but Timer has never offered this, and adding it now would be a breaking
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
//
sealed class TimerHolder
{
internal TimerQueueTimer m_timer;
public TimerHolder(TimerQueueTimer timer)
{
m_timer = timer;
}
~TimerHolder()
{
//
// If shutdown has started, another thread may be suspended while holding the timer lock.
// So we can't safely close the timer.
//
// Similarly, we should not close the timer during AD-unload's live-object finalization phase.
// A rude abort may have prevented us from releasing the lock.
//
// Note that in either case, the Timer still won't fire, because ThreadPool threads won't be
// allowed to run in this AppDomain.
//
if (Environment.HasShutdownStarted /*|| AppDomain.CurrentDomain.IsFinalizingForUnload()*/)
return;
m_timer.Close();
}
public void Close()
{
m_timer.Close();
GC.SuppressFinalize(this);
}
//public bool Close(WaitHandle notifyObject)
//{
// bool result = m_timer.Close(notifyObject);
// GC.SuppressFinalize(this);
// return result;
//}
}
public sealed class Timer : IDisposable
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
internal const uint UnsignedInfiniteTimeout = unchecked((uint)-1);
private TimerHolder m_timer;
public Timer(TimerCallback callback,
Object state,
int dueTime,
int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
public Timer(TimerCallback callback,
Object state,
TimeSpan dueTime,
TimeSpan period)
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
throw new ArgumentOutOfRangeException("dueTm", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("dueTm", SR.ArgumentOutOfRange_TimeoutTooLarge);
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
throw new ArgumentOutOfRangeException("periodTm", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("periodTm", SR.ArgumentOutOfRange_PeriodTooLarge);
TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm);
}
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
if (callback == null)
throw new ArgumentNullException("TimerCallback");
Contract.EndContractBlock();
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period));
}
#if FEATURE_LEGACYNETCFFAS
internal static void Pause()
{
TimerQueue.Instance.Pause();
}
internal static void Resume()
{
TimerQueue.Instance.Resume();
}
#endif // FEATURE_LEGACYNETCFFAS
public bool Change(int dueTime, int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Change(TimeSpan dueTime, TimeSpan period)
{
return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
}
private bool Change(long dueTime, long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_PeriodTooLarge);
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
//public bool Dispose(WaitHandle notifyObject)
//{
// if (notifyObject==null)
// throw new ArgumentNullException("notifyObject");
// Contract.EndContractBlock();
// return m_timer.Close(notifyObject);
//}
public void Dispose()
{
m_timer.Close();
}
internal void KeepRootedWhileScheduled()
{
GC.SuppressFinalize(m_timer);
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
namespace Jovian.ImagePHP
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class TenChannel
{
StreamWriter Output;
/// <summary>
/// The main entry point for the application.
/// </summary>
///
class chan10color
{
public Color R;
public Color G;
public Color B;
public Color C;
public chan10color(Color r, Color g, Color b, Color c)
{
R = r; G = g; B = b; C = c;
if(B.A < 5)
{
B = Color.FromArgb(0,0,0,0);
}
if(G.A < 5)
{
G = Color.FromArgb(0,0,0,0);
}
if(R.A < 5)
{
R = Color.FromArgb(0,0,0,0);
}
if(C.A < 5)
{
C = Color.FromArgb(0,0,0,0);
}
if(G.A==255)
{
B = Color.FromArgb(0,0,0,0);
}
}
public bool Equal(chan10color c)
{
return (R.R == c.R.R && R.A == c.R.A) && (G.G == c.G.G && G.A == c.G.A) && (B.B == c.B.B && B.A == c.B.A) && (C.R == c.C.R && C.G == c.C.G && C.B == c.C.B && C.A == c.C.A);
}
}
class chan10bitmap
{
public Bitmap _R;
public Bitmap _G;
public Bitmap _B;
public Bitmap _C;
public int Height;
public int Width;
public chan10bitmap(Bitmap R, Bitmap G, Bitmap B, Bitmap C)
{ _R = R; _G = G; _B = B; _C = C; Height = R.Height; Width = R.Width; }
public chan10color GetPixel(int x, int y)
{
return new chan10color(_R.GetPixel(x, y), _G.GetPixel(x, y), _B.GetPixel(x, y), _C.GetPixel(x, y));
}
public void rel()
{
_R.Dispose();
_G.Dispose();
_B.Dispose();
_C.Dispose();
}
}
int ScanX(chan10bitmap B, int x, int y, bool[][] Used, int max)
{
chan10color C = B.GetPixel(x, y);
for(int k = 1; k < max; k++)
{
chan10color R = B.GetPixel(x + k, y);
if (!C.Equal(R))
{
return k-1;
}
}
return max;
}
int ScanY(chan10bitmap B, int x, int y, bool[][] Used, int max)
{
chan10color C = B.GetPixel(x, y);
for(int k = 1; k < max; k++)
{
chan10color R = B.GetPixel(x, y + k);
if(! C.Equal(R) )
{
return k-1;
}
}
return max;
}
void LineX(chan10bitmap B, int start, int y, bool[][] Used, int end, chan10color C)
{
for(int x = start; x < start+end; x++)
{
Used[y][x] = true;
}
Output.WriteLine("imageline($i," + start + "," + y + "," + (start + end - 1) + "," + y + ",$c);");
}
void LineY(chan10bitmap B, int x, int start, bool[][] Used, int end, chan10color C)
{
for(int y = start; y < start+end; y++)
{
Used[y][x] = true;
}
Output.WriteLine("imageline($i," + x + "," + start + "," + x + "," + (start + end - 1) + ",$c);");
}
void ScanColor(chan10bitmap B, bool[][] Used, chan10color C)
{
if(C.C.A==0)
{
Output.WriteLine("$c = m1($i," + C.R.R + "," + C.R.A + "," + C.G.G + "," + C.G.A + "," + C.B.B + "," + C.B.A + ");");
}
else
{
Output.WriteLine("$c = mc($i," + C.R.R + "," + C.R.A + "," + C.G.G + "," + C.G.A + "," + C.B.B + "," + C.B.A + "," + C.C.R + "," + C.C.G + "," + C.C.B + "," + C.C.A + ");");
}
// + C.B + "," + (127 - C.A / 2) + ");");
for (int y = 0; y < B.Height; y++)
{
for (int x = 0; x < B.Width; x++)
{
chan10color LC = B.GetPixel(x, y);
if (LC.Equal(C))
{
if (!Used[y][x])
{
int Take = ScanY(B, x, y, Used, B.Height - y);
if (Take >= 2)
{
LineY(B, x, y, Used, Take, C);
}
}
}
}
}
for (int y = 0; y < B.Height; y++)
{
for (int x = 0; x < B.Width; x++)
{
chan10color LC = B.GetPixel(x, y);
if(LC.Equal(C))
{
if (!Used[y][x])
{
int Take = ScanX(B, x, y, Used, B.Width - x);
if (Take >= 2)
{
LineX(B, x, y, Used, Take, C);
}
}
}
}
}
for (int y = 0; y < B.Height; y++)
{
for (int x = 0; x < B.Width; x++)
{
if (!Used[y][x])
{
chan10color LC = B.GetPixel(x, y);
if (LC.Equal(C))
{
Output.WriteLine("imagesetpixel($i," + x + "," + y + ",$c);");
Used[y][x] = true;
}
}
}
}
}
public void CompileImage2Php(string imageRed, string imageGreen, string imageBlue, string imageWhite, string outfilename)
{
Output = new StreamWriter(outfilename);
chan10bitmap B = new chan10bitmap(new Bitmap(imageRed), new Bitmap(imageGreen), new Bitmap(imageBlue), new Bitmap(imageWhite));
Output.WriteLine("<?php");
Output.WriteLine("include_once('blend10.inc');");
Output.WriteLine("cache(\"" + outfilename.Substring(0, outfilename.Length - 4).ToLower().Substring(4) + "\");");
Output.WriteLine("$i=ib(" + B.Width + "," + B.Height + ");");
bool [][] Used = new bool[B.Height][];
for(int y = 0; y < B.Height; y++)
{ Used[y] = new bool[B.Width]; }
for(int y = 0; y < B.Height; y++)
{ for(int x = 0; x < B.Width; x++)
{ Used[y][x] = false;
}
}
for (int y = 0; y < B.Height; y++)
{
for (int x = 0; x < B.Width; x++)
{
if (!Used[y][x])
{
chan10color C = B.GetPixel(x, y);
ScanColor(B, Used, C);
}
}
}
B.rel();
Output.WriteLine("fin($i);");
Output.WriteLine("?>");
Output.Flush();
Output.Close();
}
/*
[STAThread]
static void Main(string[] args)
{
//Bitmap B = new Bitmap("rs-tr.png");
//Bitmap B = new Bitmap(args[0]);
//B.Dispose();
}
*/
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System.Diagnostics;
namespace NUnit.ConsoleRunner
{
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Resources;
using System.Text;
using NUnit.Core;
using NUnit.Core.Filters;
using NUnit.Util;
/// <summary>
/// Summary description for ConsoleUi.
/// </summary>
public class ConsoleUi
{
public static readonly int OK = 0;
public static readonly int INVALID_ARG = -1;
public static readonly int FILE_NOT_FOUND = -2;
public static readonly int FIXTURE_NOT_FOUND = -3;
public static readonly int UNEXPECTED_ERROR = -100;
private string workDir;
public ConsoleUi()
{
}
public int Execute( ConsoleOptions options )
{
this.workDir = options.work;
if (workDir == null || workDir == string.Empty)
workDir = Environment.CurrentDirectory;
else
{
workDir = Path.GetFullPath(workDir);
if (!Directory.Exists(workDir))
Directory.CreateDirectory(workDir);
}
TextWriter outWriter = Console.Out;
bool redirectOutput = options.output != null && options.output != string.Empty;
if ( redirectOutput )
{
StreamWriter outStreamWriter = new StreamWriter( Path.Combine(workDir, options.output) );
outStreamWriter.AutoFlush = true;
outWriter = outStreamWriter;
}
TextWriter errorWriter = Console.Error;
bool redirectError = options.err != null && options.err != string.Empty;
if ( redirectError )
{
StreamWriter errorStreamWriter = new StreamWriter( Path.Combine(workDir, options.err) );
errorStreamWriter.AutoFlush = true;
errorWriter = errorStreamWriter;
}
TestPackage package = MakeTestPackage(options);
ProcessModel processModel = package.Settings.Contains("ProcessModel")
? (ProcessModel)package.Settings["ProcessModel"]
: ProcessModel.Default;
DomainUsage domainUsage = package.Settings.Contains("DomainUsage")
? (DomainUsage)package.Settings["DomainUsage"]
: DomainUsage.Default;
RuntimeFramework framework = package.Settings.Contains("RuntimeFramework")
? (RuntimeFramework)package.Settings["RuntimeFramework"]
: RuntimeFramework.CurrentFramework;
#if CLR_2_0 || CLR_4_0
Console.WriteLine("ProcessModel: {0} DomainUsage: {1}", processModel, domainUsage);
Console.WriteLine("Execution Runtime: {0}", framework);
#else
Console.WriteLine("DomainUsage: {0}", domainUsage);
if (processModel != ProcessModel.Default && processModel != ProcessModel.Single)
Console.WriteLine("Warning: Ignoring project setting 'processModel={0}'", processModel);
if (!RuntimeFramework.CurrentFramework.Supports(framework))
Console.WriteLine("Warning: Ignoring project setting 'runtimeFramework={0}'", framework);
#endif
using (TestRunner testRunner = new DefaultTestRunnerFactory().MakeTestRunner(package))
{
testRunner.Load(package);
if (testRunner.Test == null)
{
testRunner.Unload();
Console.Error.WriteLine("Unable to locate fixture {0}", options.fixture);
return FIXTURE_NOT_FOUND;
}
EventCollector collector = new EventCollector( options, outWriter, errorWriter );
TestFilter testFilter;
if(!CreateTestFilter(options, out testFilter))
return INVALID_ARG;
TestResult result = null;
string savedDirectory = Environment.CurrentDirectory;
TextWriter savedOut = Console.Out;
TextWriter savedError = Console.Error;
try
{
result = testRunner.Run( collector, testFilter, true, LoggingThreshold.Off );
}
finally
{
outWriter.Flush();
errorWriter.Flush();
if (redirectOutput)
outWriter.Close();
if (redirectError)
errorWriter.Close();
Environment.CurrentDirectory = savedDirectory;
Console.SetOut( savedOut );
Console.SetError( savedError );
}
Console.WriteLine();
int returnCode = UNEXPECTED_ERROR;
if (result != null)
{
string xmlOutput = CreateXmlOutput(result);
ResultSummarizer summary = new ResultSummarizer(result);
if (options.xmlConsole)
{
Console.WriteLine(xmlOutput);
}
else
{
WriteSummaryReport(summary);
bool hasErrors = summary.Errors > 0 || summary.Failures > 0 || result.IsError || result.IsFailure;
if (options.stoponerror && (hasErrors || summary.NotRunnable > 0))
{
Console.WriteLine("Test run was stopped after first error, as requested.");
Console.WriteLine();
}
if (hasErrors)
WriteErrorsAndFailuresReport(result);
if (summary.TestsNotRun > 0)
WriteNotRunReport(result);
if (!options.noresult)
{
// Write xml output here
string xmlResultFile = options.result == null || options.result == string.Empty
? "TestResult.xml" : options.result;
using (StreamWriter writer = new StreamWriter(Path.Combine(workDir, xmlResultFile)))
{
writer.Write(xmlOutput);
}
}
}
returnCode = summary.Errors + summary.Failures + summary.NotRunnable;
}
if (collector.HasExceptions)
{
collector.WriteExceptions();
returnCode = UNEXPECTED_ERROR;
}
return returnCode;
}
}
internal static bool CreateTestFilter(ConsoleOptions options, out TestFilter testFilter)
{
testFilter = TestFilter.Empty;
SimpleNameFilter nameFilter = new SimpleNameFilter();
if (options.run != null && options.run != string.Empty)
{
Console.WriteLine("Selected test(s): " + options.run);
foreach (string name in TestNameParser.Parse(options.run))
nameFilter.Add(name);
testFilter = nameFilter;
}
if (options.runlist != null && options.runlist != string.Empty)
{
Console.WriteLine("Run list: " + options.runlist);
try
{
using (StreamReader rdr = new StreamReader(options.runlist))
{
// NOTE: We can't use rdr.EndOfStream because it's
// not present in .NET 1.x.
string line = rdr.ReadLine();
while (line != null && line.Length > 0)
{
if (line[0] != '#')
nameFilter.Add(line);
line = rdr.ReadLine();
}
}
}
catch (Exception e)
{
if (e is FileNotFoundException || e is DirectoryNotFoundException)
{
Console.WriteLine("Unable to locate file: " + options.runlist);
return false;
}
throw;
}
testFilter = nameFilter;
}
if (options.include != null && options.include != string.Empty)
{
TestFilter includeFilter = new CategoryExpression(options.include).Filter;
Console.WriteLine("Included categories: " + includeFilter.ToString());
if (testFilter.IsEmpty)
testFilter = includeFilter;
else
testFilter = new AndFilter(testFilter, includeFilter);
}
if (options.exclude != null && options.exclude != string.Empty)
{
TestFilter excludeFilter = new NotFilter(new CategoryExpression(options.exclude).Filter);
Console.WriteLine("Excluded categories: " + excludeFilter.ToString());
if (testFilter.IsEmpty)
testFilter = excludeFilter;
else if (testFilter is AndFilter)
((AndFilter) testFilter).Add(excludeFilter);
else
testFilter = new AndFilter(testFilter, excludeFilter);
}
if (testFilter is NotFilter)
((NotFilter) testFilter).TopLevel = true;
return true;
}
#region Helper Methods
// TODO: See if this can be unified with the Gui's MakeTestPackage
private TestPackage MakeTestPackage( ConsoleOptions options )
{
TestPackage package;
DomainUsage domainUsage = DomainUsage.Default;
ProcessModel processModel = ProcessModel.Default;
RuntimeFramework framework = null;
string[] parameters = new string[options.ParameterCount];
for (int i = 0; i < options.ParameterCount; i++)
parameters[i] = Path.GetFullPath((string)options.Parameters[i]);
if (options.IsTestProject)
{
NUnitProject project =
Services.ProjectService.LoadProject(parameters[0]);
string configName = options.config;
if (configName != null)
project.SetActiveConfig(configName);
package = project.ActiveConfig.MakeTestPackage();
processModel = project.ProcessModel;
domainUsage = project.DomainUsage;
framework = project.ActiveConfig.RuntimeFramework;
}
else if (parameters.Length == 1)
{
package = new TestPackage(parameters[0]);
domainUsage = DomainUsage.Single;
}
else
{
// TODO: Figure out a better way to handle "anonymous" packages
package = new TestPackage(null, parameters);
package.AutoBinPath = true;
domainUsage = DomainUsage.Multiple;
}
if (options.basepath != null && options.basepath != string.Empty)
{
package.BasePath = options.basepath;
}
if (options.privatebinpath != null && options.privatebinpath != string.Empty)
{
package.AutoBinPath = false;
package.PrivateBinPath = options.privatebinpath;
}
#if CLR_2_0 || CLR_4_0
if (options.framework != null)
framework = RuntimeFramework.Parse(options.framework);
if (options.process != ProcessModel.Default)
processModel = options.process;
#endif
if (options.domain != DomainUsage.Default)
domainUsage = options.domain;
package.TestName = options.fixture;
package.Settings["ProcessModel"] = processModel;
package.Settings["DomainUsage"] = domainUsage;
if (framework != null)
package.Settings["RuntimeFramework"] = framework;
if (domainUsage == DomainUsage.None)
{
// Make sure that addins are available
CoreExtensions.Host.AddinRegistry = Services.AddinRegistry;
}
package.Settings["ShadowCopyFiles"] = !options.noshadow;
package.Settings["UseThreadedRunner"] = !options.nothread;
package.Settings["DefaultTimeout"] = options.timeout;
package.Settings["WorkDirectory"] = this.workDir;
package.Settings["StopOnError"] = options.stoponerror;
if (options.apartment != System.Threading.ApartmentState.Unknown)
package.Settings["ApartmentState"] = options.apartment;
return package;
}
private static string CreateXmlOutput( TestResult result )
{
StringBuilder builder = new StringBuilder();
new XmlResultWriter(new StringWriter( builder )).SaveTestResult(result);
return builder.ToString();
}
private static void WriteSummaryReport( ResultSummarizer summary )
{
Console.WriteLine(
"Tests run: {0}, Errors: {1}, Failures: {2}, Inconclusive: {3}, Time: {4} seconds",
summary.TestsRun, summary.Errors, summary.Failures, summary.Inconclusive, summary.Time);
Console.WriteLine(
" Not run: {0}, Invalid: {1}, Ignored: {2}, Skipped: {3}",
summary.TestsNotRun, summary.NotRunnable, summary.Ignored, summary.Skipped);
Console.WriteLine();
}
private void WriteErrorsAndFailuresReport(TestResult result)
{
reportIndex = 0;
Console.WriteLine("Errors and Failures:");
WriteErrorsAndFailures(result);
Console.WriteLine();
}
private void WriteErrorsAndFailures(TestResult result)
{
if (result.Executed)
{
if (result.HasResults)
{
if (result.IsFailure || result.IsError)
if (result.FailureSite == FailureSite.SetUp || result.FailureSite == FailureSite.TearDown)
WriteSingleResult(result);
foreach (TestResult childResult in result.Results)
WriteErrorsAndFailures(childResult);
}
else if (result.IsFailure || result.IsError)
{
WriteSingleResult(result);
}
}
}
private void WriteNotRunReport(TestResult result)
{
reportIndex = 0;
Console.WriteLine("Tests Not Run:");
WriteNotRunResults(result);
Console.WriteLine();
}
private int reportIndex = 0;
private void WriteNotRunResults(TestResult result)
{
if (result.HasResults)
foreach (TestResult childResult in result.Results)
WriteNotRunResults(childResult);
else if (!result.Executed)
WriteSingleResult( result );
}
private void WriteSingleResult( TestResult result )
{
string status = result.IsFailure || result.IsError
? string.Format("{0} {1}", result.FailureSite, result.ResultState)
: result.ResultState.ToString();
Console.WriteLine("{0}) {1} : {2}", ++reportIndex, status, result.FullName);
if ( result.Message != null && result.Message != string.Empty )
Console.WriteLine(" {0}", result.Message);
if (result.StackTrace != null && result.StackTrace != string.Empty)
Console.WriteLine( result.IsFailure
? StackTraceFilter.Filter(result.StackTrace)
: result.StackTrace + Environment.NewLine );
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using Eto.Drawing;
using SD = System.Drawing;
using UIKit;
using Foundation;
using CoreGraphics;
namespace Eto.iOS.Drawing
{
public class BitmapDataHandler : BitmapData
{
public BitmapDataHandler(Image image, IntPtr data, int scanWidth, int bitsPerPixel, object controlObject)
: base(image, data, scanWidth, bitsPerPixel, controlObject)
{
}
public override int TranslateArgbToData(int argb)
{
return argb; //(argb & 0xFF00FF00) | ((argb & 0xFF) << 16) | ((argb & 0xFF0000) >> 16);
}
public override int TranslateDataToArgb(int bitmapData)
{
return bitmapData; //(bitmapData & 0xFF00FF00) | ((bitmapData & 0xFF) << 16) | ((bitmapData & 0xFF0000) >> 16);
}
public override bool Flipped
{
get
{
return false;
}
}
}
public class BitmapHandler : ImageHandler<UIImage, Bitmap>, Bitmap.IHandler
{
CGDataProvider provider;
CGImage cgimage;
public NSMutableData Data { get; private set; }
public void Create(string fileName)
{
Control = new UIImage(fileName);
}
public void Create(Stream stream)
{
Control = new UIImage(NSData.FromStream(stream));
}
public BitmapHandler()
{
}
public BitmapHandler(UIImage image)
{
Control = image;
}
public void Create(int width, int height, PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat.Format32bppRgba:
{
const int numComponents = 4;
const int bitsPerComponent = 8;
const int bitsPerPixel = numComponents * bitsPerComponent;
const int bytesPerPixel = bitsPerPixel / 8;
int bytesPerRow = bytesPerPixel * width;
Data = NSMutableData.FromLength(bytesPerRow * height);
provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false);
cgimage = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.PremultipliedFirst, provider, null, true, CGColorRenderingIntent.Default);
Control = UIImage.FromImage(cgimage, 0f, UIImageOrientation.Up);
break;
}
case PixelFormat.Format32bppRgb:
{
const int numComponents = 4;
const int bitsPerComponent = 8;
const int bitsPerPixel = numComponents * bitsPerComponent;
const int bytesPerPixel = bitsPerPixel / 8;
int bytesPerRow = bytesPerPixel * width;
Data = NSMutableData.FromLength(bytesPerRow * height);
//Data = new NSMutableData ((uint)(bytesPerRow * height));
provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false);
cgimage = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.NoneSkipFirst, provider, null, true, CGColorRenderingIntent.Default);
Control = UIImage.FromImage(cgimage, 0f, UIImageOrientation.Up);
break;
}
case PixelFormat.Format24bppRgb:
{
const int numComponents = 3;
const int bitsPerComponent = 8;
const int bitsPerPixel = numComponents * bitsPerComponent;
const int bytesPerPixel = bitsPerPixel / 8;
int bytesPerRow = bytesPerPixel * width;
Data = new NSMutableData((uint)(bytesPerRow * height));
provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false);
cgimage = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.PremultipliedFirst, provider, null, true, CGColorRenderingIntent.Default);
Control = UIImage.FromImage(cgimage, 0f, UIImageOrientation.Up);
break;
}
default:
throw new ArgumentOutOfRangeException("pixelFormat", pixelFormat, "Not supported");
}
}
public void Create(Image image, int width, int height, ImageInterpolation interpolation)
{
var source = image.ToUI();
// todo: use interpolation
Control = source.Scale(new CGSize(width, height), 0f);
}
public void Create(int width, int height, Graphics graphics)
{
Create(width, height, PixelFormat.Format32bppRgba);
}
public BitmapData Lock()
{
cgimage = cgimage ?? Control.CGImage;
if (Data == null)
{
Data = (NSMutableData)cgimage.DataProvider.CopyData().MutableCopy();
provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false);
cgimage = new CGImage((int)cgimage.Width, (int)cgimage.Height, (int)cgimage.BitsPerComponent, (int)cgimage.BitsPerPixel, (int)cgimage.BytesPerRow, cgimage.ColorSpace, cgimage.BitmapInfo, provider, null, cgimage.ShouldInterpolate, cgimage.RenderingIntent);
Control = UIImage.FromImage(cgimage);
}
return new BitmapDataHandler(Widget, Data.MutableBytes, (int)cgimage.BytesPerRow, (int)cgimage.BitsPerPixel, Control);
}
public void Unlock(BitmapData bitmapData)
{
// don't need to do anythin
}
public void Save(string fileName, ImageFormat format)
{
using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
Save(stream, format);
}
}
public void Save(Stream stream, ImageFormat format)
{
NSData data;
switch (format)
{
case ImageFormat.Jpeg:
data = Control.AsJPEG();
break;
case ImageFormat.Png:
data = Control.AsPNG();
break;
case ImageFormat.Bitmap:
case ImageFormat.Gif:
case ImageFormat.Tiff:
default:
throw new NotSupportedException();
}
data.AsStream().CopyTo(stream);
data.Dispose();
}
public override Size Size
{
get { return Control.Size.ToEtoSize(); }
}
public override void DrawImage(GraphicsHandler graphics, float x, float y)
{
var nsimage = Control;
var destRect = new CGRect(x, y, (int)nsimage.Size.Width, (int)nsimage.Size.Height);
nsimage.Draw(destRect, CGBlendMode.Normal, 1);
}
public override void DrawImage(GraphicsHandler graphics, RectangleF source, RectangleF destination)
{
var destRect = destination;
var drawRect = GetDrawRect(ref source, ref destRect, Control.Size.ToEto());
graphics.Control.ClipToRect(destRect.ToNS()); // first apply the clip since destination is in view coordinates.
Control.Draw(drawRect.ToNS(), CGBlendMode.Normal, 1);
}
private static RectangleF GetDrawRect(ref RectangleF source, ref RectangleF destRect, SizeF imageSize)
{
var scale = destRect.Size / source.Size;
var scaledImageSize = imageSize * scale;
// We want the source rectangle's location to coincide with the destination rectangle's location.
// However the source image is drawn scaled.
// The relevant equation is:
// source.Location * scale + offset = destination.Location, which gives:
var offset = (destRect.Location - (source.Location * scale));
var drawRect = new RectangleF(offset, scaledImageSize);
return drawRect;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (Data != null)
{
Data.Dispose();
Data = null;
}
}
}
public override UIImage GetUIImage(int? maxSize = null)
{
var size = Size;
var imgSize = Math.Max(size.Width, size.Height);
if (maxSize != null && imgSize > maxSize.Value)
{
size = (Size)(size * ((float)maxSize.Value / (float)imgSize));
var img = new Bitmap(Widget, size.Width, size.Height);
return img.ToUI();
}
return Control;
}
public Bitmap Clone(Rectangle? rectangle = null)
{
if (rectangle == null)
return new Bitmap(new BitmapHandler { Control = new UIImage(Control.CGImage.Clone()) });
else
{
var rect = rectangle.Value;
cgimage = cgimage ?? Control.CGImage;
PixelFormat format;
if (cgimage.BitsPerPixel == 24)
format = PixelFormat.Format24bppRgb;
else if (cgimage.AlphaInfo == CGImageAlphaInfo.None)
format = PixelFormat.Format32bppRgb;
else
format = PixelFormat.Format32bppRgba;
var bmp = new Bitmap(rect.Width, rect.Height, format);
using (var graphics = new Graphics (bmp))
{
graphics.DrawImage(Widget, rect, new Rectangle(rect.Size));
}
return bmp;
}
}
public Color GetPixel(int x, int y)
{
using (var data = Lock ())
{
unsafe
{
var srcrow = (byte*)data.Data;
srcrow += y * data.ScanWidth;
srcrow += x * data.BytesPerPixel;
if (data.BytesPerPixel == 4)
{
return Color.FromArgb(data.TranslateDataToArgb(*(int*)srcrow));
}
else if (data.BytesPerPixel == 3)
{
var b = *(srcrow ++);
var g = *(srcrow ++);
var r = *(srcrow ++);
return Color.FromArgb(r, g, b);
}
else
throw new NotSupportedException();
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Batch
{
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>
/// ApplicationPackageOperations operations.
/// </summary>
internal partial class ApplicationPackageOperations : IServiceOperations<BatchManagementClient>, IApplicationPackageOperations
{
/// <summary>
/// Initializes a new instance of the ApplicationPackageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ApplicationPackageOperations(BatchManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the BatchManagementClient
/// </summary>
public BatchManagementClient Client { get; private set; }
/// <summary>
/// Activates the specified application package.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The ID of the application.
/// </param>
/// <param name='version'>
/// The version of the application to activate.
/// </param>
/// <param name='format'>
/// The format of the application package binary file.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> ActivateWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, string format, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "version");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (format == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "format");
}
ActivateApplicationPackageParameters parameters = new ActivateApplicationPackageParameters();
if (format != null)
{
parameters.Format = format;
}
// 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("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Activate", 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.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}/activate").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("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;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates an application package record.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The ID of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </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<ApplicationPackage>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "version");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// 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 != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (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<ApplicationPackage>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationPackage>(_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>
/// Deletes an application package record and its associated binary file.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The ID of the application.
/// </param>
/// <param name='version'>
/// The version of the application to delete.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "version");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets information about the specified application package.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The ID of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </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<ApplicationPackage>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "version");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (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<ApplicationPackage>();
_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<ApplicationPackage>(_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;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type EventInstancesCollectionRequest.
/// </summary>
public partial class EventInstancesCollectionRequest : BaseRequest, IEventInstancesCollectionRequest
{
/// <summary>
/// Constructs a new EventInstancesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public EventInstancesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="instancesEvent">The Event to add.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event instancesEvent)
{
return this.AddAsync(instancesEvent, CancellationToken.None);
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="instancesEvent">The Event to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event instancesEvent, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Event>(instancesEvent, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IEventInstancesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IEventInstancesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<EventInstancesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest Expand(Expression<Func<Event, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest Select(Expression<Func<Event, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IEventInstancesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Tests
{
/// <summary>
/// Contains tests that ensure the correctness of the Queue class.
/// </summary>
public abstract partial class Queue_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
{
#region Queue<T> Helper Methods
protected Queue<T> GenericQueueFactory()
{
return new Queue<T>();
}
protected Queue<T> GenericQueueFactory(int count)
{
Queue<T> queue = new Queue<T>(count);
int seed = count * 34;
for (int i = 0; i < count; i++)
queue.Enqueue(CreateT(seed++));
return queue;
}
#endregion
#region IGenericSharedAPI<T> Helper Methods
protected override IEnumerable<T> GenericIEnumerableFactory()
{
return GenericQueueFactory();
}
protected override IEnumerable<T> GenericIEnumerableFactory(int count)
{
return GenericQueueFactory(count);
}
protected override int Count(IEnumerable<T> enumerable) => ((Queue<T>)enumerable).Count;
protected override void Add(IEnumerable<T> enumerable, T value) => ((Queue<T>)enumerable).Enqueue(value);
protected override void Clear(IEnumerable<T> enumerable) => ((Queue<T>)enumerable).Clear();
protected override bool Contains(IEnumerable<T> enumerable, T value) => ((Queue<T>)enumerable).Contains(value);
protected override void CopyTo(IEnumerable<T> enumerable, T[] array, int index) => ((Queue<T>)enumerable).CopyTo(array, index);
protected override bool Remove(IEnumerable<T> enumerable) { ((Queue<T>)enumerable).Dequeue(); return true; }
protected override bool Enumerator_Current_UndefinedOperation_Throws => true;
protected override Type IGenericSharedAPI_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException);
#endregion
#region Constructor_IEnumerable
[Theory]
[MemberData(nameof(EnumerableTestData))]
public void Queue_Generic_Constructor_IEnumerable(EnumerableType enumerableType, int setLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements)
{
IEnumerable<T> enumerable = CreateEnumerable(enumerableType, null, enumerableLength, 0, numberOfDuplicateElements);
Queue<T> queue = new Queue<T>(enumerable);
Assert.Equal(enumerable, queue);
}
[Fact]
public void Queue_Generic_Constructor_IEnumerable_Null_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("collection", () => new Queue<T>(null));
}
#endregion
#region Constructor_Capacity
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_Constructor_int(int count)
{
Queue<T> queue = new Queue<T>(count);
Assert.Equal(Array.Empty<T>(), queue.ToArray());
queue.Clear();
Assert.Equal(Array.Empty<T>(), queue.ToArray());
}
[Fact]
public void Queue_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue<T>(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue<T>(int.MinValue));
}
#endregion
#region Dequeue
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_Dequeue_AllElements(int count)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> elements = queue.ToList();
foreach (T element in elements)
Assert.Equal(element, queue.Dequeue());
}
[Fact]
public void Queue_Generic_Dequeue_OnEmptyQueue_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => new Queue<T>().Dequeue());
}
[Theory]
[InlineData(0, 5)]
[InlineData(1, 1)]
[InlineData(3, 100)]
public void Queue_Generic_EnqueueAndDequeue(int capacity, int items)
{
int seed = 53134;
var q = new Queue<T>(capacity);
Assert.Equal(0, q.Count);
// Enqueue some values and make sure the count is correct
List<T> source = (List<T>)CreateEnumerable(EnumerableType.List, null, items, 0, 0);
foreach (T val in source)
{
q.Enqueue(val);
}
Assert.Equal(source, q);
// Dequeue to make sure the values are removed in the right order and the count is updated
for (int i = 0; i < items; i++)
{
T itemToRemove = source[0];
source.RemoveAt(0);
Assert.Equal(itemToRemove, q.Dequeue());
Assert.Equal(items - i - 1, q.Count);
}
// Can't dequeue when empty
Assert.Throws<InvalidOperationException>(() => q.Dequeue());
// But can still be used after a failure and after bouncing at empty
T itemToAdd = CreateT(seed++);
q.Enqueue(itemToAdd);
Assert.Equal(itemToAdd, q.Dequeue());
}
#endregion
#region ToArray
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_ToArray(int count)
{
Queue<T> queue = GenericQueueFactory(count);
Assert.True(queue.ToArray().SequenceEqual(queue.ToArray<T>()));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_ToArray_NonWrappedQueue(int count)
{
Queue<T> collection = new Queue<T>(count + 1);
AddToCollection(collection, count);
T[] elements = collection.ToArray();
elements.Reverse();
Assert.True(Enumerable.SequenceEqual(elements, collection.ToArray<T>()));
}
#endregion
#region Peek
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_Peek_AllElements(int count)
{
Queue<T> queue = GenericQueueFactory(count);
List<T> elements = queue.ToList();
foreach (T element in elements)
{
Assert.Equal(element, queue.Peek());
queue.Dequeue();
}
}
[Fact]
public void Queue_Generic_Peek_OnEmptyQueue_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => new Queue<T>().Peek());
}
#endregion
#region TrimExcess
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_OnValidQueueThatHasntBeenRemovedFrom(int count)
{
Queue<T> queue = GenericQueueFactory(count);
queue.TrimExcess();
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_Repeatedly(int count)
{
Queue<T> queue = GenericQueueFactory(count); ;
List<T> expected = queue.ToList();
queue.TrimExcess();
queue.TrimExcess();
queue.TrimExcess();
Assert.True(queue.SequenceEqual(expected));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_AfterRemovingOneElement(int count)
{
if (count > 0)
{
Queue<T> queue = GenericQueueFactory(count); ;
List<T> expected = queue.ToList();
queue.TrimExcess();
T removed = queue.Dequeue();
expected.Remove(removed);
queue.TrimExcess();
Assert.True(queue.SequenceEqual(expected));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_AfterClearingAndAddingSomeElementsBack(int count)
{
if (count > 0)
{
Queue<T> queue = GenericQueueFactory(count); ;
queue.TrimExcess();
queue.Clear();
queue.TrimExcess();
Assert.Equal(0, queue.Count);
AddToCollection(queue, count / 10);
queue.TrimExcess();
Assert.Equal(count / 10, queue.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Queue_Generic_TrimExcess_AfterClearingAndAddingAllElementsBack(int count)
{
if (count > 0)
{
Queue<T> queue = GenericQueueFactory(count); ;
queue.TrimExcess();
queue.Clear();
queue.TrimExcess();
Assert.Equal(0, queue.Count);
AddToCollection(queue, count);
queue.TrimExcess();
Assert.Equal(count, queue.Count);
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.