context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using Xunit;
public partial class CompareInfoTests
{
[Theory]
[InlineData("")]
[InlineData("en")]
[InlineData("en-US")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void GetCompareInfo(string localeName)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(localeName, ci.Name);
}
[Fact]
public static void GetCompareInfoBadCompareType()
{
Assert.Throws<ArgumentNullException>(() => CompareInfo.GetCompareInfo(null));
}
[Theory]
[MemberData("CompareToData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void Compare(string localeName, string left, string right, int expected, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expected, Math.Sign(ci.Compare(left, right, options)));
if (options == CompareOptions.None)
{
Assert.Equal(expected, Math.Sign(ci.Compare(left, right)));
}
}
[Theory]
[InlineData(null, -1)]
[InlineData("", -1)]
[InlineData("abc", -1)]
[InlineData("abc", 4)]
public static void CompareArgumentOutOfRangeIndex(string badString, int badOffset)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, badString, badOffset));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, "good", 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, badString, badOffset, CompareOptions.None));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, "good", 0, CompareOptions.None));
}
[Theory]
[InlineData(null, 0, -1)]
[InlineData(null, -1, 0)]
[InlineData(null, -1, -1)]
[InlineData("", 0, -1)]
[InlineData("", -1, 0)]
[InlineData("", -1, -1)]
[InlineData("abc", 0, 4)]
[InlineData("abc", 4, 0)]
[InlineData("abc", 0, -1)]
[InlineData("abc", -1, 3)]
[InlineData("abc", 2, 2)]
public static void CompareArgumentOutOfRangeIndexAndCount(string badString, int badOffset, int badCount)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, 4, badString, badOffset, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, badCount, "good", 0, 4));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, 4, badString, badOffset, badCount, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, badCount, "good", 0, 4, CompareOptions.Ordinal));
}
[Fact]
public static void CompareBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.Compare("a", "b", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.Compare("a", "b", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.Compare("a", "b", (CompareOptions)(-1)));
}
[Theory]
[MemberData("IndexOfData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IndexOf(string localeName, string source, string value, int expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.IndexOf(source, value, options));
if (value.Length == 1)
{
Assert.Equal(expectedResult, ci.IndexOf(source, value[0], options));
}
if (options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.IndexOf(source, value));
}
if (value.Length == 1 && options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.IndexOf(source, value[0]));
}
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IndexOfMinusOneCompatability()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
// This behavior was for .NET Framework 1.1 compatability. We early outed for empty source strings
// even with invalid offsets.
Assert.Equal(0, ci.IndexOf("", "", -1, CompareOptions.None));
Assert.Equal(-1, ci.IndexOf("", "a", -1, CompareOptions.None));
}
[Theory]
[InlineData("", 'a', 1)]
[InlineData("abc", 'a', -1)]
[InlineData("abc", 'a', 4)]
public static void IndexOfArgumentOutOfRangeIndex(string source, char value, int badStartIndex)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, value, badStartIndex, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, valueAsString, badStartIndex, CompareOptions.Ordinal));
}
[Theory]
[InlineData("abc", 'a', 0, -1)]
[InlineData("abc", 'a', 0, 4)]
[InlineData("abc", 'a', 2, 2)]
[InlineData("abc", 'a', 4, 0)]
[InlineData("abc", 'a', 4, -1)]
public static void IndexOfArgumentOutOfRangeIndexAndCount(string source, char value, int badStartIndex, int badCount)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, value, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, value, badStartIndex, badCount, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, valueAsString, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, valueAsString, badStartIndex, badCount, CompareOptions.Ordinal));
}
[Fact]
public static void IndexOfArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a'));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a"));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', 0, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", 0, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, 0, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', 0, 1));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", 0, 1));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, 0, 1));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', 0, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", 0, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, 0, 1, CompareOptions.Ordinal));
}
[Fact]
public static void IndexOfBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", (CompareOptions)(-1)));
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", CompareOptions.StringSort));
}
[Theory]
[MemberData("LastIndexOfData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void LastIndexOf(string localeName, string source, string value, int expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.LastIndexOf(source, value, options));
if (value.Length == 1)
{
Assert.Equal(expectedResult, ci.LastIndexOf(source, value[0], options));
}
if (options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.LastIndexOf(source, value));
}
if (value.Length == 1 && options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.LastIndexOf(source, value[0]));
}
}
[Theory]
[InlineData("", 'a', 1)]
[InlineData("abc", 'a', -1)]
[InlineData("abc", 'a', 4)]
public static void LastIndexOfArgumentOutOfRangeIndex(string source, char value, int badStartIndex)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, value, badStartIndex, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, valueAsString, badStartIndex, CompareOptions.Ordinal));
}
[Theory]
[InlineData("abc", 'a', 2, -1)]
[InlineData("abc", 'a', 2, 4)]
[InlineData("abc", 'a', 1, 3)]
[InlineData("abc", 'a', 4, 0)]
[InlineData("abc", 'a', 4, -1)]
public static void LastIndexOfArgumentOutOfRangeIndexAndCount(string source, char value, int badStartIndex, int badCount)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, value, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, value, badStartIndex, badCount, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, valueAsString, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, valueAsString, badStartIndex, badCount, CompareOptions.Ordinal));
}
[Fact]
public static void LastIndexOfArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a'));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a"));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', 1, 1));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", 1, 1));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, 1, 1));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', 1, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", 1, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, 1, 1, CompareOptions.Ordinal));
}
[Fact]
public static void LastIndexOfBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", (CompareOptions)(-1)));
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", CompareOptions.StringSort));
}
[Theory]
[MemberData("IsPrefixData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IsPrefix(string localeName, string source, string prefix, bool expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.IsPrefix(source, prefix, options));
}
[Fact]
public static void IsPrefixBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", CompareOptions.StringSort));
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", (CompareOptions)(-1)));
}
[Fact]
public static void IsPrefixArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, ""));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, "", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix("", null));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix("", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, null));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, null, CompareOptions.Ordinal));
}
[Theory]
[MemberData("IsSuffixData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IsSuffix(string localeName, string source, string suffix, bool expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.IsSuffix(source, suffix, options));
}
[Fact]
public static void IsSuffixBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", CompareOptions.StringSort));
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", (CompareOptions)(-1)));
}
[Fact]
public static void IsSuffixArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, ""));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, "", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix("", null));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix("", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, null));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, null, CompareOptions.Ordinal));
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void EqualsAndHashCode()
{
CompareInfo ciInvariantFromCultureInfo = CultureInfo.InvariantCulture.CompareInfo;
CompareInfo ciInvariantFromFactory = CompareInfo.GetCompareInfo("");
CompareInfo ciEnUs = CompareInfo.GetCompareInfo("en-US");
Assert.True(ciInvariantFromCultureInfo.Equals(ciInvariantFromFactory));
Assert.False(ciEnUs.Equals(ciInvariantFromCultureInfo));
Assert.False(ciEnUs.Equals(new object()));
Assert.Equal(ciInvariantFromCultureInfo.GetHashCode(), ciInvariantFromFactory.GetHashCode());
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void GetHashCodeOfString()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Equal("abc".GetHashCode(), ci.GetHashCode("abc", CompareOptions.Ordinal));
Assert.Equal(ci.GetHashCode("abc", CompareOptions.OrdinalIgnoreCase), ci.GetHashCode("ABC", CompareOptions.OrdinalIgnoreCase));
// This behavior of the empty string is specical cased today.
Assert.Equal(0, ci.GetHashCode("", CompareOptions.None));
// Not much we can assert about the hashcode of a string itself, but we can assume that computing it twice yeilds the same value.
int hashCode1 = ci.GetHashCode("abc", CompareOptions.None);
int hashCode2 = ci.GetHashCode("abc", CompareOptions.None);
Assert.Equal(hashCode1, hashCode2);
}
[Fact]
public static void GetHashCodeOfStringNullSource()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.GetHashCode(null, CompareOptions.None));
}
[Fact]
public static void GetHashCodeOfStringBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.GetHashCode("", CompareOptions.StringSort));
Assert.Throws<ArgumentException>(() => ci.GetHashCode("", CompareOptions.Ordinal | CompareOptions.IgnoreSymbols));
Assert.Throws<ArgumentException>(() => ci.GetHashCode("", (CompareOptions)(-1)));
}
[Fact]
public static void ToStringReturnsNonNullNonEmpty()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.NotNull(ci.ToString());
Assert.NotEqual("", ci.ToString());
}
}
| |
/*
Copyright 2012 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Google.Apis.Json;
using Google.Apis.Logging;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util;
namespace Google.Apis.Tests.Apis.Upload
{
class ResumableUploadTest
{
/// <summary>
/// Mock string to upload to the media server. It contains 453 bytes, and in most cases we will use a chunk
/// size of 100.
/// </summary>
static string UploadTestData = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit
anim id est laborum.";
public ResumableUploadTest()
{
// Change the false parameter to true if you want to enable logging during tests. (Not supported yet)
SetUp(false);
}
private void SetUp(bool useLogger)
{
if (useLogger)
{
// TODO(neil-119): Log4Net support
//ApplicationContext.RegisterLogger(new Google.Apis.Logging.Log4NetLogger());
ApplicationContext.RegisterLogger(new NullLogger());
}
}
#region Handlers
/// <summary>Base mock handler which contains the upload Uri.</summary>
private abstract class BaseMockMessageHandler : CountableMessageHandler
{
/// <summary>The upload Uri for uploading the media.</summary>
protected static Uri uploadUri = new Uri("http://upload.com");
}
/// <summary>A handler which handles uploading an empty file.</summary>
private class EmptyFileMessageHandler : BaseMockMessageHandler
{
protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage();
switch (Calls)
{
case 1:
// First call is initialization.
Assert.Equal(request.RequestUri.Query, Is.EqualTo("?uploadType=resumable"));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Type").First(), Is.EqualTo("text/plain"));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Length").First(), Is.EqualTo("0"));
response.Headers.Location = uploadUri;
break;
case 2:
// Receiving an empty stream.
Assert.Equal(request.RequestUri, Is.EqualTo(uploadUri));
var range = String.Format("bytes */0");
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(range));
Assert.Equal(request.Content.Headers.ContentLength, Is.EqualTo(0));
break;
}
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
}
/// <summary>A handler which handles a request object on the initialization request.</summary>
private class RequestResponseMessageHandler<TRequest> : BaseMockMessageHandler
{
/// <summary>
/// Gets or sets the expected request object. Server checks that the initialization request contains that
/// object in the request.
/// </summary>
public TRequest ExpectedRequest { get; set; }
/// <summary>
/// Gets or sets the expected response object which server returns as a response for the upload request.
/// </summary>
public object ExpectedResponse { get; set; }
/// <summary>Gets or sets the serializer which is used to serialize and deserialize objects.</summary>
public ISerializer Serializer { get; set; }
protected override async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage();
switch (Calls)
{
case 1:
{
// Initialization and receiving the request object.
Assert.Equal(request.RequestUri.Query, Is.EqualTo("?uploadType=resumable"));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Type").First(), Is.EqualTo("text/plain"));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Length").First(), Is.EqualTo(UploadTestData.Length.ToString()));
response.Headers.Location = uploadUri;
var body = await request.Content.ReadAsStringAsync();
var reqObject = Serializer.Deserialize<TRequest>(body);
Assert.Equal(reqObject, Is.EqualTo(ExpectedRequest));
break;
}
case 2:
{
// Check that the server received the media.
Assert.Equal(request.RequestUri, Is.EqualTo(uploadUri));
var range = String.Format("bytes 0-{0}/{1}", UploadTestData.Length - 1,
UploadTestData.Length);
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(range));
// Send the response-body.
var responseObject = Serializer.Serialize(ExpectedResponse);
response.Content = new StringContent(responseObject, Encoding.UTF8, "application/json");
break;
}
}
return response;
}
}
/// <summary>A handler which handles a request for single chunk.</summary>
private class SingleChunkMessageHandler : BaseMockMessageHandler
{
/// <summary>Gets or sets the expected stream length.</summary>
public long StreamLength { get; set; }
/// <summary>Gets or sets the query parameters which should be part of the initialize request.</summary>
public string QueryParameters { get; set; }
/// <summary>Gets or sets the path parameters which should be part of the initialize request.</summary>
public string PathParameters { get; set; }
protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage();
var range = string.Empty;
switch (Calls)
{
case 1:
if (PathParameters == null)
{
Assert.Equal(request.RequestUri.AbsolutePath, Is.EqualTo("/"));
}
else
{
Assert.Equal(request.RequestUri.AbsolutePath, Is.EqualTo("/" + PathParameters));
}
Assert.Equal(request.RequestUri.Query, Is.EqualTo("?uploadType=resumable" + QueryParameters));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Type").First(), Is.EqualTo("text/plain"));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Length").First(), Is.EqualTo(StreamLength.ToString()));
response.Headers.Location = uploadUri;
break;
case 2:
Assert.Equal(request.RequestUri, Is.EqualTo(uploadUri));
range = String.Format("bytes 0-{0}/{1}", StreamLength - 1, StreamLength);
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(range));
Assert.Equal(request.Content.Headers.ContentLength, Is.EqualTo(StreamLength));
break;
}
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
}
/// <summary>
/// A handler which demonstrate a server which reads partial data (e.g. on the first upload request the client
/// sends X bytes, but the server actually read only Y of them)
/// </summary>
private class ReadPartialMessageHandler : BaseMockMessageHandler
{
/// <summary>Received stream which contains the data that the server reads.</summary>
public MemoryStream ReceivedData = new MemoryStream();
private bool knownSize;
private int len;
private int chunkSize;
const int readInFirstRequest = 120;
/// <summary>
/// Constructs a new handler with the given stream length, chunkd size and indication if the length is
/// known.
/// </summary>
public ReadPartialMessageHandler(bool knownSize, int len, int chunkSize)
{
this.knownSize = knownSize;
this.len = len;
this.chunkSize = chunkSize;
}
protected override async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage();
byte[] bytes = null;
switch (Calls)
{
case 1:
// Initialization request.
Assert.Equal(request.RequestUri.Query, Is.EqualTo("?uploadType=resumable"));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Type").First(), Is.EqualTo("text/plain"));
if (knownSize)
{
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Length").First(), Is.EqualTo(UploadTestData.Length.ToString()));
}
else
{
Assert.False(request.Headers.Contains("X-Upload-Content-Length"));
}
response.Headers.Location = uploadUri;
break;
case 2:
// First client upload request. server reads only <c>readInFirstRequest</c> bytes and returns
// a response with Range header - "bytes 0-readInFirstRequest".
Assert.Equal(request.RequestUri, Is.EqualTo(uploadUri));
var range = String.Format("bytes {0}-{1}/{2}", 0, chunkSize - 1,
knownSize ? len.ToString() : "*");
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(range));
response.StatusCode = (HttpStatusCode)308;
response.Headers.Add("Range", "bytes 0-" + (readInFirstRequest - 1));
bytes = await request.Content.ReadAsByteArrayAsync();
ReceivedData.Write(bytes, 0, readInFirstRequest);
break;
case 3:
// Server reads the rest of bytes.
Assert.Equal(request.RequestUri, Is.EqualTo(uploadUri));
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(
string.Format("bytes {0}-{1}/{2}", readInFirstRequest, len - 1, len)));
bytes = await request.Content.ReadAsByteArrayAsync();
ReceivedData.Write(bytes, 0, bytes.Length);
break;
}
return response;
}
}
public enum ServerError
{
None,
Exception,
ServerUnavailable,
NotFound
}
/// <summary>A handler which demonstrate a client upload which contains multiple chunks.</summary>
private class MultipleChunksMessageHandler : BaseMockMessageHandler
{
public MemoryStream ReceivedData = new MemoryStream();
/// <summary>The cancellation token we are going to use to cancel a request.</summary>
public CancellationTokenSource CancellationTokenSource { get; set; }
/// <summary>The request index we are going to cancel.</summary>
public int CancelRequestNum { get; set; }
// On the 4th request - server returns error (if supportedError isn't none)
// On the 5th request - server returns 308 with "Range" header is "bytes 0-299" (depends on supportedError)
internal const int ErrorOnCall = 4;
// When we resuming an upload, there should be 3 more calls after the failures.
// Uploading 3 more chunks: 200-299, 300-399, 400-453.
internal const int CallAfterResume = 3;
/// <summary>
/// Gets or sets the number of bytes the server reads when error occurred. The default value is <c>0</c>,
/// meaning that on server error it won't read any bytes from the stream.
/// </summary>
public int ReadBytesOnError { get; set; }
private ServerError supportedError;
private bool knownSize;
private int len;
private int chunkSize;
private bool alwaysFailFromFirstError;
private int bytesRecieved = 0;
private string uploadSize;
/// <summary>Gets or sets the call number after resuming.</summary>
public int ResumeFromCall { get; set; }
/// <summary>Get or sets indication if the first call after resuming should fail or not.</summary>
public bool ErrorOnResume { get; set; }
public MultipleChunksMessageHandler(bool knownSize, ServerError supportedError, int len, int chunkSize,
bool alwaysFailFromFirstError = false)
{
this.knownSize = knownSize;
this.supportedError = supportedError;
this.len = len;
this.chunkSize = chunkSize;
this.alwaysFailFromFirstError = alwaysFailFromFirstError;
uploadSize = knownSize ? UploadTestData.Length.ToString() : "*";
}
protected override async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (Calls == CancelRequestNum && CancellationTokenSource != null)
{
CancellationTokenSource.Cancel();
}
var response = new HttpResponseMessage();
if (Calls == 1)
{
// Initialization request.
Assert.Equal(request.RequestUri.Query, Is.EqualTo("?uploadType=resumable"));
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Type").First(), Is.EqualTo("text/plain"));
if (knownSize)
{
Assert.Equal(request.Headers.GetValues("X-Upload-Content-Length").First(), Is.EqualTo(UploadTestData.Length.ToString()));
}
else
{
Assert.False(request.Headers.Contains("X-Upload-Content-Length"));
}
response.Headers.Location = uploadUri;
}
else
{
Assert.Equal(request.RequestUri, Is.EqualTo(uploadUri));
var chunkEnd = Math.Min(len, bytesRecieved + chunkSize) - 1;
if (chunkEnd == len - 1)
{
uploadSize = UploadTestData.Length.ToString();
}
var range = String.Format("bytes {0}-{1}/{2}", bytesRecieved, chunkEnd,
chunkEnd + 1 == len || knownSize ? UploadTestData.Length.ToString() : uploadSize);
if (Calls == ErrorOnCall && supportedError != ServerError.None)
{
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(range));
if (supportedError == ServerError.ServerUnavailable)
{
response.StatusCode = HttpStatusCode.ServiceUnavailable;
}
else if (supportedError == ServerError.NotFound)
{
response.StatusCode = HttpStatusCode.NotFound;
var error = @"{
""error"": {
""errors"": [
{
""domain"": ""global"",
""reason"": ""required"",
""message"": ""Login Required"",
""locationType"": ""header"",
""location"": ""Authorization""
}
],
""code"": 401,
""message"": ""Login Required""
}
}";
response.Content = new StringContent(error);
}
else
{
throw new Exception("ERROR");
}
var bytes = await request.Content.ReadAsByteArrayAsync();
var read = Math.Min(ReadBytesOnError, bytes.Length);
ReceivedData.Write(bytes, 0, read);
bytesRecieved += read;
}
else if ((Calls >= ErrorOnCall && alwaysFailFromFirstError && ResumeFromCall == 0) ||
(Calls == ResumeFromCall && ErrorOnResume))
{
if (supportedError == ServerError.Exception)
{
throw new Exception("ERROR");
}
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(
string.Format(@"bytes */{0}", uploadSize)));
response.StatusCode = HttpStatusCode.ServiceUnavailable;
}
else if ((Calls == ErrorOnCall + 1 && supportedError != ServerError.None) ||
(Calls == ResumeFromCall && !ErrorOnResume) ||
(Calls == ResumeFromCall + 1 && ErrorOnResume))
{
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(
string.Format(@"bytes */{0}", uploadSize)));
if (bytesRecieved != len)
{
response.StatusCode = (HttpStatusCode)308;
}
response.Headers.Add("Range", "bytes 0-" + (bytesRecieved - 1));
}
else
{
var bytes = await request.Content.ReadAsByteArrayAsync();
ReceivedData.Write(bytes, 0, bytes.Length);
bytesRecieved += bytes.Length;
Assert.Equal(request.Content.Headers.GetValues("Content-Range").First(), Is.EqualTo(range));
if (bytesRecieved != len)
{
response.StatusCode = (HttpStatusCode)308;
response.Headers.Add("Range", string.Format("bytes {0}-{1}", bytesRecieved, chunkEnd));
}
}
}
return response;
}
}
#endregion
#region ResumableUpload instances
private class MockResumableUpload : ResumableUpload<object>
{
public MockResumableUpload(IClientService service, Stream stream, string contentType)
: this(service, "path", "PUT", stream, contentType) { }
public MockResumableUpload(IClientService service, string path, string method, Stream stream,
string contentType)
: base(service, path, method, stream, contentType) { }
}
/// <summary>
/// A resumable upload class which gets a specific request object and returns a specific response object.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
private class MockResumableUploadWithResponse<TRequest, TResponse> : ResumableUpload<TRequest, TResponse>
{
public MockResumableUploadWithResponse(IClientService service,
Stream stream, string contentType)
: base(service, "path", "POST", stream, contentType) { }
}
/// <summary>A resumable upload class which contains query and path parameters.</summary>
private class MockResumableWithParameters : ResumableUpload<object>
{
public MockResumableWithParameters(IClientService service, string path, string method,
Stream stream, string contentType)
: base(service, path, method, stream, contentType)
{
}
[Google.Apis.Util.RequestParameter("id", RequestParameterType.Path)]
public int Id { get; set; }
[Google.Apis.Util.RequestParameter("queryA", RequestParameterType.Query)]
public string QueryA { get; set; }
[Google.Apis.Util.RequestParameter("queryB", RequestParameterType.Query)]
public string QueryB { get; set; }
[Google.Apis.Util.RequestParameter("time", RequestParameterType.Query)]
public DateTime? MinTime { get; set; }
}
#endregion
/// <summary>Mimics a stream whose size is unknown.</summary>
private class UnknownSizeMemoryStream : MemoryStream
{
public UnknownSizeMemoryStream(byte[] buffer) : base(buffer) { }
public override bool CanSeek
{
get { return false; }
}
}
#region Request and Response objects
/// <summary>A mock request object.</summary>
public class TestRequest : IEquatable<TestRequest>
{
public string Name { get; set; }
public string Description { get; set; }
public bool Equals(TestRequest other)
{
if (other == null)
return false;
return Name == null ? other.Name == null : Name.Equals(other.Name) &&
Description == null ? other.Description == null : Description.Equals(other.Description);
}
}
/// <summary>A mock response object.</summary>
public class TestResponse : IEquatable<TestResponse>
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Equals(TestResponse other)
{
if (other == null)
return false;
return Id.Equals(other.Id) &&
Name == null ? other.Name == null : Name.Equals(other.Name) &&
Description == null ? other.Description == null : Description.Equals(other.Description);
}
}
#endregion
/// <summary>Tests uploading a single chunk.</summary>
[Fact]
public void TestUploadSingleChunk()
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(UploadTestData));
var handler = new SingleChunkMessageHandler()
{
StreamLength = stream.Length
};
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var upload = new MockResumableUpload(service, "", "POST", stream, "text/plain");
// Chunk size is bigger than the data we are sending.
upload.chunkSize = UploadTestData.Length + 10;
upload.Upload();
}
Assert.Equal(handler.Calls, Is.EqualTo(2));
}
/// <summary>Tests uploading a single chunk.</summary>
[Fact]
public void TestUploadSingleChunk_ExactChunkSize()
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(UploadTestData));
var handler = new SingleChunkMessageHandler()
{
StreamLength = stream.Length
};
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var upload = new MockResumableUpload(service, "", "POST", stream, "text/plain");
// Chunk size is the exact size we are sending.
upload.chunkSize = UploadTestData.Length;
upload.Upload();
}
Assert.Equal(handler.Calls, Is.EqualTo(2));
}
/// <summary>Tests uploading empty file.</summary>
[Fact]
public void TestUploadEmptyFile()
{
var handler = new EmptyFileMessageHandler();
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var stream = new MemoryStream(new byte[0]);
var upload = new MockResumableUpload(service, stream, "text/plain");
upload.Upload();
}
Assert.Equal(handler.Calls, Is.EqualTo(2));
}
/// <summary>
/// Tests that the upload client accepts 308 responses when uploading chunks on a stream with known size.
/// </summary>
[Fact]
public void TestChunkUpload_KnownSize()
{
// We expect 6 calls: 1 initial request + 5 chunks (0-99, 100-199, 200-299, 300-399, 400-453).
SubtestTestChunkUpload(true, 6);
}
/// <summary>
/// Tests that the upload client accepts 308 responses when uploading chunks on a stream with unknown size.
/// </summary>
[Fact]
public void TestChunkUpload_UnknownSize()
{
// We expect 6 calls: 1 initial request + 5 chunks (0-99, 100-199, 200-299, 300-399, 400-453).
SubtestTestChunkUpload(false, 6);
}
/// <summary>
/// Tests that client accepts 308 and 503 responses when uploading chunks when the stream size is known.
/// </summary>
[Fact]
public void TestChunkUpload_ServerUnavailable_KnownSize()
{
SubtestChunkUpload_ServerUnavailable(true);
}
/// <summary>
/// Tests that client accepts 308 and 503 responses when uploading chunks when the stream size is unknown.
/// </summary>
[Fact]
public void TestChunkUpload_ServerUnavailable_UnknownSize()
{
SubtestChunkUpload_ServerUnavailable(false);
}
/// <summary>
/// A helper test which tests that the client accepts 308 and 503 responses when uploading chunks. This test
/// contains sub tests which check the different possibilities:
/// <list type="number">
/// <item><description>Server didn't read any bytes when it sends back 503</description></item>
/// <item><description>Server read partial bytes from stream when it sends back 503</description></item>
/// <item><description>Server read all bytes from stream when it sends back 503</description></item>
/// </list>
/// </summary>
private void SubtestChunkUpload_ServerUnavailable(bool knownSize)
{
// Server didn't receive any bytes from chunk 4
// we expect 6 calls: 1 initial request + 1 call to query the range + 6 chunks (0-99, 100-199, 200-299,
// 200-299, 300-399, 400-453)
SubtestTestChunkUpload(knownSize, 8, ServerError.ServerUnavailable);
// Server received all bytes from chunk 4
// we expect 7 calls: 1 initial request + 1 call to query the range + 5 chunks (0-99, 100-199, 200-299,
// 300-399, 400-453)
SubtestTestChunkUpload(knownSize, 7, ServerError.ServerUnavailable, 100, 100);
// Server received partial bytes from chunk 4
// we expect 12 calls: 1 initial request + 1 call to query the range + 10 chunks (0-49, 50-99, 100-149,
// 110-159, 160-209, 210-259, 260-309, 310-359, 360-409, 410-453
SubtestTestChunkUpload(knownSize, 12, ServerError.ServerUnavailable, 50, 10);
// Server received partial bytes from chunk 4
// we expect 12 calls: 1 initial request + 1 call to query the range + 11 chunks (0-49, 50-99, 100-149,
// 101-150, 151-200, 201-250, 251-300, 301-350, 351-400, 401-450, 451-453
SubtestTestChunkUpload(knownSize, 13, ServerError.ServerUnavailable, 50, 1);
// Server received partial bytes from chunk 4 (the final chunk the client sent)
// we expect 6 calls: 1 initial request + 1 call to query the range + 4 chunks (0-199, 200-399, 400-453,
// 410-453)
SubtestTestChunkUpload(knownSize, 6, ServerError.ServerUnavailable, 200, 10);
// Server received partial bytes from chunk 4 (the final chunk the client sent)
// we expect 5 calls: 1 initial request + 1 call to query the range + 3 chunks (0-199, 200-399, 400-453).
// In the final chunk, although the client received 503, the server read all the bytes.
SubtestTestChunkUpload(knownSize, 5, ServerError.ServerUnavailable, 200, 54);
}
/// <summary>
/// Tests that the upload client accepts 308 and exception on a request when uploading chunks on a stream with
/// unknown size.
/// </summary>
[Fact]
public void TestChunkUpload_Exception_UnknownSize()
{
// we expect 6 calls: 1 initial request + 1 call to query the range + 6 chunks (0-99, 100-199, 200-299,
// 200-299, 300-399, 400-453)
SubtestTestChunkUpload(false, 8, ServerError.Exception);
}
/// <summary>
/// Tests that upload fails when server returns an error which the client can't handle (not 5xx).
/// </summary>
[Fact]
public void TestChunkUpload_NotFound_KnownSize()
{
// we expect 4 calls: 1 initial request + 3 chunks (0-99, 100-199, 200-299) [on the 3rd chunk, the client
// receives 4xx error. The client can't recover from it, so the upload stops
SubtestTestChunkUpload(true, 4, ServerError.NotFound);
}
/// <summary>Tests a single upload request.</summary>
/// <param name="knownSize">Defines if the stream size is known</param>
/// <param name="expectedCalls">How many HTTP calls should be made to the server</param>
/// <param name="error">Defines the type of error this test tests. The default value is none</param>
/// <param name="chunkSize">Defines the size of a chunk</param>
/// <param name="readBytesOnError">How many bytes the server reads when it returns 5xx</param>
private void SubtestTestChunkUpload(bool knownSize, int expectedCalls, ServerError error = ServerError.None,
int chunkSize = 100, int readBytesOnError = 0)
{
// If an error isn't supported by the media upload (4xx) - the upload fails.
// Otherwise, we simulate server 503 error or exception, as following:
// On the 3th chunk (4th chunk including the initial request), we mimic an error.
// In the next request we expect the client to send the content range header with "bytes */[size]", and
// server return that the upload was interrupted after x bytes.
// From that point the server works as expected, and received the last chunks successfully
var payload = Encoding.UTF8.GetBytes(UploadTestData);
var handler = new MultipleChunksMessageHandler(knownSize, error, payload.Length, chunkSize);
handler.ReadBytesOnError = readBytesOnError;
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var stream = knownSize ? new MemoryStream(payload) : new UnknownSizeMemoryStream(payload);
var upload = new MockResumableUpload(service, stream, "text/plain");
upload.chunkSize = chunkSize;
IUploadProgress lastProgress = null;
upload.ProgressChanged += (p) => lastProgress = p;
upload.Upload();
Assert.NotNull(lastProgress);
if (error == ServerError.NotFound)
{
// Upload fails.
Assert.Equal(lastProgress.Status, Is.EqualTo(UploadStatus.Failed));
Assert.True(lastProgress.Exception.Message.Contains(
@"Message[Login Required] Location[Authorization - header] Reason[required] Domain[global]"),
"Error message is invalid");
}
else
{
Assert.Equal(lastProgress.Status, Is.EqualTo(UploadStatus.Completed));
Assert.Equal(payload, Is.EqualTo(handler.ReceivedData.ToArray()));
}
Assert.Equal(handler.Calls, Is.EqualTo(expectedCalls));
}
}
/// <summary>
/// Tests that the upload client accepts 308 responses and reads the "Range" header to know from which point to
/// continue (stream size is known).
/// </summary>
[Fact]
public void TestChunkUpload_ServerRecievedPartOfRequest_KnownSize()
{
SubtestTestChunkUpload_ServerRecievedPartOfRequest(true);
}
/// <summary>
/// Tests that the upload client accepts 308 responses and reads the "Range" header to know from which point to
/// continue (stream size is unknown).
/// </summary>
[Fact]
public void TestChunkUpload_ServerRecievedPartOfRequest_UnknownSize()
{
SubtestTestChunkUpload_ServerRecievedPartOfRequest(false);
}
private void SubtestTestChunkUpload_ServerRecievedPartOfRequest(bool knownSize)
{
int chunkSize = 400;
var payload = Encoding.UTF8.GetBytes(UploadTestData);
var handler = new ReadPartialMessageHandler(knownSize, payload.Length, chunkSize);
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var stream = knownSize ? new MemoryStream(payload) : new UnknownSizeMemoryStream(payload);
var upload = new MockResumableUpload(service, stream, "text/plain");
upload.chunkSize = chunkSize;
upload.Upload();
Assert.Equal(payload, Is.EqualTo(handler.ReceivedData.ToArray()));
// 1 initialization request and 2 uploads requests.
Assert.Equal(handler.Calls, Is.EqualTo(3));
}
}
/// <summary>Test helper to test a fail uploading by with the given server error.</summary>
/// <param name="error">The error kind.</param>
/// <param name="resume">Whether we should resume uploading the stream after the failure.</param>
/// <param name="errorOnResume">Whether the first call after resuming should fail.</param>
private void SubtestChunkUploadFail(ServerError error, bool resume = false, bool errorOnResume = false)
{
int chunkSize = 100;
var payload = Encoding.UTF8.GetBytes(UploadTestData);
var handler = new MultipleChunksMessageHandler(true, error, payload.Length, chunkSize, true);
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var stream = new MemoryStream(payload);
var upload = new MockResumableUpload(service, stream, "text/plain");
upload.chunkSize = chunkSize;
IUploadProgress lastProgressStatus = null;
upload.ProgressChanged += (p) =>
{
lastProgressStatus = p;
};
upload.Upload();
// Upload should fail.
var exepctedCalls = MultipleChunksMessageHandler.ErrorOnCall +
service.HttpClient.MessageHandler.NumTries - 1;
Assert.Equal(handler.Calls, Is.EqualTo(exepctedCalls));
Assert.NotNull(lastProgressStatus);
Assert.NotNull(lastProgressStatus.Exception);
Assert.Equal(lastProgressStatus.Status, Is.EqualTo(UploadStatus.Failed));
if (resume)
{
// Hack the handler, so when calling the resume method the upload should succeeded.
handler.ResumeFromCall = exepctedCalls + 1;
handler.ErrorOnResume = errorOnResume;
upload.Resume();
// The first request after resuming is to query the server where the media upload was interrupted.
// If errorOnResume is true, the server's first response will be 503.
exepctedCalls += MultipleChunksMessageHandler.CallAfterResume + 1 + (errorOnResume ? 1 : 0);
Assert.Equal(handler.Calls, Is.EqualTo(exepctedCalls));
Assert.NotNull(lastProgressStatus);
Assert.Null(lastProgressStatus.Exception);
Assert.Equal(lastProgressStatus.Status, Is.EqualTo(UploadStatus.Completed));
Assert.Equal(payload, Is.EqualTo(handler.ReceivedData.ToArray()));
}
}
}
/// <summary>
/// Tests failed uploading media (server returns 5xx responses all the time from some request).
/// </summary>
[Fact]
public void TestChunkUploadFail_ServerUnavailable()
{
SubtestChunkUploadFail(ServerError.ServerUnavailable);
}
/// <summary>Tests the resume method.</summary>
[Fact]
public void TestResumeAfterFail()
{
SubtestChunkUploadFail(ServerError.ServerUnavailable, true);
}
/// <summary>Tests the resume method. The first call after resuming returns server unavailable.</summary>
[Fact]
public void TestResumeAfterFail_FirstCallAfterResumeIsServerUnavailable()
{
SubtestChunkUploadFail(ServerError.ServerUnavailable, true, true);
}
/// <summary>Tests failed uploading media (exception is thrown all the time from some request).</summary>
[Fact]
public void TestChunkUploadFail_Exception()
{
SubtestChunkUploadFail(ServerError.Exception);
}
/// <summary>Tests uploading media when canceling a request in the middle.</summary>
[Fact]
public void TestChunkUploadFail_Cancel()
{
TestChunkUploadFail_Cancel(1); // Cancel the request initialization
TestChunkUploadFail_Cancel(2); // Cancel the first media upload data
TestChunkUploadFail_Cancel(5); // Cancel a request in the middle of the upload
}
/// <summary>Helper test to test canceling media upload in the middle.</summary>
/// <param name="cancelRequest">The request index to cancel.</param>
private void TestChunkUploadFail_Cancel(int cancelRequest)
{
int chunkSize = 100;
var payload = Encoding.UTF8.GetBytes(UploadTestData);
var handler = new MultipleChunksMessageHandler(true, ServerError.None, payload.Length, chunkSize, false);
handler.CancellationTokenSource = new CancellationTokenSource();
handler.CancelRequestNum = cancelRequest;
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var stream = new MemoryStream(payload);
var upload = new MockResumableUpload(service, stream, "text/plain");
upload.chunkSize = chunkSize;
try
{
var result = upload.UploadAsync(handler.CancellationTokenSource.Token).Result;
Assert.True(false, "Upload should be canceled");
}
catch (AggregateException ex)
{
Assert.IsType<TaskCanceledException>(ex.InnerException);
}
Assert.Equal(handler.Calls, Is.EqualTo(cancelRequest));
}
}
/// <summary>Tests that upload function fires progress events as expected.</summary>
[Fact]
public void TestUploadProgress()
{
int chunkSize = 200;
var payload = Encoding.UTF8.GetBytes(UploadTestData);
var handler = new MultipleChunksMessageHandler(true, ServerError.None, payload.Length, chunkSize);
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var stream = new MemoryStream(payload);
var upload = new MockResumableUpload(service, stream, "text/plain");
upload.chunkSize = chunkSize;
var progressEvents = new List<IUploadProgress>();
upload.ProgressChanged += (progress) =>
{
progressEvents.Add(progress);
};
upload.Upload();
// Starting (1) + Uploading (2) + Completed (1).
Assert.Equal(progressEvents.Count, Is.EqualTo(4));
Assert.Equal(progressEvents[0].Status, Is.EqualTo(UploadStatus.Starting));
Assert.Equal(progressEvents[1].Status, Is.EqualTo(UploadStatus.Uploading));
Assert.Equal(progressEvents[2].Status, Is.EqualTo(UploadStatus.Uploading));
Assert.Equal(progressEvents[3].Status, Is.EqualTo(UploadStatus.Completed));
}
}
/// <summary>Tests uploading media with query and path parameters on the initialization request.</summary>
[Fact]
public void TestUploadWithQueryAndPathParameters()
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(UploadTestData));
const int id = 123;
var handler = new SingleChunkMessageHandler()
{
PathParameters = "testPath/" + id.ToString(),
QueryParameters = "&queryA=valuea&queryB=VALUEB&time=2002-02-25T12%3A57%3A32.777Z",
StreamLength = stream.Length
};
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler)
}))
{
var upload = new MockResumableWithParameters(service, "testPath/{id}", "POST", stream, "text/plain")
{
Id = id,
QueryA = "valuea",
QueryB = "VALUEB",
MinTime = new DateTime(2002, 2, 25, 12, 57, 32, 777, DateTimeKind.Utc)
};
upload.Upload();
Assert.Equal(handler.Calls, Is.EqualTo(2));
}
}
/// <summary>Tests an upload with JSON request and response body.</summary>
[Fact]
public void TestUploadWithRequestAndResponseBody()
{
var body = new TestRequest()
{
Name = "test object",
Description = "the description",
};
var handler = new RequestResponseMessageHandler<TestRequest>()
{
ExpectedRequest = body,
ExpectedResponse = new TestResponse
{
Name = "foo",
Id = 100,
Description = "bar",
},
Serializer = new NewtonsoftJsonSerializer()
};
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(handler),
GZipEnabled = false // TODO(peleyal): test with GZipEnabled as well
}))
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(UploadTestData));
var upload = new MockResumableUploadWithResponse<TestRequest, TestResponse>
(service, stream, "text/plain")
{
Body = body
};
TestResponse response = null;
int reponseReceivedCount = 0;
upload.ResponseReceived += (r) => { response = r; reponseReceivedCount++; };
upload.Upload();
Assert.Equal(upload.ResponseBody, Is.EqualTo(handler.ExpectedResponse));
Assert.Equal(reponseReceivedCount, Is.EqualTo(1));
Assert.Equal(handler.Calls, Is.EqualTo(2));
}
}
/// <summary>Tests chunk size setter.</summary>
[Fact]
public void TestChunkSize()
{
using (var service = new MockClientService(new BaseClientService.Initializer()))
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(UploadTestData));
var upload = new MockResumableUploadWithResponse<TestRequest, TestResponse>
(service, stream, "text/plain");
// Negative chunk size.
try
{
upload.ChunkSize = -1;
Assert.True(false);
}
catch (ArgumentOutOfRangeException)
{
// Expected.
}
// Less than the minimum.
try
{
upload.ChunkSize = MockResumableUpload.MinimumChunkSize - 1;
Assert.True(false);
}
catch (ArgumentOutOfRangeException)
{
// Expected.
}
// Valid chunk size.
upload.ChunkSize = MockResumableUpload.MinimumChunkSize;
upload.ChunkSize = MockResumableUpload.MinimumChunkSize * 2;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace MongoDB.Messaging.Logging
{
/// <summary>
/// A logger class for starting log messages.
/// </summary>
public sealed class Logger : ILogger
{
private static ILogWriter _logWriter;
private static readonly ObjectPool<LogBuilder> _objectPool;
// only create if used
#if !PORTABLE
private static readonly Lazy<IPropertyContext> _asyncProperties;
private static readonly ThreadLocal<IPropertyContext> _threadProperties;
#endif
private static readonly Lazy<IPropertyContext> _globalProperties;
private readonly Lazy<IPropertyContext> _properties;
/// <summary>
/// Initializes the <see cref="Logger"/> class.
/// </summary>
static Logger()
{
_globalProperties = new Lazy<IPropertyContext>(CreateGlobal);
#if !PORTABLE
_threadProperties = new ThreadLocal<IPropertyContext>(CreateLocal);
_asyncProperties = new Lazy<IPropertyContext>(CreateAsync);
_logWriter = new TraceLogWriter();
#else
_logWriter = new DelegateLogWriter();
#endif
_objectPool = new ObjectPool<LogBuilder>(() => new LogBuilder(_logWriter, _objectPool), 25);
}
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class.
/// </summary>
public Logger()
{
_properties = new Lazy<IPropertyContext>(() => new PropertyContext());
}
/// <summary>
/// Gets the global property context. All values are copied to each log on write.
/// </summary>
/// <value>
/// The global property context.
/// </value>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static IPropertyContext GlobalProperties
{
get { return _globalProperties.Value; }
}
#if !PORTABLE
/// <summary>
/// Gets the thread-local property context. All values are copied to each log on write.
/// </summary>
/// <value>
/// The thread-local property context.
/// </value>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static IPropertyContext ThreadProperties
{
get { return _threadProperties.Value; }
}
/// <summary>
/// Gets the property context that maintains state across asynchronous tasks and call contexts. All values are copied to each log on write.
/// </summary>
/// <value>
/// The asynchronous property context.
/// </value>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static IPropertyContext AsyncProperties
{
get { return _asyncProperties.Value; }
}
#endif
/// <summary>
/// Gets the logger initial default properties. All values are copied to each log.
/// </summary>
/// <value>
/// The logger initial default properties.
/// </value>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public IPropertyContext Properties
{
get { return _properties.Value; }
}
/// <summary>
/// Gets the logger name.
/// </summary>
/// <value>
/// The logger name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Start a fluent <see cref="LogBuilder" /> with the specified <see cref="LogLevel" />.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>
/// A fluent Logger instance.
/// </returns>
public static ILogBuilder Log(LogLevel logLevel, [CallerFilePath]string callerFilePath = null)
{
return CreateBuilder(logLevel, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogBuilder" /> with the specified <see cref="LogLevel" />.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Log(LogLevel logLevel)
{
return CreateBuilder(logLevel);
}
/// <summary>
/// Start a fluent <see cref="LogBuilder" /> with the computed <see cref="LogLevel" />.
/// </summary>
/// <param name="logLevelFactory">The log level factory.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>
/// A fluent Logger instance.
/// </returns>
public static ILogBuilder Log(Func<LogLevel> logLevelFactory, [CallerFilePath]string callerFilePath = null)
{
var logLevel = (logLevelFactory != null)
? logLevelFactory()
: LogLevel.Debug;
return CreateBuilder(logLevel, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogBuilder" /> with the computed <see cref="LogLevel" />.
/// </summary>
/// <param name="logLevelFactory">The log level factory.</param>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Log(Func<LogLevel> logLevelFactory)
{
var logLevel = (logLevelFactory != null)
? logLevelFactory()
: LogLevel.Debug;
return CreateBuilder(logLevel);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Trace"/> logger.
/// </summary>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>A fluent Logger instance.</returns>
public static ILogBuilder Trace([CallerFilePath]string callerFilePath = null)
{
return CreateBuilder(LogLevel.Trace, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Trace" /> logger.
/// </summary>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Trace()
{
return CreateBuilder(LogLevel.Trace);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Debug"/> logger.
/// </summary>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>A fluent Logger instance.</returns>
public static ILogBuilder Debug([CallerFilePath]string callerFilePath = null)
{
return CreateBuilder(LogLevel.Debug, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Debug" /> logger.
/// </summary>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Debug()
{
return CreateBuilder(LogLevel.Debug);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Info"/> logger.
/// </summary>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>A fluent Logger instance.</returns>
public static ILogBuilder Info([CallerFilePath]string callerFilePath = null)
{
return CreateBuilder(LogLevel.Info, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Info" /> logger.
/// </summary>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Info()
{
return CreateBuilder(LogLevel.Info);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Warn"/> logger.
/// </summary>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>A fluent Logger instance.</returns>
public static ILogBuilder Warn([CallerFilePath]string callerFilePath = null)
{
return CreateBuilder(LogLevel.Warn, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Warn" /> logger.
/// </summary>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Warn()
{
return CreateBuilder(LogLevel.Warn);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Error"/> logger.
/// </summary>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>A fluent Logger instance.</returns>
public static ILogBuilder Error([CallerFilePath]string callerFilePath = null)
{
return CreateBuilder(LogLevel.Error, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Error" /> logger.
/// </summary>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Error()
{
return CreateBuilder(LogLevel.Error);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Fatal"/> logger.
/// </summary>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param>
/// <returns>A fluent Logger instance.</returns>
public static ILogBuilder Fatal([CallerFilePath]string callerFilePath = null)
{
return CreateBuilder(LogLevel.Fatal, callerFilePath);
}
/// <summary>
/// Start a fluent <see cref="LogLevel.Fatal" /> logger.
/// </summary>
/// <returns>
/// A fluent Logger instance.
/// </returns>
ILogBuilder ILogger.Fatal()
{
return CreateBuilder(LogLevel.Fatal);
}
/// <summary>
/// Registers a <see langword="delegate"/> to write logs to.
/// </summary>
/// <param name="writer">The <see langword="delegate"/> to write logs to.</param>
public static void RegisterWriter(Action<LogData> writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
var logWriter = new DelegateLogWriter(writer);
RegisterWriter(logWriter);
}
/// <summary>
/// Registers a ILogWriter to write logs to.
/// </summary>
/// <param name="writer">The ILogWriter to write logs to.</param>
public static void RegisterWriter<TWriter>(TWriter writer)
where TWriter : ILogWriter
{
if (writer == null)
throw new ArgumentNullException("writer");
if (writer.Equals(_logWriter))
return;
var current = _logWriter;
if (Interlocked.CompareExchange(ref _logWriter, writer, current) != current)
return;
// clear object pool
_objectPool.Clear();
}
/// <summary>
/// Creates a new <see cref="ILogger"/> using the specified fluent <paramref name="builder"/> action.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static ILogger CreateLogger(Action<LoggerCreateBuilder> builder)
{
var factory = new Logger();
var factoryBuilder = new LoggerCreateBuilder(factory);
builder(factoryBuilder);
return factory;
}
/// <summary>
/// Creates a new <see cref="ILogger"/> using the caller file name as the logger name.
/// </summary>
/// <returns></returns>
public static ILogger CreateLogger([CallerFilePath]string callerFilePath = null)
{
return new Logger { Name = GetName(callerFilePath) };
}
/// <summary>
/// Creates a new <see cref="ILogger" /> using the specified type as the logger name.
/// </summary>
/// <param name="type">The type to use as the logger name.</param>
/// <returns></returns>
public static ILogger CreateLogger(Type type)
{
return new Logger { Name = type.FullName };
}
/// <summary>
/// Creates a new <see cref="ILogger" /> using the specified type as the logger name.
/// </summary>
/// <typeparam name="T">The type to use as the logger name.</typeparam>
/// <returns></returns>
public static ILogger CreateLogger<T>()
{
return CreateLogger(typeof(T));
}
private static ILogBuilder CreateBuilder(LogLevel logLevel, string callerFilePath)
{
string name = GetName(callerFilePath);
var builder = _objectPool.Allocate();
builder
.Reset()
.Level(logLevel)
.Logger(name);
MergeProperties(builder);
return builder;
}
private ILogBuilder CreateBuilder(LogLevel logLevel)
{
var builder = _objectPool.Allocate();
builder
.Reset()
.Level(logLevel);
MergeProperties(builder);
MergeDefaults(builder);
return builder;
}
private static string GetName(string path)
{
path = GetFileName(path);
if (path == null)
return null;
int i;
if ((i = path.LastIndexOf('.')) != -1)
return path.Substring(0, i);
return path;
}
private static string GetFileName(string path)
{
if (path == null)
return path;
int length = path.Length;
for (int i = length; --i >= 0;)
{
char ch = path[i];
if (ch == '\\' || ch == '/' || ch == ':')
return path.Substring(i + 1, length - i - 1);
}
return path;
}
#if !PORTABLE
private static IPropertyContext CreateAsync()
{
var propertyContext = new AsynchronousContext();
return propertyContext;
}
private static IPropertyContext CreateLocal()
{
var propertyContext = new PropertyContext();
propertyContext.Set("ThreadId", Thread.CurrentThread.ManagedThreadId);
return propertyContext;
}
#endif
private static IPropertyContext CreateGlobal()
{
var propertyContext = new PropertyContext();
#if !PORTABLE
propertyContext.Set("MachineName", Environment.MachineName);
#endif
return propertyContext;
}
private static void MergeProperties(ILogBuilder builder)
{
// copy global properties to current builder only if it has been created
if (_globalProperties.IsValueCreated)
_globalProperties.Value.Apply(builder);
#if !PORTABLE
// copy thread-local properties to current builder only if it has been created
if (_threadProperties.IsValueCreated)
_threadProperties.Value.Apply(builder);
// copy async properties to current builder only if it has been created
if (_asyncProperties.IsValueCreated)
_asyncProperties.Value.Apply(builder);
#endif
}
private ILogBuilder MergeDefaults(ILogBuilder builder)
{
// copy logger name
if (!String.IsNullOrEmpty(Name))
builder.Logger(Name);
// copy properties to current builder
if (_properties.IsValueCreated)
_properties.Value.Apply(builder);
return builder;
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticBeanstalk.Model
{
/// <summary>
/// Container for the parameters to the DescribeEvents operation.
/// <para>Returns list of event descriptions matching criteria up to the last 6 weeks.</para> <para><b>NOTE:</b> This action returns the most
/// recent 1,000 events from the specified NextToken. </para>
/// </summary>
/// <seealso cref="Amazon.ElasticBeanstalk.AmazonElasticBeanstalk.DescribeEvents"/>
public class DescribeEventsRequest : AmazonWebServiceRequest
{
private string applicationName;
private string versionLabel;
private string templateName;
private string environmentId;
private string environmentName;
private string requestId;
private string severity;
private DateTime? startTime;
private DateTime? endTime;
private int? maxRecords;
private string nextToken;
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only those associated with this application.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ApplicationName
{
get { return this.applicationName; }
set { this.applicationName = value; }
}
/// <summary>
/// Sets the ApplicationName property
/// </summary>
/// <param name="applicationName">The value to set for the ApplicationName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithApplicationName(string applicationName)
{
this.applicationName = applicationName;
return this;
}
// Check to see if ApplicationName property is set
internal bool IsSetApplicationName()
{
return this.applicationName != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this application version.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string VersionLabel
{
get { return this.versionLabel; }
set { this.versionLabel = value; }
}
/// <summary>
/// Sets the VersionLabel property
/// </summary>
/// <param name="versionLabel">The value to set for the VersionLabel property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithVersionLabel(string versionLabel)
{
this.versionLabel = versionLabel;
return this;
}
// Check to see if VersionLabel property is set
internal bool IsSetVersionLabel()
{
return this.versionLabel != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that are associated with this environment configuration.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string TemplateName
{
get { return this.templateName; }
set { this.templateName = value; }
}
/// <summary>
/// Sets the TemplateName property
/// </summary>
/// <param name="templateName">The value to set for the TemplateName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithTemplateName(string templateName)
{
this.templateName = templateName;
return this;
}
// Check to see if TemplateName property is set
internal bool IsSetTemplateName()
{
return this.templateName != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this environment.
///
/// </summary>
public string EnvironmentId
{
get { return this.environmentId; }
set { this.environmentId = value; }
}
/// <summary>
/// Sets the EnvironmentId property
/// </summary>
/// <param name="environmentId">The value to set for the EnvironmentId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithEnvironmentId(string environmentId)
{
this.environmentId = environmentId;
return this;
}
// Check to see if EnvironmentId property is set
internal bool IsSetEnvironmentId()
{
return this.environmentId != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this environment.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>4 - 23</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string EnvironmentName
{
get { return this.environmentName; }
set { this.environmentName = value; }
}
/// <summary>
/// Sets the EnvironmentName property
/// </summary>
/// <param name="environmentName">The value to set for the EnvironmentName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithEnvironmentName(string environmentName)
{
this.environmentName = environmentName;
return this;
}
// Check to see if EnvironmentName property is set
internal bool IsSetEnvironmentName()
{
return this.environmentName != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the described events to include only those associated with this request ID.
///
/// </summary>
public string RequestId
{
get { return this.requestId; }
set { this.requestId = value; }
}
/// <summary>
/// Sets the RequestId property
/// </summary>
/// <param name="requestId">The value to set for the RequestId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithRequestId(string requestId)
{
this.requestId = requestId;
return this;
}
// Check to see if RequestId property is set
internal bool IsSetRequestId()
{
return this.requestId != null;
}
/// <summary>
/// If specified, limits the events returned from this call to include only those with the specified severity or higher.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>TRACE, DEBUG, INFO, WARN, ERROR, FATAL</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Severity
{
get { return this.severity; }
set { this.severity = value; }
}
/// <summary>
/// Sets the Severity property
/// </summary>
/// <param name="severity">The value to set for the Severity property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithSeverity(string severity)
{
this.severity = severity;
return this;
}
// Check to see if Severity property is set
internal bool IsSetSeverity()
{
return this.severity != null;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that occur on or after this time.
///
/// </summary>
public DateTime StartTime
{
get { return this.startTime ?? default(DateTime); }
set { this.startTime = value; }
}
/// <summary>
/// Sets the StartTime property
/// </summary>
/// <param name="startTime">The value to set for the StartTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithStartTime(DateTime startTime)
{
this.startTime = startTime;
return this;
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this.startTime.HasValue;
}
/// <summary>
/// If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that occur up to, but not including, the <c>EndTime</c>.
///
/// </summary>
public DateTime EndTime
{
get { return this.endTime ?? default(DateTime); }
set { this.endTime = value; }
}
/// <summary>
/// Sets the EndTime property
/// </summary>
/// <param name="endTime">The value to set for the EndTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithEndTime(DateTime endTime)
{
this.endTime = endTime;
return this;
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this.endTime.HasValue;
}
/// <summary>
/// Specifies the maximum number of events that can be returned, beginning with the most recent event.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - 1000</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int MaxRecords
{
get { return this.maxRecords ?? default(int); }
set { this.maxRecords = value; }
}
/// <summary>
/// Sets the MaxRecords property
/// </summary>
/// <param name="maxRecords">The value to set for the MaxRecords property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithMaxRecords(int maxRecords)
{
this.maxRecords = maxRecords;
return this;
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this.maxRecords.HasValue;
}
/// <summary>
/// Pagination token. If specified, the events return the next batch of results.
///
/// </summary>
public string NextToken
{
get { return this.nextToken; }
set { this.nextToken = value; }
}
/// <summary>
/// Sets the NextToken property
/// </summary>
/// <param name="nextToken">The value to set for the NextToken property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeEventsRequest WithNextToken(string nextToken)
{
this.nextToken = nextToken;
return this;
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this.nextToken != null;
}
}
}
| |
using CodeHub.Helpers;
using CodeHub.Services;
using CodeHub.Views;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using Octokit;
using System.Collections.ObjectModel;
using System.Linq;
using Windows.UI.Xaml.Controls;
using static CodeHub.Helpers.GlobalHelper;
using Task = System.Threading.Tasks.Task;
using ToastNotificationManager = Windows.UI.Notifications.ToastNotificationManager;
namespace CodeHub.ViewModels
{
public class NotificationsViewmodel : AppViewmodel
{
#region properties
public static ObservableCollection<Notification> AllNotifications { get; set; }
public static ObservableCollection<Notification> ParticipatingNotifications { get; set; }
public bool _ZeroAllCount;
public bool ZeroAllCount
{
get => _ZeroAllCount;
set => Set(() => ZeroAllCount, ref _ZeroAllCount, value);
}
public bool _ZeroUnreadCount;
public bool ZeroUnreadCount
{
get => _ZeroUnreadCount;
set => Set(() => ZeroUnreadCount, ref _ZeroUnreadCount, value);
}
public bool _ZeroParticipatingCount;
public bool ZeroParticipatingCount
{
get => _ZeroParticipatingCount;
set => Set(() => ZeroParticipatingCount, ref _ZeroParticipatingCount, value);
}
public bool _isloadingAll;
public bool IsLoadingAll
{
get => _isloadingAll;
set => Set(() => IsLoadingAll, ref _isloadingAll, value);
}
public bool _isloadingUnread;
public bool IsLoadingUnread
{
get => _isloadingUnread;
set => Set(() => IsLoadingUnread, ref _isloadingUnread, value);
}
public bool _isloadingParticipating;
public bool IsloadingParticipating
{
get => _isloadingParticipating;
set => Set(() => IsloadingParticipating, ref _isloadingParticipating, value);
}
#endregion
public NotificationsViewmodel()
{
UnreadNotifications = UnreadNotifications ?? new ObservableCollection<Notification>();
AllNotifications = AllNotifications ?? new ObservableCollection<Notification>();
ParticipatingNotifications = ParticipatingNotifications ?? new ObservableCollection<Notification>();
}
public async Task Load()
{
if (!IsInternet())
{
//Sending NoInternet message to all viewModels
Messenger.Default.Send(new NoInternet().SendMessage());
}
else
{
IsLoadingUnread = true;
await LoadUnreadNotifications();
IsLoadingUnread = false;
IsLoadingAll = true;
await LoadAllNotifications();
IsLoadingAll = false;
IsloadingParticipating = true;
await LoadParticipatingNotifications();
IsloadingParticipating = false;
}
}
public async void RefreshAll()
{
if (!IsInternet())
{
//Sending NoInternet message to all viewModels
Messenger.Default.Send(new NoInternet().SendMessage());
}
else
{
IsLoadingAll = true;
await LoadAllNotifications();
IsLoadingAll = false;
}
}
public async void RefreshUnread()
{
if (!IsInternet())
{
//Sending NoInternet message to all viewModels
Messenger.Default.Send(new NoInternet().SendMessage());
}
else
{
IsLoadingUnread = true;
await LoadUnreadNotifications();
IsLoadingUnread = false;
}
}
public async void RefreshParticipating()
{
if (!IsInternet())
{
//Sending NoInternet message to all viewModels
Messenger.Default.Send(new NoInternet().SendMessage());
}
else
{
IsloadingParticipating = true;
await LoadParticipatingNotifications();
IsloadingParticipating = false;
}
}
public async void MarkAllNotificationsAsRead()
{
if (!IsInternet())
{
//Sending NoInternet message to all viewModels
Messenger.Default.Send(new NoInternet().SendMessage());
}
else
{
IsLoadingAll = IsLoadingUnread = IsloadingParticipating = true;
await NotificationsService.MarkAllNotificationsAsRead();
IsLoadingAll = IsLoadingUnread = IsloadingParticipating = false;
Messenger.Default.Send(new UpdateAllNotificationsCountMessageType
{
Count = 0
});
}
}
public void RecieveSignOutMessage(SignOutMessageType empty)
{
IsLoggedin = false;
User = null;
AllNotifications = UnreadNotifications = ParticipatingNotifications = null;
}
public async void RecieveSignInMessage(User user)
{
if (user != null)
{
IsLoggedin = true;
User = user;
await Load();
}
}
private async Task LoadAllNotifications()
{
await BackgroundTaskService.LoadAllNotifications();
}
private async Task LoadUnreadNotifications()
{
await BackgroundTaskService.LoadUnreadNotifications();
}
private async Task LoadParticipatingNotifications()
{
await BackgroundTaskService.LoadParticipatingNotifications();
}
public async void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var p = sender as Pivot;
if (p.SelectedIndex == 0)
{
IsLoadingUnread = true;
await LoadUnreadNotifications();
IsLoadingUnread = false;
}
else if (p.SelectedIndex == 1)
{
IsloadingParticipating = true;
await LoadParticipatingNotifications();
IsloadingParticipating = false;
}
else if (p.SelectedIndex == 2)
{
IsLoadingAll = true;
await LoadAllNotifications();
IsLoadingAll = false;
}
}
public async void NotificationsListView_ItemClick(object sender, ItemClickEventArgs e)
{
var notif = e.ClickedItem as Notification;
var isIssue = notif.Subject.Type.ToLower().Equals("issue");
Issue issue = null;
PullRequest pr = null;
if (isIssue)
{
if (int.TryParse(notif.Subject.Url.Split('/').Last().Split('?')[0], out int id))
{
issue = await IssueUtility.GetIssue(notif.Repository.Id, id);
await SimpleIoc.Default.GetInstance<IAsyncNavigationService>().NavigateAsync(typeof(IssueDetailView), new System.Tuple<Repository, Issue>(notif.Repository, issue));
}
}
else
{
if (int.TryParse(notif.Subject.Url.Split('/').Last().Split('?')[0], out int id))
{
pr = await PullRequestUtility.GetPullRequest(notif.Repository.Id, id);
await SimpleIoc.Default.GetInstance<IAsyncNavigationService>().NavigateAsync(typeof(PullRequestDetailView), new System.Tuple<Repository, PullRequest>(notif.Repository, pr));
}
}
if (notif.Unread)
{
await NotificationsService.MarkNotificationAsRead(notif.Id);
await BackgroundTaskService.LoadUnreadNotifications();
}
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AudioManager.iOS;
using AudioManager.Interfaces;
using AVFoundation;
using Foundation;
using Xamarin.Forms;
[assembly: Dependency(typeof(AppleAudioManager))]
namespace AudioManager.iOS
{
public class AppleAudioManager : IAudioManager
{
#region Private Variables
private readonly List<AVAudioPlayer> _soundEffects = new List<AVAudioPlayer>();
private AVAudioPlayer _backgroundMusic;
private string _backgroundSong = "";
//This is needed for iOS and Andriod because they do not await loading music
private bool _backgroundMusicLoading = false;
private bool _musicOn = true;
private bool _effectsOn = true;
private float _backgroundMusicVolume = 0.5f;
private float _effectsVolume = 1.0f;
#endregion
#region Computed Properties
public float BackgroundMusicVolume
{
get
{
return _backgroundMusicVolume;
}
set
{
_backgroundMusicVolume = value;
if (_backgroundMusic != null)
_backgroundMusic.Volume = _backgroundMusicVolume;
}
}
public bool MusicOn
{
get { return _musicOn; }
set
{
_musicOn = value;
if (!MusicOn)
SuspendBackgroundMusic();
else
#pragma warning disable 4014
RestartBackgroundMusic();
#pragma warning restore 4014
}
}
public bool EffectsOn
{
get { return _effectsOn; }
set
{
_effectsOn = value;
if (!EffectsOn && _soundEffects.Any())
foreach (var s in _soundEffects) s.Stop();
}
}
public float EffectsVolume
{
get { return _effectsVolume; }
set
{
_effectsVolume = value;
if (_soundEffects.Any())
foreach (var s in _soundEffects) s.Volume = _effectsVolume;
}
}
public string SoundPath { get; set; } = "Sounds";
#endregion
#region Constructors
public AppleAudioManager()
{
// Initialize
ActivateAudioSession();
}
#endregion
#region Public Methods
public void ActivateAudioSession()
{
// Initialize Audio
var session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.Ambient);
session.SetActive(true);
}
public void DeactivateAudioSession()
{
var session = AVAudioSession.SharedInstance();
session.SetActive(false);
}
public void ReactivateAudioSession()
{
var session = AVAudioSession.SharedInstance();
session.SetActive(true);
}
public async Task<bool> PlayBackgroundMusic(string filename)
{
// Music enabled?
if (!MusicOn || _backgroundMusicLoading) return false;
_backgroundMusicLoading = true;
// Any existing background music?
if (_backgroundMusic != null)
{
//Stop and dispose of any background music
_backgroundMusic.Stop();
_backgroundMusic.Dispose();
}
_backgroundSong = filename;
// Initialize background music
_backgroundMusic = await NewSound(filename, BackgroundMusicVolume, true);
_backgroundMusicLoading = false;
return true;
}
public void StopBackgroundMusic()
{
// If any background music is playing, stop it
_backgroundSong = "";
if (_backgroundMusic != null)
{
_backgroundMusic.Stop();
_backgroundMusic.Dispose();
}
}
public void SuspendBackgroundMusic()
{
// If any background music is playing, stop it
if (_backgroundMusic != null)
{
_backgroundMusic.Stop();
_backgroundMusic.Dispose();
}
}
public async Task<bool> RestartBackgroundMusic()
{
// Music enabled?
if (!MusicOn) return false;
// Was a song previously playing?
if (_backgroundSong == "") return false;
// Restart song to fix issue with wonky music after sleep
return await PlayBackgroundMusic(_backgroundSong);
}
public async Task<bool> PlaySound(string filename)
{
// Music enabled?
if (!EffectsOn) return false;
// Initialize sound
var effect = await NewSound(filename, EffectsVolume);
_soundEffects.Add(effect);
return true;
}
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
private async Task<AVAudioPlayer> NewSound(string filename, float defaultVolume, bool isLooping = false)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
{
var songUrl = new NSUrl(Path.Combine(SoundPath, filename));
NSError err;
var fileType = filename.Split('.').Last();
var sound = new AVAudioPlayer(songUrl, fileType, out err)
{
Volume = defaultVolume,
NumberOfLoops = isLooping ? -1 : 0
};
sound.FinishedPlaying += SoundOnFinishedPlaying;
sound.Play();
return sound;
}
private void SoundOnFinishedPlaying(object sender, AVStatusEventArgs avStatusEventArgs)
{
var se = sender as AVAudioPlayer;
if (se != _backgroundMusic)
_soundEffects.Remove(se);
//todo: This casues an error
//se?.Dispose();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using KakashiService.Core.Entities;
namespace KakashiService.Core.Modules.Read
{
public class ParseWsdl
{
public String ServiceAddress { get; private set; }
public String ServiceClientName { get; set; }
public List<Function> Functions { get; private set; }
public List<ObjectType> ObjectTypes { get; private set; }
public List<EnumType> EnumTypes { get; private set; }
public List<ElementType> ElementTypes { get; private set; }
public List<BindingObj> BindingsObj { get; private set; }
public ParseWsdl(List<XmlDocument> xmls)
{
Functions = new List<Function>();
BindingsObj = new List<BindingObj>();
ObjectTypes = new List<ObjectType>();
EnumTypes = new List<EnumType>();
ElementTypes = new List<ElementType>();
try
{
var xd = xmls.First().ToXDocument();
XNamespace wsdlNamespace = XNamespace.Get("http://schemas.xmlsoap.org/wsdl/");
XNamespace xmlNamespace = XNamespace.Get("http://www.w3.org/2001/XMLSchema");
var definitions = xd.Descendants(wsdlNamespace + "definitions");
var types = definitions.Descendants(wsdlNamespace + "types");
var portType = definitions.Descendants(wsdlNamespace + "portType");
var operationsWSDL = portType.Descendants(wsdlNamespace + "operation");
var messages = definitions.Descendants(wsdlNamespace + "message");
var bindings = definitions.Descendants(wsdlNamespace + "binding");
var schemas = types.Descendants(xmlNamespace + "schema");
var elements = schemas.Elements(xmlNamespace + "element");
GetBindings(wsdlNamespace, bindings);
GetFunctions(wsdlNamespace, xmlNamespace, operationsWSDL, messages, elements);
GetObjectsAndEnums(wsdlNamespace, xmlNamespace, schemas);//.Where(a => a.Attribute("targetNamespace").Value != "http://schemas.microsoft.com/2003/10/Serialization/"));
GetServiceName(wsdlNamespace, definitions);
}
catch (Exception e)
{
throw new Exception("Error on Parsing", e);
}
}
private void GetObjectsAndEnums(XNamespace wsdlNamespace, XNamespace xmlNamespace, IEnumerable<XElement> schemas)
{
foreach (var schema in schemas)
{
var complexTypes = schema.Elements(xmlNamespace + "complexType");
var simpleTypes = schema.Elements(xmlNamespace + "simpleType");
var elementTypes = schema.Elements(xmlNamespace + "element");
// For elements
foreach (var elementType in elementTypes)
{
var elementName = elementType.Attribute("name").Value;
var elementNamespace = String.Empty;
var elementTypeAttr = elementType.Attribute("type");
if(elementTypeAttr != null)
elementNamespace = elementType.Attribute("type").Value.Split(':')[0];
var temp = new ElementType(){Name = elementName, Namespace = elementNamespace};
ElementTypes.Add(temp);
}
// For enums
foreach (var simpleType in simpleTypes)
{
var elementObj = Util.GetName(simpleType.Attribute("name").Value, ElementTypes);
//var elementObj = ElementTypes.FirstOrDefault(a => a.Name.Contains(enumName));
// var temp = new EnumType(elementObj);
var temp = new EnumType(elementObj);
var simpleEnums = simpleType.Descendants(xmlNamespace + "enumeration");
foreach(var simpleEnum in simpleEnums)
{
var valueName = simpleEnum.Attribute("value").Value;
temp.Enumerators.Add(Util.NormalizeEnum(valueName));
}
EnumTypes.Add(temp);
}
// For objects
foreach (var complexType in complexTypes)
{
var complexName = complexType.Attribute("name").Value;
if (complexName == "ArrayOfKeyValueOfanyTypeanyType")
complexName = complexName.Replace("ArrayOf", "");
if (complexName.StartsWith("ArrayOf"))
continue;
var elementObj = Util.GetName(complexName, ElementTypes);
var temp = new ObjectType(elementObj);
var sequence = complexType.Elements(xmlNamespace + "sequence");
var elements = sequence.Elements(xmlNamespace + "element");
foreach (var element in elements)
{
var name = element.Attribute("name").Value;
var elementType = element.Attribute("type");
if (elementType == null)
{
var seqElements = element.Descendants(xmlNamespace + "element");
foreach (var seqElement in seqElements)
{
var seqName = seqElement.Attribute("name").Value;
var seqType = seqElement.Attribute("type").Value;
temp.AddAttribute(seqName, seqType);
}
}
else
{
var type = elementType.Value;
temp.AddAttribute(name, type);
}
}
ObjectTypes.Add(temp);
}
}
}
private void GetServiceName(XNamespace wsdlNamespace, IEnumerable<XElement> definitions)
{
var serviceNode = definitions.Descendants(wsdlNamespace + "service").First();
ServiceAddress = serviceNode.Descendants(wsdlNamespace + "port").First().Attribute("name").Value;
ServiceClientName = definitions.Descendants(wsdlNamespace + "portType").First().Attribute("name").Value;
if (ServiceClientName[0] == 'I')
ServiceClientName = ServiceClientName.Substring(1);
}
private void GetBindings(XNamespace wsdlNamespace, IEnumerable<XElement> bindings)
{
foreach (var binding in bindings)
{
var bindingObj = new BindingObj();
bindingObj.Name = binding.Attribute("name").Value;
var operations = binding.Descendants(wsdlNamespace + "operation");
foreach (var operation in operations)
{
var name = operation.Attribute("name").Value;
var soapAction = operation.Descendants().FirstOrDefault(a => a.Attribute("soapAction") != null);
if (soapAction != null)
bindingObj.Operations.Add(new OperationObj() { Name = name, SoapAction = soapAction.Attribute("soapAction").Value });
}
BindingsObj.Add(bindingObj);
}
}
private void GetFunctions(XNamespace wsdlNamespace, XNamespace xmlNamespace, IEnumerable<XElement> operationsWSDL, IEnumerable<XElement> messages, IEnumerable<XElement> elements)
{
foreach (var operation in operationsWSDL)
{
var func = new Function();
var name = operation.Attribute("name").Value;
func.Name = name;
var bindingAction = BindingsObj.First().Operations.FirstOrDefault(a => a.Name == name);
func.Action = bindingAction == null ? "" : bindingAction.SoapAction;
var input = operation.Element(wsdlNamespace + "input").Attribute("message").Value.Split(':')[1];
var output = operation.Element(wsdlNamespace + "output").Attribute("message").Value.Split(':')[1];
var messageInput = messages.FirstOrDefault(a => a.Attribute("name").Value == input);
var messageOutput = messages.FirstOrDefault(a => a.Attribute("name").Value == output);
var elementNameInput = String.Empty;
var elementNameOutput = String.Empty;
if (messageInput != null && messageOutput != null)
{
elementNameInput = messageInput.Element(wsdlNamespace + "part").Attribute("element").Value
.Split(':')[1];
elementNameOutput = messageOutput.Element(wsdlNamespace + "part").Attribute("element").Value
.Split(':')[1];
}
var elementInput = elements.FirstOrDefault(a => a.Attribute("name").Value == elementNameInput);
var elementOutput = elements.FirstOrDefault(a => a.Attribute("name").Value == elementNameOutput);
if (elementInput != null)
{
var index = 0;
var elementsInput = elementInput.Descendants(xmlNamespace + "element");
foreach (var element in elementsInput)
{
var temp = Parameter.GetElementFromWSDL(element, xmlNamespace);
temp.Order = index;
func.Parameters.Add(temp);
index++;
}
}
var returnElements = elementOutput.Descendants(xmlNamespace + "element").ToList();
if (returnElements.Count == 0)
{
func.ReturnType = "void";
}
else
{
var returnElement = returnElements.FirstOrDefault(a => a.Attribute("name").Value.Contains(elementNameInput));
if (returnElement == null)
func.ReturnType = "void";
else
{
var attribute = returnElement.Attribute("type");
func.ReturnType = attribute == null ? "void" : Util.NormalizeType(attribute.Value);
}
var otherElements = returnElements.Where(a => a.Attribute("name") == null || !a.Attribute("name").Value.Contains(elementNameInput)).ToList();
if (otherElements != null && otherElements.Count > 0)
{
foreach (var elem in otherElements)
{
var parameterElem = Parameter.GetElementFromWSDL(elem, xmlNamespace);
if (parameterElem == null)
continue;
var parameter = func.Parameters.FirstOrDefault(a => a.Name == parameterElem.Name);
if (parameter == null)
{
var biggestOrder = func.Parameters.Max(a => a.Order);
parameterElem.Order = biggestOrder + 1;
parameterElem.Type = "out " + parameterElem.Type;
func.Parameters.Add(parameterElem);
}
else
{
parameter.Type = "ref " + parameter.Type;
}
}
}
}
Functions.Add(func);
}
}
}
}
| |
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Support.IO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// On-disk sorting of byte arrays. Each byte array (entry) is a composed of the following
/// fields:
/// <list type="bullet">
/// <item><description>(two bytes) length of the following byte array,</description></item>
/// <item><description>exactly the above count of bytes for the sequence to be sorted.</description></item>
/// </list>
/// </summary>
public sealed class OfflineSorter
{
private void InitializeInstanceFields()
{
buffer = new BytesRefArray(bufferBytesUsed);
}
/// <summary>
/// Convenience constant for megabytes </summary>
public static readonly long MB = 1024 * 1024;
/// <summary>
/// Convenience constant for gigabytes </summary>
public static readonly long GB = MB * 1024;
/// <summary>
/// Minimum recommended buffer size for sorting.
/// </summary>
public static readonly long MIN_BUFFER_SIZE_MB = 32;
/// <summary>
/// Absolute minimum required buffer size for sorting.
/// </summary>
public static readonly long ABSOLUTE_MIN_SORT_BUFFER_SIZE = MB / 2;
private static readonly string MIN_BUFFER_SIZE_MSG = "At least 0.5MB RAM buffer is needed";
/// <summary>
/// Maximum number of temporary files before doing an intermediate merge.
/// </summary>
public static readonly int MAX_TEMPFILES = 128;
/// <summary>
/// A bit more descriptive unit for constructors.
/// </summary>
/// <seealso cref="Automatic()"/>
/// <seealso cref="Megabytes(long)"/>
public sealed class BufferSize
{
internal readonly int bytes;
private BufferSize(long bytes)
{
if (bytes > int.MaxValue)
{
throw new System.ArgumentException("Buffer too large for Java (" + (int.MaxValue / MB) + "mb max): " + bytes);
}
if (bytes < ABSOLUTE_MIN_SORT_BUFFER_SIZE)
{
throw new System.ArgumentException(MIN_BUFFER_SIZE_MSG + ": " + bytes);
}
this.bytes = (int)bytes;
}
/// <summary>
/// Creates a <see cref="BufferSize"/> in MB. The given
/// values must be > 0 and < 2048.
/// </summary>
public static BufferSize Megabytes(long mb)
{
return new BufferSize(mb * MB);
}
/// <summary>
/// Approximately half of the currently available free heap, but no less
/// than <see cref="ABSOLUTE_MIN_SORT_BUFFER_SIZE"/>. However if current heap allocation
/// is insufficient or if there is a large portion of unallocated heap-space available
/// for sorting consult with max allowed heap size.
/// </summary>
public static BufferSize Automatic()
{
long max, total, free;
using (var proc = Process.GetCurrentProcess())
{
// take sizes in "conservative" order
max = proc.PeakVirtualMemorySize64; // max allocated; java has it as Runtime.maxMemory();
total = proc.VirtualMemorySize64; // currently allocated; java has it as Runtime.totalMemory();
free = proc.PrivateMemorySize64; // unused portion of currently allocated; java has it as Runtime.freeMemory();
}
long totalAvailableBytes = max - total + free;
// by free mem (attempting to not grow the heap for this)
long sortBufferByteSize = free / 2;
long minBufferSizeBytes = MIN_BUFFER_SIZE_MB * MB;
if (sortBufferByteSize < minBufferSizeBytes || totalAvailableBytes > 10 * minBufferSizeBytes) // lets see if we need/should to grow the heap
{
if (totalAvailableBytes / 2 > minBufferSizeBytes) // there is enough mem for a reasonable buffer
{
sortBufferByteSize = totalAvailableBytes / 2; // grow the heap
}
else
{
//heap seems smallish lets be conservative fall back to the free/2
sortBufferByteSize = Math.Max(ABSOLUTE_MIN_SORT_BUFFER_SIZE, sortBufferByteSize);
}
}
return new BufferSize(Math.Min((long)int.MaxValue, sortBufferByteSize));
}
}
/// <summary>
/// Sort info (debugging mostly).
/// </summary>
public class SortInfo
{
private readonly OfflineSorter outerInstance;
/// <summary>
/// Number of temporary files created when merging partitions </summary>
public int TempMergeFiles { get; set; }
/// <summary>
/// Number of partition merges </summary>
public int MergeRounds { get; set; }
/// <summary>
/// Number of lines of data read </summary>
public int Lines { get; set; }
/// <summary>
/// Time spent merging sorted partitions (in milliseconds) </summary>
public long MergeTime { get; set; }
/// <summary>
/// Time spent sorting data (in milliseconds) </summary>
public long SortTime { get; set; }
/// <summary>
/// Total time spent (in milliseconds) </summary>
public long TotalTime { get; set; }
/// <summary>
/// Time spent in i/o read (in milliseconds) </summary>
public long ReadTime { get; set; }
/// <summary>
/// Read buffer size (in bytes) </summary>
public long BufferSize { get; private set; }
/// <summary>
/// Create a new <see cref="SortInfo"/> (with empty statistics) for debugging. </summary>
public SortInfo(OfflineSorter outerInstance)
{
this.outerInstance = outerInstance;
BufferSize = outerInstance.ramBufferSize.bytes;
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture,
"time={0:0.00} sec. total ({1:0.00} reading, {2:0.00} sorting, {3:0.00} merging), lines={4}, temp files={5}, merges={6}, soft ram limit={7:0.00} MB",
TotalTime / 1000.0d, ReadTime / 1000.0d, SortTime / 1000.0d, MergeTime / 1000.0d,
Lines, TempMergeFiles, MergeRounds,
(double)BufferSize / MB);
}
}
private readonly BufferSize ramBufferSize;
private readonly Counter bufferBytesUsed = Counter.NewCounter();
private BytesRefArray buffer;
private SortInfo sortInfo;
private readonly int maxTempFiles;
private readonly IComparer<BytesRef> comparer;
/// <summary>
/// Default comparer: sorts in binary (codepoint) order </summary>
public static readonly IComparer<BytesRef> DEFAULT_COMPARER = Utf8SortedAsUnicodeComparer.Instance;
/// <summary>
/// Defaults constructor.
/// </summary>
/// <seealso cref="DefaultTempDir()"/>
/// <seealso cref="BufferSize.Automatic()"/>
public OfflineSorter()
: this(DEFAULT_COMPARER, BufferSize.Automatic(), DefaultTempDir(), MAX_TEMPFILES)
{
}
/// <summary>
/// Defaults constructor with a custom comparer.
/// </summary>
/// <seealso cref="DefaultTempDir()"/>
/// <seealso cref="BufferSize.Automatic()"/>
public OfflineSorter(IComparer<BytesRef> comparer)
: this(comparer, BufferSize.Automatic(), DefaultTempDir(), MAX_TEMPFILES)
{
}
/// <summary>
/// All-details constructor.
/// </summary>
public OfflineSorter(IComparer<BytesRef> comparer, BufferSize ramBufferSize, DirectoryInfo tempDirectory, int maxTempfiles)
{
InitializeInstanceFields();
if (ramBufferSize.bytes < ABSOLUTE_MIN_SORT_BUFFER_SIZE)
{
throw new System.ArgumentException(MIN_BUFFER_SIZE_MSG + ": " + ramBufferSize.bytes);
}
if (maxTempfiles < 2)
{
throw new System.ArgumentException("maxTempFiles must be >= 2");
}
this.ramBufferSize = ramBufferSize;
this.maxTempFiles = maxTempfiles;
this.comparer = comparer;
}
/// <summary>
/// Sort input to output, explicit hint for the buffer size. The amount of allocated
/// memory may deviate from the hint (may be smaller or larger).
/// </summary>
public SortInfo Sort(FileInfo input, FileInfo output)
{
sortInfo = new SortInfo(this) { TotalTime = Environment.TickCount };
output.Delete();
var merges = new List<FileInfo>();
bool success2 = false;
try
{
var inputStream = new ByteSequencesReader(input);
bool success = false;
try
{
int lines = 0;
while ((lines = ReadPartition(inputStream)) > 0)
{
merges.Add(SortPartition(lines));
sortInfo.TempMergeFiles++;
sortInfo.Lines += lines;
// Handle intermediate merges.
if (merges.Count == maxTempFiles)
{
var intermediate = new FileInfo(Path.GetTempFileName());
try
{
MergePartitions(merges, intermediate);
}
finally
{
foreach (var file in merges)
{
file.Delete();
}
merges.Clear();
merges.Add(intermediate);
}
sortInfo.TempMergeFiles++;
}
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(inputStream);
}
else
{
IOUtils.DisposeWhileHandlingException(inputStream);
}
}
// One partition, try to rename or copy if unsuccessful.
if (merges.Count == 1)
{
FileInfo single = merges[0];
Copy(single, output);
try
{
File.Delete(single.FullName);
}
catch (Exception)
{
// ignored
}
}
else
{
// otherwise merge the partitions with a priority queue.
MergePartitions(merges, output);
}
success2 = true;
}
finally
{
foreach (FileInfo file in merges)
{
file.Delete();
}
if (!success2)
{
output.Delete();
}
}
sortInfo.TotalTime = (Environment.TickCount - sortInfo.TotalTime);
return sortInfo;
}
/// <summary>
/// Returns the default temporary directory. By default, the System's temp folder. If not accessible
/// or not available, an <see cref="IOException"/> is thrown.
/// </summary>
public static DirectoryInfo DefaultTempDir()
{
return new DirectoryInfo(Path.GetTempPath());
}
/// <summary>
/// Copies one file to another.
/// </summary>
private static void Copy(FileInfo file, FileInfo output)
{
using (Stream inputStream = file.OpenRead())
{
using (Stream outputStream = output.OpenWrite())
{
inputStream.CopyTo(outputStream);
}
}
}
/// <summary>
/// Sort a single partition in-memory. </summary>
private FileInfo SortPartition(int len) // LUCENENET NOTE: made private, since protected is not valid in a sealed class
{
var data = this.buffer;
FileInfo tempFile = FileSupport.CreateTempFile("sort", "partition", DefaultTempDir());
long start = Environment.TickCount;
sortInfo.SortTime += (Environment.TickCount - start);
using (var @out = new ByteSequencesWriter(tempFile))
{
BytesRef spare;
IBytesRefIterator iter = buffer.GetIterator(comparer);
while ((spare = iter.Next()) != null)
{
Debug.Assert(spare.Length <= ushort.MaxValue);
@out.Write(spare);
}
}
// Clean up the buffer for the next partition.
data.Clear();
return tempFile;
}
/// <summary>
/// Merge a list of sorted temporary files (partitions) into an output file. </summary>
internal void MergePartitions(IEnumerable<FileInfo> merges, FileInfo outputFile)
{
long start = Environment.TickCount;
var @out = new ByteSequencesWriter(outputFile);
PriorityQueue<FileAndTop> queue = new PriorityQueueAnonymousInnerClassHelper(this, merges.Count());
var streams = new ByteSequencesReader[merges.Count()];
try
{
// Open streams and read the top for each file
for (int i = 0; i < merges.Count(); i++)
{
streams[i] = new ByteSequencesReader(merges.ElementAt(i));
byte[] line = streams[i].Read();
if (line != null)
{
queue.InsertWithOverflow(new FileAndTop(i, line));
}
}
// Unix utility sort() uses ordered array of files to pick the next line from, updating
// it as it reads new lines. The PQ used here is a more elegant solution and has
// a nicer theoretical complexity bound :) The entire sorting process is I/O bound anyway
// so it shouldn't make much of a difference (didn't check).
FileAndTop top;
while ((top = queue.Top) != null)
{
@out.Write(top.Current);
if (!streams[top.Fd].Read(top.Current))
{
queue.Pop();
}
else
{
queue.UpdateTop();
}
}
sortInfo.MergeTime += Environment.TickCount - start;
sortInfo.MergeRounds++;
}
finally
{
// The logic below is: if an exception occurs in closing out, it has a priority over exceptions
// happening in closing streams.
try
{
IOUtils.Dispose(streams);
}
finally
{
IOUtils.Dispose(@out);
}
}
}
private class PriorityQueueAnonymousInnerClassHelper : PriorityQueue<FileAndTop>
{
private readonly OfflineSorter outerInstance;
public PriorityQueueAnonymousInnerClassHelper(OfflineSorter outerInstance, int size)
: base(size)
{
this.outerInstance = outerInstance;
}
protected internal override bool LessThan(FileAndTop a, FileAndTop b)
{
return outerInstance.comparer.Compare(a.Current, b.Current) < 0;
}
}
/// <summary>
/// Read in a single partition of data. </summary>
internal int ReadPartition(ByteSequencesReader reader)
{
long start = Environment.TickCount;
var scratch = new BytesRef();
while ((scratch.Bytes = reader.Read()) != null)
{
scratch.Length = scratch.Bytes.Length;
buffer.Append(scratch);
// Account for the created objects.
// (buffer slots do not account to buffer size.)
if (ramBufferSize.bytes < bufferBytesUsed.Get())
{
break;
}
}
sortInfo.ReadTime += (Environment.TickCount - start);
return buffer.Length;
}
internal class FileAndTop
{
internal int Fd { get; private set; }
internal BytesRef Current { get; private set; }
internal FileAndTop(int fd, byte[] firstLine)
{
this.Fd = fd;
this.Current = new BytesRef(firstLine);
}
}
/// <summary>
/// Utility class to emit length-prefixed <see cref="T:byte[]"/> entries to an output stream for sorting.
/// Complementary to <see cref="ByteSequencesReader"/>.
/// </summary>
public class ByteSequencesWriter : IDisposable
{
private readonly DataOutput os;
/// <summary>
/// Constructs a <see cref="ByteSequencesWriter"/> to the provided <see cref="FileInfo"/>. </summary>
public ByteSequencesWriter(FileInfo file)
: this(NewBinaryWriterDataOutput(file))
{
}
/// <summary>
/// Constructs a <see cref="ByteSequencesWriter"/> to the provided <see cref="DataOutput"/>. </summary>
public ByteSequencesWriter(DataOutput os)
{
this.os = os;
}
/// <summary>
/// LUCENENET specific - ensures the file has been created with no BOM
/// if it doesn't already exist and opens the file for writing.
/// Java doesn't use a BOM by default.
/// </summary>
private static BinaryWriterDataOutput NewBinaryWriterDataOutput(FileInfo file)
{
string fileName = file.FullName;
// Create the file (without BOM) if it doesn't already exist
if (!File.Exists(fileName))
{
// Create the file
File.WriteAllText(fileName, string.Empty, new UTF8Encoding(false) /* No BOM */);
}
return new BinaryWriterDataOutput(new BinaryWriter(new FileStream(fileName, FileMode.Open, FileAccess.Write)));
}
/// <summary>
/// Writes a <see cref="BytesRef"/>. </summary>
/// <seealso cref="Write(byte[], int, int)"/>
public virtual void Write(BytesRef @ref)
{
Debug.Assert(@ref != null);
Write(@ref.Bytes, @ref.Offset, @ref.Length);
}
/// <summary>
/// Writes a byte array. </summary>
/// <seealso cref="Write(byte[], int, int)"/>
public virtual void Write(byte[] bytes)
{
Write(bytes, 0, bytes.Length);
}
/// <summary>
/// Writes a byte array.
/// <para/>
/// The length is written as a <see cref="short"/>, followed
/// by the bytes.
/// </summary>
public virtual void Write(byte[] bytes, int off, int len)
{
Debug.Assert(bytes != null);
Debug.Assert(off >= 0 && off + len <= bytes.Length);
Debug.Assert(len >= 0);
os.WriteInt16((short)len);
os.WriteBytes(bytes, off, len); // LUCENENET NOTE: We call WriteBytes, since there is no Write() on Lucene's version of DataOutput
}
/// <summary>
/// Disposes the provided <see cref="DataOutput"/> if it is <see cref="IDisposable"/>.
/// </summary>
public void Dispose()
{
var os = this.os as IDisposable;
if (os != null)
{
os.Dispose();
}
}
}
/// <summary>
/// Utility class to read length-prefixed <see cref="T:byte[]"/> entries from an input.
/// Complementary to <see cref="ByteSequencesWriter"/>.
/// </summary>
public class ByteSequencesReader : IDisposable
{
private readonly DataInput inputStream;
/// <summary>
/// Constructs a <see cref="ByteSequencesReader"/> from the provided <see cref="FileInfo"/>. </summary>
public ByteSequencesReader(FileInfo file)
: this(new BinaryReaderDataInput(new BinaryReader(new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))))
{
}
/// <summary>
/// Constructs a <see cref="ByteSequencesReader"/> from the provided <see cref="DataInput"/>. </summary>
public ByteSequencesReader(DataInput inputStream)
{
this.inputStream = inputStream;
}
/// <summary>
/// Reads the next entry into the provided <see cref="BytesRef"/>. The internal
/// storage is resized if needed.
/// </summary>
/// <returns> Returns <c>false</c> if EOF occurred when trying to read
/// the header of the next sequence. Returns <c>true</c> otherwise. </returns>
/// <exception cref="EndOfStreamException"> If the file ends before the full sequence is read. </exception>
public virtual bool Read(BytesRef @ref)
{
ushort length;
try
{
length = (ushort)inputStream.ReadInt16();
}
catch (EndOfStreamException)
{
return false;
}
@ref.Grow(length);
@ref.Offset = 0;
@ref.Length = length;
inputStream.ReadBytes(@ref.Bytes, 0, length);
return true;
}
/// <summary>
/// Reads the next entry and returns it if successful.
/// </summary>
/// <seealso cref="Read(BytesRef)"/>
/// <returns> Returns <c>null</c> if EOF occurred before the next entry
/// could be read. </returns>
/// <exception cref="EndOfStreamException"> If the file ends before the full sequence is read. </exception>
public virtual byte[] Read()
{
ushort length;
try
{
length = (ushort)inputStream.ReadInt16();
}
catch (EndOfStreamException)
{
return null;
}
Debug.Assert(length >= 0, "Sanity: sequence length < 0: " + length);
byte[] result = new byte[length];
inputStream.ReadBytes(result, 0, length);
return result;
}
/// <summary>
/// Disposes the provided <see cref="DataInput"/> if it is <see cref="IDisposable"/>.
/// </summary>
public void Dispose()
{
var @is = inputStream as IDisposable;
if (@is != null)
{
@is.Dispose();
}
}
}
/// <summary>
/// Returns the comparer in use to sort entries </summary>
public IComparer<BytesRef> Comparer
{
get
{
return comparer;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ChaseCamera.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using BoxCollider;
#endregion
namespace ShipGame
{
/// <remarks>This class was first seen in the Chase Camera sample.</remarks>
public class ChaseCamera
{
#region Chased object properties (set externally each frame)
/// <summary>
/// Position of object being chased.
/// </summary>
public Vector3 ChasePosition
{
get { return chasePosition; }
set { chasePosition = value; }
}
private Vector3 chasePosition;
/// <summary>
/// Direction the chased object is facing.
/// </summary>
public Vector3 ChaseDirection
{
get { return chaseDirection; }
set { chaseDirection = value; }
}
private Vector3 chaseDirection;
/// <summary>
/// Chased object's Up vector.
/// </summary>
public Vector3 Up
{
get { return up; }
set { up = value; }
}
private Vector3 up = Vector3.Up;
#endregion
#region Desired camera positioning (set when creating camera or changing view)
/// <summary>
/// Desired camera position in the chased object's coordinate system.
/// </summary>
public Vector3 DesiredPositionOffset
{
get { return desiredPositionOffset; }
set { desiredPositionOffset = value; }
}
private Vector3 desiredPositionOffset = new Vector3(0, 2.0f, 2.0f);
/// <summary>
/// Desired camera position in world space.
/// </summary>
public Vector3 DesiredPosition
{
get
{
// Ensure correct value even if update has not been called this frame
UpdateWorldPositions();
return desiredPosition;
}
}
private Vector3 desiredPosition;
/// <summary>
/// Look at point in the chased object's coordinate system.
/// </summary>
public Vector3 LookAtOffset
{
get { return lookAtOffset; }
set { lookAtOffset = value; }
}
private Vector3 lookAtOffset = new Vector3(0, 2.8f, 0);
/// <summary>
/// Look at point in world space.
/// </summary>
public Vector3 LookAt
{
get
{
// Ensure correct value even if update has not been called this frame
UpdateWorldPositions();
return lookAt;
}
}
private Vector3 lookAt;
#endregion
#region Camera physics (typically set when creating camera)
/// <summary>
/// Physics coefficient which controls the influence of the camera's position
/// over the spring force. The stiffer the spring, the closer it will stay to
/// the chased object.
/// </summary>
public float Stiffness
{
get { return stiffness; }
set { stiffness = value; }
}
private float stiffness = 1800.0f;
/// <summary>
/// Physics coefficient which approximates internal friction of the spring.
/// Sufficient damping will prevent the spring from oscillating infinitely.
/// </summary>
public float Damping
{
get { return damping; }
set { damping = value; }
}
private float damping = 600.0f;
/// <summary>
/// Mass of the camera body. Heaver objects require stiffer springs with less
/// damping to move at the same rate as lighter objects.
/// </summary>
public float Mass
{
get { return mass; }
set { mass = value; }
}
private float mass = 50.0f;
#endregion
#region Current camera properties (updated by camera physics)
/// <summary>
/// Position of camera in world space.
/// </summary>
public Vector3 Position
{
get { return collisionPosition; }
}
private Vector3 position;
private Vector3 collisionPosition;
/// <summary>
/// Velocity of camera.
/// </summary>
public Vector3 Velocity
{
get { return velocity; }
}
private Vector3 velocity;
#endregion
#region Matrix properties
/// <summary>
/// View transform matrix.
/// </summary>
public Matrix View
{
get { return view; }
}
private Matrix view;
#endregion
#region Methods
/// <summary>
/// Rebuilds object space values in world space. Invoke before publicly
/// returning or privately accessing world space values.
/// </summary>
private void UpdateWorldPositions()
{
// Construct a matrix to transform from object space to worldspace
Matrix transform = Matrix.Identity;
transform.Forward = ChaseDirection;
transform.Up = Up;
transform.Right = Vector3.Cross(Up, ChaseDirection);
// Calculate desired camera properties in world space
desiredPosition = ChasePosition +
Vector3.TransformNormal(DesiredPositionOffset, transform);
lookAt = ChasePosition +
Vector3.TransformNormal(LookAtOffset, transform);
}
/// <summary>
/// Rebuilds camera's view and projection matricies.
/// </summary>
private void UpdateMatrices()
{
view = Matrix.CreateLookAt(this.Position, this.LookAt, this.Up);
}
/// <summary>
/// Forces camera to be at desired position and to stop moving. The is useful
/// when the chased object is first created or after it has been teleported.
/// Failing to call this after a large change to the chased object's position
/// will result in the camera quickly flying across the world.
/// </summary>
public void Reset()
{
UpdateWorldPositions();
// Stop motion
velocity = Vector3.Zero;
// Force desired position
position = desiredPosition;
UpdateMatrices();
}
/// <summary>
/// Animates the camera from its current position towards the desired offset
/// behind the chased object. The camera's animation is controlled by a simple
/// physical spring attached to the camera and anchored to the desired position.
/// </summary>
public void Update(float elapsedTime, CollisionMesh collision)
{
UpdateWorldPositions();
// Calculate spring force
Vector3 stretch = position - desiredPosition;
Vector3 force = -stiffness * stretch - damping * velocity;
// Apply acceleration
Vector3 acceleration = force / mass;
velocity += acceleration * elapsedTime;
// Apply velocity
position += velocity * elapsedTime;
collisionPosition = position;
// test camera for collision with world
if (collision != null)
{
float collisionDistance;
Vector3 collisionPoint, collisionNormal;
if (collision.PointIntersect(lookAt, position, out collisionDistance,
out collisionPoint, out collisionNormal))
{
Vector3 dir = Vector3.Normalize(collisionPoint - lookAt);
collisionPosition = collisionPoint - 10 * dir;
}
}
UpdateMatrices();
}
#endregion
}
}
| |
#if UNITY_EDITOR
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Zios {
using Containers;
public static class GUISkinExtension {
public static Hierarchy<GUISkin, string, GUIStyle> cachedStyles = new Hierarchy<GUISkin, string, GUIStyle>();
public static GUISkin Copy(this GUISkin current) {
var copy = ScriptableObject.CreateInstance<GUISkin>();
copy.font = current.font;
copy.name = current.name;
copy.box = new GUIStyle(current.box);
copy.button = new GUIStyle(current.button);
copy.toggle = new GUIStyle(current.toggle);
copy.label = new GUIStyle(current.label);
copy.textField = new GUIStyle(current.textField);
copy.textArea = new GUIStyle(current.textArea);
copy.window = new GUIStyle(current.window);
copy.horizontalSlider = new GUIStyle(current.horizontalSlider);
copy.horizontalSliderThumb = new GUIStyle(current.horizontalSliderThumb);
copy.verticalSlider = new GUIStyle(current.verticalSlider);
copy.verticalSliderThumb = new GUIStyle(current.verticalScrollbarThumb);
copy.horizontalScrollbar = new GUIStyle(current.horizontalScrollbar);
copy.horizontalScrollbarThumb = new GUIStyle(current.horizontalScrollbarThumb);
copy.horizontalScrollbarLeftButton = new GUIStyle(current.horizontalScrollbarLeftButton);
copy.horizontalScrollbarRightButton = new GUIStyle(current.horizontalScrollbarRightButton);
copy.verticalScrollbar = new GUIStyle(current.verticalScrollbar);
copy.verticalScrollbarThumb = new GUIStyle(current.verticalScrollbarThumb);
copy.verticalScrollbarUpButton = new GUIStyle(current.verticalScrollbarUpButton);
copy.verticalScrollbarDownButton = new GUIStyle(current.verticalScrollbarDownButton);
copy.scrollView = new GUIStyle(current.scrollView);
copy.settings.doubleClickSelectsWord = current.settings.doubleClickSelectsWord;
copy.settings.tripleClickSelectsLine = current.settings.tripleClickSelectsLine;
copy.settings.cursorColor = current.settings.cursorColor;
copy.settings.cursorFlashSpeed = current.settings.cursorFlashSpeed;
copy.settings.selectionColor = current.settings.selectionColor;
var styles = new List<GUIStyle>();
foreach (var style in current.customStyles) {
styles.Add(new GUIStyle(style));
}
copy.customStyles = styles.ToArray();
return copy;
}
public static GUIStyle Get(this GUISkin current, string name) {
if (GUISkinExtension.cachedStyles.AddNew(current).ContainsKey(name)) {
return GUISkinExtension.cachedStyles[current][name];
}
foreach (var style in current.GetStyles()) {
if (style.name == name) {
GUISkinExtension.cachedStyles[current][name] = style;
return style;
}
}
return null;
}
public static GUISkin Use(this GUISkin current, GUISkin other, bool useBuiltin = true, bool inline = false) {
if (other.IsNull()) { return current; }
other.customStyles = other.customStyles ?? new GUIStyle[0];
other.customStyles = other.customStyles.Where(x => !x.IsNull()).ToArray();
current.customStyles = current.customStyles ?? new GUIStyle[0];
current.customStyles = current.customStyles.Where(x => !x.IsNull()).ToArray();
if (useBuiltin) {
current.font = other.font;
current.settings.doubleClickSelectsWord = other.settings.doubleClickSelectsWord;
current.settings.tripleClickSelectsLine = other.settings.tripleClickSelectsLine;
current.settings.cursorColor = other.settings.cursorColor;
current.settings.cursorFlashSpeed = other.settings.cursorFlashSpeed;
current.settings.selectionColor = other.settings.selectionColor;
}
if (inline) {
var currentStyles = current.GetNamedStyles(useBuiltin);
var otherStyles = other.GetNamedStyles(useBuiltin);
foreach (var style in currentStyles) {
if (otherStyles.ContainsKey(style.Key)) {
style.Value.Use(otherStyles[style.Key]);
}
}
} else {
if (useBuiltin) {
current.box = other.box;
current.button = other.button;
current.toggle = other.toggle;
current.label = other.label;
current.textField = other.textField;
current.textArea = other.textArea;
current.window = other.window;
current.horizontalSlider = other.horizontalSlider;
current.horizontalSliderThumb = other.horizontalSliderThumb;
current.verticalSlider = other.verticalSlider;
current.verticalSliderThumb = other.verticalScrollbarThumb;
current.horizontalScrollbar = other.horizontalScrollbar;
current.horizontalScrollbarThumb = other.horizontalScrollbarThumb;
current.horizontalScrollbarLeftButton = other.horizontalScrollbarLeftButton;
current.horizontalScrollbarRightButton = other.horizontalScrollbarRightButton;
current.verticalScrollbar = other.verticalScrollbar;
current.verticalScrollbarThumb = other.verticalScrollbarThumb;
current.verticalScrollbarUpButton = other.verticalScrollbarUpButton;
current.verticalScrollbarDownButton = other.verticalScrollbarDownButton;
current.scrollView = other.scrollView;
}
current.customStyles = current.customStyles.ToDictionary(x => x.name, x => x).Merge(other.customStyles.ToDictionary(x => x.name, x => x)).ToDictionary().Values.ToArray();
}
return current;
}
public static Dictionary<string, GUIStyle> GetNamedStyles(this GUISkin current, bool includeStandard = true, bool includeCustom = true, bool trimBaseName = false) {
var data = new Dictionary<string, GUIStyle>();
var styles = current.GetStyles(includeStandard, includeCustom);
for (int index = 0; index < styles.Length; ++index) {
var style = styles[index];
var name = trimBaseName ? style.name.Split("[")[0].Trim() : style.name;
if (name.IsEmpty()) {
data["Element " + index] = style;
continue;
}
while (data.ContainsKey(name)) {
name = name.ToLetterSequence();
style.name = name;
}
data[name] = style;
}
return data;
}
public static GUIStyle[] GetStyles(this GUISkin current, bool includeStandard = true, bool includeCustom = true) {
var styles = new List<GUIStyle>();
if (includeStandard) {
styles.Add(current.box);
styles.Add(current.button);
styles.Add(current.toggle);
styles.Add(current.label);
styles.Add(current.textField);
styles.Add(current.textArea);
styles.Add(current.window);
styles.Add(current.horizontalSlider);
styles.Add(current.horizontalSliderThumb);
styles.Add(current.verticalSlider);
styles.Add(current.verticalSliderThumb);
styles.Add(current.horizontalScrollbar);
styles.Add(current.horizontalScrollbarThumb);
styles.Add(current.horizontalScrollbarLeftButton);
styles.Add(current.horizontalScrollbarRightButton);
styles.Add(current.verticalScrollbar);
styles.Add(current.verticalScrollbarThumb);
styles.Add(current.verticalScrollbarUpButton);
styles.Add(current.verticalScrollbarDownButton);
styles.Add(current.scrollView);
}
if (includeCustom) { styles.AddRange(current.customStyles); }
return styles.ToArray();
}
public static void InvertTextColors(this GUISkin current, float intensityCompare, float difference = 1.0f) {
foreach (var style in current.GetStyles()) {
foreach (var state in style.GetStates()) {
state.InvertTextColor(intensityCompare, difference);
}
}
}
public static void SaveBackgrounds(this GUISkin current, string path, bool includeBuiltin = true) {
foreach (var style in current.GetStyles()) {
foreach (var state in style.GetStates()) {
if (!state.background.IsNull()) {
string assetPath = FileManager.GetPath(state.background);
string savePath = path + "/" + state.background.name + ".png";
if (!includeBuiltin && assetPath.Contains("unity editor resources")) { continue; }
if (!FileManager.Exists(savePath)) {
state.background.SaveAs(savePath, true);
}
}
}
}
}
public static GUIStyle AddStyle(this GUISkin current, GUIStyle style) {
if (style.IsNull()) { return null; }
return current.AddStyle(style.name, style);
}
public static GUIStyle AddStyle(this GUISkin current, string name, GUIStyle style) {
if (!style.IsNull() && !current.customStyles.Exists(x => x.name == name)) {
current.customStyles = current.customStyles.Add(style);
}
return style;
}
#if UNITY_EDITOR
public static void SaveFonts(this GUISkin current, string path, bool includeBuiltin = true) {
foreach (var style in current.GetStyles()) {
if (!style.font.IsNull()) {
string assetPath = FileManager.GetPath(style.font);
string savePath = path + "/" + assetPath.GetPathTerm();
if (!includeBuiltin && assetPath.Contains("unity editor resources")) { continue; }
if (!FileManager.Exists(savePath)) {
AssetDatabase.CopyAsset(assetPath, savePath);
}
}
}
}
#endif
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
namespace System.Net.WebSockets
{
internal class WinHttpWebSocket : WebSocket
{
#region Constants
// TODO (#7893): This code needs to be shared with WinHttpClientHandler
private const string HeaderNameCookie = "Cookie";
private const string HeaderNameWebSocketProtocol = "Sec-WebSocket-Protocol";
#endregion
// TODO (Issue 2503): move System.Net.* strings to resources as appropriate.
// NOTE: All WinHTTP operations must be called while holding the _operation.Lock.
// It is critical that no handle gets closed while a WinHTTP function is running.
private WebSocketCloseStatus? _closeStatus = null;
private string _closeStatusDescription = null;
private string _subProtocol = null;
private bool _disposed = false;
private WinHttpWebSocketState _operation = new WinHttpWebSocketState();
public WinHttpWebSocket()
{
}
#region Properties
public override WebSocketCloseStatus? CloseStatus
{
get
{
return _closeStatus;
}
}
public override string CloseStatusDescription
{
get
{
return _closeStatusDescription;
}
}
public override WebSocketState State
{
get
{
return _operation.State;
}
}
public override string SubProtocol
{
get
{
return _subProtocol;
}
}
#endregion
readonly static WebSocketState[] s_validConnectStates = { WebSocketState.None };
readonly static WebSocketState[] s_validConnectingStates = { WebSocketState.Connecting };
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validConnectingStates);
// Must grab lock until RequestHandle is populated, otherwise we risk resource leaks on Abort.
//
// TODO (Issue 2506): Alternatively, release the lock between WinHTTP operations and check, under lock, that the
// state is still valid to continue operation.
_operation.SessionHandle = InitializeWinHttp(options);
_operation.ConnectionHandle = Interop.WinHttp.WinHttpConnectWithCallback(
_operation.SessionHandle,
uri.IdnHost,
(ushort)uri.Port,
0);
ThrowOnInvalidHandle(_operation.ConnectionHandle);
bool secureConnection = uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss;
_operation.RequestHandle = Interop.WinHttp.WinHttpOpenRequestWithCallback(
_operation.ConnectionHandle,
"GET",
uri.PathAndQuery,
null,
Interop.WinHttp.WINHTTP_NO_REFERER,
null,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(_operation.RequestHandle);
_operation.IncrementHandlesOpenWithCallback();
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET,
IntPtr.Zero,
0))
{
WinHttpException.ThrowExceptionUsingLastError();
}
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SECURE_FAILURE;
if (Interop.WinHttp.WinHttpSetStatusCallback(
_operation.RequestHandle,
WinHttpWebSocketCallback.s_StaticCallbackDelegate,
notificationFlags,
IntPtr.Zero) == (IntPtr)Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.RequestHandle.AttachCallback();
// We need to pin the operation object at this point in time since the WinHTTP callback
// has been fully wired to the request handle and the operation object has been set as
// the context value of the callback. Any notifications from activity on the handle will
// result in the callback being called with the context value.
_operation.Pin();
AddRequestHeaders(uri, options);
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
}
await InternalSendWsUpgradeRequestAsync().ConfigureAwait(false);
await InternalReceiveWsUpgradeResponse().ConfigureAwait(false);
lock (_operation.Lock)
{
VerifyUpgradeResponse();
ThrowOnInvalidConnectState();
_operation.WebSocketHandle =
Interop.WinHttp.WinHttpWebSocketCompleteUpgrade(_operation.RequestHandle, IntPtr.Zero);
ThrowOnInvalidHandle(_operation.WebSocketHandle);
_operation.IncrementHandlesOpenWithCallback();
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.WebSocketHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.WebSocketHandle.AttachCallback();
_operation.UpdateState(WebSocketState.Open);
if (_operation.RequestHandle != null)
{
_operation.RequestHandle.Dispose();
// RequestHandle will be set to null in the callback.
}
_operation.TcsUpgrade = null;
ctr.Dispose();
}
}
}
// Requires lock taken.
private Interop.WinHttp.SafeWinHttpHandle InitializeWinHttp(ClientWebSocketOptions options)
{
Interop.WinHttp.SafeWinHttpHandle sessionHandle;
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
null,
null,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return sessionHandle;
}
private Task<bool> InternalSendWsUpgradeRequestAsync()
{
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
if (!Interop.WinHttp.WinHttpSendRequest(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_NO_ADDITIONAL_HEADERS,
0,
IntPtr.Zero,
0,
0,
_operation.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private Task<bool> InternalReceiveWsUpgradeResponse()
{
// TODO (Issue 2507): Potential optimization: move this in WinHttpWebSocketCallback.
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
if (!Interop.WinHttp.WinHttpReceiveResponse(_operation.RequestHandle, IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private void ThrowOnInvalidConnectState()
{
// A special behavior for WebSocket upgrade: throws ConnectFailure instead of other Abort messages.
if (_operation.State != WebSocketState.Connecting)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
private readonly static WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived };
public override Task SendAsync(
ArraySegment<byte> buffer,
WebSocketMessageType messageType,
bool endOfMessage,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validSendStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
var bufferType = WebSocketMessageTypeAdapter.GetWinHttpMessageType(messageType, endOfMessage);
_operation.PinSendBuffer(buffer);
bool sendOperationAlreadyPending = false;
if (_operation.PendingWriteOperation == false)
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validSendStates);
if (_operation.PendingWriteOperation == false)
{
_operation.PendingWriteOperation = true;
_operation.TcsSend = new TaskCompletionSource<bool>();
uint ret = Interop.WinHttp.WinHttpWebSocketSend(
_operation.WebSocketHandle,
bufferType,
buffer.Count > 0 ? Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset) : IntPtr.Zero,
(uint)buffer.Count);
if (Interop.WinHttp.ERROR_SUCCESS != ret)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
else
{
sendOperationAlreadyPending = true;
}
}
}
else
{
sendOperationAlreadyPending = true;
}
if (sendOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "SendAsync"));
_operation.TcsSend.TrySetException(exception);
Abort();
}
return _operation.TcsSend.Task;
}
}
private readonly static WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent };
private readonly static WebSocketState[] s_validAfterReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent, WebSocketState.CloseReceived };
public override async Task<WebSocketReceiveResult> ReceiveAsync(
ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validReceiveStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.PinReceiveBuffer(buffer);
await InternalReceiveAsync(buffer).ConfigureAwait(false);
// Check for abort.
_operation.InterlockedCheckValidStates(s_validAfterReceiveStates);
WebSocketMessageType bufferType;
bool endOfMessage;
bufferType = WebSocketMessageTypeAdapter.GetWebSocketMessageType(_operation.BufferType, out endOfMessage);
int bytesTransferred = 0;
checked
{
bytesTransferred = (int)_operation.BytesTransferred;
}
WebSocketReceiveResult ret;
if (bufferType == WebSocketMessageType.Close)
{
UpdateServerCloseStatus();
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage, _closeStatus, _closeStatusDescription);
}
else
{
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage);
}
return ret;
}
}
private Task<bool> InternalReceiveAsync(ArraySegment<byte> buffer)
{
bool receiveOperationAlreadyPending = false;
if (_operation.PendingReadOperation == false)
{
lock (_operation.Lock)
{
if (_operation.PendingReadOperation == false)
{
_operation.CheckValidState(s_validReceiveStates);
_operation.TcsReceive = new TaskCompletionSource<bool>();
_operation.PendingReadOperation = true;
uint bytesRead = 0;
Interop.WinHttp.WINHTTP_WEB_SOCKET_BUFFER_TYPE winHttpBufferType = 0;
uint status = Interop.WinHttp.WinHttpWebSocketReceive(
_operation.WebSocketHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset),
(uint)buffer.Count,
out bytesRead, // Unused in async mode: ignore.
out winHttpBufferType); // Unused in async mode: ignore.
if (Interop.WinHttp.ERROR_SUCCESS != status)
{
throw WinHttpException.CreateExceptionUsingError((int)status);
}
}
else
{
receiveOperationAlreadyPending = true;
}
}
}
else
{
receiveOperationAlreadyPending = true;
}
if (receiveOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "ReceiveAsync"));
_operation.TcsReceive.TrySetException(exception);
Abort();
}
return _operation.TcsReceive.Task;
}
private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override async Task CloseAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.TcsClose = new TaskCompletionSource<bool>();
await InternalCloseAsync(closeStatus, statusDescription).ConfigureAwait(false);
UpdateServerCloseStatus();
}
}
private Task<bool> InternalCloseAsync(WebSocketCloseStatus closeStatus, string statusDescription)
{
uint ret;
_operation.TcsClose = new TaskCompletionSource<bool>();
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseStates);
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsClose.Task;
}
private void UpdateServerCloseStatus()
{
uint ret;
ushort serverStatus;
var closeDescription = new byte[WebSocketValidate.MaxControlFramePayloadLength];
uint closeDescriptionConsumed;
lock (_operation.Lock)
{
ret = Interop.WinHttp.WinHttpWebSocketQueryCloseStatus(
_operation.WebSocketHandle,
out serverStatus,
closeDescription,
(uint)closeDescription.Length,
out closeDescriptionConsumed);
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
_closeStatus = (WebSocketCloseStatus)serverStatus;
_closeStatusDescription = Encoding.UTF8.GetString(closeDescription, 0, (int)closeDescriptionConsumed);
}
}
private readonly static WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived };
private readonly static WebSocketState[] s_validCloseOutputStatesAfterUpdate = { WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override Task CloseOutputAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseOutputStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseOutputStatesAfterUpdate);
uint ret;
_operation.TcsCloseOutput = new TaskCompletionSource<bool>();
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsCloseOutput.Task;
}
}
private void VerifyUpgradeResponse()
{
// Check the status code
var statusCode = GetHttpStatusCode();
if (statusCode != HttpStatusCode.SwitchingProtocols)
{
Abort();
return;
}
_subProtocol = GetResponseHeader(HeaderNameWebSocketProtocol);
}
private void AddRequestHeaders(Uri uri, ClientWebSocketOptions options)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (options.Cookies != null)
{
string cookieHeader = GetCookieHeader(uri, options.Cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(options.RequestHeaders.ToString());
var subProtocols = options.RequestedSubProtocols;
if (subProtocols.Count > 0)
{
requestHeadersBuffer.AppendLine(string.Format("{0}: {1}", HeaderNameWebSocketProtocol,
string.Join(", ", subProtocols)));
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
_operation.RequestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static string GetCookieHeader(Uri uri, CookieContainer cookies)
{
string cookieHeader = null;
Debug.Assert(cookies != null);
string cookieValues = cookies.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
cookieHeader = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", HeaderNameCookie, cookieValues);
}
return cookieHeader;
}
private HttpStatusCode GetHttpStatusCode()
{
uint infoLevel = Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER;
uint result = 0;
uint resultSize = sizeof(uint);
if (!Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
ref result,
ref resultSize,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return (HttpStatusCode)result;
}
private unsafe string GetResponseHeader(string headerName, char[] buffer = null)
{
const int StackLimit = 128;
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
if (buffer == null)
{
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = buffer)
{
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[bufferLength];
return GetResponseHeader(headerName, buffer);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
private unsafe bool QueryHeaders(string headerName, char* buffer, ref int bufferLength)
{
Debug.Assert(bufferLength >= 0, "bufferLength must not be negative.");
uint index = 0;
// Convert the char buffer length to the length in bytes.
uint bufferLengthInBytes = (uint)bufferLength * sizeof(char);
// The WinHttpQueryHeaders buffer length is in bytes,
// but the API actually returns Unicode characters.
bool result = Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_CUSTOM,
headerName,
new IntPtr(buffer),
ref bufferLengthInBytes,
ref index);
// Convert the byte buffer length back to the length in chars.
bufferLength = (int)bufferLengthInBytes / sizeof(char);
return result;
}
public override void Dispose()
{
if (!_disposed)
{
lock (_operation.Lock)
{
// Disposing will involve calling WinHttpClose on handles. It is critical that no other WinHttp
// function is running at the same time.
if (!_disposed)
{
_operation.Dispose();
_disposed = true;
}
}
}
// No need to suppress finalization since the finalizer is not overridden.
}
public override void Abort()
{
lock (_operation.Lock)
{
if ((State != WebSocketState.None) && (State != WebSocketState.Connecting))
{
_operation.UpdateState(WebSocketState.Aborted);
}
else
{
// ClientWebSocket Desktop behavior: a ws that was not connected will not switch state to Aborted.
_operation.UpdateState(WebSocketState.Closed);
}
Dispose();
}
CancelAllOperations();
}
private void CancelAllOperations()
{
if (_operation.TcsClose != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsClose.TrySetException(exception);
}
if (_operation.TcsCloseOutput != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsCloseOutput.TrySetException(exception);
}
if (_operation.TcsReceive != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsReceive.TrySetException(exception);
}
if (_operation.TcsSend != null)
{
var exception = new OperationCanceledException();
_operation.TcsSend.TrySetException(exception);
}
if (_operation.TcsUpgrade != null)
{
var exception = new WebSocketException(SR.net_webstatus_ConnectFailure);
_operation.TcsUpgrade.TrySetException(exception);
}
}
private void ThrowOnInvalidHandle(Interop.WinHttp.SafeWinHttpHandle value)
{
if (value.IsInvalid)
{
Abort();
throw new WebSocketException(
SR.net_webstatus_ConnectFailure,
WinHttpException.CreateExceptionUsingLastError());
}
}
private CancellationTokenRegistration ThrowOrRegisterCancellation(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
Abort();
cancellationToken.ThrowIfCancellationRequested();
}
CancellationTokenRegistration cancellationRegistration =
cancellationToken.Register(s => ((WinHttpWebSocket)s).Abort(), this);
return cancellationRegistration;
}
}
}
| |
/*
* This file is part of PathEdit.
*
* PathEdit is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace PathEdit
{
/// <summary>
/// Form to edit a path variable
/// </summary>
public class FormEditAddPath : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Label labelPath;
private System.ComponentModel.Container components = null;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.Button buttonBrowse;
private bool cancel = false;
#region Constructors and Destructor
public FormEditAddPath()
{
// Required for Windows Form Designer support
InitializeComponent();
}
public FormEditAddPath(String path)
{
// Required for Windows Form Designer support
InitializeComponent();
textBox1.Text = path;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelPath = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.buttonOK = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.buttonBrowse = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelPath
//
this.labelPath.Location = new System.Drawing.Point(8, 8);
this.labelPath.Name = "labelPath";
this.labelPath.Size = new System.Drawing.Size(72, 16);
this.labelPath.TabIndex = 0;
this.labelPath.Tag = "";
this.labelPath.Text = "Path Entry:";
this.labelPath.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(72, 8);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(256, 20);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "";
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_EnterPress);
//
// buttonOK
//
this.buttonOK.Location = new System.Drawing.Point(112, 40);
this.buttonOK.Name = "buttonOK";
this.buttonOK.TabIndex = 3;
this.buttonOK.Text = "OK";
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(192, 40);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonBrowse
//
this.buttonBrowse.Location = new System.Drawing.Point(328, 8);
this.buttonBrowse.Name = "buttonBrowse";
this.buttonBrowse.Size = new System.Drawing.Size(24, 20);
this.buttonBrowse.TabIndex = 2;
this.buttonBrowse.Text = "...";
this.buttonBrowse.Click += new System.EventHandler(this.buttonBrowse_Click);
//
// FormEditAddPath
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(360, 75);
this.Controls.Add(this.buttonBrowse);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.labelPath);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormEditAddPath";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Add/Edit Path";
this.ResumeLayout(false);
}
#endregion
#region Form Menber Functions
private void buttonOK_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void buttonCancel_Click(object sender, System.EventArgs e)
{
cancel = true;
this.Close();
}
/// <summary>
/// Close the form on enter key
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void textBox1_EnterPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == 13 || e.KeyChar == 27) this.Close();
}
/// <summary>
/// Browse button click event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonBrowse_Click(object sender, System.EventArgs e)
{
folderBrowserDialog1.Description = "Select Folder to Add to Path";
if (textBox1.Text != "") folderBrowserDialog1.SelectedPath = textBox1.Text;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
}
textBox1.Focus();
}
#endregion
/// <summary>
/// Accessor method to retrieve path specified in textbox
/// </summary>
/// <returns></returns>
public String GetPath()
{
if (cancel == true) return null;
if (textBox1.Text == "") return null;
return textBox1.Text;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
{
internal sealed class InternalDecoderBestFitFallback : DecoderFallback
{
// Our variables
internal Encoding encoding = null;
internal char[] arrayBestFit = null;
internal char cReplacement = '?';
internal InternalDecoderBestFitFallback(Encoding encoding)
{
// Need to load our replacement characters table.
this.encoding = encoding;
this.bIsMicrosoftBestFitFallback = true;
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalDecoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(Object value)
{
InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback;
if (that != null)
{
return (this.encoding.CodePage == that.encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return this.encoding.CodePage;
}
}
internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer
{
// Our variables
internal char cBestFit = '\0';
internal int iCount = -1;
internal int iSize;
private InternalDecoderBestFitFallback oFallback;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback)
{
oFallback = fallback;
if (oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
if (oFallback.arrayBestFit == null)
oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData();
}
}
}
// Fallback methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
cBestFit = TryBestFit(bytesUnknown);
if (cBestFit == '\0')
cBestFit = oFallback.cReplacement;
iCount = iSize = 1;
return true;
}
// Default version is overridden in DecoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (iCount == int.MaxValue)
{
iCount = -1;
return '\0';
}
// Return the best fit character
return cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (iCount >= 0)
iCount++;
// Return true if we could do it.
return (iCount >= 0 && iCount <= iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (iCount > 0) ? iCount : 0;
}
}
// Clear the buffer
public override unsafe void Reset()
{
iCount = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length (always 1 for InternalDecoderBestFitFallback, either
// a best fit char or ?
return 1;
}
// private helper methods
private char TryBestFit(byte[] bytesCheck)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
int highBound = oFallback.arrayBestFit.Length;
int index;
char cCheck;
// Check trivial case first (no best fit)
if (highBound == 0)
return '\0';
// If our array is too small or too big we can't check
if (bytesCheck.Length == 0 || bytesCheck.Length > 2)
return '\0';
if (bytesCheck.Length == 1)
cCheck = unchecked((char)bytesCheck[0]);
else
cCheck = unchecked((char)((bytesCheck[0] << 8) + bytesCheck[1]));
// Check trivial out of range case
if (cCheck < oFallback.arrayBestFit[0] || cCheck > oFallback.arrayBestFit[highBound - 2])
return '\0';
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because it must be word aligned.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = oFallback.arrayBestFit[index];
if (cTest == cCheck)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
else if (cTest < cCheck)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (oFallback.arrayBestFit[index] == cCheck)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
using System;
namespace Lambda2Js
{
public static class ScriptVersionHelper
{
// See: ECMAScript 5/6/7 compatibility tables
// https://github.com/kangax/compat-table
// http://kangax.github.io/compat-table
// See: Ecma International, Technical Committee 39 - ECMAScript
// https://github.com/tc39
/// <summary>
/// Indicates whether the specified version of JavaScript supports the given syntax.
/// </summary>
/// <param name="scriptVersion"></param>
/// <param name="syntax"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static bool Supports(this ScriptVersion scriptVersion, JavascriptSyntaxFeature syntax)
{
switch (syntax)
{
case JavascriptSyntaxFeature.ArrowFunction:
case JavascriptSyntaxFeature.ArraySpread:
return scriptVersion.IsSupersetOf(ScriptVersion.Es60);
default:
throw new ArgumentOutOfRangeException(nameof(syntax));
}
}
/// <summary>
/// Indicates whether the specified version of JavaScript supports the given syntax.
/// </summary>
/// <param name="scriptVersion"></param>
/// <param name="api"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static bool Supports(this ScriptVersion scriptVersion, JavascriptApiFeature api)
{
switch (api)
{
case JavascriptApiFeature.String_prototype_substring:
case JavascriptApiFeature.String_prototype_toUpperCase:
case JavascriptApiFeature.String_prototype_toLowerCase:
case JavascriptApiFeature.String_prototype_indexOf:
case JavascriptApiFeature.String_prototype_lastIndexOf:
return true;
case JavascriptApiFeature.String_prototype_trimLeft:
case JavascriptApiFeature.String_prototype_trimRight:
if (scriptVersion.IsSupersetOf(ScriptVersion.Js181))
return true;
throw new ArgumentOutOfRangeException(nameof(api));
case JavascriptApiFeature.String_prototype_trim:
return scriptVersion.IsSupersetOf(ScriptVersion.Es51);
case JavascriptApiFeature.String_prototype_startsWith:
case JavascriptApiFeature.String_prototype_endsWith:
case JavascriptApiFeature.String_prototype_includes:
return scriptVersion.IsSupersetOf(ScriptVersion.Es60);
case JavascriptApiFeature.String_prototype_padStart:
case JavascriptApiFeature.String_prototype_padEnd:
return scriptVersion.IsSupersetOf(ScriptVersion.Es80);
default:
throw new ArgumentOutOfRangeException(nameof(api));
}
}
/// <summary>
/// Creates a new ScriptVersion with the given parameters.
/// </summary>
/// <param name="spec">The specification to use, or 0 (zero) to use ECMA standard.</param>
/// <param name="specVersion">The specification version. Pass 0 if using ECMA standard.</param>
/// <param name="ecmaVersion"></param>
/// <param name="allowDeprecated"></param>
/// <param name="allowProposals"></param>
/// <returns></returns>
public static ScriptVersion Create(ScriptVersion spec, int specVersion, int ecmaVersion, bool allowDeprecated, bool allowProposals)
{
if (spec.GetSpecification() != spec)
throw new ArgumentException("Pure specification expected in parameter.", nameof(spec));
if (spec == 0 && specVersion != 0)
throw new ArgumentException("Specification version must be zero when no specification is passed.", nameof(specVersion));
var specVerFld = specVersion * Consts.SVerFld;
if (specVerFld >= Consts.SVerLim)
throw new ArgumentException("Specification version overflow.", nameof(specVersion));
var ecmaVerFld = ecmaVersion * Consts.EcmaFld;
if (ecmaVerFld >= Consts.EcmaLim)
throw new ArgumentException("ECMAScript version overflow.", nameof(ecmaVersion));
var flags = (allowProposals ? 1 : 0) + (allowDeprecated ? 2 : 0);
return spec + specVerFld + ecmaVerFld + flags * Consts.FlagFld;
}
/// <summary>
/// Changes the script version to accept deprecated features.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion Deprecated(this ScriptVersion scriptVersion)
{
return Create(
scriptVersion.GetSpecification(),
scriptVersion.GetSpecificationVersion(),
scriptVersion.GetStandardVersion(),
true,
scriptVersion.IsProposals());
}
/// <summary>
/// Changes the script version to accept deprecated features.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion Deprecated(this ScriptVersion scriptVersion, bool value)
{
return Create(
scriptVersion.GetSpecification(),
scriptVersion.GetSpecificationVersion(),
scriptVersion.GetStandardVersion(),
value,
scriptVersion.IsProposals());
}
/// <summary>
/// Changes the script version to accept proposed features.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion Proposals(this ScriptVersion scriptVersion)
{
return Create(
scriptVersion.GetSpecification(),
scriptVersion.GetSpecificationVersion(),
scriptVersion.GetStandardVersion(),
scriptVersion.IsDeprecated(),
true);
}
/// <summary>
/// Changes the script version to accept proposed features.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion Proposals(this ScriptVersion scriptVersion, bool value)
{
return Create(
scriptVersion.GetSpecification(),
scriptVersion.GetSpecificationVersion(),
scriptVersion.GetStandardVersion(),
scriptVersion.IsDeprecated(),
value);
}
/// <summary>
/// Changes the script version to accept only ECMAScript standard features.
/// Won't change deprecated nor proposals flags.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion ToStandard(this ScriptVersion scriptVersion)
{
return Create(
0,
0,
scriptVersion.GetStandardVersion(),
scriptVersion.IsDeprecated(),
scriptVersion.IsProposals());
}
/// <summary>
/// Changes the script version to accept non-standard features from any specification.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion NonStandard(this ScriptVersion scriptVersion)
{
if (scriptVersion.GetSpecification() != 0)
throw new ArgumentException("Script version must have no assigned specification.", nameof(scriptVersion));
return Create(
ScriptVersion.NonStandard,
scriptVersion.GetSpecificationVersion(),
scriptVersion.GetStandardVersion(),
scriptVersion.IsDeprecated(),
scriptVersion.IsProposals());
}
/// <summary>
/// Changes the script version to accept JScript features.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion MicrosoftJScript(this ScriptVersion scriptVersion, int specVersion)
{
if (scriptVersion.GetSpecification() != 0)
throw new ArgumentException("Script version must have no assigned specification.", nameof(scriptVersion));
return Create(
ScriptVersion.MsJ,
specVersion,
scriptVersion.GetStandardVersion(),
scriptVersion.IsDeprecated(),
scriptVersion.IsProposals());
}
/// <summary>
/// Changes the script version to accept Javascript (Mozilla) features.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion Javascript(this ScriptVersion scriptVersion, int specVersion)
{
if (scriptVersion.GetSpecification() != 0)
throw new ArgumentException("Script version must have no assigned specification.", nameof(scriptVersion));
return Create(
ScriptVersion.Js,
specVersion,
scriptVersion.GetStandardVersion(),
scriptVersion.IsDeprecated(),
scriptVersion.IsProposals());
}
/// <summary>
/// Whether a specific version of the script is a superset of another version.
/// This can be used as a rather general feature indicator, but there may be exceptions, such as deprecated features.
/// </summary>
/// <param name="scriptVersion"></param>
/// <param name="baseScriptVersion"></param>
/// <returns></returns>
public static bool IsSupersetOf(this ScriptVersion scriptVersion, ScriptVersion baseScriptVersion)
{
var specOther = baseScriptVersion.GetSpecification();
if (specOther == 0)
return scriptVersion.GetStandardVersion() >= baseScriptVersion.GetStandardVersion();
var specThis = scriptVersion.GetSpecification();
if (specThis == ScriptVersion.NonStandard)
return scriptVersion.GetStandardVersion() >= baseScriptVersion.GetStandardVersion();
if (specThis == specOther)
return scriptVersion.GetSpecificationVersion() >= baseScriptVersion.GetSpecificationVersion();
return false;
}
/// <summary>
/// Gets the version of the non-standard specification, if one is present.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static int GetSpecificationVersion(this ScriptVersion scriptVersion)
{
return ((int)scriptVersion % Consts.SVerLim) / Consts.SVerFld;
}
/// <summary>
/// Gets the version of the ECMAScript standard.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static int GetStandardVersion(this ScriptVersion scriptVersion)
{
return ((int)scriptVersion % Consts.EcmaLim) / Consts.EcmaFld;
}
/// <summary>
/// Gets the version of the non-standard specification.
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static ScriptVersion GetSpecification(this ScriptVersion scriptVersion)
{
return (ScriptVersion)(((int)scriptVersion / Consts.SpecFld) * Consts.SpecFld);
}
/// <summary>
/// Gets a value indicating whether the script version supports proposals
/// (i.e. next ECMAScript proposed features).
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static bool IsProposals(this ScriptVersion scriptVersion)
{
return (((int)scriptVersion / (int)ScriptVersion.Proposals) & 1) == 1;
}
/// <summary>
/// Gets a value indicating whether the script version supports deprecated features
/// (i.e. features excluded from the standard, but present in one of Js or MsJ specification).
/// </summary>
/// <param name="scriptVersion"></param>
/// <returns></returns>
public static bool IsDeprecated(this ScriptVersion scriptVersion)
{
return (((int)scriptVersion / (int)ScriptVersion.Deprecated) & 1) == 1;
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SpatialAnalysis.IsovistUtility;
using SpatialAnalysis.Geometry;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using SpatialAnalysis.Data;
namespace SpatialAnalysis.Agents.OptionalScenario.Visualization
{
/// <summary>
/// Interaction logic for RealTimeFreeNavigationControler.xaml
/// </summary>
public partial class RealTimeFreeNavigationControler : Window
{
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
this.Owner.WindowState = this.WindowState;
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
this._velocityMin.TextChanged -= _velocityMin_TextChanged;
this._velocity.ValueChanged -= _velocity_ValueChanged;
this._velocityMax.TextChanged -= _velocityMax_TextChanged;
this._angularVelocityMin.TextChanged -= _angularVelocityMin_TextChanged;
this._angularVelocity.ValueChanged -= _angularVelocity_ValueChanged;
this._angularVelocityMax.TextChanged -= _angularVelocityMax_TextChanged;
this._bodySizeMin.TextChanged -= _bodySizeMin_TextChanged;
this._bodySize.ValueChanged -= _bodySize_ValueChanged;
this._bodySizeMax.TextChanged -= _bodySizeMax_TextChanged;
this._viewAngleMin.TextChanged -= _viewAngleMin_TextChanged;
this._viewAngle.ValueChanged -= _viewAngle_ValueChanged;
this._viewAngleMax.TextChanged -= _viewAngleMax_TextChanged;
this._minDecisionMakingPeriod.TextChanged -= _minDecisionMakingPeriod_TextChanged;
this._decisionMakingPeriod.ValueChanged -= _decisionMakingPeriod_ValueChanged;
this._maxDecisionMakingPeriod.TextChanged -= _maxDecisionMakingPeriod_TextChanged;
this._angleWeightMin.TextChanged -= _angleWeightMin_TextChanged;
this._angleWeight.ValueChanged -= _angleWeight_ValueChanged;
this._angleWeightMax.TextChanged -= _angleWeightMax_TextChanged;
this._desirabilityWeightMin.TextChanged -= _desirabilityWeightMin_TextChanged;
this._desirabilityWeight.ValueChanged -= _desirabilityWeight_ValueChanged;
this._desirabilityWeightMax.TextChanged -= _desirabilityWeightMax_TextChanged;
this._minBarrierRepulsionRange.TextChanged -= _minBarrierRepulsionRange_TextChanged;
this._barrierRepulsionRange.ValueChanged -= _barrierRepulsionRange_ValueChanged;
this._maxBarrierRepulsionRange.TextChanged -= _maxBarrierRepulsionRange_TextChanged;
this._minRepulsionChangeRate.TextChanged -= _minRepulsionChangeRate_TextChanged;
this._repulsionChangeRate.ValueChanged -= _repulsionChangeRate_ValueChanged;
this._maxRepulsionChangeRate.TextChanged -= _maxRepulsionChangeRate_TextChanged;
this._accelerationMagnitudeMin.TextChanged -= _accelerationMagnitudeMin_TextChanged;
this._accelerationMagnitude.ValueChanged -= _accelerationMagnitude_ValueChanged;
this._accelerationMagnitudeMax.TextChanged -= _accelerationMagnitudeMax_TextChanged;
this._barrierFrictionMin.TextChanged -= _barrierFrictionMin_TextChanged;
this._barrierFriction.ValueChanged -= _barrierFriction_ValueChanged;
this._barrierFrictionMax.TextChanged -= _barrierFrictionMax_TextChanged;
this._bodyElasticityMin.TextChanged -= _bodyElasticityMin_TextChanged;
this._bodyElasticity.ValueChanged -= _bodyElasticity_ValueChanged;
this._bodyElasticityMax.TextChanged -= _bodyElasticityMax_TextChanged;
}
public RealTimeFreeNavigationControler()
{
InitializeComponent();
this._velocityMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Minimum.ToString();
this._velocityMin.TextChanged += _velocityMin_TextChanged;
this._velocity.Value = Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Value;
this._velocity.ValueChanged += _velocity_ValueChanged;
this._velocityMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Maximum.ToString();
this._velocityMax.TextChanged += _velocityMax_TextChanged;
this._angularVelocityMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Minimum.ToString();
this._angularVelocityMin.TextChanged += _angularVelocityMin_TextChanged;
this._angularVelocity.Value = Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Value;
this._angularVelocity.ValueChanged += _angularVelocity_ValueChanged;
this._angularVelocityMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Maximum.ToString();
this._angularVelocityMax.TextChanged += _angularVelocityMax_TextChanged;
this._bodySizeMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Minimum.ToString();
this._bodySizeMin.TextChanged += _bodySizeMin_TextChanged;
this._bodySize.Value = Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Value;
this._bodySize.ValueChanged += _bodySize_ValueChanged;
this._bodySizeMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Maximum.ToString();
this._bodySizeMax.TextChanged += _bodySizeMax_TextChanged;
this._viewAngleMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Minimum.ToString();
this._viewAngleMin.TextChanged += _viewAngleMin_TextChanged;
this._viewAngle.Value = Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Value;
this._viewAngle.ValueChanged += _viewAngle_ValueChanged;
this._viewAngleMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Maximum.ToString();
this._viewAngleMax.TextChanged += _viewAngleMax_TextChanged;
this._minDecisionMakingPeriod.Text = Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Minimum.ToString();
this._minDecisionMakingPeriod.TextChanged += _minDecisionMakingPeriod_TextChanged;
this._decisionMakingPeriod.Value = Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Value;
this._decisionMakingPeriod.ValueChanged += _decisionMakingPeriod_ValueChanged;
this._maxDecisionMakingPeriod.Text = Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Maximum.ToString();
this._maxDecisionMakingPeriod.TextChanged += _maxDecisionMakingPeriod_TextChanged;
this._angleWeightMin.Text = Parameter.DefaultParameters[AgentParameters.OPT_AngleDistributionLambdaFactor].Minimum.ToString();
this._angleWeightMin.TextChanged += _angleWeightMin_TextChanged;
this._angleWeight.Value = Parameter.DefaultParameters[AgentParameters.OPT_AngleDistributionLambdaFactor].Value;
this._angleWeight.ValueChanged += _angleWeight_ValueChanged;
this._angleWeightMax.Text = Parameter.DefaultParameters[AgentParameters.OPT_AngleDistributionLambdaFactor].Maximum.ToString();
this._angleWeightMax.TextChanged += _angleWeightMax_TextChanged;
this._desirabilityWeightMin.Text = Parameter.DefaultParameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor].Minimum.ToString();
this._desirabilityWeightMin.TextChanged += _desirabilityWeightMin_TextChanged;
this._desirabilityWeight.Value = Parameter.DefaultParameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor].Value;
this._desirabilityWeight.ValueChanged += _desirabilityWeight_ValueChanged;
this._desirabilityWeightMax.Text = Parameter.DefaultParameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor].Maximum.ToString();
this._desirabilityWeightMax.TextChanged += _desirabilityWeightMax_TextChanged;
this._minBarrierRepulsionRange.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Minimum.ToString();
this._minBarrierRepulsionRange.TextChanged += _minBarrierRepulsionRange_TextChanged;
this._barrierRepulsionRange.Value = Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Value;
this._barrierRepulsionRange.ValueChanged += _barrierRepulsionRange_ValueChanged;
this._maxBarrierRepulsionRange.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Maximum.ToString();
this._maxBarrierRepulsionRange.TextChanged += _maxBarrierRepulsionRange_TextChanged;
this._minRepulsionChangeRate.Text = Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Minimum.ToString();
this._minRepulsionChangeRate.TextChanged += _minRepulsionChangeRate_TextChanged;
this._repulsionChangeRate.Value = Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Value;
this._repulsionChangeRate.ValueChanged += _repulsionChangeRate_ValueChanged;
this._maxRepulsionChangeRate.Text = Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Maximum.ToString();
this._maxRepulsionChangeRate.TextChanged += _maxRepulsionChangeRate_TextChanged;
this._accelerationMagnitudeMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Minimum.ToString();
this._accelerationMagnitudeMin.TextChanged += _accelerationMagnitudeMin_TextChanged;
this._accelerationMagnitude.Value = Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Value;
this._accelerationMagnitude.ValueChanged += _accelerationMagnitude_ValueChanged;
this._accelerationMagnitudeMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Maximum.ToString();
this._accelerationMagnitudeMax.TextChanged += _accelerationMagnitudeMax_TextChanged;
this._barrierFrictionMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Minimum.ToString();
this._barrierFrictionMin.TextChanged += _barrierFrictionMin_TextChanged;
this._barrierFriction.Value = Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Value;
this._barrierFriction.ValueChanged += _barrierFriction_ValueChanged;
this._barrierFrictionMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Maximum.ToString();
this._barrierFrictionMax.TextChanged += _barrierFrictionMax_TextChanged;
this._bodyElasticityMin.Text = Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Minimum.ToString();
this._bodyElasticityMin.TextChanged += _bodyElasticityMin_TextChanged;
this._bodyElasticity.Value = Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Value;
this._bodyElasticity.ValueChanged += _bodyElasticity_ValueChanged;
this._bodyElasticityMax.Text = Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Maximum.ToString();
this._bodyElasticityMax.TextChanged += _bodyElasticityMax_TextChanged;
}
void _bodyElasticityMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _bodyElasticity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Value = e.NewValue;
}
void _bodyElasticityMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AgentBodyElasticity].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _barrierFrictionMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _barrierFriction_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Value = e.NewValue;
}
void _barrierFrictionMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierFriction].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _accelerationMagnitudeMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _accelerationMagnitude_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Value = e.NewValue;
}
void _accelerationMagnitudeMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AccelerationMagnitude].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _maxRepulsionChangeRate_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _repulsionChangeRate_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Value = e.NewValue;
}
void _minRepulsionChangeRate_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_MaximumRepulsion].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _maxBarrierRepulsionRange_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _barrierRepulsionRange_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Value = e.NewValue;
}
void _minBarrierRepulsionRange_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BarrierRepulsionRange].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _desirabilityWeightMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _desirabilityWeight_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor].Value = e.NewValue;
}
void _desirabilityWeightMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _angleWeightMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.OPT_AngleDistributionLambdaFactor].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _angleWeight_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.OPT_AngleDistributionLambdaFactor].Value = e.NewValue;
}
void _angleWeightMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.OPT_AngleDistributionLambdaFactor].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _maxDecisionMakingPeriod_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _decisionMakingPeriod_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Value = e.NewValue;
}
void _minDecisionMakingPeriod_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _viewAngleMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _viewAngle_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Value = e.NewValue;
}
void _viewAngleMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VisibilityAngle].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _bodySizeMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _bodySize_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Value = e.NewValue;
}
void _bodySizeMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_BodySize].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _angularVelocityMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _angularVelocity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Value = e.NewValue;
}
catch (Exception ) { }
}
void _angularVelocityMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_AngularVelocity].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _velocityMax_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Maximum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
void _velocity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Value = e.NewValue;
}
void _velocityMin_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
double x;
if (double.TryParse(textBox.Text, out x))
{
try
{
Parameter.DefaultParameters[AgentParameters.GEN_VelocityMagnitude].Minimum = x;
textBox.Foreground = Brushes.Black;
}
catch (Exception)
{
textBox.Foreground = Brushes.Red;
}
}
else
{
textBox.Foreground = Brushes.Red;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Generic hash table implementation
**
** #DictionaryVersusHashtableThreadSafety
** Hashtable has multiple reader/single writer (MR/SW) thread safety built into
** certain methods and properties, whereas Dictionary doesn't. If you're
** converting framework code that formerly used Hashtable to Dictionary, it's
** important to consider whether callers may have taken a dependence on MR/SW
** thread safety. If a reader writer lock is available, then that may be used
** with a Dictionary to get the same thread safety guarantee.
**
===========================================================*/
namespace System.Collections.Generic
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
/// <summary>
/// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
internal enum InsertionBehavior : byte
{
/// <summary>
/// The default insertion behavior.
/// </summary>
None = 0,
/// <summary>
/// Specifies that an existing entry with the same key should be overwritten if encountered.
/// </summary>
OverwriteExisting = 1,
/// <summary>
/// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
/// </summary>
ThrowOnExisting = 2
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback
{
private struct Entry
{
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
private int count;
private int version;
private int freeList;
private int freeCount;
private IEqualityComparer<TKey> comparer;
private KeyCollection keys;
private ValueCollection values;
private Object _syncRoot;
// constants for serialization
private const String VersionName = "Version"; // Do not rename (binary serialization)
private const String HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length
private const String KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization)
private const String ComparerName = "Comparer"; // Do not rename (binary serialization)
public Dictionary() : this(0, null) { }
public Dictionary(int capacity) : this(capacity, null) { }
public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { }
public Dictionary(int capacity, IEqualityComparer<TKey> comparer)
{
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
if (this.comparer == EqualityComparer<string>.Default)
{
this.comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
}
public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) :
this(dictionary != null ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
// It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>))
{
Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d.count;
Entry[] entries = d.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
Add(entries[i].key, entries[i].value);
}
}
return;
}
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) :
this(collection, null)
{ }
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) :
this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context)
{
//We can't do anything with the keys and values until the entire graph has been deserialized
//and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
//we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer
{
get
{
return comparer;
}
}
public int Count
{
get { return count - freeCount; }
}
public KeyCollection Keys
{
get
{
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
public ValueCollection Values
{
get
{
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
if (values == null) values = new ValueCollection(this);
return values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
if (values == null) values = new ValueCollection(this);
return values;
}
}
public TValue this[TKey key]
{
get
{
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
public void Add(TKey key, TValue value)
{
bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value))
{
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear()
{
if (count > 0)
{
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
Array.Clear(entries, 0, count);
freeList = -1;
count = 0;
freeCount = 0;
version++;
}
}
public bool ContainsKey(TKey key)
{
return FindEntry(key) >= 0;
}
public bool ContainsValue(TValue value)
{
if (value == null)
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0 && entries[i].value == null) return true;
}
}
else
{
EqualityComparer<TValue> c = EqualityComparer<TValue>.Default;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true;
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, version);
info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>));
info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array.
if (buckets != null)
{
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
private void Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
buckets = new int[size];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[size];
freeList = -1;
}
private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets == null) Initialize(0);
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int targetBucket = hashCode % buckets.Length;
int collisionCount = 0;
for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
collisionCount++;
}
int index;
if (freeCount > 0)
{
index = freeList;
freeList = entries[index].next;
freeCount--;
}
else
{
if (count == entries.Length)
{
Resize();
targetBucket = hashCode % buckets.Length;
}
index = count;
count++;
}
entries[index].hashCode = hashCode;
entries[index].next = buckets[targetBucket];
entries[index].key = key;
entries[index].value = value;
buckets[targetBucket] = index;
version++;
// If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// i.e. EqualityComparer<string>.Default.
if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default)
{
comparer = (IEqualityComparer<TKey>)EqualityComparer<string>.Default;
Resize(entries.Length, true);
}
return true;
}
public virtual void OnDeserialization(Object sender)
{
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
if (siInfo == null)
{
// It might be necessary to call OnDeserialization from a container if the container object also implements
// OnDeserialization. However, remoting will call OnDeserialization again.
// We can return immediately if this function is called twice.
// Note we set remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
if (hashsize != 0)
{
buckets = new int[hashsize];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[hashsize];
freeList = -1;
KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i = 0; i < array.Length; i++)
{
if (array[i].Key == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Add(array[i].Key, array[i].Value);
}
}
else
{
buckets = null;
}
version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize()
{
Resize(HashHelpers.ExpandPrime(count), false);
}
private void Resize(int newSize, bool forceNewHashCodes)
{
Debug.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
if (forceNewHashCodes)
{
for (int i = 0; i < count; i++)
{
if (newEntries[i].hashCode != -1)
{
newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF);
}
}
}
for (int i = 0; i < count; i++)
{
if (newEntries[i].hashCode >= 0)
{
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
}
}
buckets = newBuckets;
entries = newEntries;
}
// The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
int i = buckets[bucket];
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && comparer.Equals(entry.key, key))
{
if (last < 0)
{
buckets[bucket] = entry.next;
}
else
{
entries[last].next = entry.next;
}
entry.hashCode = -1;
entry.next = freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default(TKey);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default(TValue);
}
freeList = i;
freeCount++;
version++;
return true;
}
last = i;
i = entry.next;
}
}
return false;
}
// This overload is a copy of the overload Remove(TKey key) with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key, out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
int i = buckets[bucket];
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && comparer.Equals(entry.key, key))
{
if (last < 0)
{
buckets[bucket] = entry.next;
}
else
{
entries[last].next = entry.next;
}
value = entry.value;
entry.hashCode = -1;
entry.next = freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default(TKey);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default(TValue);
}
freeList = i;
freeCount++;
version++;
return true;
}
last = i;
i = entry.next;
}
}
value = default(TValue);
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
int i = FindEntry(key);
if (i >= 0)
{
value = entries[i].value;
return true;
}
value = default(TValue);
return false;
}
public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null)
{
CopyTo(pairs, index);
}
else if (array is DictionaryEntry[])
{
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
int count = this.count;
Entry[] entries = this.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
ICollection IDictionary.Keys
{
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values
{
get { return (ICollection)Values; }
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = FindEntry((TKey)key);
if (i >= 0)
{
return entries[i].value;
}
}
return null;
}
set
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return (key is TKey);
}
void IDictionary.Add(object key, object value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int version;
private int index;
private KeyValuePair<TKey, TValue> current;
private int getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
this.getEnumeratorRetType = getEnumeratorRetType;
current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
while ((uint)index < (uint)dictionary.count)
{
ref Entry entry = ref dictionary.entries[index++];
if (entry.hashCode >= 0)
{
current = new KeyValuePair<TKey, TValue>(entry.key, entry.value);
return true;
}
}
index = dictionary.count + 1;
current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey, TValue> Current
{
get { return current; }
}
public void Dispose()
{
}
object IEnumerator.Current
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (getEnumeratorRetType == DictEntry)
{
return new System.Collections.DictionaryEntry(current.Key, current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
}
}
}
void IEnumerator.Reset()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(current.Key, current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return current.Value;
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private Dictionary<TKey, TValue> dictionary;
public KeyCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(dictionary);
}
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
public int Count
{
get { return dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item)
{
return dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null)
{
CopyTo(keys, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get { return ((ICollection)dictionary).SyncRoot; }
}
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TKey currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentKey = default(TKey);
}
public void Dispose()
{
}
public bool MoveNext()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count)
{
ref Entry entry = ref dictionary.entries[index++];
if (entry.hashCode >= 0)
{
currentKey = entry.key;
return true;
}
}
index = dictionary.count + 1;
currentKey = default(TKey);
return false;
}
public TKey Current
{
get
{
return currentKey;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentKey;
}
}
void System.Collections.IEnumerator.Reset()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
currentKey = default(TKey);
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private Dictionary<TKey, TValue> dictionary;
public ValueCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(dictionary);
}
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
public int Count
{
get { return dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item)
{
return dictionary.ContainsValue(item);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return new Enumerator(dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
TValue[] values = array as TValue[];
if (values != null)
{
CopyTo(values, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get { return ((ICollection)dictionary).SyncRoot; }
}
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> dictionary;
private int index;
private int version;
private TValue currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentValue = default(TValue);
}
public void Dispose()
{
}
public bool MoveNext()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)index < (uint)dictionary.count)
{
ref Entry entry = ref dictionary.entries[index++];
if (entry.hashCode >= 0)
{
currentValue = entry.value;
return true;
}
}
index = dictionary.count + 1;
currentValue = default(TValue);
return false;
}
public TValue Current
{
get
{
return currentValue;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (index == 0 || (index == dictionary.count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return currentValue;
}
}
void System.Collections.IEnumerator.Reset()
{
if (version != dictionary.version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
currentValue = default(TValue);
}
}
}
}
}
| |
// 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;
using System.Collections.Generic;
namespace System.Linq
{
internal static class Enumerable
{
public static IEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, false);
}
}
internal abstract class OrderedEnumerable<TElement> : IEnumerable<TElement>
{
internal IEnumerable<TElement> source;
public IEnumerator<TElement> GetEnumerator()
{
Buffer<TElement> buffer = new Buffer<TElement>(source);
if (buffer.count > 0)
{
EnumerableSorter<TElement> sorter = GetEnumerableSorter(null);
int[] map = sorter.Sort(buffer.items, buffer.count);
sorter = null;
for (int i = 0; i < buffer.count; i++) yield return buffer.items[map[i]];
}
}
internal abstract EnumerableSorter<TElement> GetEnumerableSorter(EnumerableSorter<TElement> next);
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class OrderedEnumerable<TElement, TKey> : OrderedEnumerable<TElement>
{
internal OrderedEnumerable<TElement> parent;
internal Func<TElement, TKey> keySelector;
internal IComparer<TKey> comparer;
internal bool descending;
internal OrderedEnumerable(IEnumerable<TElement> source, Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
this.source = source;
this.parent = null;
this.keySelector = keySelector;
this.comparer = comparer != null ? comparer : Comparer<TKey>.Default;
this.descending = descending;
}
internal override EnumerableSorter<TElement> GetEnumerableSorter(EnumerableSorter<TElement> next)
{
EnumerableSorter<TElement> sorter = new EnumerableSorter<TElement, TKey>(keySelector, comparer, descending, next);
if (parent != null) sorter = parent.GetEnumerableSorter(sorter);
return sorter;
}
}
internal abstract class EnumerableSorter<TElement>
{
internal abstract void ComputeKeys(TElement[] elements, int count);
internal abstract int CompareKeys(int index1, int index2);
internal int[] Sort(TElement[] elements, int count)
{
ComputeKeys(elements, count);
int[] map = new int[count];
for (int i = 0; i < count; i++) map[i] = i;
QuickSort(map, 0, count - 1);
return map;
}
void QuickSort(int[] map, int left, int right)
{
do
{
int i = left;
int j = right;
int x = map[i + ((j - i) >> 1)];
do
{
while (i < map.Length && CompareKeys(x, map[i]) > 0) i++;
while (j >= 0 && CompareKeys(x, map[j]) < 0) j--;
if (i > j) break;
if (i < j)
{
int temp = map[i];
map[i] = map[j];
map[j] = temp;
}
i++;
j--;
} while (i <= j);
if (j - left <= right - i)
{
if (left < j) QuickSort(map, left, j);
left = i;
}
else
{
if (i < right) QuickSort(map, i, right);
right = j;
}
} while (left < right);
}
}
internal class EnumerableSorter<TElement, TKey> : EnumerableSorter<TElement>
{
internal Func<TElement, TKey> keySelector;
internal IComparer<TKey> comparer;
internal bool descending;
internal EnumerableSorter<TElement> next;
internal TKey[] keys;
internal EnumerableSorter(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending, EnumerableSorter<TElement> next)
{
this.keySelector = keySelector;
this.comparer = comparer;
this.descending = descending;
this.next = next;
}
internal override void ComputeKeys(TElement[] elements, int count)
{
keys = new TKey[count];
for (int i = 0; i < count; i++) keys[i] = keySelector(elements[i]);
if (next != null) next.ComputeKeys(elements, count);
}
internal override int CompareKeys(int index1, int index2)
{
int c = comparer.Compare(keys[index1], keys[index2]);
if (c == 0)
{
if (next == null) return index1 - index2;
return next.CompareKeys(index1, index2);
}
return descending ? -c : c;
}
}
struct Buffer<TElement>
{
internal TElement[] items;
internal int count;
internal Buffer(IEnumerable<TElement> source)
{
TElement[] items = null;
int count = 0;
ICollection<TElement> collection = source as ICollection<TElement>;
if (collection != null)
{
count = collection.Count;
if (count > 0)
{
items = new TElement[count];
collection.CopyTo(items, 0);
}
}
else
{
foreach (TElement item in source)
{
if (items == null)
{
items = new TElement[4];
}
else if (items.Length == count)
{
TElement[] newItems = new TElement[checked(count * 2)];
Array.Copy(items, 0, newItems, 0, count);
items = newItems;
}
items[count] = item;
count++;
}
}
this.items = items;
this.count = count;
}
internal TElement[] ToArray()
{
if (count == 0) return new TElement[0];
if (items.Length == count) return items;
TElement[] result = new TElement[count];
Array.Copy(items, 0, result, 0, count);
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection.Metadata;
using ApiContractGenerator.Model.TypeReferences;
namespace ApiContractGenerator
{
public sealed partial class CSharpTextFormatter
{
private sealed class SignatureTypeProvider : IMetadataTypeReferenceVisitor<ImmutableNode<string>>
{
private readonly string currentNamespace;
public SignatureTypeProvider(string currentNamespace)
{
this.currentNamespace = currentNamespace;
}
private static ImmutableNode<string> Literal(string value) => new ImmutableNode<string>(null, value, null);
private static readonly ImmutableNode<string>[] PrimitiveTypesByCode =
{
null,
Literal("void"),
Literal("bool"),
Literal("char"),
Literal("sbyte"),
Literal("byte"),
Literal("short"),
Literal("ushort"),
Literal("int"),
Literal("uint"),
Literal("long"),
Literal("ulong"),
Literal("float"),
Literal("double"),
Literal("string"),
null,
null,
null,
null,
null,
null,
null,
Literal("System.TypedReference"),
null,
Literal("System.IntPtr"),
Literal("System.UIntPtr"),
null,
null,
Literal("object")
};
private static readonly ImmutableNode<string> DecimalPrimitiveType = Literal("decimal");
public ImmutableNode<string> Visit(PrimitiveTypeReference primitiveTypeReference)
{
return PrimitiveTypesByCode[(int)primitiveTypeReference.Code];
}
private static readonly List<string> ArraySuffixesByDimension = new List<string> { null, "[]", "[,]", "[,,]", "[,,,]", "[,,,,]", "[,,,,,]", "[,,,,,,]", "[,,,,,,,]" };
public ImmutableNode<string> Visit(ArrayTypeReference array)
{
while (ArraySuffixesByDimension.Count < array.Rank)
{
var buffer = new char[array.Rank + 1];
buffer[0] = '[';
for (var i = 1; i < buffer.Length - 2; i++)
buffer[i] = ',';
buffer[buffer.Length - 1] = ']';
ArraySuffixesByDimension.Add(new string(buffer));
}
return new ImmutableNode<string>(array.ElementType.Accept(this), ArraySuffixesByDimension[array.Rank], null);
}
private static readonly ImmutableNode<string> GenericParameterListEnd = new ImmutableNode<string>(null, ">", null);
private static ImmutableNode<string> BuildNameWithArity(string rawName)
{
var (name, arity) = NameUtils.ParseGenericArity(rawName);
var arityBuilder = (ImmutableNode<string>)null;
if (arity != 0)
{
arityBuilder = GenericParameterListEnd;
for (var i = 1; i < arity; i++)
arityBuilder = new ImmutableNode<string>(null, ",", arityBuilder);
arityBuilder = new ImmutableNode<string>(null, "<", arityBuilder);
}
return new ImmutableNode<string>(null, name, arityBuilder);
}
public ImmutableNode<string> Visit(TopLevelTypeReference topLevelTypeReference)
{
if (topLevelTypeReference.Namespace == "System")
{
switch (topLevelTypeReference.Name)
{
case "Void":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Void];
case "Boolean":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Boolean];
case "Char":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Char];
case "SByte":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.SByte];
case "Byte":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Byte];
case "Int16":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Int16];
case "UInt16":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.UInt16];
case "Int32":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Int32];
case "UInt32":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.UInt32];
case "Int64":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Int64];
case "UInt64":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.UInt64];
case "Single":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Single];
case "Double":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Double];
case "String":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.String];
case "Object":
return PrimitiveTypesByCode[(int)PrimitiveTypeCode.Object];
case "Decimal":
return DecimalPrimitiveType;
}
}
return AddNamespace(topLevelTypeReference, BuildNameWithArity(topLevelTypeReference.Name));
}
private ImmutableNode<string> AddNamespace(TopLevelTypeReference topLevelTypeReference, ImmutableNode<string> name)
{
return currentNamespace == topLevelTypeReference.Namespace || string.IsNullOrEmpty(topLevelTypeReference.Namespace) ? name :
new ImmutableNode<string>(new ImmutableNode<string>(null, topLevelTypeReference.Namespace, null), ".", name);
}
public ImmutableNode<string> Visit(GenericParameterTypeReference genericParameterTypeReference)
{
return new ImmutableNode<string>(null, genericParameterTypeReference.TypeParameter.Name, null);
}
public ImmutableNode<string> Visit(GenericInstantiationTypeReference genericInstantiationTypeReference)
{
var args = genericInstantiationTypeReference.GenericTypeArguments;
if (args.Count == 1
&& genericInstantiationTypeReference.TypeDefinition is TopLevelTypeReference topLevel
&& topLevel.Name == "Nullable`1"
&& topLevel.Namespace == "System")
{
return new ImmutableNode<string>(args[0].Accept(this), "?", null);
}
if (IsValueTuple(genericInstantiationTypeReference, minArgs: 2) && TryUseTupleSyntax(args, out var tupleSyntax))
{
return tupleSyntax;
}
var builder = (ImmutableNode<string>)null;
var argumentsLeft = genericInstantiationTypeReference.GenericTypeArguments.Count;
void BuildNext(string typeName)
{
var (name, arity) = NameUtils.ParseGenericArity(typeName);
if (arity != 0)
{
if (argumentsLeft < arity) throw new InvalidOperationException("Number of generic arguments provided does not match combined type arity.");
builder = new ImmutableNode<string>(null, ">", builder);
for (var i = 0; i < arity; i++)
{
argumentsLeft--;
builder = new ImmutableNode<string>(
genericInstantiationTypeReference.GenericTypeArguments[argumentsLeft].Accept(this),
i == 0 ? null : ", ",
builder);
}
builder = new ImmutableNode<string>(null, "<", builder);
}
builder = new ImmutableNode<string>(null, name, builder);
}
var currentType = genericInstantiationTypeReference.TypeDefinition;
for (; currentType is NestedTypeReference nested; currentType = nested.DeclaringType)
{
BuildNext(nested.Name);
builder = new ImmutableNode<string>(null, ".", builder);
}
topLevel = currentType as TopLevelTypeReference ??
throw new InvalidOperationException("Nested types must be declared by either a top-level type or another nested type.");
BuildNext(topLevel.Name);
if (argumentsLeft != 0) throw new InvalidOperationException("Number of generic arguments provided does not match combined type arity.");
return AddNamespace(topLevel, builder);
}
private static readonly string[] ValueTupleNamesByArity =
{
null, "ValueTuple`1", "ValueTuple`2", "ValueTuple`3", "ValueTuple`4", "ValueTuple`5", "ValueTuple`6", "ValueTuple`7", "ValueTuple`8"
};
private static bool IsValueTuple(GenericInstantiationTypeReference genericInstantiationTypeReference, int minArgs)
{
var args = genericInstantiationTypeReference.GenericTypeArguments;
return args.Count >= minArgs
&& args.Count <= 8
&& genericInstantiationTypeReference.TypeDefinition is TopLevelTypeReference topLevel
&& topLevel.Name == ValueTupleNamesByArity[args.Count]
&& topLevel.Namespace == "System";
}
private bool TryUseTupleSyntax(IReadOnlyList<MetadataTypeReference> args, out ImmutableNode<string> tupleSyntax)
{
var tupleElements = new List<MetadataTypeReference>(args.Count);
while (args.Count == 8)
{
if (!(args[7] is GenericInstantiationTypeReference genericRest && IsValueTuple(genericRest, minArgs: 1)))
{
tupleSyntax = null;
return false;
}
for (var i = 0; i < 7; i++)
tupleElements.Add(args[i]);
args = genericRest.GenericTypeArguments;
}
for (var i = 0; i < args.Count; i++)
tupleElements.Add(args[i]);
var current = new ImmutableNode<string>(tupleElements[tupleElements.Count - 1].Accept(this), ")", null);
for (var i = tupleElements.Count - 2; i >= 0; i--)
current = new ImmutableNode<string>(tupleElements[i].Accept(this), ", ", current);
tupleSyntax = new ImmutableNode<string>(null, "(", current);
return true;
}
public ImmutableNode<string> Visit(ByRefTypeReference byRefTypeReference)
{
return new ImmutableNode<string>(null, "ref ", byRefTypeReference.ElementType.Accept(this));
}
public ImmutableNode<string> Visit(NestedTypeReference nestedTypeReference)
{
return new ImmutableNode<string>(nestedTypeReference.DeclaringType.Accept(this), ".", BuildNameWithArity(nestedTypeReference.Name));
}
public ImmutableNode<string> Visit(PointerTypeReference pointerTypeReference)
{
return new ImmutableNode<string>(pointerTypeReference.ElementType.Accept(this), "*", null);
}
}
}
}
| |
//
// Mono.Google.GoogleConnection.cs:
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
// Stephane Delcroix ([email protected])
//
// (C) Copyright 2006 Novell, Inc. (http://www.novell.com)
// (C) Copyright 2007 S. 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.
//
// Check the Google Authentication Page at http://code.google.com/apis/accounts/AuthForInstalledApps.html
//
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Reflection;
namespace Mono.Google {
public class GoogleConnection {
string user;
GoogleService service;
string auth;
string appname;
public GoogleConnection (GoogleService service)
{
this.service = service;
}
public string ApplicationName {
get {
if (appname == null) {
Assembly assembly = Assembly.GetEntryAssembly ();
if (assembly == null)
throw new InvalidOperationException ("You need to set GoogleConnection.ApplicationName.");
AssemblyName aname = assembly.GetName ();
appname = String.Format ("{0}-{1}", aname.Name, aname.Version);
}
return appname;
}
set {
if (value == null || value == "")
throw new ArgumentException ("Cannot be null or empty", "value");
appname = value;
}
}
public void Authenticate (string user, string password)
{
if (user == null)
throw new ArgumentNullException ("user");
if (this.user != null)
throw new InvalidOperationException (String.Format ("Already authenticated for {0}", this.user));
this.user = user;
this.auth = Authentication.GetAuthorization (this, user, password, service, null, null);
if (this.auth == null) {
this.user = null;
throw new Exception (String.Format ("Authentication failed for user {0}", user));
}
}
public void Authenticate (string user, string password, string token, string captcha)
{
if (user == null)
throw new ArgumentNullException ("user");
if (token == null)
throw new ArgumentNullException ("token");
if (captcha == null)
throw new ArgumentNullException ("captcha");
if (this.user != null)
throw new InvalidOperationException (String.Format ("Already authenticated for {0}", this.user));
this.user = user;
this.auth = Authentication.GetAuthorization (this, user, password, service, token, captcha);
if (this.auth == null) {
this.user = null;
throw new Exception (String.Format ("Authentication failed for user {0}", user));
}
}
public HttpWebRequest AuthenticatedRequest (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
if (auth != null)
req.Headers.Add ("Authorization: GoogleLogin auth=" + auth);
return req;
}
public string DownloadString (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
string received = null;
HttpWebRequest req = AuthenticatedRequest (url);
HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
Encoding encoding = Encoding.UTF8;
if (response.ContentEncoding != "") {
try {
encoding = Encoding.GetEncoding (response.ContentEncoding);
} catch {}
}
using (Stream stream = response.GetResponseStream ()) {
StreamReader sr = new StreamReader (stream, encoding);
received = sr.ReadToEnd ();
}
response.Close ();
return received;
}
public byte [] DownloadBytes (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
HttpWebRequest req = AuthenticatedRequest (url);
HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
byte [] bytes = null;
using (Stream stream = response.GetResponseStream ()) {
if (response.ContentLength != -1) {
bytes = new byte [response.ContentLength];
stream.Read (bytes, 0, bytes.Length);
} else {
MemoryStream ms = new MemoryStream ();
bytes = new byte [4096];
int nread;
while ((nread = stream.Read (bytes, 0, bytes.Length)) > 0) {
ms.Write (bytes, 0, nread);
if (nread < bytes.Length)
break;
}
bytes = ms.ToArray ();
}
}
response.Close ();
return bytes;
}
public void DownloadToStream (string url, Stream output)
{
if (url == null)
throw new ArgumentNullException ("url");
if (output == null)
throw new ArgumentNullException ("output");
if (!output.CanWrite)
throw new ArgumentException ("The stream is not writeable", "output");
HttpWebRequest req = AuthenticatedRequest (url);
HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
byte [] bytes = null;
using (Stream stream = response.GetResponseStream ()) {
bytes = new byte [4096];
int nread;
while ((nread = stream.Read (bytes, 0, bytes.Length)) > 0) {
output.Write (bytes, 0, nread);
}
}
response.Close ();
}
public string User {
get { return user; }
}
public GoogleService Service {
get { return service; }
}
internal string AuthToken {
get { return auth; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AsyncControllers.Areas.HelpPage.SampleGeneration
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator _simpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return _simpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new[] { 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 ((IEnumerable)list).AsQueryable();
}
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[] { 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;
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;
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 => 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 => 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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace TchApp.HttpSimulator
{
internal partial class Frame
{
private static readonly Type IHttpRequestFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature);
private static readonly Type IHttpResponseFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature);
private static readonly Type IHttpRequestIdentifierFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature);
private static readonly Type IServiceProvidersFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature);
private static readonly Type IHttpRequestLifetimeFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature);
private static readonly Type IHttpConnectionFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature);
private static readonly Type IHttpAuthenticationFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature);
private static readonly Type IQueryFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IQueryFeature);
private static readonly Type IFormFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IFormFeature);
private static readonly Type IHttpUpgradeFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature);
private static readonly Type IResponseCookiesFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature);
private static readonly Type IItemsFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IItemsFeature);
private static readonly Type ITlsConnectionFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature);
private static readonly Type IHttpWebSocketFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature);
private static readonly Type ISessionFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.ISessionFeature);
private static readonly Type IHttpSendFileFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature);
private object _currentIHttpRequestFeature;
private object _currentIHttpResponseFeature;
private object _currentIHttpRequestIdentifierFeature;
private object _currentIServiceProvidersFeature;
private object _currentIHttpRequestLifetimeFeature;
private object _currentIHttpConnectionFeature;
private object _currentIHttpAuthenticationFeature;
private object _currentIQueryFeature;
private object _currentIFormFeature;
private object _currentIHttpUpgradeFeature;
private object _currentIResponseCookiesFeature;
private object _currentIItemsFeature;
private object _currentITlsConnectionFeature;
private object _currentIHttpWebSocketFeature;
private object _currentISessionFeature;
private object _currentIHttpSendFileFeature;
private void FastReset()
{
_currentIHttpRequestFeature = this;
_currentIHttpResponseFeature = this;
_currentIHttpUpgradeFeature = this;
_currentIHttpRequestLifetimeFeature = this;
_currentIHttpConnectionFeature = this;
_currentIHttpRequestIdentifierFeature = null;
_currentIServiceProvidersFeature = null;
_currentIHttpAuthenticationFeature = null;
_currentIQueryFeature = null;
_currentIFormFeature = null;
_currentIResponseCookiesFeature = null;
_currentIItemsFeature = null;
_currentITlsConnectionFeature = null;
_currentIHttpWebSocketFeature = null;
_currentISessionFeature = null;
_currentIHttpSendFileFeature = null;
}
private object FastFeatureGet(Type key)
{
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature))
{
return _currentIHttpRequestFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature))
{
return _currentIHttpResponseFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature))
{
return _currentIHttpRequestIdentifierFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature))
{
return _currentIServiceProvidersFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature))
{
return _currentIHttpRequestLifetimeFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature))
{
return _currentIHttpConnectionFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature))
{
return _currentIHttpAuthenticationFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IQueryFeature))
{
return _currentIQueryFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IFormFeature))
{
return _currentIFormFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature))
{
return _currentIHttpUpgradeFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature))
{
return _currentIResponseCookiesFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IItemsFeature))
{
return _currentIItemsFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature))
{
return _currentITlsConnectionFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature))
{
return _currentIHttpWebSocketFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ISessionFeature))
{
return _currentISessionFeature;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature))
{
return _currentIHttpSendFileFeature;
}
return ExtraFeatureGet(key);
}
private void FastFeatureSet(Type key, object feature)
{
_featureRevision++;
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature))
{
_currentIHttpRequestFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature))
{
_currentIHttpResponseFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature))
{
_currentIHttpRequestIdentifierFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature))
{
_currentIServiceProvidersFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature))
{
_currentIHttpRequestLifetimeFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature))
{
_currentIHttpConnectionFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature))
{
_currentIHttpAuthenticationFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IQueryFeature))
{
_currentIQueryFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IFormFeature))
{
_currentIFormFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature))
{
_currentIHttpUpgradeFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature))
{
_currentIResponseCookiesFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IItemsFeature))
{
_currentIItemsFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature))
{
_currentITlsConnectionFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature))
{
_currentIHttpWebSocketFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ISessionFeature))
{
_currentISessionFeature = feature;
return;
}
if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature))
{
_currentIHttpSendFileFeature = feature;
return;
};
ExtraFeatureSet(key, feature);
}
private IEnumerable<KeyValuePair<Type, object>> FastEnumerable()
{
if (_currentIHttpRequestFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpRequestFeatureType, _currentIHttpRequestFeature as global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature);
}
if (_currentIHttpResponseFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpResponseFeatureType, _currentIHttpResponseFeature as global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature);
}
if (_currentIHttpRequestIdentifierFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpRequestIdentifierFeatureType, _currentIHttpRequestIdentifierFeature as global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature);
}
if (_currentIServiceProvidersFeature != null)
{
yield return new KeyValuePair<Type, object>(IServiceProvidersFeatureType, _currentIServiceProvidersFeature as global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature);
}
if (_currentIHttpRequestLifetimeFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpRequestLifetimeFeatureType, _currentIHttpRequestLifetimeFeature as global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature);
}
if (_currentIHttpConnectionFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpConnectionFeatureType, _currentIHttpConnectionFeature as global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature);
}
if (_currentIHttpAuthenticationFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpAuthenticationFeatureType, _currentIHttpAuthenticationFeature as global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature);
}
if (_currentIQueryFeature != null)
{
yield return new KeyValuePair<Type, object>(IQueryFeatureType, _currentIQueryFeature as global::Microsoft.AspNetCore.Http.Features.IQueryFeature);
}
if (_currentIFormFeature != null)
{
yield return new KeyValuePair<Type, object>(IFormFeatureType, _currentIFormFeature as global::Microsoft.AspNetCore.Http.Features.IFormFeature);
}
if (_currentIHttpUpgradeFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpUpgradeFeatureType, _currentIHttpUpgradeFeature as global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature);
}
if (_currentIResponseCookiesFeature != null)
{
yield return new KeyValuePair<Type, object>(IResponseCookiesFeatureType, _currentIResponseCookiesFeature as global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature);
}
if (_currentIItemsFeature != null)
{
yield return new KeyValuePair<Type, object>(IItemsFeatureType, _currentIItemsFeature as global::Microsoft.AspNetCore.Http.Features.IItemsFeature);
}
if (_currentITlsConnectionFeature != null)
{
yield return new KeyValuePair<Type, object>(ITlsConnectionFeatureType, _currentITlsConnectionFeature as global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature);
}
if (_currentIHttpWebSocketFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpWebSocketFeatureType, _currentIHttpWebSocketFeature as global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature);
}
if (_currentISessionFeature != null)
{
yield return new KeyValuePair<Type, object>(ISessionFeatureType, _currentISessionFeature as global::Microsoft.AspNetCore.Http.Features.ISessionFeature);
}
if (_currentIHttpSendFileFeature != null)
{
yield return new KeyValuePair<Type, object>(IHttpSendFileFeatureType, _currentIHttpSendFileFeature as global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature);
}
if (MaybeExtra != null)
{
foreach(var item in MaybeExtra)
{
yield return item;
}
}
}
}
}
| |
using System.Collections;
using System.Text;
using System;
using System.Reflection;
namespace Arch.CMessaging.Client.Core.Collections
{
public class RedBlack
{
private int intCount;
private int intHashCode;
private string strIdentifier;
private RedBlackNode rbTree;
public RedBlackNode sentinelNode;
private RedBlackNode lastNodeFound;
private Random rand = new Random();
public RedBlack()
{
strIdentifier = base.ToString() + rand.Next();
intHashCode = rand.Next();
sentinelNode = new RedBlackNode();
sentinelNode.Left = null;
sentinelNode.Right = null;
sentinelNode.Parent = null;
sentinelNode.Color = RedBlackNode.BLACK;
rbTree = sentinelNode;
lastNodeFound = sentinelNode;
}
public RedBlack(string strIdentifier)
{
intHashCode = rand.Next();
this.strIdentifier = strIdentifier;
}
public void Add(IComparable key, object data)
{
if(key == null || data == null)
throw(new RedBlackException("RedBlackNode key and data must not be null"));
int result = 0;
RedBlackNode node = new RedBlackNode();
RedBlackNode temp = rbTree; ;
while(temp != sentinelNode)
{
node.Parent = temp;
result = key.CompareTo(temp.Key);
if(result == 0)
throw(new RedBlackException("A Node with the same key already exists"));
if(result > 0)
temp = temp.Right;
else
temp = temp.Left;
}
node.Key = key;
node.Data = data;
node.Left = sentinelNode;
node.Right = sentinelNode;
if(node.Parent != null)
{
result = node.Key.CompareTo(node.Parent.Key);
if(result > 0)
node.Parent.Right = node;
else
node.Parent.Left = node;
}
else
rbTree = node;
RestoreAfterInsert(node);
lastNodeFound = node;
intCount = intCount + 1;
}
private void RestoreAfterInsert(RedBlackNode x)
{
RedBlackNode y;
while(x != rbTree && x.Parent.Color == RedBlackNode.RED)
{
if(x.Parent == x.Parent.Parent.Left)
{
y = x.Parent.Parent.Right;
if(y!= null && y.Color == RedBlackNode.RED)
{
x.Parent.Color = RedBlackNode.BLACK;
y.Color = RedBlackNode.BLACK;
x.Parent.Parent.Color = RedBlackNode.RED;
x = x.Parent.Parent;
}
else
{
if(x == x.Parent.Right)
{
x = x.Parent;
RotateLeft(x);
}
x.Parent.Color = RedBlackNode.BLACK;
x.Parent.Parent.Color = RedBlackNode.RED;
RotateRight(x.Parent.Parent);
}
}
else
{
y = x.Parent.Parent.Left;
if(y!= null && y.Color == RedBlackNode.RED)
{
x.Parent.Color = RedBlackNode.BLACK;
y.Color = RedBlackNode.BLACK;
x.Parent.Parent.Color = RedBlackNode.RED;
x = x.Parent.Parent;
}
else
{
if(x == x.Parent.Left)
{
x = x.Parent;
RotateRight(x);
}
x.Parent.Color = RedBlackNode.BLACK;
x.Parent.Parent.Color = RedBlackNode.RED;
RotateLeft(x.Parent.Parent);
}
}
}
rbTree.Color = RedBlackNode.BLACK;
}
public void RotateLeft(RedBlackNode x)
{
RedBlackNode y = x.Right;
x.Right = y.Left;
if(y.Left != sentinelNode)
y.Left.Parent = x;
if(y != sentinelNode)
y.Parent = x.Parent;
if(x.Parent != null)
{
if(x == x.Parent.Left)
x.Parent.Left = y;
else
x.Parent.Right = y;
}
else
rbTree = y;
y.Left = x;
if(x != sentinelNode)
x.Parent = y;
}
public void RotateRight(RedBlackNode x)
{
RedBlackNode y = x.Left;
x.Left = y.Right;
if(y.Right != sentinelNode)
y.Right.Parent = x;
if(y != sentinelNode)
y.Parent = x.Parent;
if(x.Parent != null)
{
if(x == x.Parent.Right)
x.Parent.Right = y;
else
x.Parent.Left = y;
}
else
rbTree = y;
y.Right = x;
if(x != sentinelNode)
x.Parent = y;
}
public bool TryGetValue(IComparable key, out object value)
{
int result;
value = null;
var keyFound = false;
RedBlackNode treeNode = rbTree;
while(treeNode != sentinelNode)
{
result = key.CompareTo(treeNode.Key);
if(result == 0)
{
lastNodeFound = treeNode;
value = treeNode.Data;
keyFound = true;
break;
}
if(result < 0)
treeNode = treeNode.Left;
else
treeNode = treeNode.Right;
}
return keyFound;
}
public IComparable GetMinKey()
{
RedBlackNode treeNode = rbTree;
if(treeNode == null || treeNode == sentinelNode)
throw(new RedBlackException("RedBlack tree is empty"));
while(treeNode.Left != sentinelNode)
treeNode = treeNode.Left;
lastNodeFound = treeNode;
return treeNode.Key;
}
public IComparable GetMaxKey()
{
RedBlackNode treeNode = rbTree;
if(treeNode == null || treeNode == sentinelNode)
throw(new RedBlackException("RedBlack tree is empty"));
while(treeNode.Right != sentinelNode)
treeNode = treeNode.Right;
lastNodeFound = treeNode;
return treeNode.Key;
}
public object GetMinValue()
{
object value = null;
TryGetValue(GetMinKey(), out value);
return value;
}
public object GetMaxValue()
{
object value = null;
TryGetValue(GetMaxKey(), out value);
return value;
}
public RedBlackEnumerator GetEnumerator()
{
return Elements(true);
}
public RedBlackEnumerator Keys()
{
return Keys(true);
}
public RedBlackEnumerator Keys(bool ascending)
{
return new RedBlackEnumerator(this, rbTree, true, ascending);
}
public RedBlackEnumerator Values()
{
return Elements(true);
}
public RedBlackEnumerator Elements()
{
return Elements(true);
}
public RedBlackEnumerator Elements(bool ascending)
{
return new RedBlackEnumerator(this, rbTree, false, ascending);
}
public bool IsEmpty()
{
return (rbTree == null);
}
public void Remove(IComparable key)
{
if(key == null)
throw(new RedBlackException("RedBlackNode key is null"));
int result;
RedBlackNode node;
result = key.CompareTo(lastNodeFound.Key);
if(result == 0)
node = lastNodeFound;
else
{
node = rbTree;
while(node != sentinelNode)
{
result = key.CompareTo(node.Key);
if(result == 0)
break;
if(result < 0)
node = node.Left;
else
node = node.Right;
}
if(node == sentinelNode)
return;
}
Delete(node);
intCount = intCount - 1;
}
private void Delete(RedBlackNode z)
{
RedBlackNode x = new RedBlackNode();
RedBlackNode y;
if(z.Left == sentinelNode || z.Right == sentinelNode)
y = z;
else
{
y = z.Right;
while(y.Left != sentinelNode)
y = y.Left;
}
if(y.Left != sentinelNode)
x = y.Left;
else
x = y.Right;
x.Parent = y.Parent;
if(y.Parent != null)
if(y == y.Parent.Left)
y.Parent.Left = x;
else
y.Parent.Right = x;
else
rbTree = x;
if(y != z)
{
z.Key = y.Key;
z.Data = y.Data;
}
if(y.Color == RedBlackNode.BLACK)
RestoreAfterDelete(x);
lastNodeFound = sentinelNode;
}
private void RestoreAfterDelete(RedBlackNode x)
{
RedBlackNode y;
while(x != rbTree && x.Color == RedBlackNode.BLACK)
{
if(x == x.Parent.Left)
{
y = x.Parent.Right;
if(y.Color == RedBlackNode.RED)
{
y.Color = RedBlackNode.BLACK;
x.Parent.Color = RedBlackNode.RED;
RotateLeft(x.Parent);
y = x.Parent.Right;
}
if(y.Left.Color == RedBlackNode.BLACK &&
y.Right.Color == RedBlackNode.BLACK)
{
y.Color = RedBlackNode.RED;
x = x.Parent;
}
else
{
if(y.Right.Color == RedBlackNode.BLACK)
{
y.Left.Color = RedBlackNode.BLACK;
y.Color = RedBlackNode.RED;
RotateRight(y);
y = x.Parent.Right;
}
y.Color = x.Parent.Color;
x.Parent.Color = RedBlackNode.BLACK;
y.Right.Color = RedBlackNode.BLACK;
RotateLeft(x.Parent);
x = rbTree;
}
}
else
{
y = x.Parent.Left;
if(y.Color == RedBlackNode.RED)
{
y.Color = RedBlackNode.BLACK;
x.Parent.Color = RedBlackNode.RED;
RotateRight (x.Parent);
y = x.Parent.Left;
}
if(y.Right.Color == RedBlackNode.BLACK &&
y.Left.Color == RedBlackNode.BLACK)
{
y.Color = RedBlackNode.RED;
x = x.Parent;
}
else
{
if(y.Left.Color == RedBlackNode.BLACK)
{
y.Right.Color = RedBlackNode.BLACK;
y.Color = RedBlackNode.RED;
RotateLeft(y);
y = x.Parent.Left;
}
y.Color = x.Parent.Color;
x.Parent.Color = RedBlackNode.BLACK;
y.Left.Color = RedBlackNode.BLACK;
RotateRight(x.Parent);
x = rbTree;
}
}
}
x.Color = RedBlackNode.BLACK;
}
public void RemoveMin()
{
if(rbTree == null)
throw(new RedBlackException("RedBlackNode is null"));
Remove(GetMinKey());
}
public void RemoveMax()
{
if(rbTree == null)
throw(new RedBlackException("RedBlackNode is null"));
Remove(GetMaxKey());
}
public void Clear ()
{
rbTree = sentinelNode;
intCount = 0;
}
public int Size()
{
return intCount;
}
public override bool Equals(object obj)
{
if(obj == null)
return false;
if(!(obj is RedBlackNode ))
return false;
if(this == obj)
return true;
return (ToString().Equals(((RedBlackNode)(obj)).ToString()));
}
public override int GetHashCode()
{
return intHashCode;
}
public override string ToString()
{
return strIdentifier.ToString();
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
namespace Microsoft.Live
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Live.Operations;
/// <summary>
/// This class contain the public methods that LiveConnectClient implements.
/// The methods in this partial class implement the Task async pattern.
/// </summary>
public partial class LiveConnectClient
{
#region Public Methods
/// <summary>
/// Makes a GET call to Api service
/// </summary>
/// <param name="path">relative path to the resource.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> GetAsync(string path)
{
return this.Api(path, ApiMethod.Get, null, new CancellationToken(false));
}
/// <summary>
/// Makes a GET call to Api service
/// </summary>
/// <param name="path">relative path to the resource.</param>
/// <param name="ct">a token that is used to cancel the get operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> GetAsync(string path, CancellationToken ct)
{
return this.Api(path, ApiMethod.Get, null, ct);
}
/// <summary>
/// Makes a DELETE call to Api service
/// </summary>
/// <param name="path">relative path to the resource being deleted.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> DeleteAsync(string path)
{
return this.Api(path, ApiMethod.Delete, null, new CancellationToken(false));
}
/// <summary>
/// Makes a DELETE call to Api service
/// </summary>
/// <param name="path">relative path to the resource being deleted.</param>
/// <param name="ct">a token that is used to cancel the delete operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> DeleteAsync(string path, CancellationToken ct)
{
return this.Api(path, ApiMethod.Delete, null, ct);
}
/// <summary>
/// Makes a POST call to Api service
/// </summary>
/// <param name="path">relative path to the resource collection to which the new object should be added.</param>
/// <param name="body">properties of the new resource in json.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PostAsync(string path, string body)
{
return this.Api(path, ApiMethod.Post, body, new CancellationToken(false));
}
/// <summary>
/// Makes a POST call to Api service
/// </summary>
/// <param name="path">relative path to the resource collection to which the new object should be added.</param>
/// <param name="body">properties of the new resource in name-value pairs.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PostAsync(string path, IDictionary<string, object> body)
{
return this.Api(path, ApiMethod.Post, ApiOperation.SerializePostBody(body), new CancellationToken(false));
}
/// <summary>
/// Makes a POST call to Api service
/// </summary>
/// <param name="path">relative path to the resource collection to which the new object should be added.</param>
/// <param name="body">properties of the new resource in json.</param>
/// <param name="ct">a token that is used to cancel the post operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PostAsync(string path, string body, CancellationToken ct)
{
return this.Api(path, ApiMethod.Post, body, ct);
}
/// <summary>
/// Makes a POST call to Api service
/// </summary>
/// <param name="path">relative path to the resource collection to which the new object should be added.</param>
/// <param name="body">properties of the new resource in name-value pairs.</param>
/// <param name="ct">a token that is used to cancel the post operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PostAsync(string path, IDictionary<string, object> body, CancellationToken ct)
{
return this.Api(path, ApiMethod.Post, ApiOperation.SerializePostBody(body), ct);
}
/// <summary>
/// Makes a PUT call to Api service
/// </summary>
/// <param name="path">relative path to the resource to be updated.</param>
/// <param name="body">properties of the updated resource in json.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PutAsync(string path, string body)
{
return this.Api(path, ApiMethod.Put, body, new CancellationToken(false));
}
/// <summary>
/// Makes a PUT call to Api service
/// </summary>
/// <param name="path">relative path to the resource to be updated.</param>
/// <param name="body">properties of the updated resource in name-value pairs.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PutAsync(string path, IDictionary<string, object> body)
{
return this.Api(path, ApiMethod.Put, ApiOperation.SerializePostBody(body), new CancellationToken(false));
}
/// <summary>
/// Makes a PUT call to Api service
/// </summary>
/// <param name="path">relative path to the resource to be updated.</param>
/// <param name="body">properties of the updated resource in json.</param>
/// <param name="ct">a token that is used to cancel the put operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PutAsync(string path, string body, CancellationToken ct)
{
return this.Api(path, ApiMethod.Put, body, ct);
}
/// <summary>
/// Makes a PUT call to Api service
/// </summary>
/// <param name="path">relative path to the resource to be updated.</param>
/// <param name="body">properties of the updated resource in json.</param>
/// <param name="ct">a token that is used to cancel the put operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> PutAsync(string path, IDictionary<string, object> body, CancellationToken ct)
{
return this.Api(path, ApiMethod.Put, ApiOperation.SerializePostBody(body), ct);
}
/// <summary>
/// Move a file from one location to another
/// </summary>
/// <param name="path">relative path to the file resource to be moved.</param>
/// <param name="destination">relative path to the folder resource where the file should be moved to.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> MoveAsync(string path, string destination)
{
return this.MoveOrCopy(path, destination, ApiMethod.Move, new CancellationToken(false));
}
/// <summary>
/// Move a file from one location to another
/// </summary>
/// <param name="path">relative path to the file resource to be moved.</param>
/// <param name="destination">relative path to the folder resource where the file should be moved to.</param>
/// <param name="ct">a token that is used to cancel the move operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> MoveAsync(string path, string destination, CancellationToken ct)
{
return this.MoveOrCopy(path, destination, ApiMethod.Move, ct);
}
/// <summary>
/// Copy a file to another location.
/// </summary>
/// <param name="path">relative path to the file resource to be copied.</param>
/// <param name="destination">relative path to the folder resource where the file should be copied to.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> CopyAsync(string path, string destination)
{
return this.MoveOrCopy(path, destination, ApiMethod.Copy, new CancellationToken(false));
}
/// <summary>
/// Copy a file to another location.
/// </summary>
/// <param name="path">relative path to the file resource to be copied.</param>
/// <param name="destination">relative path to the folder resource where the file should be copied to.</param>
/// <param name="ct">a token that is used to cancel the copy operation.</param>
/// <returns>A Task object representing the asynchronous operation.</returns>
public Task<LiveOperationResult> CopyAsync(string path, string destination, CancellationToken ct)
{
return this.MoveOrCopy(path, destination, ApiMethod.Copy, ct);
}
#endregion
#region Private methods
private Task<LiveOperationResult> MoveOrCopy(string path, string destination, ApiMethod method, CancellationToken ct)
{
if (destination == null)
{
throw new ArgumentNullException("destination");
}
if (string.IsNullOrWhiteSpace(destination))
{
throw new ArgumentException("destination");
}
string body = string.Format(CultureInfo.InvariantCulture, ApiOperation.MoveRequestBodyTemplate, destination);
return this.Api(path, method, body, ct);
}
private Task<LiveOperationResult> Api(string path, ApiMethod method, string body, CancellationToken ct)
{
ApiOperation op = this.GetApiOperation(path, method, body);
return this.ExecuteApiOperation(op, ct);
}
private Task<LiveOperationResult> ExecuteApiOperation(ApiOperation op, CancellationToken ct)
{
if (this.Session == null)
{
throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn"));
}
var tcs = new TaskCompletionSource<LiveOperationResult>();
op.OperationCompletedCallback = (LiveOperationResult opResult) =>
{
if (opResult.IsCancelled)
{
tcs.TrySetCanceled();
}
else if (opResult.Error != null)
{
tcs.TrySetException(opResult.Error);
}
else
{
tcs.TrySetResult(opResult);
}
};
ct.Register(op.Cancel);
op.Execute();
return tcs.Task;
}
#endregion
}
}
| |
/*
* Copyright 2011 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: PipeTerminalParameter.cs,v 1.3 2011/11/01 15:35:44 kzmi Exp $
*/
using System;
using Poderosa.Protocols;
using Poderosa.MacroEngine;
namespace Poderosa.Pipe {
/// <summary>
/// Terminal Parameters
/// </summary>
internal class PipeTerminalParameter : ITerminalParameter, IAutoExecMacroParameter {
/// <summary>
/// Environment variable entry
/// </summary>
public class EnvironmentVariable {
public readonly string Name;
public readonly string Value;
public EnvironmentVariable(string name, string value) {
Name = name;
Value = value;
}
}
private string _terminalType;
private string _autoExecMacro;
private string _exeFilePath;
private string _commandLineOptions;
private EnvironmentVariable[] _environmentVariables;
private string _inputPipePath;
private string _outputPipePath;
/// <summary>
/// Constructor
/// </summary>
public PipeTerminalParameter() {
}
/// <summary>
/// Path of an executable file to invoke (or null)
/// </summary>
/// <remarks>
/// ExeFilePath and InputPipePath must be set exclusively from each other.
/// </remarks>
[MacroConnectionParameter]
public string ExeFilePath {
get {
return _exeFilePath;
}
set {
_exeFilePath = value;
}
}
/// <summary>
/// Command line options for invoking the executable file (or null)
/// </summary>
/// <remarks>
/// This property is meaningful only if ExeFilePath was not null.
/// </remarks>
[MacroConnectionParameter]
public string CommandLineOptions {
get {
return _commandLineOptions;
}
set {
_commandLineOptions = value;
}
}
/// <summary>
/// Environment variables to be set before invoking the executable file (or null)
/// </summary>
/// <remarks>
/// This property is meaningful only if ExeFilePath was not null.
/// </remarks>
[MacroConnectionParameter]
public EnvironmentVariable[] EnvironmentVariables {
get {
return _environmentVariables;
}
set {
_environmentVariables = value;
}
}
/// <summary>
/// Path of a pipe for input (or null)
/// </summary>
/// <remarks>
/// InputPipePath and ExeFilePath must be set exclusively from each other.
/// </remarks>
[MacroConnectionParameter]
public string InputPipePath {
get {
return _inputPipePath;
}
set {
_inputPipePath = value;
}
}
/// <summary>
/// Path of a pipe for output (or null)
/// </summary>
/// <remarks>
/// This property is meaningful only if InputPipePath was not null.
/// If this property was null, a file handle of the InputPipePath is used for output.
/// </remarks>
[MacroConnectionParameter]
public string OutputPipePath {
get {
return _outputPipePath;
}
set {
_outputPipePath = value;
}
}
#region ITerminalParameter
public int InitialWidth {
get {
return 80;
}
}
public int InitialHeight {
get {
return 25;
}
}
public string TerminalType {
get {
return _terminalType;
}
}
public void SetTerminalName(string terminaltype) {
_terminalType = terminaltype;
}
public void SetTerminalSize(int width, int height) {
// do nothing
}
public bool UIEquals(ITerminalParameter t) {
PipeTerminalParameter p = t as PipeTerminalParameter;
return p != null
&& ((_exeFilePath == null && p._exeFilePath == null)
|| (_exeFilePath != null && p._exeFilePath != null && String.Compare(_exeFilePath, p._exeFilePath, true) == 0))
&& ((_commandLineOptions == null && p._commandLineOptions == null)
|| (_commandLineOptions != null && p._commandLineOptions != null && String.Compare(_commandLineOptions, p._commandLineOptions, false) == 0))
&& ((_inputPipePath == null && p._inputPipePath == null)
|| (_inputPipePath != null && p._inputPipePath != null && String.Compare(_inputPipePath, p._inputPipePath, true) == 0))
&& ((_outputPipePath == null && p._outputPipePath == null)
|| (_outputPipePath != null && p._outputPipePath != null && String.Compare(_outputPipePath, p._outputPipePath, true) == 0));
}
#endregion
#region IAdaptable
public IAdaptable GetAdapter(System.Type adapter) {
return PipePlugin.Instance.AdapterManager.GetAdapter(this, adapter);
}
#endregion
#region ICloneable
public object Clone() {
PipeTerminalParameter p = (PipeTerminalParameter)MemberwiseClone();
if (_environmentVariables != null)
p._environmentVariables = (EnvironmentVariable[])_environmentVariables.Clone();
return p;
}
#endregion
#region IAutoExecMacroParameter
public string AutoExecMacroPath {
get {
return _autoExecMacro;
}
set {
_autoExecMacro = value;
}
}
#endregion
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.ComponentModel;
using System.IO;
using Alphaleonis.Win32;
using Alphaleonis.Win32.Filesystem;
using Directory = Alphaleonis.Win32.Filesystem.Directory;
using DriveInfo = Alphaleonis.Win32.Filesystem.DriveInfo;
using Path = Alphaleonis.Win32.Filesystem.Path;
using SysIOPath = System.IO.Path;
using SysIOFile = System.IO.File;
using SysIODirectory = System.IO.Directory;
namespace AlphaFS.UnitTest
{
partial class DirectoryTest
{
// Pattern: <class>_<function>_<scenario>_<expected result>
#region AlreadyExistsException: FileExistsWithSameNameAsDirectory
[TestMethod]
public void Directory_CreateDirectory_FileExistsWithSameNameAsDirectory_LocalAndUNC_AlreadyExistsException()
{
Directory_CreateDirectory_FileExistsWithSameNameAsDirectory_AlreadyExistsException(false);
Directory_CreateDirectory_FileExistsWithSameNameAsDirectory_AlreadyExistsException(true);
}
private void Directory_CreateDirectory_FileExistsWithSameNameAsDirectory_AlreadyExistsException(bool isNetwork)
{
UnitTestConstants.PrintUnitTestHeader(isNetwork);
string tempPath = Path.GetTempPath("Directory.CreateDirectory()-FileExistsWithSameNameAsDirectory-" + Path.GetRandomFileName());
if (isNetwork)
tempPath = Path.LocalToUnc(tempPath);
try
{
using (SysIOFile.Create(tempPath)) { }
const int expectedLastError = (int) Win32Errors.ERROR_ALREADY_EXISTS;
const string expectedException = "System.IO.IOException";
bool exception = false;
try
{
Directory.CreateDirectory(tempPath);
}
catch (AlreadyExistsException ex)
{
exception = true;
Console.WriteLine("\nCaught: [{0}]\n\n[{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));
}
catch (Exception ex)
{
Console.WriteLine("\nCaught unexpected {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
}
finally
{
if (SysIOFile.Exists(tempPath))
{
SysIOFile.Delete(tempPath);
Assert.IsFalse(SysIOFile.Exists(tempPath), "Cleanup failed: File should have been removed.");
}
}
}
#endregion // AlreadyExistsException: FileExistsWithSameNameAsDirectory
#region ArgumentException: PathContainsInvalidCharacters
[TestMethod]
public void Directory_CreateDirectory_PathContainsInvalidCharacters_ArgumentException()
{
const string expectedException = "System.ArgumentException";
bool exception = false;
try
{
Directory.CreateDirectory(UnitTestConstants.SysDrive + @"\<>");
}
catch (ArgumentException ex)
{
exception = true;
Console.WriteLine("\nCaught: [{0}]\n\n[{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
catch (Exception ex)
{
Console.WriteLine("\nCaught unexpected {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
}
#endregion // ArgumentException: PathContainsInvalidCharacters
#region ArgumentException: PathStartsWithColon
[TestMethod]
public void Directory_CreateDirectory_PathStartsWithColon_ArgumentException()
{
string tempPath = @":AAAAAAAAAA";
const string expectedException = "System.ArgumentException";
bool exception = false;
try
{
Directory.CreateDirectory(tempPath);
}
catch (ArgumentException ex)
{
exception = true;
Console.WriteLine("\nCaught: [{0}]\n\n[{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
catch (Exception ex)
{
Console.WriteLine("\nCaught unexpected {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
}
#endregion // ArgumentException: PathStartsWithColon
#region DirectoryNotFoundException & IOException: NonExistingDriveLetterLocal
// Note: isNetwork ? "System.IO.IOException" : "System.IO.DirectoryNotFoundException";
[TestMethod]
public void Directory_CreateDirectory_NonExistingDriveLetter_LocalAndUNC_DirectoryNotFoundException()
{
Directory_CreateDirectory_NonExistingDriveLetter_XxxException(false);
Directory_CreateDirectory_NonExistingDriveLetter_XxxException(true);
}
private void Directory_CreateDirectory_NonExistingDriveLetter_XxxException(bool isNetwork)
{
UnitTestConstants.PrintUnitTestHeader(isNetwork);
string tempPath = DriveInfo.GetFreeDriveLetter() + @":\NonExistingDriveLetter";
if (isNetwork)
tempPath = Path.LocalToUnc(tempPath);
int expectedLastError = (int) (isNetwork ? Win32Errors.ERROR_BAD_NET_NAME : Win32Errors.ERROR_PATH_NOT_FOUND);
string expectedException = isNetwork ? "System.IO.IOException" : "System.IO.DirectoryNotFoundException";
bool exception = false;
try
{
Directory.CreateDirectory(tempPath);
}
catch (DirectoryNotFoundException ex)
{
var win32Error = new Win32Exception("", ex);
exception = true;
Console.WriteLine("\nCaught: [{0}]\n\n[{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));
Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode));
}
catch (IOException ex)
{
exception = isNetwork;
Console.WriteLine("\nCaught: [{0}]\n\n[{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError));
}
catch (Exception ex)
{
Console.WriteLine("\nCaught unexpected {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
}
#endregion // DirectoryNotFoundException & IOException: NonExistingDriveLetterLocal
#region NotSupportedException: PathContainsColon
[TestMethod]
public void Directory_CreateDirectory_PathContainsColon_LocalAndUNC_NotSupportedException()
{
Directory_CreateDirectory_PathContainsColon_NotSupportedException(false);
Directory_CreateDirectory_PathContainsColon_NotSupportedException(true);
}
private void Directory_CreateDirectory_PathContainsColon_NotSupportedException(bool isNetwork)
{
UnitTestConstants.PrintUnitTestHeader(isNetwork);
string colonText = ":aaa.txt";
string tempPath = UnitTestConstants.SysDrive + @"\dev\test\"+ colonText;
if (isNetwork)
tempPath = Path.LocalToUnc(tempPath) + colonText;
const string expectedException = "System.NotSupportedException";
bool exception = false;
try
{
Directory.CreateDirectory(tempPath);
}
catch (NotSupportedException ex)
{
exception = true;
Console.WriteLine("\nCaught: [{0}]\n\n[{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
catch (Exception ex)
{
Console.WriteLine("\nCaught unexpected {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " "));
}
Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException);
}
#endregion // NotSupportedException: PathContainsColon
[TestMethod]
public void Directory_CreateDirectory_LocalAndUNC_Success()
{
Directory_CreateDirectory(false);
Directory_CreateDirectory(true);
}
private void Directory_CreateDirectory(bool isNetwork)
{
UnitTestConstants.PrintUnitTestHeader(isNetwork);
// Directory depth level.
int level = new Random().Next(1, 1000);
#if NET35
string emspace = "\u3000";
string tempPath = Path.GetTempPath("Directory.CreateDirectory()-" + level + "-" + SysIOPath.GetRandomFileName() + emspace);
#else
// MSDN: .NET 4+ Trailing spaces are removed from the end of the path parameter before deleting the directory.
string tempPath = Path.GetTempPath("Directory.CreateDirectory()-" + level + "-" + Path.GetRandomFileName());
#endif
if (isNetwork)
tempPath = Path.LocalToUnc(tempPath);
try
{
string root = SysIOPath.Combine(tempPath, "MaxPath-Hit-The-Road");
for (int i = 0; i < level; i++)
root = SysIOPath.Combine(root, "-" + (i + 1) + "-subdir");
Directory.CreateDirectory(root);
Console.WriteLine("\nCreated directory structure: Depth: [{0}], path length: [{1}] characters.", level, root.Length);
Console.WriteLine("\n{0}", root);
Assert.IsTrue(Directory.Exists(root), "Directory should exist.");
}
finally
{
if (SysIODirectory.Exists(tempPath))
Directory.Delete(tempPath, true);
//SysIODirectory.Delete(tempPath, true);
Assert.IsFalse(SysIODirectory.Exists(tempPath), "Cleanup failed: Directory should have been removed.");
Console.WriteLine("\nDirectory deleted.");
}
Console.WriteLine();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace System.Reflection.TypeLoading
{
/// <summary>
/// Base type for all RoTypes that return true for IsTypeDefinition.
/// </summary>
internal abstract partial class RoDefinitionType : RoInstantiationProviderType
{
protected RoDefinitionType()
: base()
{
}
public sealed override bool IsTypeDefinition => true;
protected sealed override bool HasElementTypeImpl() => false;
protected sealed override bool IsArrayImpl() => false;
public sealed override bool IsSZArray => false;
public sealed override bool IsVariableBoundArray => false;
protected sealed override bool IsByRefImpl() => false;
protected sealed override bool IsPointerImpl() => false;
public sealed override bool IsConstructedGenericType => false;
public sealed override bool IsGenericParameter => false;
public sealed override bool IsGenericTypeParameter => false;
public sealed override bool IsGenericMethodParameter => false;
public sealed override bool ContainsGenericParameters => IsGenericTypeDefinition;
protected sealed override string ComputeFullName()
{
Debug.Assert(!IsConstructedGenericType);
Debug.Assert(!IsGenericParameter);
Debug.Assert(!HasElementType);
string name = Name;
Type declaringType = DeclaringType;
if (declaringType != null)
{
string declaringTypeFullName = declaringType.FullName;
return declaringTypeFullName + "+" + name;
}
string ns = Namespace;
if (ns == null)
return name;
return ns + "." + name;
}
public sealed override string ToString() => Loader.GetDisposedString() ?? FullName;
internal abstract int GetGenericParameterCount();
internal abstract override RoType[] GetGenericTypeParametersNoCopy();
public sealed override IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
foreach (CustomAttributeData cad in GetTrueCustomAttributes())
{
yield return cad;
}
if (0 != (Attributes & TypeAttributes.Import))
{
ConstructorInfo ci = Loader.TryGetComImportCtor();
if (ci != null)
yield return new RoPseudoCustomAttributeData(ci);
}
}
}
protected abstract IEnumerable<CustomAttributeData> GetTrueCustomAttributes();
public sealed override Type GetGenericTypeDefinition() => IsGenericTypeDefinition ? this : throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => SpecializeBaseType(Instantiation);
internal abstract RoType SpecializeBaseType(RoType[] instantiation);
protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces() => SpecializeInterfaces(Instantiation);
internal abstract IEnumerable<RoType> SpecializeInterfaces(RoType[] instantiation);
public sealed override Type MakeGenericType(params Type[] typeArguments)
{
if (typeArguments == null)
throw new ArgumentNullException(nameof(typeArguments));
if (!IsGenericTypeDefinition)
throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this));
int count = typeArguments.Length;
if (count != GetGenericParameterCount())
throw new ArgumentException(SR.Argument_GenericArgsCount, nameof(typeArguments));
bool foundSigType = false;
RoType[] runtimeTypeArguments = new RoType[count];
for (int i = 0; i < count; i++)
{
Type typeArgument = typeArguments[i];
if (typeArgument == null)
throw new ArgumentNullException();
if (typeArgument.IsSignatureType())
{
foundSigType = true;
}
else
{
if (!(typeArgument is RoType roTypeArgument && roTypeArgument.Loader == Loader))
throw new ArgumentException(SR.Format(SR.MakeGenericType_NotLoadedByTypeLoader, typeArgument));
runtimeTypeArguments[i] = roTypeArgument;
}
}
if (foundSigType)
return this.MakeSignatureGenericType(typeArguments);
// We are intentionally not validating constraints as constraint validation is an execution-time issue that does not block our
// library and should not block a metadata inspection tool.
return this.GetUniqueConstructedGenericType(runtimeTypeArguments);
}
public sealed override Guid GUID
{
get
{
CustomAttributeData cad = TryFindCustomAttribute(Utf8Constants.SystemRuntimeInteropServices, Utf8Constants.GuidAttribute);
if (cad == null)
return default;
IList<CustomAttributeTypedArgument> ctas = cad.ConstructorArguments;
if (ctas.Count != 1)
return default;
CustomAttributeTypedArgument cta = ctas[0];
if (cta.ArgumentType != Loader.TryGetCoreType(CoreType.String))
return default;
if (!(cta.Value is string guidString))
return default;
return new Guid(guidString);
}
}
public sealed override StructLayoutAttribute StructLayoutAttribute
{
get
{
const int DefaultPackingSize = 8;
// Note: CoreClr checks HasElementType and IsGenericParameter in addition to IsInterface but those properties cannot be true here as this
// RoType subclass is solely for TypeDef types.)
if (IsInterface)
return null;
TypeAttributes attributes = Attributes;
LayoutKind layoutKind;
switch (attributes & TypeAttributes.LayoutMask)
{
case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break;
case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break;
case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break;
default: layoutKind = LayoutKind.Auto; break;
}
CharSet charSet;
switch (attributes & TypeAttributes.StringFormatMask)
{
case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break;
case TypeAttributes.AutoClass: charSet = CharSet.Auto; break;
case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break;
default: charSet = CharSet.None; break;
}
GetPackSizeAndSize(out int pack, out int size);
// Metadata parameter checking should not have allowed 0 for packing size.
// The runtime later converts a packing size of 0 to 8 so do the same here
// because it's more useful from a user perspective.
if (pack == 0)
pack = DefaultPackingSize;
return new StructLayoutAttribute(layoutKind)
{
CharSet = charSet,
Pack = pack,
Size = size,
};
}
}
protected abstract void GetPackSizeAndSize(out int packSize, out int size);
protected sealed override TypeCode GetTypeCodeImpl()
{
Type t = IsEnum ? GetEnumUnderlyingType() : this;
CoreTypes ct = Loader.GetAllFoundCoreTypes();
if (t == ct[CoreType.Boolean])
return TypeCode.Boolean;
if (t == ct[CoreType.Char])
return TypeCode.Char;
if (t == ct[CoreType.SByte])
return TypeCode.SByte;
if (t == ct[CoreType.Byte])
return TypeCode.Byte;
if (t == ct[CoreType.Int16])
return TypeCode.Int16;
if (t == ct[CoreType.UInt16])
return TypeCode.UInt16;
if (t == ct[CoreType.Int32])
return TypeCode.Int32;
if (t == ct[CoreType.UInt32])
return TypeCode.UInt32;
if (t == ct[CoreType.Int64])
return TypeCode.Int64;
if (t == ct[CoreType.UInt64])
return TypeCode.UInt64;
if (t == ct[CoreType.Single])
return TypeCode.Single;
if (t == ct[CoreType.Double])
return TypeCode.Double;
if (t == ct[CoreType.String])
return TypeCode.String;
if (t == ct[CoreType.DateTime])
return TypeCode.DateTime;
if (t == ct[CoreType.Decimal])
return TypeCode.Decimal;
if (t == ct[CoreType.DBNull])
return TypeCode.DBNull;
return TypeCode.Object;
}
internal sealed override RoType GetRoElementType() => null;
public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
internal sealed override RoType[] GetGenericTypeArgumentsNoCopy() => Array.Empty<RoType>();
protected internal sealed override RoType[] GetGenericArgumentsNoCopy() => GetGenericTypeParametersNoCopy();
public sealed override GenericParameterAttributes GenericParameterAttributes => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
public sealed override int GenericParameterPosition => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
public sealed override Type[] GetGenericParameterConstraints() => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
public sealed override MethodBase DeclaringMethod => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter) => SpecializeConstructors(filter, this);
internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType) => SpecializeMethods(filter, reflectedType, this);
internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter filter, Type reflectedType) => SpecializeEvents(filter, reflectedType, this);
internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter filter, Type reflectedType) => SpecializeFields(filter, reflectedType, this);
internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter filter, Type reflectedType) => SpecializeProperties(filter, reflectedType, this);
// Like CoreGetDeclared but allows specifying an alternate declaringType (which must be a generic instantiation of the true declaring type)
internal abstract IEnumerable<ConstructorInfo> SpecializeConstructors(NameFilter filter, RoInstantiationProviderType declaringType);
internal abstract IEnumerable<MethodInfo> SpecializeMethods(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
internal abstract IEnumerable<EventInfo> SpecializeEvents(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
internal abstract IEnumerable<FieldInfo> SpecializeFields(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
internal abstract IEnumerable<PropertyInfo> SpecializeProperties(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
// Helpers for the typeref-resolution/name lookup logic.
internal abstract bool IsTypeNameEqual(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
internal abstract RoDefinitionType GetNestedTypeCore(ReadOnlySpan<byte> utf8Name);
internal sealed override RoType[] Instantiation => GetGenericTypeParametersNoCopy();
}
}
| |
//
// AudioscrobblerConnection.cs
//
// Author:
// Chris Toshok <[email protected]>
// Alexander Hixon <[email protected]>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Timers;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
using System.Web;
using Hyena;
using Mono.Unix;
namespace Lastfm
{
public class AudioscrobblerConnection
{
private enum State {
Idle,
NeedHandshake,
NeedTransmit,
WaitingForRequestStream,
WaitingForHandshakeResp,
WaitingForResponse
};
private const int TICK_INTERVAL = 2000; /* 2 seconds */
private const int FAILURE_LOG_MINUTES = 5; /* 5 minute delay on logging failure to upload information */
private const int RETRY_SECONDS = 60; /* 60 second delay for transmission retries */
private const int MAX_RETRY_SECONDS = 7200; /* 2 hours, as defined in the last.fm protocol */
private const int TIME_OUT = 5000; /* 5 seconds timeout for webrequests */
private const string CLIENT_ID = "bsh";
private const string CLIENT_VERSION = "0.1";
private const string SCROBBLER_URL = "http://post.audioscrobbler.com/";
private const string SCROBBLER_VERSION = "1.2.1";
private string post_url;
private string session_id = null;
private string now_playing_url;
private bool connected = false; /* if we're connected to network or not */
public bool Connected {
get { return connected; }
}
private bool started = false; /* engine has started and was/is connected to AS */
public bool Started {
get { return started; }
}
private System.Timers.Timer timer;
private DateTime next_interval;
private DateTime last_upload_failed_logged;
private IQueue queue;
private int hard_failures = 0;
private int hard_failure_retry_sec = 60;
private HttpWebRequest now_playing_post;
private bool now_playing_started;
private string current_now_playing_data;
private HttpWebRequest current_web_req;
private IAsyncResult current_async_result;
private State state;
internal AudioscrobblerConnection (IQueue queue)
{
LastfmCore.Account.Updated += AccountUpdated;
state = State.Idle;
this.queue = queue;
}
private void AccountUpdated (object o, EventArgs args)
{
Stop ();
session_id = null;
Start ();
}
public void UpdateNetworkState (bool connected)
{
Log.DebugFormat ("Audioscrobbler state: {0}", connected ? "connected" : "disconnected");
this.connected = connected;
}
public void Start ()
{
if (started) {
return;
}
started = true;
hard_failures = 0;
queue.TrackAdded += delegate(object o, EventArgs args) {
StartTransitionHandler ();
};
queue.Load ();
StartTransitionHandler ();
}
private void StartTransitionHandler ()
{
if (!started) {
// Don't run if we're not actually started.
return;
}
if (timer == null) {
timer = new System.Timers.Timer ();
timer.Interval = TICK_INTERVAL;
timer.AutoReset = true;
timer.Elapsed += new ElapsedEventHandler (StateTransitionHandler);
timer.Start ();
} else if (!timer.Enabled) {
timer.Start ();
}
}
public void Stop ()
{
StopTransitionHandler ();
if (current_web_req != null) {
current_web_req.Abort ();
}
queue.Save ();
started = false;
}
private void StopTransitionHandler ()
{
if (timer != null) {
timer.Stop ();
}
}
private void StateTransitionHandler (object o, ElapsedEventArgs e)
{
// if we're not connected, don't bother doing anything involving the network.
if (!connected) {
return;
}
if ((state == State.Idle || state == State.NeedTransmit) && hard_failures > 2) {
state = State.NeedHandshake;
hard_failures = 0;
}
// and address changes in our engine state
switch (state) {
case State.Idle:
if (LastfmCore.Account.UserName != null &&
LastfmCore.Account.SessionKey != null && session_id == null) {
state = State.NeedHandshake;
} else {
if (queue.Count > 0 && session_id != null) {
state = State.NeedTransmit;
} else if (current_now_playing_data != null && session_id != null) {
// Now playing info needs to be sent
NowPlaying (current_now_playing_data);
} else {
StopTransitionHandler ();
}
}
break;
case State.NeedHandshake:
if (DateTime.Now > next_interval) {
Handshake ();
}
break;
case State.NeedTransmit:
if (DateTime.Now > next_interval) {
TransmitQueue ();
}
break;
case State.WaitingForResponse:
case State.WaitingForRequestStream:
case State.WaitingForHandshakeResp:
// nothing here
break;
}
}
//
// Async code for transmitting the current queue of tracks
//
internal class TransmitState
{
public StringBuilder StringBuilder;
public int Count;
}
private void TransmitQueue ()
{
int num_tracks_transmitted;
// save here in case we're interrupted before we complete
// the request. we save it again when we get an OK back
// from the server
queue.Save ();
next_interval = DateTime.MinValue;
if (post_url == null || !connected) {
return;
}
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("s={0}", session_id);
sb.Append (queue.GetTransmitInfo (out num_tracks_transmitted));
current_web_req = (HttpWebRequest) WebRequest.Create (post_url);
current_web_req.UserAgent = LastfmCore.UserAgent;
current_web_req.Method = "POST";
current_web_req.ContentType = "application/x-www-form-urlencoded";
current_web_req.ContentLength = sb.Length;
//Console.WriteLine ("Sending {0} ({1} bytes) to {2}", sb.ToString (), sb.Length, post_url);
TransmitState ts = new TransmitState ();
ts.Count = num_tracks_transmitted;
ts.StringBuilder = sb;
state = State.WaitingForRequestStream;
current_async_result = current_web_req.BeginGetRequestStream (TransmitGetRequestStream, ts);
if (!(current_async_result.AsyncWaitHandle.WaitOne (TIME_OUT, false))) {
Log.Warning ("Audioscrobbler upload failed", "The request timed out and was aborted", false);
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
hard_failures++;
state = State.Idle;
current_web_req.Abort();
}
}
private void TransmitGetRequestStream (IAsyncResult ar)
{
Stream stream;
try {
stream = current_web_req.EndGetRequestStream (ar);
} catch (Exception e) {
Log.Exception ("Failed to get the request stream", e);
state = State.Idle;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
return;
}
TransmitState ts = (TransmitState) ar.AsyncState;
StringBuilder sb = ts.StringBuilder;
StreamWriter writer = new StreamWriter (stream);
writer.Write (sb.ToString ());
writer.Close ();
state = State.WaitingForResponse;
current_async_result = current_web_req.BeginGetResponse (TransmitGetResponse, ts);
if (current_async_result == null) {
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
hard_failures++;
state = State.Idle;
}
}
private void TransmitGetResponse (IAsyncResult ar)
{
WebResponse resp;
try {
resp = current_web_req.EndGetResponse (ar);
}
catch (Exception e) {
Log.Warning (String.Format("Failed to get the response: {0}", e), false);
state = State.Idle;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
return;
}
TransmitState ts = (TransmitState) ar.AsyncState;
Stream s = resp.GetResponseStream ();
StreamReader sr = new StreamReader (s, Encoding.UTF8);
string line;
line = sr.ReadLine ();
DateTime now = DateTime.Now;
if (line.StartsWith ("FAILED")) {
if (now - last_upload_failed_logged > TimeSpan.FromMinutes(FAILURE_LOG_MINUTES)) {
Log.Warning ("Audioscrobbler upload failed", line.Substring ("FAILED".Length).Trim(), false);
last_upload_failed_logged = now;
}
// retransmit the queue on the next interval
hard_failures++;
state = State.NeedTransmit;
}
else if (line.StartsWith ("BADSESSION")) {
if (now - last_upload_failed_logged > TimeSpan.FromMinutes(FAILURE_LOG_MINUTES)) {
Log.Warning ("Audioscrobbler upload failed", "session ID sent was invalid", false);
last_upload_failed_logged = now;
}
// attempt to re-handshake (and retransmit) on the next interval
session_id = null;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
state = State.NeedHandshake;
return;
} else if (line.StartsWith ("OK")) {
/* if we've previously logged failures, be nice and log the successful upload. */
if (last_upload_failed_logged != DateTime.MinValue) {
Log.Debug ("Audioscrobbler upload succeeded");
last_upload_failed_logged = DateTime.MinValue;
}
hard_failures = 0;
// we succeeded, pop the elements off our queue
queue.RemoveRange (0, ts.Count);
queue.Save ();
state = State.Idle;
} else {
if (now - last_upload_failed_logged > TimeSpan.FromMinutes(FAILURE_LOG_MINUTES)) {
Log.Warning ("Audioscrobbler upload failed", String.Format ("Unrecognized response: {0}", line), false);
last_upload_failed_logged = now;
}
state = State.Idle;
}
}
//
// Async code for handshaking
//
private string UnixTime ()
{
return ((int) (DateTime.UtcNow - new DateTime (1970, 1, 1)).TotalSeconds).ToString ();
}
private void Handshake ()
{
string timestamp = UnixTime();
string authentication_token = Hyena.CryptoUtil.Md5Encode
(LastfmCore.ApiSecret + timestamp);
string api_url = LastfmCore.Account.ScrobbleUrl;
if (String.IsNullOrEmpty (api_url)) {
api_url = SCROBBLER_URL;
} else {
Log.DebugFormat ("Scrobbling to non-standard API URL: {0}", api_url);
}
string uri = String.Format ("{0}?hs=true&p={1}&c={2}&v={3}&u={4}&t={5}&a={6}&api_key={7}&sk={8}",
api_url,
SCROBBLER_VERSION,
CLIENT_ID, CLIENT_VERSION,
HttpUtility.UrlEncode (LastfmCore.Account.UserName),
timestamp,
authentication_token,
LastfmCore.ApiKey,
LastfmCore.Account.SessionKey);
current_web_req = (HttpWebRequest) WebRequest.Create (uri);
state = State.WaitingForHandshakeResp;
current_async_result = current_web_req.BeginGetResponse (HandshakeGetResponse, null);
if (current_async_result == null) {
next_interval = DateTime.Now + new TimeSpan (0, 0, hard_failure_retry_sec);
hard_failures++;
if (hard_failure_retry_sec < MAX_RETRY_SECONDS)
hard_failure_retry_sec *= 2;
state = State.NeedHandshake;
}
}
private void HandshakeGetResponse (IAsyncResult ar)
{
bool success = false;
bool hard_failure = false;
WebResponse resp;
try {
resp = current_web_req.EndGetResponse (ar);
}
catch (Exception e) {
Log.Warning ("Failed to handshake: {0}", e.ToString (), false);
// back off for a time before trying again
state = State.Idle;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
return;
}
Stream s = resp.GetResponseStream ();
StreamReader sr = new StreamReader (s, Encoding.UTF8);
string line;
line = sr.ReadLine ();
if (line.StartsWith ("BANNED")) {
Log.Warning ("Audioscrobbler sign-on failed", "Player is banned", false);
} else if (line.StartsWith ("BADAUTH")) {
Log.Warning ("Audioscrobbler sign-on failed", Catalog.GetString ("Last.fm username is invalid or Banshee is not authorized to access you account."));
LastfmCore.Account.SessionKey = null;
} else if (line.StartsWith ("BADTIME")) {
Log.Warning ("Audioscrobbler sign-on failed",
"timestamp provided was not close enough to the current time", false);
} else if (line.StartsWith ("FAILED")) {
Log.Warning ("Audioscrobbler sign-on failed",
String.Format ("Temporary server failure: {0}", line.Substring ("FAILED".Length).Trim ()), false);
hard_failure = true;
} else if (line.StartsWith ("OK")) {
success = true;
} else {
Log.Error ("Audioscrobbler sign-on failed", String.Format ("Unknown error: {0}", line.Trim()));
hard_failure = true;
}
if (success == true) {
Log.Debug ("Audioscrobbler sign-on succeeded", "Session ID received");
session_id = sr.ReadLine ().Trim ();
now_playing_url = sr.ReadLine ().Trim ();
post_url = sr.ReadLine ().Trim ();
hard_failures = 0;
hard_failure_retry_sec = 60;
} else {
if (hard_failure == true) {
next_interval = DateTime.Now + new TimeSpan (0, 0, hard_failure_retry_sec);
hard_failures++;
if (hard_failure_retry_sec < MAX_RETRY_SECONDS)
hard_failure_retry_sec *= 2;
}
}
state = State.Idle;
}
//
// Async code for now playing
public void NowPlaying (string artist, string title, string album, double duration,
int tracknum)
{
NowPlaying (artist, title, album, duration, tracknum, "");
}
public void NowPlaying (string artist, string title, string album, double duration,
int tracknum, string mbrainzid)
{
if (String.IsNullOrEmpty(artist) || String.IsNullOrEmpty(title) || !connected) {
return;
}
string str_track_number = String.Empty;
if (tracknum != 0) {
str_track_number = tracknum.ToString();
}
// Fall back to prefixing the URL with a # in case we haven't actually
// authenticated yet. We replace it with the now_playing_url and session_id
// later on in NowPlaying(uri).
string dataprefix = "#";
if (session_id != null) {
dataprefix = String.Format ("s={0}", session_id);
}
string data = String.Format ("{0}&a={1}&t={2}&b={3}&l={4}&n={5}&m={6}",
dataprefix,
HttpUtility.UrlEncode(artist),
HttpUtility.UrlEncode(title),
HttpUtility.UrlEncode(album),
duration.ToString("F0"),
str_track_number,
mbrainzid);
NowPlaying (data);
}
private void NowPlaying (string data)
{
if (now_playing_started) {
return;
}
// If the URI begins with #, then we know the URI was created before we
// had actually authenticated. So, because we didn't know the session_id and
// now_playing_url previously, we should now, so we put that in and create our
// new URI.
if (data.StartsWith ("#") && session_id != null) {
data = String.Format ("s={0}{1}",
session_id,
data.Substring (1));
}
current_now_playing_data = data;
if (session_id == null) {
// Go connect - we'll come back later in main timer loop.
Start ();
return;
}
try {
now_playing_post = (HttpWebRequest) WebRequest.Create (now_playing_url);
now_playing_post.UserAgent = LastfmCore.UserAgent;
now_playing_post.Method = "POST";
now_playing_post.ContentType = "application/x-www-form-urlencoded";
if (state == State.Idle) {
// Don't actually POST it until we're idle (that is, we
// probably have stuff queued which will reset the Now
// Playing if we send them first).
now_playing_started = true;
now_playing_post.BeginGetRequestStream (NowPlayingGetRequestStream, data);
}
} catch (Exception ex) {
Log.Warning ("Audioscrobbler NowPlaying failed",
String.Format ("Exception while creating request: {0}", ex), false);
// Reset current_now_playing_data if it was the problem.
current_now_playing_data = null;
}
}
private void NowPlayingGetRequestStream (IAsyncResult ar)
{
try {
string data = ar.AsyncState as string;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] data_bytes = encoding.GetBytes (data);
Stream request_stream = now_playing_post.EndGetRequestStream (ar);
request_stream.Write (data_bytes, 0, data_bytes.Length);
request_stream.Close ();
now_playing_post.BeginGetResponse (NowPlayingGetResponse, null);
} catch (Exception e) {
Log.Exception (e);
}
}
private void NowPlayingGetResponse (IAsyncResult ar)
{
try {
WebResponse my_resp = now_playing_post.EndGetResponse (ar);
Stream s = my_resp.GetResponseStream ();
StreamReader sr = new StreamReader (s, Encoding.UTF8);
string line = sr.ReadLine ();
if (line == null) {
Log.Warning ("Audioscrobbler NowPlaying failed", "No response", false);
}
if (line.StartsWith ("BADSESSION")) {
Log.Warning ("Audioscrobbler NowPlaying failed", "Session ID sent was invalid", false);
// attempt to re-handshake on the next interval
session_id = null;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
state = State.NeedHandshake;
StartTransitionHandler ();
return;
} else if (line.StartsWith ("OK")) {
// NowPlaying submitted
Log.DebugFormat ("Submitted NowPlaying track to Audioscrobbler");
now_playing_started = false;
now_playing_post = null;
current_now_playing_data = null;
return;
} else {
Log.Warning ("Audioscrobbler NowPlaying failed", "Unexpected or no response", false);
}
}
catch (Exception e) {
Log.Warning ("Audioscrobbler NowPlaying failed",
String.Format("Failed to post NowPlaying: {0}", e), false);
}
// NowPlaying error/success is non-crucial.
hard_failures++;
if (hard_failures < 3) {
NowPlaying (current_now_playing_data);
} else {
// Give up - NowPlaying status information is non-critical.
current_now_playing_data = null;
now_playing_started = false;
now_playing_post = null;
}
}
}
}
| |
// -----
// GNU General Public License
// The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
// The Forex Professional Analyzer is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
// See the GNU Lesser General Public License for more details.
// -----
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel;
namespace fxpa
{
/// <summary>
/// This class brings together the (Data/OrderExecution)Provider(s) and the ChartSeries, allowing the data to be rendered.
/// </summary>
public class ProviderTradeChartSeries : TradeChartSeries
{
IDataProvider _dataProvider;
IOrderExecutionProvider _orderExecutionProvider;
Image _imageUp;
Image _imageDown;
Image _imageCross;
volatile bool _showOrderArrow = true;
/// <summary>
/// Show the orders arrow below the bar.
/// </summary>
public bool ShowOrderArrow
{
get { return _showOrderArrow; }
set { _showOrderArrow = value; }
}
volatile bool _showOrderSpot = true;
/// <summary>
/// Show the circle and line on the spot of the very order price.
/// </summary>
public bool ShowOrderSpot
{
get { return _showOrderSpot; }
set { _showOrderSpot = value; }
}
volatile bool _showClosedOrdersTracing = true;
/// <summary>
/// Show order tracing line - from open to close.
/// </summary>
public bool ShowClosedOrdersTracing
{
get { return _showClosedOrdersTracing; }
set { _showClosedOrdersTracing = value; }
}
volatile bool _showPendingOrdersTracing = true;
/// <summary>
/// Show order tracing line for open orders - from open price to current price.
/// </summary>
public bool ShowPendingOrdersTracing
{
get { return _showPendingOrdersTracing; }
set { _showPendingOrdersTracing = value; }
}
Pen _buyDashedPen = new Pen(Color.Green);
Pen _sellDashedPen = new Pen(Color.Red);
volatile bool _drawCurrentPriceLevel = true;
public bool DrawCurrentPriceLevel
{
get { return _drawCurrentPriceLevel; }
set { _drawCurrentPriceLevel = value; }
}
Pen _priceLevelPen = new Pen(Color.Gray);
public Pen PriceLevelPen
{
set { _priceLevelPen = value; }
}
/// <summary>
///
/// </summary>
public ProviderTradeChartSeries()
{
}
/// <summary>
///
/// </summary>
public ProviderTradeChartSeries(string name)
{
base.Name = name;
}
public void Initialize(IDataProvider dataProvider, IOrderExecutionProvider orderExecutionProvider)
{
lock (this)
{
_dataProvider = dataProvider;
_dataProvider.ValuesUpdateEvent += new ValuesUpdatedDelegate(_provider_ValuesUpdateEvent);
_orderExecutionProvider = orderExecutionProvider;
if (_orderExecutionProvider != null)
{
_orderExecutionProvider.OrderAddedEvent += new GeneralHelper.GenericDelegate<Order>(_orderExecutionProvider_OrderUpdate);
_orderExecutionProvider.OrderRemovedEvent += new GeneralHelper.GenericDelegate<Order>(_orderExecutionProvider_OrderUpdate);
_orderExecutionProvider.OrderUpdatedEvent += new GeneralHelper.GenericDelegate<Order>(_orderExecutionProvider_OrderUpdate);
}
ComponentResourceManager resources = new ComponentResourceManager(typeof(ProviderTradeChartSeries));
_imageDown = ((Image)(resources.GetObject("imageDown")));
_imageUp = ((Image)(resources.GetObject("imageUp")));
_imageCross = ((Image)(resources.GetObject("imageCross")));
_buyDashedPen.DashPattern = new float[] { 5, 5 };
_buyDashedPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
_priceLevelPen.DashPattern = new float[] { 3, 3 };
_priceLevelPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
_sellDashedPen.DashPattern = new float[] { 5, 5 };
_sellDashedPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
}
}
void _orderExecutionProvider_OrderUpdate(Order parameter1)
{
RaiseValuesUpdated(true);
}
void UpdateValues()
{
lock (this)
{
BarData[] bars = new BarData[_dataProvider.DataUnits.Count];
_dataProvider.DataUnits.CopyTo(bars, 0);
double scaling = 1;
for (int i = 0; i < bars.Length; i++)
{
BarData bar = bars[i];
bars[i] = new BarData(bar.DateTime, bar.Open * scaling, bar.Close * scaling, bar.Low * scaling, bar.High * scaling, bar.Volume * scaling);
}
if (bars.Length > 0)
{
this.SetBarData(bars, _dataProvider.TimeInterval);
}
RaiseValuesUpdated(true);
}
}
void _provider_ValuesUpdateEvent(IDataProvider dataProvider, UpdateType updateType, int updatedItemsCount, int stepsRemaining)
{
if (stepsRemaining == 0)
{
UpdateValues();
}
}
public void UnInitialize()
{
lock (this)
{
if (_dataProvider != null)
{
_dataProvider.ValuesUpdateEvent -= new ValuesUpdatedDelegate(_provider_ValuesUpdateEvent);
_dataProvider = null;
}
if (_orderExecutionProvider != null)
{
_orderExecutionProvider.OrderAddedEvent -= new GeneralHelper.GenericDelegate<Order>(_orderExecutionProvider_OrderUpdate);
_orderExecutionProvider.OrderRemovedEvent -= new GeneralHelper.GenericDelegate<Order>(_orderExecutionProvider_OrderUpdate);
_orderExecutionProvider.OrderUpdatedEvent -= new GeneralHelper.GenericDelegate<Order>(_orderExecutionProvider_OrderUpdate);
_orderExecutionProvider = null;
}
_buyDashedPen.Dispose();
_sellDashedPen.Dispose();
}
}
protected override void OnAddedToChart()
{
UpdateValues();
}
protected override void OnRemovedFromChart()
{
UnInitialize();
}
public override void Draw(GraphicsWrapper g, int unitsUnification,
RectangleF clippingRectangle, float itemWidth, float itemMargin)
{
base.Draw(g, unitsUnification, clippingRectangle, itemWidth, itemMargin);
if (Visible == false)
{
return;
}
// Draw ask line.
if (_dataProvider != null && _drawCurrentPriceLevel ) //&& _dataProvider.OperationalState == OperationalStateEnum.Operational)
{
float price = (float)_dataProvider.Bid;
g.DrawLine(_priceLevelPen, clippingRectangle.X, price, clippingRectangle.X + clippingRectangle.Width, price);
}
List<Order> ordersOpening;
// Draw orders locations on chart.
lock(this)
{
if (_orderExecutionProvider == null)
{
return;
}
// Render orders.
ordersOpening = new List<Order>(_orderExecutionProvider.Orders);
}
// Use for orders closes.
List<Order> ordersClosing = new List<Order>();
foreach (Order order in ordersOpening)
{
if (order.IsOpen == false)
{// Only add orders already closed.
ordersClosing.Add(order);
}
}
// This is used later on, since ordersClosing is modified.
List<Order> ordersClosed = new List<Order>(ordersClosing);
// Orders opening at current bar.
List<Order> pendingOpeningOrders = new List<Order>();
// Order closing at current bar.
List<Order> pendingClosingOrders = new List<Order>();
PointF drawingPoint = new PointF();
int startIndex, endIndex;
GetDrawingRangeIndecesFromClippingRectange(clippingRectangle, drawingPoint, unitsUnification, out startIndex, out endIndex, itemWidth, itemMargin);
lock (this)
{
float lastBarX = (itemMargin + itemWidth) * _dataBars.Count;
for (int i = startIndex; i < endIndex && i < _dataBars.Count
&& (ordersOpening.Count > 0 || ordersClosing.Count > 0); i++)
{// Foreach bar, draw orders (and volume).
while (ordersOpening.Count > 0)
{// All orders before now.
if (ordersOpening[0].SourceOpenTime < (_dataBars[i].DateTime - _dataProvider.TimeInterval))
{// Order before time period.
if (ordersOpening[0].IsOpen && _showPendingOrdersTracing)
{// Since it is an open pending order, we shall also need to draw it as well.
pendingOpeningOrders.Add(ordersOpening[0]);
}
ordersOpening.RemoveAt(0);
continue;
}
if (ordersOpening[0].SourceOpenTime > _dataBars[i].DateTime)
{// Order after time period - look no further.
break;
}
// Order open is within the current period.
// Only if order is part of the current period - add to pending.
pendingOpeningOrders.Add(ordersOpening[0]);
ordersOpening.RemoveAt(0);
}
for (int j = ordersClosing.Count - 1; j >= 0; j--)
{
if (ordersClosing[j].SourceCloseTime >= (_dataBars[i].DateTime - _dataProvider.TimeInterval) &&
ordersClosing[j].SourceCloseTime <= _dataBars[i].DateTime)
{// Order close is within the current period.
pendingClosingOrders.Add(ordersClosing[j]);
ordersClosing.RemoveAt(j);
}
}
drawingPoint.X = i * (itemMargin + itemWidth);
DrawOrders(g, i, drawingPoint, itemWidth, itemMargin, pendingOpeningOrders, pendingClosingOrders, _dataProvider.DataUnits[i], lastBarX);
pendingOpeningOrders.Clear();
pendingClosingOrders.Clear();
}
if (_showClosedOrdersTracing && _dataBars.Count > 0 && startIndex < _dataBars.Count)
{// Since a closed order may be before or after (or during) the curren set of periods - make a special search and render for them.
endIndex = Math.Max(0, endIndex);
endIndex = Math.Min(_dataBars.Count - 1, endIndex);
foreach (Order order in ordersClosed)
{
if (order.SourceOpenTime <= _dataBars[endIndex].DateTime
&& order.SourceCloseTime >= _dataBars[startIndex].DateTime - _dataProvider.TimeInterval)
{
int openIndex = _dataProvider.GetBarIndexAtTime(order.SourceOpenTime);
int closeIndex = _dataProvider.GetBarIndexAtTime(order.SourceCloseTime);
Pen pen = _buyDashedPen;
if (order.IsBuy == false)
{
pen = _sellDashedPen;
}
g.DrawLine(pen, new PointF(openIndex * (itemWidth + itemMargin), (float)order.OpenPrice),
new PointF(closeIndex * (itemWidth + itemMargin), (float)order.ClosePrice));
}
}
}
} // Lock
}
void DrawOrders(GraphicsWrapper g, int index, PointF drawingPoint, float itemWidth, float itemMargin,
List<Order> openingOrders, List<Order> closingOrders, BarData orderBarData, float lastBarX)
{
// Width is same as items in real coordinates.
float actualImageHeight = _imageDown.Height / Math.Abs(g.DrawingSpaceTransform.Elements[3]);
float yToXScaling = Math.Abs(g.DrawingSpaceTransform.Elements[0] / g.DrawingSpaceTransform.Elements[3]);
PointF updatedImageDrawingPoint = drawingPoint;
foreach (Order order in openingOrders)
{
DrawOrder(g, ref updatedImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, orderBarData, lastBarX, true);
}
foreach (Order order in closingOrders)
{
DrawOrder(g, ref updatedImageDrawingPoint, order, itemWidth, itemMargin, yToXScaling, orderBarData, lastBarX, false);
}
}
void DrawOrder(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin,
float yToXScaling, BarData orderBarData, float lastBarX, bool drawOpening)
{
Image image = _imageUp;
Brush brush = Brushes.Green;
Pen dashedPen = _buyDashedPen;
Pen pen = Pens.GreenYellow;
if (order.IsBuy == false)
{
image = _imageDown;
brush = Brushes.Red;
pen = Pens.Red;
dashedPen = _sellDashedPen;
}
if (drawOpening == false)
{
image = _imageCross;
}
float price = (float)order.OpenPrice;
if (drawOpening == false)
{
price = (float)order.ClosePrice;
}
if (drawOpening && _showPendingOrdersTracing && order.IsOpen)
{// Open orders tracking line.
PointF point1 = new PointF(updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + price);
float sellPrice = (float)_dataProvider.Bid;
if (order.IsBuy == false)
{
sellPrice = (float)_dataProvider.Ask;
}
PointF point2 = new PointF(lastBarX - itemWidth / 2f, updatedImageDrawingPoint.Y + sellPrice);
g.DrawLine(dashedPen, point1, point2);
}
//if (drawOpening && _showClosedOrdersTracing && order.IsOpen == false)
//{// Closed order tracking.
// Close order tracing is implemented in main draw function.
//}
if (_showOrderSpot)
{
PointF basePoint = new PointF(updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + price);
float height = (yToXScaling * itemWidth);
if (order.IsBuy == false)
{
height = -height;
}
if (drawOpening)
{
g.FillPolygon(brush, new PointF[] { basePoint, new PointF(basePoint.X + itemWidth, basePoint.Y),
new PointF(basePoint.X + (itemWidth / 2f), basePoint.Y + height) });
g.DrawPolygon(Pens.White, new PointF[] { basePoint, new PointF(basePoint.X + itemWidth, basePoint.Y),
new PointF(basePoint.X + (itemWidth / 2f), basePoint.Y + height) });
// Take profit level.
if (double.IsInfinity(order.SourceTakeProfit) == false
&& double.IsNaN(order.SourceTakeProfit) == false
&& order.SourceTakeProfit != 0)
{
g.DrawLine(pen, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit,
updatedImageDrawingPoint.X + itemWidth, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit);
g.DrawLine(pen, updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit,
updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceTakeProfit - height);
}
// Stop loss level.
if (double.IsInfinity(order.SourceStopLoss) == false
&& double.IsNaN(order.SourceStopLoss) == false
&& order.SourceStopLoss != 0)
{
g.DrawLine(pen, updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss,
updatedImageDrawingPoint.X + itemWidth, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss);
g.DrawLine(pen, updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss,
updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.SourceStopLoss + height);
}
}
else
{
g.DrawRectangle(Pens.White, basePoint.X, basePoint.Y,
itemWidth, yToXScaling * itemWidth);
}
}
float imageHeight = 2 * (yToXScaling * itemWidth);
if (_showOrderArrow)
{
// Draw up image.
g.DrawImage(image, updatedImageDrawingPoint.X - (itemWidth / 2f), updatedImageDrawingPoint.Y +
(float)orderBarData.Low - (yToXScaling * itemWidth), 2 * itemWidth, -imageHeight);
updatedImageDrawingPoint.Y -= 1.2f * imageHeight;
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=StickyNoteContentControl.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Implementation of StickyNoteControl's internal TextBox/RichTextBox and InkCanvas helper classes.
//
// See spec at http://tabletpc/longhorn/Specs/StickyNoteControlSpec.mht
//
// History:
// 03/03/2005 - waynezen - Created
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Ink;
using System.Windows.Markup;
using System.Xml;
namespace MS.Internal.Controls.StickyNote
{
/// <summary>
/// An abstract class which defines the basic operation for StickyNote content
/// </summary>
internal abstract class StickyNoteContentControl
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
protected StickyNoteContentControl(FrameworkElement innerControl)
{
SetInnerControl(innerControl);
}
private StickyNoteContentControl() { }
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Saves the content to an Xml node
/// </summary>
/// <param name="node"></param>
public abstract void Save(XmlNode node);
/// <summary>
/// Load the content from an Xml node
/// </summary>
/// <param name="node"></param>
public abstract void Load(XmlNode node);
/// <summary>
/// Clears the current content.
/// </summary>
public abstract void Clear();
#endregion Public Methods
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Checks if the content is empty
/// </summary>
abstract public bool IsEmpty
{
get;
}
/// <summary>
/// Returns the content type
/// </summary>
abstract public StickyNoteType Type
{
get;
}
/// <summary>
/// Returns the inner control associated to this content.
/// </summary>
public FrameworkElement InnerControl
{
get
{
return _innerControl;
}
}
#endregion Public Properties
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// Sets the internal control. The method also loads the custom style for the control if it's avaliable.
/// </summary>
/// <param name="innerControl">The inner control</param>
protected void SetInnerControl(FrameworkElement innerControl)
{
_innerControl = innerControl;
}
#endregion Protected Methods
//-------------------------------------------------------------------
//
// Protected Fields
//
//-------------------------------------------------------------------
#region Protected Fields
protected FrameworkElement _innerControl;
// The maximum size of a byte buffer before its converted to a base64 string.
protected const long MaxBufferSize = (Int32.MaxValue / 4) * 3;
#endregion Protected Fields
}
/// <summary>
/// A factory class which creates SticktNote content controls
/// </summary>
internal static class StickyNoteContentControlFactory
{
//-------------------------------------------------------------------
//
// Private classes
//
//-------------------------------------------------------------------
#region Private classes
/// <summary>
/// RichTextBox content implementation
/// </summary>
private class StickyNoteRichTextBox : StickyNoteContentControl
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
public StickyNoteRichTextBox(RichTextBox rtb)
: base(rtb)
{
// Used to restrict enforce certain data format during pasting
DataObject.AddPastingHandler(rtb, new DataObjectPastingEventHandler(OnPastingDataObject));
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Clears the inner RichTextBox
/// </summary>
public override void Clear()
{
((RichTextBox)InnerControl).Document = new FlowDocument(new Paragraph(new Run()));
}
/// <summary>
/// Save the RichTextBox data to an Xml node
/// </summary>
/// <param name="node"></param>
public override void Save(XmlNode node)
{
// make constant
Debug.Assert(node != null && !IsEmpty);
RichTextBox richTextBox = (RichTextBox)InnerControl;
TextRange rtbRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
if (!rtbRange.IsEmpty)
{
using (MemoryStream buffer = new MemoryStream())
{
rtbRange.Save(buffer, DataFormats.Xaml);
if (buffer.Length.CompareTo(MaxBufferSize) > 0)
throw new InvalidOperationException(SR.Get(SRID.MaximumNoteSizeExceeded));
// Using GetBuffer avoids making a copy of the buffer which isn't necessary
// Safe cast because the array's length can never be greater than Int.MaxValue
node.InnerText = Convert.ToBase64String(buffer.GetBuffer(), 0, (int)buffer.Length);
}
}
}
/// <summary>
/// Load the RichTextBox data from an Xml node
/// </summary>
/// <param name="node"></param>
public override void Load(XmlNode node)
{
Debug.Assert(node != null);
RichTextBox richTextBox = (RichTextBox)InnerControl;
FlowDocument document = new FlowDocument();
TextRange rtbRange = new TextRange(document.ContentStart, document.ContentEnd);
using (MemoryStream buffer = new MemoryStream(Convert.FromBase64String(node.InnerText)))
{
rtbRange.Load(buffer, DataFormats.Xaml);
}
richTextBox.Document = document;
}
#endregion Public Methods
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// A flag whidh indicates if RichTextBox is empty
/// </summary>
public override bool IsEmpty
{
get
{
RichTextBox richTextBox = (RichTextBox)InnerControl;
TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
return textRange.IsEmpty;
}
}
/// <summary>
/// Returns Text Type
/// </summary>
public override StickyNoteType Type
{
get
{
return StickyNoteType.Text;
}
}
#endregion Public Properties
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Serialization of Images isn't working so we restrict the pasting of images (and as a side effect
/// all UIElements) into a text StickyNote until the serialization problem is corrected.
/// </summary>
private void OnPastingDataObject(Object sender, DataObjectPastingEventArgs e)
{
if (e.FormatToApply == DataFormats.Rtf)
{
UTF8Encoding encoding = new UTF8Encoding();
// Convert the RTF to Avalon content
String rtfString = e.DataObject.GetData(DataFormats.Rtf) as String;
MemoryStream data = new MemoryStream(encoding.GetBytes(rtfString));
FlowDocument document = new FlowDocument();
TextRange range = new TextRange(document.ContentStart, document.ContentEnd);
range.Load(data, DataFormats.Rtf);
// Serialize the content without UIElements and make it the preferred content for the paste
MemoryStream buffer = new MemoryStream();
range.Save(buffer, DataFormats.Xaml);
DataObject dataObject = new DataObject();
dataObject.SetData(DataFormats.Xaml, encoding.GetString(buffer.GetBuffer()));
e.DataObject = dataObject;
e.FormatToApply = DataFormats.Xaml;
}
else if (e.FormatToApply == DataFormats.Bitmap ||
e.FormatToApply == DataFormats.EnhancedMetafile ||
e.FormatToApply == DataFormats.MetafilePicture ||
e.FormatToApply == DataFormats.Tiff)
{
// Cancel all paste operations of stand-alone images
e.CancelCommand();
}
else if (e.FormatToApply == DataFormats.XamlPackage)
{
// Choose Xaml without UIElements over a XamlPackage
e.FormatToApply = DataFormats.Xaml;
}
}
#endregion Private Methods
}
/// <summary>
/// InkCanvas content implementation
/// </summary>
private class StickyNoteInkCanvas : StickyNoteContentControl
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
public StickyNoteInkCanvas(InkCanvas canvas)
: base(canvas)
{
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Clears the inner InkCanvas
/// </summary>
public override void Clear()
{
( (InkCanvas)InnerControl ).Strokes.Clear();
}
/// <summary>
/// Save the stroks data to an Xml node
/// </summary>
/// <param name="node"></param>
public override void Save(XmlNode node)
{
Debug.Assert(node != null && !IsEmpty);
StrokeCollection strokes = ((InkCanvas)InnerControl).Strokes;
using ( MemoryStream buffer = new MemoryStream() )
{
strokes.Save(buffer);
if (buffer.Length.CompareTo(MaxBufferSize) > 0)
throw new InvalidOperationException(SR.Get(SRID.MaximumNoteSizeExceeded));
// Using GetBuffer avoids making a copy of the buffer which isn't necessary
// Safe cast because the array's length can never be greater than Int.MaxValue
node.InnerText = Convert.ToBase64String(buffer.GetBuffer(), 0, (int)buffer.Length);
}
}
/// <summary>
/// Load the stroks data from an Xml node
/// </summary>
/// <param name="node"></param>
public override void Load(XmlNode node)
{
Debug.Assert(node != null, "Try to load data from an invalid node");
StrokeCollection strokes = null;
if ( string.IsNullOrEmpty(node.InnerText) )
{
// Create an empty StrokeCollection
strokes = new StrokeCollection();
}
else
{
using ( MemoryStream stream = new MemoryStream(Convert.FromBase64String(node.InnerText)) )
{
strokes = new StrokeCollection(stream);
}
}
((InkCanvas)InnerControl).Strokes = strokes;
}
#endregion Public Methods
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// A flag which indicates whether the InkCanvas is empty
/// </summary>
public override bool IsEmpty
{
get
{
return ( (InkCanvas)InnerControl ).Strokes.Count == 0;
}
}
/// <summary>
/// Returns the Ink type
/// </summary>
public override StickyNoteType Type
{
get
{
return StickyNoteType.Ink;
}
}
#endregion Public Properties
}
#endregion Private classes
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// A method which creates a specified type content control.
/// </summary>
/// <param name="type"></param>
/// <param name="content"></param>
/// <returns></returns>
public static StickyNoteContentControl CreateContentControl(StickyNoteType type, UIElement content)
{
StickyNoteContentControl contentControl = null;
switch ( type )
{
case StickyNoteType.Text:
{
RichTextBox rtb = content as RichTextBox;
if (rtb == null)
throw new InvalidOperationException(SR.Get(SRID.InvalidStickyNoteTemplate, type, typeof(RichTextBox), SNBConstants.c_ContentControlId));
contentControl = new StickyNoteRichTextBox(rtb);
break;
}
case StickyNoteType.Ink:
{
InkCanvas canvas = content as InkCanvas;
if (canvas == null)
throw new InvalidOperationException(SR.Get(SRID.InvalidStickyNoteTemplate, type, typeof(InkCanvas), SNBConstants.c_ContentControlId));
contentControl = new StickyNoteInkCanvas(canvas);
break;
}
}
return contentControl;
}
#endregion Public Methods
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="BookList.cs" company="HIVacSim">
// Copyright (c) 2014 HIVacSim Contributors
// </copyright>
// <author>Israel Vieira</author>
// ----------------------------------------------------------------------------
namespace HIVacSim
{
using System;
using System.Text;
/// <summary>
/// Adjacency list data structure class to hold the individuals
/// list of acquaintances.
/// </summary>
[Serializable]
public class BookList
{
#region Internal Class
/// <summary>
/// Defines a element in the BookList
/// </summary>
[Serializable]
private class Node
{
#region Local variables
/// <summary>
/// The data stored in this element of the BookList
/// </summary>
private Person _data;
/// <summary>
/// Pointer to the next element in the BookList
/// </summary>
private Node _next;
/// <summary>
/// Pointer to previous element in the BookList
/// </summary>
private Node _previous;
#endregion
#region Public methods
/// <summary>
/// Initializes a element of the BookList
/// </summary>
/// <param name="data">The data to store in this element</param>
/// <param name="next">Point to next element in the BookList</param>
/// <param name="previous">Point to previous element in the BookList</param>
public Node(Person data, Node next, Node previous)
{
this._data = data;
this._next = next;
this._previous = previous;
}
/// <summary>
/// Data in this BookList element
/// </summary>
public Person Data
{
get {return this._data;}
set {this._data = value;}
}
/// <summary>
/// Pointer to next element of the BookList
/// </summary>
public Node Next
{
get {return this._next;}
set {this._next=value;}
}
/// <summary>
/// Pointer to previous element of the BookList
/// </summary>
public Node Previous
{
get {return this._previous;}
set {this._previous = value;}
}
#endregion
}
#endregion
#region Local variables
/// <summary>
/// The first element of the BookList
/// </summary>
private Node _head;
private Node _current;
/// <summary>
/// The number of elements in the BookList
/// </summary>
private int _count;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the BookList class
/// </summary>
public BookList()
{
this._head = new Node(null,null,null);
this._head.Next = this._head;
this._head.Previous = this._head;
this._current = this._head;
this._count = 0;
}
#endregion
#region Public properties
/// <summary>
/// Gets the number of elements contained in the BookList
/// </summary>
public int Count
{
get{return this._count;}
}
/// <summary>
/// Gets or sets the <see cref="Person"/> at the specified index
/// </summary>
public Person this[int index]
{
get {return FindAt(index).Data;}
set {FindAt(index).Data = value;}
}
/// <summary>
/// Returns the current person in the friends list
/// </summary>
public Person Current
{
get {return this._current.Data;}
}
#endregion
#region Public methods
/// <summary>
/// Resets the current person to beginning of the list
/// </summary>
public void Reset()
{
this._current = this._head;
}
/// <summary>
/// Move the current selection to the next person in the list
/// </summary>
/// <returns>
/// True if the next person has been selected, false otherwise
/// </returns>
public bool MoveNext()
{
this._current = this._current.Next;
if (this._current != this._head)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Inserts an <see cref="Person"/> into the <see cref="BookList"/>
/// at the specified <paramref name="index"/>.
/// </summary>
/// <param name="index">
/// The zero-based <paramref name="index"/> at which
/// <paramref name="data"/> should be inserted.</param>
/// <param name="data"> The <see cref="Person"/> to insert. </param>
/// <returns>True for successful addition, false otherwise.</returns>
public bool Insert(int index, Person data)
{
if (this.Contains(data))
{
return false;
}
else
{
Node node;
if (index == this._count)
{
node = new Node(data, this._head, this._head.Previous);
}
else
{
Node temp = FindAt(index);
node = new Node(data, temp, temp.Previous);
}
node.Previous.Next = node;
node.Next.Previous = node;
this._count++;
return true;
}
}
/// <summary>
/// Adds an <see cref="Person"/> to the end of the <see cref="BookList"/>.
/// </summary>
/// <param name="data">
/// The <see cref="Person"/> to be added to the end of the <see cref="BookList"/>
/// </param>
/// <returns>
/// True for successful addition, false otherwise.
/// </returns>
public bool Add(Person data)
{
return Insert(this._count, data);
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="Relation"/>
/// from the <see cref="BookList"/>.
/// </summary>
/// <param name="friend">
/// The <see cref="Relation"/> to remove from the <see cref="BookList"/>.
/// </param>
public bool Remove(Person friend)
{
for (Node node = this._head.Next; node != this._head; node = node.Next)
{
if (node.Data == friend)
{
return Remove(node);
}
}
return false;
}
/// <summary>
/// Removes the <see cref="Relation"/> at the specified
/// <paramref name="index"/> of the <see cref="BookList"/>.
/// </summary>
/// <param name="index">
/// The zero-based <paramref name="index"/> of the
/// <see cref="Relation"/> to remove.
/// </param>
public bool RemoveAt(int index)
{
return Remove(FindAt(index));
}
/// <summary>
/// Determines whether an <see cref="Person"/> is in the <see cref="BookList"/>.
/// </summary>
/// <param name="friend">
/// <br>The <see cref="Person"/> to locate in the <see cref="BookList"/>.</br>
/// The <see cref="Person"/> to locate can be a <c>null</c> reference).
/// </param>
/// <returns>
/// <c>true</c> if <paramref name="friend"/> is found in the
/// <see cref="BookList"/>; otherwise, false.
/// </returns>
public bool Contains(Person friend)
{
return (0 <= IndexOf(friend));
}
/// <summary>
/// Searches for the specified <see cref="Person"/> and returns
/// the zero-based index of the first occurrence within the
/// entire <see cref="BookList"/>.
/// </summary>
/// <param name="friend">
/// The <see cref="Person"/> to locate in the <see cref="BookList"/>.
/// </param>
/// <returns>
/// The zero-based index of the first occurrence of
/// <paramref name="friend"/> within the entire
/// <see cref="BookList"/>, if found; otherwise, -1.
/// </returns>
public int IndexOf(Person friend)
{
int currentIndex = 0;
for (Node node = this._head.Next; node != this._head; node = node.Next)
{
if (node.Data == friend)
{
break;
}
currentIndex++;
}
if (this._count <= currentIndex)
{
currentIndex = -1;
}
return currentIndex;
}
/// <summary>
/// Copies the entire <see cref="BookList"/> to a one-dimensional <see cref="Array"/>.
/// The <see cref="Array"/> must have zero-based indexing.
/// </summary>
/// <returns>A one-dimension array representing the BookList</returns>
public Person[] ToArray()
{
if (this._count > 0)
{
int i = 0;
Person[] data = new Person[this._count];
for (Node node = this._head.Next; node != this._head; node = node.Next)
{
data[i] = node.Data;
i++;
}
return data;
}
else
{
return null;
}
}
/// <summary>
/// Creates a list of person's unique identification separated by comma
/// </summary>
/// <returns>The list of persons in the list</returns>
public string ToCSV()
{
StringBuilder list = new System.Text.StringBuilder();
for (Node node = this._head.Next; node != this._head; node = node.Next)
{
list.Append(node.Data.Id.ToString() + ",");
}
//Remove last comma
if (list.Length > 0)
{
list.Remove(list.Length - 1, 1);
return list.ToString();
}
return string.Empty;
}
/// <summary>
/// Removes all <see cref="Person"/>s from the <see cref="BookList"/>.
/// </summary>
public void Clear()
{
this._head.Next = this._head;
this._head.Previous = this._head;
this._count = 0;
}
#endregion
#region Private methods
/// <summary>
/// Returns the <see cref="Node"/> at the provided <paramref name="index"/>.
/// </summary>
/// <param name="index">
/// The zero-based <paramref name="index"/> of the <see cref="Node"/>.
/// </param>
/// <returns>
/// The <see cref="Node"/> at the provided <paramref name="index"/>.
/// </returns>
/// <exception cref="IndexOutOfRangeException">
/// If the <paramref name="index"/> is invalid.
/// </exception>
private Node FindAt(int index)
{
if (index < 0 || this._count <= index)
{
throw new IndexOutOfRangeException(
"Attempted to access index " + index +
", while the total count is " + this._count + ".");
}
Node node = this._head;
if (index < (this._count / 2))
{
for (int i = 0; i <= index; i++)
{
node = node.Next;
}
}
else
{
for (int i = this._count; i > index; i--)
{
node = node.Previous;
}
}
return node;
}
/// <summary>
/// Removes a <see cref="Node"/> from the <see cref="BookList"/>.
/// </summary>
/// <param name="node">The node to be removed</param>
/// <remarks>
/// This removal adjusts the remaining <see cref="Node"/> accordingly.
/// </remarks>
private bool Remove(Node node)
{
if (node != this._head)
{
node.Previous.Next = node.Next;
node.Next.Previous = node.Previous;
this._count--;
return true;
}
return false;
}
#endregion
}
}
| |
//
// Grevit - Create Autodesk Revit (R) Models in McNeel's Rhino Grassopper 3D (R)
// For more Information visit grevit.net or food4rhino.com/project/grevit
// Copyright (C) 2015
// Authors: Maximilian Thumfart,
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System.Diagnostics;
using System.Xml;
using System.Net.Sockets;
using System.Net;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;
using System.Threading;
using Grevit.Types;
using System.Windows.Media.Imaging;
using Grevit.Revit;
namespace Grevit.Revit
{
/// <summary>
/// Extends all Grevit Elements by Revit specific Create Methods
/// </summary>
public static class CreateExtension
{
public static Element Create(this Grevit.Types.Filter filter)
{
List<ElementId> categories = new List<ElementId>();
Dictionary<string,ElementId> parameters = new Dictionary<string,ElementId>();
foreach (Category category in GrevitBuildModel.document.Settings.Categories)
{
if (filter.categories.Contains(category.Name) || filter.categories.Count == 0) categories.Add(category.Id);
FilteredElementCollector collector = new FilteredElementCollector(GrevitBuildModel.document).OfCategoryId(category.Id);
if (collector.Count() > 0)
{
foreach (Autodesk.Revit.DB.Parameter parameter in collector.FirstElement().Parameters)
if (!parameters.ContainsKey(parameter.Definition.Name)) parameters.Add(parameter.Definition.Name, parameter.Id);
}
}
ParameterFilterElement parameterFilter = null;
FilteredElementCollector collect = new FilteredElementCollector(GrevitBuildModel.document).OfClass(typeof(ParameterFilterElement));
foreach (ParameterFilterElement existingFilter in collect.ToElements())
{
if (existingFilter.Name == filter.name)
{
existingFilter.ClearRules();
parameterFilter = existingFilter;
}
}
if (parameterFilter == null) parameterFilter = ParameterFilterElement.Create(GrevitBuildModel.document, filter.name, categories);
View view = (View)Utilities.GetElementByName(GrevitBuildModel.document, typeof(View), filter.view);
view.AddFilter(parameterFilter.Id);
#region Apply Rules
List<FilterRule> filterRules = new List<FilterRule>();
foreach (Grevit.Types.Rule rule in filter.Rules)
{
if (parameters.ContainsKey(rule.name))
{
FilterRule filterRule = rule.ToRevitRule(parameters[rule.name]);
if (filterRule != null) filterRules.Add(filterRule);
}
}
#if (Revit2015 || Revit2016 || Revit2017 || Revit2018 || Revit2019)
parameterFilter.SetRules(filterRules);
#else
ElementParameterFilter elementParameterFilter = new ElementParameterFilter(filterRules);
parameterFilter.SetElementFilter(elementParameterFilter);
#endif
#endregion
#region Apply Overrides
OverrideGraphicSettings filterSettings = new OverrideGraphicSettings();
// Apply Colors
if (filter.CutLineColor != null) filterSettings.SetCutLineColor(filter.CutLineColor.ToRevitColor());
if (filter.ProjectionLineColor != null) filterSettings.SetProjectionLineColor(filter.ProjectionLineColor.ToRevitColor());
// Apply Lineweight
if (filter.CutLineWeight != -1) filterSettings.SetCutLineWeight(filter.CutLineWeight);
if (filter.ProjectionLineWeight != -1) filterSettings.SetProjectionLineWeight(filter.ProjectionLineWeight);
// Apply Patterns
if (filter.CutLinePattern != null)
{
LinePatternElement pattern = (LinePatternElement)Utilities.GetElementByName(GrevitBuildModel.document, typeof(LinePatternElement), filter.CutLinePattern);
filterSettings.SetCutLinePatternId(pattern.Id);
}
if (filter.ProjectionLinePattern != null)
{
LinePatternElement pattern = (LinePatternElement)Utilities.GetElementByName(GrevitBuildModel.document, typeof(LinePatternElement), filter.ProjectionLinePattern);
filterSettings.SetProjectionLinePatternId(pattern.Id);
}
view.SetFilterOverrides(parameterFilter.Id, filterSettings);
#endregion
return parameterFilter;
}
/// <summary>
/// Set a Revit Curtain Panel
/// </summary>
/// <param name="setCurtainPanel"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.SetCurtainPanel setCurtainPanel)
{
// If there arent any valid properties return null
if (setCurtainPanel.panelID == 0 || setCurtainPanel.panelType == "") return null;
// Get the panel to change
Panel panel = (Panel)GrevitBuildModel.document.GetElement(new ElementId(setCurtainPanel.panelID));
// get its host wall
Element wallElement = panel.Host;
if (wallElement.GetType() == typeof(Autodesk.Revit.DB.Wall))
{
// Cast the Wall
Autodesk.Revit.DB.Wall wall = (Autodesk.Revit.DB.Wall)wallElement;
// Try to get the curtain panel type
FilteredElementCollector collector = new FilteredElementCollector(GrevitBuildModel.document).OfClass(typeof(PanelType));
Element paneltype = collector.FirstElement();
foreach (Element em in collector.ToElements()) if (em.Name == setCurtainPanel.panelType) paneltype = em;
// Cast the Element type
ElementType type = (ElementType)paneltype;
// Change the panel type
wall.CurtainGrid.ChangePanelType(panel, type);
}
return panel;
}
/// <summary>
/// Create a new Family Instance
/// </summary>
/// <param name="familyInstance"></param>
/// <returns></returns>
public static Element Create(this Familyinstance familyInstance)
{
// Get the structural type
Autodesk.Revit.DB.Structure.StructuralType stype = familyInstance.structuralType.ToRevitStructuralType();
// Get the FamilySymbol
bool found = false;
Element familySymbolElement = null;
switch (stype)
{
case Autodesk.Revit.DB.Structure.StructuralType.Beam:
case Autodesk.Revit.DB.Structure.StructuralType.Brace:
familySymbolElement = GrevitBuildModel.document.GetElementByName(typeof(FamilySymbol), familyInstance.FamilyOrStyle, familyInstance.TypeOrLayer, out found, BuiltInCategory.OST_StructuralFraming);
break;
case Autodesk.Revit.DB.Structure.StructuralType.Column:
familySymbolElement = GrevitBuildModel.document.GetElementByName(typeof(FamilySymbol), familyInstance.FamilyOrStyle, familyInstance.TypeOrLayer, out found, BuiltInCategory.OST_StructuralColumns);
break;
default:
familySymbolElement = GrevitBuildModel.document.GetElementByName(typeof(FamilySymbol), familyInstance.FamilyOrStyle, familyInstance.TypeOrLayer, out found);
break;
}
// Setup a new Family Instance
Autodesk.Revit.DB.FamilyInstance newFamilyInstance = null;
// If the familySymbol is valid create a new instance
if (familySymbolElement != null)
{
// Cast the familySymbolElement
FamilySymbol familySymbol = (FamilySymbol)familySymbolElement;
if (!familySymbol.IsActive) familySymbol.Activate();
// Create a reference Element
Element referenceElement = null;
double elevation = familyInstance.points[0].z;
// If the view property is not set, the reference should be a level
// Otherwise the family is view dependent
if (familyInstance.view == null || familyInstance.view == string.Empty)
referenceElement = GrevitBuildModel.document.GetLevelByName(familyInstance.level,elevation);
else
referenceElement = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.View), familyInstance.view);
// If there is an element with the same GID existing, update it
// Otherwise create a new one
if (GrevitBuildModel.existing_Elements.ContainsKey(familyInstance.GID))
{
newFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)GrevitBuildModel.document.GetElement(GrevitBuildModel.existing_Elements[familyInstance.GID]);
if (newFamilyInstance.Location.GetType() == typeof(LocationPoint))
{
LocationPoint lp = (LocationPoint)newFamilyInstance.Location;
lp.Point = familyInstance.points[0].ToXYZ();
}
else if (newFamilyInstance.Location.GetType() == typeof(LocationCurve))
{
LocationCurve lp = (LocationCurve)newFamilyInstance.Location;
lp.Curve = Autodesk.Revit.DB.Line.CreateBound(familyInstance.points[0].ToXYZ(), familyInstance.points[1].ToXYZ());
}
}
else
{
// If there is no reference element just create the family without
if (referenceElement == null)
{
if (familyInstance.points.Count == 1) newFamilyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(familyInstance.points[0].ToXYZ(), familySymbol, stype);
}
else
{
if (familyInstance.points.Count == 1)
{
if (referenceElement.GetType() == typeof(Autodesk.Revit.DB.View))
newFamilyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(familyInstance.points[0].ToXYZ(), familySymbol, (Autodesk.Revit.DB.View)referenceElement);
else
newFamilyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(familyInstance.points[0].ToXYZ(), familySymbol, (Autodesk.Revit.DB.Level)referenceElement, stype);
}
else if (familyInstance.points.Count == 2)
{
Autodesk.Revit.DB.Line c = Autodesk.Revit.DB.Line.CreateBound(familyInstance.points[0].ToXYZ(), familyInstance.points[1].ToXYZ());
if (referenceElement.GetType() == typeof(Autodesk.Revit.DB.View))
newFamilyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(c, familySymbol, (Autodesk.Revit.DB.View)referenceElement);
else
newFamilyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(c, familySymbol, (Autodesk.Revit.DB.Level)referenceElement, stype);
}
}
}
}
return newFamilyInstance;
}
/// <summary>
/// Create a hosted family instance
/// </summary>
/// <param name="familyInstance"></param>
/// <param name="hostElement"></param>
/// <returns></returns>
public static Element Create(this Familyinstance familyInstance, Element hostElement)
{
// Get the Family Symbol
bool found = false;
Element familySymbolElement = GrevitBuildModel.document.GetElementByName(typeof(FamilySymbol), familyInstance.FamilyOrStyle, familyInstance.TypeOrLayer, out found);
// Set up a new family Instance
Autodesk.Revit.DB.FamilyInstance newFamilyInstance = null;
// If the symbol and the host element are valid create the family instance
if (familySymbolElement != null && hostElement != null)
{
// get the structural type
Autodesk.Revit.DB.Structure.StructuralType structuralType = familyInstance.structuralType.ToRevitStructuralType();
// Cast the family Symbol
FamilySymbol familySymbol = (FamilySymbol)familySymbolElement;
if (!familySymbol.IsActive) familySymbol.Activate();
double elevation = familyInstance.points[0].z;
// Get the placement level
Autodesk.Revit.DB.Level level = (Autodesk.Revit.DB.Level)GrevitBuildModel.document.GetLevelByName(familyInstance.level,elevation);
// If the element already exists just update it
// Otherwise create a new one
if (GrevitBuildModel.existing_Elements.ContainsKey(familyInstance.GID))
{
newFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)GrevitBuildModel.document.GetElement(GrevitBuildModel.existing_Elements[familyInstance.GID]);
if (newFamilyInstance.Location.GetType() == typeof(LocationPoint))
{
LocationPoint lp = (LocationPoint)newFamilyInstance.Location;
lp.Point = familyInstance.points[0].ToXYZ();
}
}
else
{
if (familyInstance.points.Count == 1)
newFamilyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(familyInstance.points[0].ToXYZ(), familySymbol, hostElement, level, structuralType);
}
}
return newFamilyInstance;
}
/// <summary>
/// Create a Line
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.RevitLine line)
{
// get revit curves from grevit curve
foreach (Curve c in Utilities.GrevitCurvesToRevitCurves(line.curve))
{
if (line.isModelCurve)
GrevitBuildModel.document.Create.NewModelCurve(c, Utilities.NewSketchPlaneFromCurve(GrevitBuildModel.document, c));
if (line.isDetailCurve)
GrevitBuildModel.document.Create.NewDetailCurve(GrevitBuildModel.document.ActiveView, c);
if (line.isRoomBounding)
{
CurveArray tmpca = new CurveArray();
tmpca.Append(c);
GrevitBuildModel.document.Create.NewRoomBoundaryLines(Utilities.NewSketchPlaneFromCurve(GrevitBuildModel.document, c), tmpca, GrevitBuildModel.document.ActiveView);
}
}
return null;
}
public static string ConceptualMassTemplatePath = GrevitBuildModel.RevitTemplateFolder + @"\Conceptual Mass\Metric Mass.rft";
/// <summary>
/// Create Extrusion
/// </summary>
/// <param name="extrusion"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.SimpleExtrusion extrusion)
{
// If the file doesnt exist ask the user for a new template
if (!File.Exists(ConceptualMassTemplatePath))
{
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Multiselect = false;
ofd.Title = ConceptualMassTemplatePath + " not found.";
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr != System.Windows.Forms.DialogResult.OK) return null;
ConceptualMassTemplatePath = ofd.FileName;
}
// Create a new family Document
Document familyDocument = GrevitBuildModel.document.Application.NewFamilyDocument(ConceptualMassTemplatePath);
// Create a new family transaction
Transaction familyTransaction = new Transaction(familyDocument, "Transaction in Family");
familyTransaction.Start();
// get family categories
Categories categories = familyDocument.Settings.Categories;
// Get the mass category
Category catMassing = categories.get_Item("Mass");
// Create a new subcategory in Mass
Category subcategory = familyDocument.Settings.Categories.NewSubcategory(catMassing, "GrevitExtrusion");
// Create a reference Array for the Profile
ReferenceArray referenceArrayProfile = new ReferenceArray();
// Translate all Points to the reference Array
for (int i = 0; i < extrusion.polyline.points.Count - 1; i++)
{
Grevit.Types.Point pkt1 = extrusion.polyline.points[i];
Grevit.Types.Point pkt2 = extrusion.polyline.points[i + 1];
referenceArrayProfile.Append(Utilities.CurveFromXYZ(familyDocument, pkt1.ToXYZ(), pkt2.ToXYZ()));
}
// Create a new Extrusion
Form extrudedMass = familyDocument.FamilyCreate.NewExtrusionForm(true, referenceArrayProfile, new XYZ(extrusion.vector.x, extrusion.vector.y, extrusion.vector.z));
// Apply the subcategory
extrudedMass.Subcategory = subcategory;
// Commit the Family Transaction
familyTransaction.Commit();
// Assemble a filename to save the family to
string filename = Path.Combine(Path.GetTempPath(), "GrevitMass-" + extrusion.GID + ".rfa");
// Save Family to Temp path and close it
SaveAsOptions opt = new SaveAsOptions();
opt.OverwriteExistingFile = true;
familyDocument.SaveAs(filename, opt);
familyDocument.Close(false);
// Load the created family to the document
Family family = null;
GrevitBuildModel.document.LoadFamily(filename, out family);
// Get the first family symbol
FamilySymbol symbol = null;
foreach (ElementId s in family.GetFamilySymbolIds())
{
symbol = (FamilySymbol)GrevitBuildModel.document.GetElement(s);
break;
}
if (!symbol.IsActive) symbol.Activate();
// Create a new Family Instance origin based
FamilyInstance familyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(new XYZ(0, 0, 0), symbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
// Activate Mass visibility
GrevitBuildModel.document.SetMassVisibilityOn();
return familyInstance;
}
/// <summary>
/// Create a Level
/// </summary>
/// <param name="level"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.Level level)
{
// Get all Levels from the document
FilteredElementCollector sollector = new FilteredElementCollector(GrevitBuildModel.document).OfClass(typeof(Autodesk.Revit.DB.Level));
// If there is any level with the same name that we are going to create return null because that level already exists
foreach (Element e in sollector.ToElements()) if (e.Name == level.name) return null;
#if (Revit2015 || Revit2016)
Autodesk.Revit.DB.Level newLevel = GrevitBuildModel.document.Create.NewLevel(level.height * GrevitBuildModel.Scale);
#else
// Create the new Level
Autodesk.Revit.DB.Level newLevel = Autodesk.Revit.DB.Level.Create(GrevitBuildModel.document, level.height * GrevitBuildModel.Scale);
#endif
// Set the Levels name
newLevel.Name = level.name;
// If we should create a view with it
if (level.addView)
{
// Get all View Family Types of familyType Floor plan
IEnumerable<ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(GrevitBuildModel.document).OfClass(typeof(ViewFamilyType))
let type = elem as ViewFamilyType
where type.ViewFamily == ViewFamily.FloorPlan
select type;
// Create a new view
ViewPlan.Create(GrevitBuildModel.document, viewFamilyTypes.First().Id, newLevel.Id);
}
return newLevel;
}
/// <summary>
/// Create Column
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.Column column)
{
// Get the Family, Type and Level
bool found = false;
XYZ location = column.location.ToXYZ();
XYZ top = column.locationTop.ToXYZ();
XYZ lower = (location.Z < top.Z) ? location : top;
XYZ upper = (location.Z < top.Z) ? top : location;
Element familyElement = GrevitBuildModel.document.GetElementByName(typeof(FamilySymbol), column.FamilyOrStyle, column.TypeOrLayer, out found, BuiltInCategory.OST_Columns);
if (familyElement == null)
familyElement = GrevitBuildModel.document.GetElementByName(typeof(FamilySymbol), column.FamilyOrStyle, column.TypeOrLayer, out found, BuiltInCategory.OST_StructuralColumns);
Element levelElement = GrevitBuildModel.document.GetLevelByName(column.levelbottom,lower.Z);
Autodesk.Revit.DB.FamilyInstance familyInstance = null;
if (familyElement != null && levelElement != null && familyElement != null)
{
// Cast the FamilySymbol and the Level
FamilySymbol sym = (FamilySymbol)familyElement;
if (!sym.IsActive) sym.Activate();
Autodesk.Revit.DB.Level level = (Autodesk.Revit.DB.Level)levelElement;
// If the column already exists update it
// Otherwise create a new one
if (GrevitBuildModel.existing_Elements.ContainsKey(column.GID))
familyInstance = (Autodesk.Revit.DB.FamilyInstance)GrevitBuildModel.document.GetElement(GrevitBuildModel.existing_Elements[column.GID]);
else
familyInstance = GrevitBuildModel.document.Create.NewFamilyInstance(lower, sym, level, Autodesk.Revit.DB.Structure.StructuralType.Column);
#region slantedColumn
// Get the Slanted Column parameter
Autodesk.Revit.DB.Parameter param = familyInstance.get_Parameter(BuiltInParameter.SLANTED_COLUMN_TYPE_PARAM);
// Set the slanted option to EndPoint which means we can set a top and a bottom point for the column
param.Set((double)SlantedOrVerticalColumnType.CT_EndPoint);
// get the locationcurve of the column
LocationCurve elementCurve = familyInstance.Location as LocationCurve;
if (elementCurve != null)
{
// Create a new line brom bottom to top
Autodesk.Revit.DB.Line line = Autodesk.Revit.DB.Line.CreateBound(lower, upper);
// Apply this line to the location curve
elementCurve.Curve = line;
}
#endregion
}
return familyInstance;
}
/// <summary>
/// Create a reference Plane
/// </summary>
/// <param name="plane"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.ReferencePlane plane)
{
// Get the supposed view element
Element view = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.View), plane.View);
// If its valid
if (view != null)
{
// Cast the View
View v = (View)view;
// Create a new plane
Autodesk.Revit.DB.ReferencePlane newPlane = GrevitBuildModel.document.Create.NewReferencePlane2(plane.EndA.ToXYZ(), plane.EndB.ToXYZ(), plane.cutVector.ToXYZ(), v);
// Set its name
plane.Name = plane.Name;
return newPlane;
}
return null;
}
/// <summary>
/// Create a gridline
/// </summary>
/// <param name="grid"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.Grid grid)
{
#if (Revit2015 || Revit2016)
// Create a new gridline
Autodesk.Revit.DB.Grid gridline = GrevitBuildModel.document.Create.NewGrid(Autodesk.Revit.DB.Line.CreateBound(grid.from.ToXYZ(), grid.to.ToXYZ()));
#else
Autodesk.Revit.DB.Grid gridline = Autodesk.Revit.DB.Grid.Create(GrevitBuildModel.document, Autodesk.Revit.DB.Line.CreateBound(grid.from.ToXYZ(), grid.to.ToXYZ()));
#endif
// If a name is supplied, set the name
if (grid.Name != null && grid.Name != "") gridline.Name = grid.Name;
return gridline;
}
/// <summary>
/// Create Hatch
/// </summary>
/// <param name="hatch"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.Hatch hatch)
{
// Get all Filled region types
FilteredElementCollector collector = new FilteredElementCollector(GrevitBuildModel.document).OfClass(typeof(Autodesk.Revit.DB.FilledRegionType));
// Get the View to place the hatch on
Element viewElement = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.View), hatch.view);
// Get the hatch pattern name and set it to solid if the hatch pattern name is invalid
string patternname = (hatch.pattern == null || hatch.pattern == string.Empty) ? patternname = "Solid fill" : hatch.pattern;
// Get the fill pattern element and filled region type
FillPatternElement fillPatternElement = FillPatternElement.GetFillPatternElementByName(GrevitBuildModel.document, FillPatternTarget.Drafting, patternname);
FilledRegionType filledRegionType = collector.FirstElement() as FilledRegionType;
// Setup a new curveloop for the outline
CurveLoop curveLoop = new CurveLoop();
List<CurveLoop> listOfCurves = new List<CurveLoop>();
// Get a closed loop from the grevit points
for (int i = 0; i < hatch.outline.Count; i++)
{
int j = i + 1;
Grevit.Types.Point p1 = hatch.outline[i];
if (j == hatch.outline.Count) j = 0;
Grevit.Types.Point p2 = hatch.outline[j];
Curve cn = Autodesk.Revit.DB.Line.CreateBound(p1.ToXYZ(), p2.ToXYZ());
curveLoop.Append(cn);
}
listOfCurves.Add(curveLoop);
// Create a filled region from the loop
return FilledRegion.Create(GrevitBuildModel.document, filledRegionType.Id, viewElement.Id, listOfCurves);
}
/// <summary>
/// Create spot Coordinate
/// </summary>
/// <param name="spotCoordinate"></param>
/// <param name="reference"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.SpotCoordinate spotCoordinate, Element reference)
{
// get View to place the spot coordinate on
Element viewElement = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.View), spotCoordinate.view);
if (viewElement != null)
{
View view = (View)viewElement;
// Get the reference point for the coordinate
XYZ pointref = spotCoordinate.refPoint.ToXYZ();
// If the reference element has a locationcurve or locationpoint use
// this point instead of the reference point
if (reference.Location.GetType() == typeof(LocationPoint))
{
LocationPoint lp = (LocationPoint)reference.Location;
pointref = lp.Point;
}
if (reference.Location.GetType() == typeof(LocationCurve))
{
LocationCurve lp = (LocationCurve)reference.Location;
pointref = lp.Curve.GetEndPoint(0);
}
// Create Spot Elevation as elevation or standard
if (spotCoordinate.isElevation)
return GrevitBuildModel.document.Create.NewSpotElevation(view, new Reference(reference), spotCoordinate.locationPoint.ToXYZ(), spotCoordinate.bendPoint.ToXYZ(), spotCoordinate.endPoint.ToXYZ(), pointref, spotCoordinate.hasLeader);
else
return GrevitBuildModel.document.Create.NewSpotCoordinate(view, new Reference(reference), spotCoordinate.locationPoint.ToXYZ(), spotCoordinate.bendPoint.ToXYZ(), spotCoordinate.endPoint.ToXYZ(), pointref, spotCoordinate.hasLeader);
}
return null;
}
/// <summary>
/// Create Topography
/// </summary>
/// <param name="topography"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.Topography topography)
{
// Translate the Grevit Points to Revit Points
List<XYZ> points = new List<XYZ>();
foreach (Grevit.Types.Point point in topography.points) points.Add(point.ToXYZ());
// Create a new Topography based on this
return Autodesk.Revit.DB.Architecture.TopographySurface.Create(GrevitBuildModel.document, points);
}
/// <summary>
/// Creates a new Revit Texnote
/// </summary>
/// <param name="textnote"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.TextNote textnote)
{
// Get the View Element to place the note on
Element viewElement = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.View), textnote.view);
if (viewElement != null)
{
// Cast to view
View view = (View)viewElement;
// Set a reasonable width
double width = textnote.text.Length * 2;
// return a new Textnote
#if (!Revit2015)
Autodesk.Revit.DB.TextNoteType type = (Autodesk.Revit.DB.TextNoteType)new FilteredElementCollector(GrevitBuildModel.document).OfClass(typeof(Autodesk.Revit.DB.TextNoteType)).FirstOrDefault();
return Autodesk.Revit.DB.TextNote.Create(GrevitBuildModel.document, view.Id, textnote.location.ToXYZ(), textnote.text, type.Id);
#else
return GrevitBuildModel.document.Create.NewTextNote(view, textnote.location.ToXYZ(), XYZ.BasisX, XYZ.BasisY, width, TextAlignFlags.TEF_ALIGN_LEFT, textnote.text);
#endif
}
return null;
}
/// <summary>
/// Creates a new Revit Slab
/// </summary>
/// <param name="slab"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.Slab slab)
{
// Create a List of Curves for the ouline
List<Curve> curves = new List<Curve>();
// Translate Grevit Curves to Revit Curves
for (int i = 0; i < slab.surface.profile[0].outline.Count; i++)
{
foreach (Curve curve in Utilities.GrevitCurvesToRevitCurves(slab.surface.profile[0].outline[i])) curves.Add(curve);
}
FloorType type = (FloorType)GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.FloorType), slab.TypeOrLayer);
if (type == null) return null;
// Get the two slope points
XYZ slopePointBottom = curves[0].GetEndPoint(0);
// XYZ slopeTopPoint = slab.top.ToXYZ();
// get a Z Value from an outline point to check if the slope points are in this plane
// double outlineZCheckValue = curves[0].GetEndPoint(0).Z;
// If one of the points is not in the same Z plane
// Create new points replacing the Z value
// if (!slopePointBottom.Z.Equals(outlineZCheckValue) || !slopeTopPoint.Z.Equals(outlineZCheckValue))
// {
// slopePointBottom = new XYZ(slopePointBottom.X, slopePointBottom.Y, outlineZCheckValue);
// slopeTopPoint = new XYZ(slopeTopPoint.X, slopeTopPoint.Y, outlineZCheckValue);
// }
// Create a new slope line between the points
// Autodesk.Revit.DB.Line slopeLine = Autodesk.Revit.DB.Line.CreateBound(slopePointBottom, slopeTopPoint);
// Sort the outline curves contiguous
Utilities.SortCurvesContiguous(GrevitBuildModel.document.Application.Create, curves);
// Create a new surve array for creating the slab
CurveArray outlineCurveArray = new CurveArray();
foreach (Curve c in curves) outlineCurveArray.Append(c);
// get the supposed level
Element levelElement = GrevitBuildModel.document.GetLevelByName(slab.levelbottom,slopePointBottom.Z);
if (levelElement != null)
{
// Create a new slab
return GrevitBuildModel.document.Create.NewFloor(outlineCurveArray, type, (Autodesk.Revit.DB.Level)levelElement, slab.structural);
}
return null;
}
public static Element Create(this Grevit.Types.Roof roof)
{
// Create a List of Curves for the ouline
List<Curve> curves = new List<Curve>();
// Get the Wall type and the level
RoofType type = (RoofType)GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.RoofType), roof.TypeOrLayer);
if (type != null)
{
// Translate Grevit Curves to Revit Curves
for (int i = 0; i < roof.surface.profile[0].outline.Count; i++)
{
foreach (Curve curve in Utilities.GrevitCurvesToRevitCurves(roof.surface.profile[0].outline[i])) curves.Add(curve);
}
// Get the two slope points
XYZ slopePointBottom = curves[0].GetEndPoint(0);
// Sort the outline curves contiguous
Utilities.SortCurvesContiguous(GrevitBuildModel.document.Application.Create, curves);
// Create a new surve array for creating the slab
CurveArray outlineCurveArray = new CurveArray();
foreach (Curve c in curves) outlineCurveArray.Append(c);
// get the supposed level
Element levelElement = GrevitBuildModel.document.GetLevelByName(roof.levelbottom, slopePointBottom.Z);
if (levelElement != null)
{
Element rvtRoof = null;
if (GrevitBuildModel.existing_Elements.ContainsKey(roof.GID))
{
rvtRoof = GrevitBuildModel.document.GetElement(GrevitBuildModel.existing_Elements[roof.GID]);
}
else
{
ModelCurveArray mapping = new ModelCurveArray();
// Create a new slab
rvtRoof = GrevitBuildModel.document.Create.NewFootPrintRoof(outlineCurveArray,
(Autodesk.Revit.DB.Level)levelElement, type, out mapping);
}
GrevitBuildModel.RoofShapePoints.Add(new Tuple<ElementId, CurveArray>(rvtRoof.Id, outlineCurveArray));
return rvtRoof;
}
}
return null;
}
/// <summary>
/// Create Profile based wall
/// </summary>
/// <param name="w"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.WallProfileBased w)
{
double elevation = 0;
bool init = false;
// Translate Profile Curves
List<Curve> curves = new List<Curve>();
foreach (Component component in w.curves)
{
foreach (Curve curve in Utilities.GrevitCurvesToRevitCurves(component))
{
curves.Add(curve);
if (!init)
{
elevation = curve.GetEndPoint(0).Z;
init = true;
}
else
{
if (curve.GetEndPoint(0).Z < elevation) elevation = curve.GetEndPoint(0).Z;
}
}
}
// Get Wall Type
Element wallTypeElement = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.WallType), w.TypeOrLayer);
// Get Level
Autodesk.Revit.DB.Level levelElement = (Autodesk.Revit.DB.Level)GrevitBuildModel.document.GetLevelByName(w.level, elevation);
if (wallTypeElement != null && levelElement != null)
{
Autodesk.Revit.DB.Wall wall;
// If the wall exists update it otherwise create a new one
if (GrevitBuildModel.existing_Elements.ContainsKey(w.GID))
GrevitBuildModel.document.Delete(GrevitBuildModel.existing_Elements[w.GID]);
double offset = elevation - levelElement.Elevation;
wall = Autodesk.Revit.DB.Wall.Create(GrevitBuildModel.document, curves, wallTypeElement.Id, levelElement.Id, true);
Autodesk.Revit.DB.Parameter paramtc = wall.LookupParameter("Top Constraint");
if (paramtc != null && !paramtc.IsReadOnly) paramtc.Set(ElementId.InvalidElementId);
if (offset != 0)
{
Autodesk.Revit.DB.Parameter param = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
if (param != null && !param.IsReadOnly) { param.Set(offset); }
}
w.SetParameters(wall);
w.StoreGID(wall.Id);
return wall;
}
return null;
}
/// <summary>
/// Create curtain Gridline
/// </summary>
/// <param name="curtainGridLine"></param>
/// <param name="hostElement"></param>
/// <returns></returns>
public static Element Create(this Grevit.Types.CurtainGridLine curtainGridLine, Element hostElement)
{
// Check host if it is a wall
if (hostElement.GetType() == typeof(Autodesk.Revit.DB.Wall))
{
// Cast the wall
Autodesk.Revit.DB.Wall wall = (Autodesk.Revit.DB.Wall)hostElement;
// Create a new Gridline on the wall
Autodesk.Revit.DB.CurtainGridLine gridline = wall.CurtainGrid.AddGridLine(curtainGridLine.horizontal, curtainGridLine.point.ToXYZ(), curtainGridLine.single);
return gridline;
}
return null;
}
/// <summary>
/// Creates a new Revit Room
/// </summary>
/// <param name="room"></param>
/// <returns></returns>
public static Element Create(this Room room)
{
// Get the rooms phase
Phase phase = null;
foreach (Phase p in GrevitBuildModel.document.Phases) if (p.Name == room.phase) phase = p;
if (phase != null)
{
// Create a new Room
Autodesk.Revit.DB.Architecture.Room newRoom = GrevitBuildModel.document.Create.NewRoom(phase);
// Set Name and Number
newRoom.Name = room.name;
newRoom.Number = room.number;
return newRoom;
}
return null;
}
/// <summary>
/// Create Adaptive Component
/// </summary>
/// <param name="adaptive"></param>
/// <returns></returns>
public static Element Create(this Adaptive adaptive)
{
// Get the family Symbol
bool found = false;
Element faimlyElement = GrevitBuildModel.document.GetElementByName(typeof(FamilySymbol), adaptive.FamilyOrStyle, adaptive.TypeOrLayer, out found);
FamilySymbol faimlySymbol = (FamilySymbol)faimlyElement;
if (faimlySymbol != null)
{
if (!faimlySymbol.IsActive) faimlySymbol.Activate();
FamilyInstance adaptiveComponent = null;
// If the adaptive component already exists get it
// Otherwise create a new one
if (GrevitBuildModel.existing_Elements.ContainsKey(adaptive.GID))
adaptiveComponent = (FamilyInstance)GrevitBuildModel.document.GetElement(GrevitBuildModel.existing_Elements[adaptive.GID]);
else
adaptiveComponent = Autodesk.Revit.DB.AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(GrevitBuildModel.document, faimlySymbol);
// Get the Placement points of the adaptive component
IList<ElementId> ids = Autodesk.Revit.DB.AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(adaptiveComponent);
// Walk thru the points and set them to the grevit points coordinates
if (adaptive.points.Count != ids.Count)
{
Grevit.Reporting.MessageBox.Show("Adaptive Component Error", String.Format("Cannot create adaptive component because the Revit family requires {0} points while only {1} have been submitted.", new object[] { ids.Count, adaptive.points.Count }));
return null;
}
for (int i = 0; i < ids.Count; i++)
{
// Get the Reference Point
ElementId id = ids[i];
Element em = GrevitBuildModel.document.GetElement(id);
ReferencePoint referencePoint = (ReferencePoint)em;
// Set the reference Point to the Grevit Point
referencePoint.Position = adaptive.points[i].ToXYZ();
}
return adaptiveComponent;
}
return null;
}
/// <summary>
/// Create Revit Wall
/// </summary>
/// <param name="grevitWall"></param>
/// <param name="from">Optional Point From</param>
/// <param name="to">Optional Point To</param>
/// <returns></returns>
public static Element Create(this Grevit.Types.Wall grevitWall, Grevit.Types.Point from = null, Grevit.Types.Point to = null)
{
#region baseLineCurve
// The Baseline curve for the wall
Autodesk.Revit.DB.Curve baselineCurve = null;
// If the from and the to point have been set
// Draw a line using those points (linear wall)
if (from != null && to != null)
{
XYZ a = from.ToXYZ();
XYZ b = to.ToXYZ();
if (a.DistanceTo(b) > 0.01)
{
baselineCurve = Autodesk.Revit.DB.Line.CreateBound(a, b);
}
}
// Otherwise check the curve type
else
{
// If the curve is a polyline (linear) split it into segments and create walls of them
if (grevitWall.curve.GetType() == typeof(Grevit.Types.PLine))
{
Grevit.Types.PLine pline = (Grevit.Types.PLine)grevitWall.curve;
// Walk thru all points and create segments
for (int i = 0; i < pline.points.Count; i++)
{
if (i == pline.points.Count - 1)
{
if (pline.closed) grevitWall.Create(pline.points[i], pline.points[0]);
}
else
grevitWall.Create(pline.points[i], pline.points[i + 1]);
}
}
// If the curve is a line just create a line
else if (grevitWall.curve.GetType() == typeof(Grevit.Types.Line))
{
Grevit.Types.Line baseline = (Grevit.Types.Line)grevitWall.curve;
baselineCurve = Autodesk.Revit.DB.Line.CreateBound(baseline.from.ToXYZ(), baseline.to.ToXYZ());
}
// If the curve is an Arc create an Arc with Centerpoint, start, radius and end
else if (grevitWall.curve.GetType() == typeof(Grevit.Types.Arc))
{
Grevit.Types.Arc baseline = (Grevit.Types.Arc)grevitWall.curve;
baselineCurve = Autodesk.Revit.DB.Arc.Create(baseline.center.ToXYZ(), baseline.radius, baseline.start, baseline.end, XYZ.BasisX, XYZ.BasisY);
}
// If the curve is a 3Point Arc, create a new 3 Point based arc.
else if (grevitWall.curve.GetType() == typeof(Grevit.Types.Curve3Points))
{
Grevit.Types.Curve3Points baseline = (Grevit.Types.Curve3Points)grevitWall.curve;
baselineCurve = Autodesk.Revit.DB.Arc.Create(baseline.a.ToXYZ(), baseline.c.ToXYZ(), baseline.b.ToXYZ());
}
}
#endregion
// Get the Wall type and the level
Element wallTypeElement = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.WallType), grevitWall.TypeOrLayer);
if (wallTypeElement != null && baselineCurve != null)
{
Autodesk.Revit.DB.Level levelElement = (Autodesk.Revit.DB.Level)GrevitBuildModel.document.GetLevelByName(grevitWall.levelbottom, baselineCurve.GetEndPoint(0).Z);
if (levelElement == null) return null;
Autodesk.Revit.DB.Wall wall;
double offset = baselineCurve.GetEndPoint(0).Z - levelElement.Elevation;
// If the wall already exists update the baseline curve
// Otherwise create a new wall
if (GrevitBuildModel.existing_Elements.ContainsKey(grevitWall.GID))
{
wall = (Autodesk.Revit.DB.Wall)GrevitBuildModel.document.GetElement(GrevitBuildModel.existing_Elements[grevitWall.GID]);
LocationCurve locationCurve = (LocationCurve)wall.Location;
locationCurve.Curve = baselineCurve;
}
else
wall = Autodesk.Revit.DB.Wall.Create(GrevitBuildModel.document, baselineCurve, wallTypeElement.Id, levelElement.Id, grevitWall.height, 0, false, true);
Autodesk.Revit.DB.Parameter paramtc = wall.LookupParameter("Top Constraint");
if (paramtc != null && !paramtc.IsReadOnly) paramtc.Set(ElementId.InvalidElementId);
Autodesk.Revit.DB.Parameter heightParam = wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);
if (heightParam != null && !heightParam.IsReadOnly) heightParam.Set(grevitWall.height);
// Apply the automatic join setting
if (!grevitWall.join)
{
WallUtils.DisallowWallJoinAtEnd(wall, 0);
WallUtils.DisallowWallJoinAtEnd(wall, 1);
}
if (offset != 0)
{
Autodesk.Revit.DB.Parameter param = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
if (param != null && !param.IsReadOnly) { param.Set(offset); }
}
// Apply Flipped status
if (grevitWall.flip) wall.Flip();
// This method is applying the parameters and GID settings
// itself because it might run recursively (see Polyline)
grevitWall.SetParameters(wall);
grevitWall.StoreGID(wall.Id);
}
// Always returns null as it handles
// parameters and GIDs within this method
return null;
}
public static Element Create(this Grevit.Types.FaceWall faceWall)
{
Reference reference = Reference.ParseFromStableRepresentation(GrevitBuildModel.document, faceWall.Reference);
if (reference == null) return null;
Element wallTypeElement = GrevitBuildModel.document.GetElementByName(typeof(Autodesk.Revit.DB.WallType), faceWall.TypeOrLayer);
if (wallTypeElement == null) return null;
WallLocationLine loc = WallLocationLine.CoreCenterline;
Enum.TryParse<WallLocationLine>(faceWall.Location, out loc);
var fw = Autodesk.Revit.DB.FaceWall.Create(GrevitBuildModel.document, wallTypeElement.Id,loc, reference);
return fw;
}
public static Element Create(this Grevit.Types.SelectionSet selection)
{
SelectionFilterElement filter = (SelectionFilterElement)Utilities.GetElementByName(GrevitBuildModel.document, typeof(SelectionFilterElement), selection.Name);
if (filter == null || filter.Name != selection.Name)
filter = Autodesk.Revit.DB.SelectionFilterElement.Create(GrevitBuildModel.document, selection.Name);
List<ElementId> elements = new List<ElementId>();
foreach (string id in selection.IDs)
{
if (GrevitBuildModel.created_Elements.ContainsKey(id))
{
ElementId eid = GrevitBuildModel.created_Elements[id];
if (eid != ElementId.InvalidElementId)
{
elements.Add(eid);
}
}
}
filter.SetElementIds(elements);
return filter;
}
public static Element Create(this Grevit.Types.Shaft shaft)
{
List<Curve> curves = new List<Curve>();
// Translate Grevit Curves to Revit Curves
for (int i = 0; i < shaft.surface.profile[0].outline.Count; i++)
{
foreach (Curve curve in Utilities.GrevitCurvesToRevitCurves(shaft.surface.profile[0].outline[i]))
curves.Add(curve);
}
Utilities.SortCurvesContiguous(GrevitBuildModel.document.Application.Create, curves);
// Create a new surve array for creating the slab
CurveArray outlineCurveArray = new CurveArray();
foreach (Curve c in curves) outlineCurveArray.Append(c);
var bottom = Utilities.GetLevelByName(GrevitBuildModel.document, shaft.levelbottom,0);
var top = Utilities.GetLevelByName(GrevitBuildModel.document, shaft.leveltop,1000);
var opening = GrevitBuildModel.document.Create.NewOpening(bottom, top, outlineCurveArray);
return opening;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Globalization;
using System.Xml;
using fyiReporting.RDL;
using fyiReporting.RdlDesign.Resources;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for DialogDatabase.
/// </summary>
public partial class DialogDatabase
{
RdlDesigner _rDesigner = null;
RdlUserControl _rUserControl = null;
static private readonly string SHARED_CONNECTION = "Shared Data Source";
string _StashConnection = null;
private List<SqlColumn> _ColumnList = null;
private string _TempFileName = null;
private string _ResultReport = "nothing";
private readonly string _Schema2003 =
"xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2003/10/reportdefinition\" xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\"";
private readonly string _Schema2005 =
"xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition\" xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\"";
private string _TemplateChart = " some junk";
private string _TemplateMatrix = " some junk";
private string _TemplateTable = @"<?xml version='1.0' encoding='UTF-8'?>
<Report |schema| >
<Description>|description|</Description>
<Author>|author|</Author>
|orientation|
<DataSources>
<DataSource Name='DS1'>
|connectionproperties|
</DataSource>
</DataSources>
<Width>7.5in</Width>
<TopMargin>.25in</TopMargin>
<LeftMargin>.25in</LeftMargin>
<RightMargin>.25in</RightMargin>
<BottomMargin>.25in</BottomMargin>
|reportparameters|
<DataSets>
<DataSet Name='Data'>
<Query>
<DataSourceName>DS1</DataSourceName>
<CommandText>|sqltext|</CommandText>
|queryparameters|
</Query>
<Fields>
|sqlfields|
</Fields>
</DataSet>
</DataSets>
<PageHeader>
<Height>.5in</Height>
|ifdef reportname|
<ReportItems>
<Textbox><Top>.1in</Top><Left>.1in</Left><Width>6in</Width><Height>.25in</Height><Value>|reportnameasis|</Value><Style><FontSize>15pt</FontSize><FontWeight>Bold</FontWeight></Style></Textbox>
</ReportItems>
|endif|
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageHeader>
<Body>
<ReportItems>
<Table>
<DataSetName>Data</DataSetName>
<NoRows>Query returned no rows!</NoRows>
<Style><BorderStyle><Default>Solid</Default></BorderStyle></Style>
<TableColumns>
|tablecolumns|
</TableColumns>
<Header>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|tableheaders|</TableCells>
</TableRow>
</TableRows>
<RepeatOnNewPage>true</RepeatOnNewPage>
</Header>
|ifdef grouping|
<TableGroups>
<TableGroup>
<Header>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>
<TableCell>
<ColSpan>|columncount|</ColSpan>
<ReportItems><Textbox><Value>=Fields.|groupbycolumn|.Value</Value><Style><PaddingLeft>2pt</PaddingLeft><BorderStyle><Default>Solid</Default></BorderStyle><FontWeight>Bold</FontWeight></Style></Textbox></ReportItems>
</TableCell>
</TableCells>
</TableRow>
</TableRows>
<RepeatOnNewPage>true</RepeatOnNewPage>
</Header>
<Footer>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|gtablefooters|</TableCells>
</TableRow>
</TableRows>
</Footer>
<Grouping Name='|groupbycolumn|Group'><GroupExpressions><GroupExpression>=Fields!|groupbycolumn|.Value</GroupExpression></GroupExpressions></Grouping>
</TableGroup>
</TableGroups>
|endif|
<Details>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|tablevalues|</TableCells>
</TableRow>
</TableRows>
</Details>
|ifdef footers|
<Footer>
<TableRows>
<TableRow>
<Height>12pt</Height>
<TableCells>|tablefooters|</TableCells>
</TableRow>
</TableRows>
</Footer>
|endif|
</Table>
</ReportItems>
<Height>|bodyheight|</Height>
</Body>
<PageFooter>
<Height>14pt</Height>
<ReportItems>
<Textbox><Top>1pt</Top><Left>10pt</Left><Height>12pt</Height><Width>3in</Width>
<Value>=Globals!PageNumber + ' of ' + Globals!TotalPages</Value>
<Style><FontSize>10pt</FontSize><FontWeight>Normal</FontWeight></Style>
</Textbox>
</ReportItems>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageFooter>
</Report>";
private string _TemplateList = @"<?xml version='1.0' encoding='UTF-8'?>
<Report |schema| >
<Description>|description|</Description>
<Author>|author|</Author>
|orientation|
<DataSources>
<DataSource Name='DS1'>
|connectionproperties|
</DataSource>
</DataSources>
<Width>7.5in</Width>
<TopMargin>.25in</TopMargin>
<LeftMargin>.25in</LeftMargin>
<RightMargin>.25in</RightMargin>
<BottomMargin>.25in</BottomMargin>
|reportparameters|
<DataSets>
<DataSet Name='Data'>
<Query>
<DataSourceName>DS1</DataSourceName>
<CommandText>|sqltext|</CommandText>
|queryparameters|
</Query>
<Fields>
|sqlfields|
</Fields>
</DataSet>
</DataSets>
<PageHeader>
<Height>.5in</Height>
<ReportItems>
|ifdef reportname|
<Textbox><Top>.02in</Top><Left>.1in</Left><Width>6in</Width><Height>.25in</Height><Value>|reportname|</Value><Style><FontSize>15pt</FontSize><FontWeight>Bold</FontWeight></Style></Textbox>
|endif|
|listheaders|
</ReportItems>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageHeader>
<Body><Height>25pt</Height>
<ReportItems>
<List>
<DataSetName>Data</DataSetName>
<Height>24pt</Height>
<NoRows>Query returned no rows!</NoRows>
<ReportItems>
|listvalues|
</ReportItems>
<Width>|listwidth|</Width>
</List>
</ReportItems>
</Body>
<PageFooter>
<Height>14pt</Height>
<ReportItems>
<Textbox><Top>1pt</Top><Left>10pt</Left><Height>12pt</Height><Width>3in</Width>
<Value>=Globals!PageNumber + ' of ' + Globals!TotalPages</Value>
<Style><FontSize>10pt</FontSize><FontWeight>Normal</FontWeight></Style>
</Textbox>
</ReportItems>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageFooter>
</Report>";
private string _TemplateEmpty = @"<?xml version='1.0' encoding='UTF-8'?>
<Report |schema| >
<Description>|description|</Description>
<Author>|author|</Author>
|orientation|
<Width>7.5in</Width>
<TopMargin>.25in</TopMargin>
<LeftMargin>.25in</LeftMargin>
<RightMargin>.25in</RightMargin>
<BottomMargin>.25in</BottomMargin>
|reportparameters|
<PageHeader>
<Height>.5in</Height>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageHeader>
<Body><Height>25pt</Height></Body>
<PageFooter>
<Height>14pt</Height>
<ReportItems>
<Textbox><Top>1pt</Top><Left>10pt</Left><Height>12pt</Height><Width>3in</Width>
<Value>=Globals!PageNumber + ' of ' + Globals!TotalPages</Value>
<Style><FontSize>10pt</FontSize><FontWeight>Normal</FontWeight></Style>
</Textbox>
</ReportItems>
<PrintOnFirstPage>true</PrintOnFirstPage>
<PrintOnLastPage>true</PrintOnLastPage>
</PageFooter>
</Report>";
public DialogDatabase(RdlDesigner rDesigner)
{
_rDesigner = rDesigner;
//
// Required for Windows Form Designer support
//
InitializeComponent();
string[] items = RdlEngineConfig.GetProviders();
Array.Sort(items);
cbConnectionTypes.Items.Add(SHARED_CONNECTION);
cbConnectionTypes.Items.AddRange(items);
cbConnectionTypes.SelectedIndex = 1;
cbOrientation.SelectedIndex = 0;
}
public DialogDatabase(RdlUserControl rDesigner)
{
_rUserControl = rDesigner;
//
// Required for Windows Form Designer support
//
InitializeComponent();
string[] items = RdlEngineConfig.GetProviders();
cbConnectionTypes.Items.Add(SHARED_CONNECTION);
cbConnectionTypes.Items.AddRange(items);
cbConnectionTypes.SelectedIndex = 1;
cbOrientation.SelectedIndex = 0;
}
public enum ConnectionType
{
MYSQL,
MSSQL,
SQLITE,
POSTGRESQL,
XML,
WEBSERVICE
}
/// <summary>
/// Pre set a connection string. This is useful when you need to create
/// a new report from a program other then RdlDesigner.
/// </summary>
/// <param name="connectionString">A full and correct database connection string</param>
/// <param name="hideConnectionTab">If true this will hide the connection string. This is useful
/// when you do not want the users to need to know this information.</param>
/// <param name="ct">The database connection type.</param>
public void SetConnection(string connectionString, bool hideConnectionTab, ConnectionType ct)
{
if (ct == ConnectionType.MSSQL)
{
cbConnectionTypes.SelectedItem = "SQL";
}
else if (ct == ConnectionType.MYSQL)
{
cbConnectionTypes.SelectedItem = "MySQL.NET";
}
else if (ct == ConnectionType.POSTGRESQL)
{
cbConnectionTypes.SelectedItem = "PostgreSQL";
}
else if (ct == ConnectionType.SQLITE)
{
cbConnectionTypes.SelectedItem = "SQLite";
}
else if (ct == ConnectionType.WEBSERVICE)
{
cbConnectionTypes.SelectedItem = "WebService";
}
else if (ct == ConnectionType.XML)
{
cbConnectionTypes.SelectedItem = "XML";
}
else
{
throw new Exception("You should not have reached this far in the SetConnection function.");
}
tbConnection.Text = connectionString;
if (hideConnectionTab == true)
{
tcDialog.TabPages.Remove(tcDialog.TabPages["DBConnection"]);
}
}
public string ResultReport
{
get { return _ResultReport; }
}
private void btnOK_Click(object sender, System.EventArgs e)
{
if (!DoReportSyntax(false))
return;
DialogResult = DialogResult.OK;
_ResultReport = tbReportSyntax.Text;
this.Close();
}
private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
{
TabControl tc = (TabControl)sender;
string tag = (string)tc.TabPages[tc.SelectedIndex].Tag;
switch (tag)
{
case "type": // nothing to do here
break;
case "connect": // nothing to do here
break;
case "sql": // obtain table and column information
DoSqlSchema();
break;
case "group": // obtain group by information using connection & sql
DoGrouping();
break;
case "syntax": // obtain report using connection, sql,
DoReportSyntax(false);
break;
case "preview": // run report using generated report syntax
DoReportPreview();
break;
default:
break;
}
}
// Fill out tvTablesColumns
private void DoSqlSchema()
{
// TODO be more efficient and remember schema info;
// need to mark changes to connections
if (tvTablesColumns.Nodes.Count > 0)
return;
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
// Get the schema information
List<SqlSchemaInfo> si = DesignerUtility.GetSchemaInfo(GetDataProvider(), GetDataConnection());
TreeNode ndRoot = new TreeNode("Tables");
tvTablesColumns.Nodes.Add(ndRoot);
bool bView = false;
foreach (SqlSchemaInfo ssi in si)
{
if (!bView && ssi.Type == "VIEW")
{ // Switch over to views
ndRoot = new TreeNode("Views");
tvTablesColumns.Nodes.Add(ndRoot);
bView = true;
}
// Add the node to the tree
TreeNode aRoot = new TreeNode(ssi.Name);
ndRoot.Nodes.Add(aRoot);
aRoot.Nodes.Add("");
}
// Now do parameters
//if (lbParameters.Items.Count > 0)
//{
// ndRoot = new TreeNode("Parameters");
// tvTablesColumns.Nodes.Add(ndRoot);
// foreach (ReportParm rp in lbParameters.Items)
// {
// string paramName;
// // force the name to start with @
// if (rp.Name[0] == '@')
// paramName = rp.Name;
// else
// paramName = "@" + rp.Name;
// // Add the node to the tree
// TreeNode aRoot = new TreeNode(paramName);
// ndRoot.Nodes.Add(aRoot);
// }
//}
tvTablesColumns.EndUpdate();
}
private void DoGrouping()
{
if (cbColumnList.Items.Count > 0) // We already have the columns?
return;
if (!rbEmpty.Checked)
{
if (_ColumnList == null)
_ColumnList = DesignerUtility.GetSqlColumns(GetDataProvider(), GetDataConnection(), tbSQL.Text, reportParameterCtl1.lbParameters.Items);
foreach (SqlColumn sq in _ColumnList)
{
cbColumnList.Items.Add(sq);
clbSubtotal.Items.Add(sq);
}
SqlColumn sqc = new SqlColumn();
sqc.Name = "";
cbColumnList.Items.Add(sqc);
}
return;
}
private bool DoReportSyntax(bool UseFullSharedDSName)
{
string template;
if (rbList.Checked)
template = _TemplateList;
else if (rbTable.Checked)
template = _TemplateTable;
else if (rbMatrix.Checked)
template = _TemplateMatrix;
else if (rbChart.Checked)
template = _TemplateChart;
else if (rbEmpty.Checked)
template = _TemplateEmpty;
else
template = _TemplateTable; // default to table- should never reach
if (!rbEmpty.Checked)
{
if (_ColumnList == null)
_ColumnList = DesignerUtility.GetSqlColumns(GetDataProvider(), GetDataConnection(), tbSQL.Text, reportParameterCtl1.lbParameters.Items);
if (_ColumnList.Count == 0) // can only happen by an error
return false;
}
string[] parts = template.Split('|');
StringBuilder sb = new StringBuilder(template.Length);
decimal left = 0m;
decimal width;
decimal bodyHeight = 0;
string name;
int skip = 0; // skip is used to allow nesting of ifdef
string args;
string canGrow;
string align;
// handle the group by column
string gbcolumn;
if (this.cbColumnList.Text.Length > 0)
gbcolumn = GetFieldName(this.cbColumnList.Text);
else
gbcolumn = null;
CultureInfo cinfo = new CultureInfo("", false);
foreach (string p in parts)
{
// Handle conditional special
int length = 5;
if (p.Length < 5)
{
length = p.Length;
}
if (p.Substring(0, length) == "ifdef")
{
args = p.Substring(6);
switch (args)
{
case "reportname":
if (tbReportName.Text.Length == 0)
skip++;
break;
case "description":
if (tbReportDescription.Text.Length == 0)
skip++;
break;
case "author":
if (tbReportAuthor.Text.Length == 0)
skip++;
break;
case "grouping":
if (gbcolumn == null)
skip++;
break;
case "footers":
if (!ckbGrandTotal.Checked)
skip++;
else if (clbSubtotal.CheckedItems.Count <= 0)
skip++;
break;
default:
throw new Exception(String.Format(Strings.DialogDatabase_Error_UnknownIfdef, args));
}
continue;
}
// if skipping lines (due to ifdef) then go to next endif
if (skip > 0 && p != "endif")
continue;
switch (p)
{
case "endif":
if (skip > 0)
skip--;
break;
case "schema":
if (this.rbSchema2003.Checked)
sb.Append(_Schema2003);
else if (this.rbSchema2005.Checked)
sb.Append(_Schema2005);
break;
case "reportname":
sb.Append(tbReportName.Text.Replace('\'', '_'));
break;
case "reportnameasis":
sb.Append(tbReportName.Text);
break;
case "description":
sb.Append(tbReportDescription.Text);
break;
case "author":
sb.Append(tbReportAuthor.Text);
break;
case "connectionproperties":
if (this.cbConnectionTypes.Text == SHARED_CONNECTION)
{
string file = this.tbConnection.Text;
if (!UseFullSharedDSName)
file = Path.GetFileNameWithoutExtension(file); // when we save report we use qualified name
sb.AppendFormat("<DataSourceReference>{0}</DataSourceReference>", file);
}
else
sb.AppendFormat("<ConnectionProperties><DataProvider>{0}</DataProvider><ConnectString>{1}</ConnectString></ConnectionProperties>",
GetDataProvider(), GetDataConnection());
break;
case "dataprovider":
sb.Append(GetDataProvider());
break;
case "connectstring":
sb.Append(tbConnection.Text);
break;
case "columncount":
sb.Append(_ColumnList.Count);
break;
case "orientation":
if (this.cbOrientation.SelectedIndex == 0)
{ // Portrait is first in the list
sb.Append("<PageHeight>11in</PageHeight><PageWidth>8.5in</PageWidth>");
}
else
{
sb.Append("<PageHeight>8.5in</PageHeight><PageWidth>11in</PageWidth>");
}
break;
case "groupbycolumn":
sb.Append(gbcolumn);
break;
case "reportparameters":
DoReportSyntaxParameters(cinfo, sb);
break;
case "queryparameters":
DoReportSyntaxQParameters(cinfo, sb, tbSQL.Text);
break;
case "sqltext":
sb.Append(tbSQL.Text.Replace("<", "<"));
break;
case "sqlfields":
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
string type = sq.DataType.FullName;
if (this.rbSchemaNo.Checked)
sb.AppendFormat(cinfo, "<Field Name='{0}'><DataField>{1}</DataField><TypeName>{2}</TypeName></Field>", name, sq.Name, type);
else
sb.AppendFormat(cinfo, "<Field Name='{0}'><DataField>{1}</DataField><rd:TypeName>{2}</rd:TypeName></Field>", name, sq.Name, type);
}
break;
case "listheaders":
left = .0m;
foreach (SqlColumn sq in _ColumnList)
{
name = sq.Name;
width = name.Length / 8m;
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"
<Textbox><Top>.3in</Top><Left>{0}in</Left><Width>{1}in</Width><Height>.2in</Height><Value>{2}</Value>
<Style><FontWeight>Bold</FontWeight><BorderStyle><Bottom>Solid</Bottom></BorderStyle>
<BorderWidth><Bottom>3pt</Bottom></BorderWidth></Style>
</Textbox>",
left,
width,
name);
left += width;
}
break;
case "listvalues":
left = .0m;
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
DoAlignAndCanGrow(sq.DataType, out canGrow, out align);
width = name.Length / 8m;
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"
<Textbox Name='{2}'><Top>.1in</Top><Left>{0}in</Left><Width>{1}in</Width><Height>.25in</Height><Value>=Fields!{2}.Value</Value><CanGrow>{3}</CanGrow><Style>{4}</Style></Textbox>",
left, width, name, canGrow, align);
left += width;
}
bodyHeight = .4m;
break;
case "listwidth": // in template list width must follow something that sets left
sb.AppendFormat(cinfo, "{0}in", left);
break;
case "tableheaders":
// the group by column is always the first one in the table
if (gbcolumn != null)
{
bodyHeight += 12m;
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox><Value>{0}</Value><Style><TextAlign>Center</TextAlign><BorderStyle><Default>Solid</Default></BorderStyle><FontWeight>Bold</FontWeight></Style></Textbox></ReportItems>
</TableCell>",
this.cbColumnList.Text);
}
bodyHeight += 12m;
foreach (SqlColumn sq in _ColumnList)
{
name = sq.Name;
if (name == this.cbColumnList.Text)
continue;
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox><Value>{0}</Value><Style><TextAlign>Center</TextAlign><BorderStyle><Default>Solid</Default></BorderStyle><FontWeight>Bold</FontWeight></Style></Textbox></ReportItems>
</TableCell>",
name);
}
break;
case "tablecolumns":
if (gbcolumn != null)
{
bodyHeight += 12m;
width = gbcolumn.Length / 8m; // TODO should really use data value
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"<TableColumn><Width>{0}in</Width></TableColumn>", width);
}
bodyHeight += 12m;
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
if (name == gbcolumn)
continue;
width = name.Length / 8m; // TODO should really use data value
if (width < 1)
width = 1;
sb.AppendFormat(cinfo, @"<TableColumn><Width>{0}in</Width></TableColumn>", width);
}
break;
case "tablevalues":
bodyHeight += 12m;
if (gbcolumn != null)
{
sb.Append(@"<TableCell>
<ReportItems><Textbox><Value></Value><Style><BorderStyle><Default>None</Default><Left>Solid</Left></BorderStyle></Style></Textbox></ReportItems>
</TableCell>");
}
foreach (SqlColumn sq in _ColumnList)
{
name = GetFieldName(sq.Name);
if (name == gbcolumn)
continue;
DoAlignAndCanGrow(sq.DataType, out canGrow, out align);
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox Name='{0}'><Value>=Fields!{0}.Value</Value><CanGrow>{1}</CanGrow><Style><BorderStyle><Default>Solid</Default></BorderStyle>{2}</Style></Textbox></ReportItems>
</TableCell>",
name, canGrow, align);
}
break;
case "gtablefooters":
case "tablefooters":
bodyHeight += 12m;
canGrow = "false";
align = "";
string nameprefix = p == "gtablefooters" ? "gf" : "tf";
if (gbcolumn != null) // handle group by column first
{
int i = clbSubtotal.FindStringExact(this.cbColumnList.Text);
SqlColumn sq = i < 0 ? null : (SqlColumn)clbSubtotal.Items[i];
if (i >= 0 && clbSubtotal.GetItemChecked(i))
{
string funct = DesignerUtility.IsNumeric(sq.DataType) ? "Sum" : "Count";
DoAlignAndCanGrow(((object)0).GetType(), out canGrow, out align);
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox Name='{4}_{0}'><Value>={1}(Fields!{0}.Value)</Value><CanGrow>{2}</CanGrow><Style><BorderStyle><Default>Solid</Default></BorderStyle>{3}</Style></Textbox></ReportItems>
</TableCell>",
gbcolumn, funct, canGrow, align, nameprefix);
}
else
{
sb.AppendFormat(cinfo, "<TableCell><ReportItems><Textbox><Value></Value><Style><BorderStyle><Default>Solid</Default></BorderStyle></Style></Textbox></ReportItems></TableCell>");
}
}
for (int i = 0; i < this.clbSubtotal.Items.Count; i++)
{
SqlColumn sq = (SqlColumn)clbSubtotal.Items[i];
name = GetFieldName(sq.Name);
if (name == gbcolumn)
continue;
if (clbSubtotal.GetItemChecked(i))
{
string funct = DesignerUtility.IsNumeric(sq.DataType) ? "Sum" : "Count";
DoAlignAndCanGrow(((object)0).GetType(), out canGrow, out align);
sb.AppendFormat(cinfo, @"
<TableCell>
<ReportItems><Textbox Name='{4}_{0}'><Value>={1}(Fields!{0}.Value)</Value><CanGrow>{2}</CanGrow><Style><BorderStyle><Default>Solid</Default></BorderStyle>{3}</Style></Textbox></ReportItems>
</TableCell>",
name, funct, canGrow, align, nameprefix);
}
else
{
sb.AppendFormat(cinfo, "<TableCell><ReportItems><Textbox><Value></Value><Style><BorderStyle><Default>Solid</Default></BorderStyle></Style></Textbox></ReportItems></TableCell>");
}
}
break;
case "bodyheight": // Note: this must follow the table definition
sb.AppendFormat(cinfo, "{0}pt", bodyHeight);
break;
default:
sb.Append(p);
break;
}
}
try
{
tbReportSyntax.Text = DesignerUtility.FormatXml(sb.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_Show_InternalError);
tbReportSyntax.Text = sb.ToString();
}
return true;
}
private string GetFieldName(string sqlName)
{
StringBuilder sb = new StringBuilder();
foreach (char c in sqlName)
{
if (Char.IsLetterOrDigit(c) || c == '_')
sb.Append(c);
else
sb.Append('_');
}
return sb.ToString();
}
private void DoAlignAndCanGrow(Type t, out string canGrow, out string align)
{
string st = t.ToString();
switch (st)
{
case "System.String":
canGrow = "true";
align = "<PaddingLeft>2pt</PaddingLeft>";
break;
case "System.Int16":
case "System.Int32":
case "System.Single":
case "System.Double":
case "System.Decimal":
canGrow = "false";
align = "<PaddingRight>2pt</PaddingRight><TextAlign>Right</TextAlign>";
break;
default:
canGrow = "false";
align = "<PaddingLeft>2pt</PaddingLeft>";
break;
}
return;
}
private void DoReportSyntaxParameters(CultureInfo cinfo, StringBuilder sb)
{
if (reportParameterCtl1.lbParameters.Items.Count <= 0)
return;
sb.Append("<ReportParameters>");
foreach (ReportParm rp in reportParameterCtl1.lbParameters.Items)
{
sb.AppendFormat(cinfo, "<ReportParameter Name=\"{0}\">", rp.Name);
sb.AppendFormat(cinfo, "<DataType>{0}</DataType>", rp.DataType);
sb.AppendFormat(cinfo, "<Nullable>{0}</Nullable>", rp.AllowNull.ToString());
if (rp.DefaultValue != null && rp.DefaultValue.Count > 0)
{
sb.AppendFormat(cinfo, "<DefaultValue><Values>");
foreach (string dv in rp.DefaultValue)
{
sb.AppendFormat(cinfo, "<Value>{0}</Value>", XmlUtil.XmlAnsi(dv));
}
sb.AppendFormat(cinfo, "</Values></DefaultValue>");
}
sb.AppendFormat(cinfo, "<AllowBlank>{0}</AllowBlank>", rp.AllowBlank);
if (rp.Prompt != null && rp.Prompt.Length > 0)
sb.AppendFormat(cinfo, "<Prompt>{0}</Prompt>", rp.Prompt);
if (rp.ValidValues != null && rp.ValidValues.Count > 0)
{
sb.Append("<ValidValues><ParameterValues>");
foreach (ParameterValueItem pvi in rp.ValidValues)
{
sb.Append("<ParameterValue>");
sb.AppendFormat(cinfo, "<Value>{0}</Value>", XmlUtil.XmlAnsi(pvi.Value));
if (pvi.Label != null)
sb.AppendFormat(cinfo, "<Label>{0}</Label>", XmlUtil.XmlAnsi(pvi.Label));
sb.Append("</ParameterValue>");
}
sb.Append("</ParameterValues></ValidValues>");
}
sb.Append("</ReportParameter>");
}
sb.Append("</ReportParameters>");
}
private void DoReportSyntaxQParameters(CultureInfo cinfo, StringBuilder sb, string sql)
{
if (reportParameterCtl1.lbParameters.Items.Count <= 0)
return;
bool bFirst = true;
foreach (ReportParm rp in reportParameterCtl1.lbParameters.Items)
{
// force the name to start with @
string paramName;
if (rp.Name[0] == '@')
paramName = rp.Name;
else
paramName = "@" + rp.Name;
// Only create a query parameter if parameter is used in the query
if (sql.IndexOf(paramName) >= 0)
{
if (bFirst)
{ // Only put out queryparameters if we actually have one
sb.Append("<QueryParameters>");
bFirst = false;
}
sb.AppendFormat(cinfo, "<QueryParameter Name=\"{0}\">", rp.Name);
sb.AppendFormat(cinfo, "<Value>=Parameters!{0}</Value>", rp.Name);
sb.Append("</QueryParameter>");
}
}
if (!bFirst)
sb.Append("</QueryParameters>");
}
private bool DoReportPreview()
{
if (!DoReportSyntax(true))
return false;
if (_rDesigner != null)
{
rdlViewer1.GetDataSourceReferencePassword = _rDesigner.SharedDatasetPassword;
}
else if (_rUserControl != null)
{
rdlViewer1.GetDataSourceReferencePassword = _rUserControl.SharedDatasetPassword;
}
rdlViewer1.SourceRdl = tbReportSyntax.Text;
return true;
}
private string GetDataProvider()
{
string cType = cbConnectionTypes.Text;
_StashConnection = null;
if (cType == SHARED_CONNECTION)
{
if (_rDesigner != null)
{
if (!DesignerUtility.GetSharedConnectionInfo(_rDesigner, tbConnection.Text, out cType, out _StashConnection))
return null;
}
else if(_rUserControl != null)
{
if (!DesignerUtility.GetSharedConnectionInfo(_rUserControl, tbConnection.Text, out cType, out _StashConnection))
return null;
}
}
else
{
_StashConnection = tbConnection.Text;
}
return cType;
}
private string GetDataConnection()
{ // GetDataProvider must be called first to ensure the DataConnection is correct.
return _StashConnection;
}
private void tvTablesColumns_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
{
tvTablesColumns_ExpandTable(e.Node);
}
private void tvTablesColumns_ExpandTable(TreeNode tNode)
{
if (tNode.Parent == null) // Check for Tables or Views
return;
if (tNode.FirstNode.Text != "") // Have we already filled it out?
return;
// Need to obtain the column information for the requested table/view
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
string sql = "SELECT * FROM " + DesignerUtility.NormalizeSqlName(tNode.Text);
List<SqlColumn> tColumns = DesignerUtility.GetSqlColumns(GetDataProvider(), GetDataConnection(), sql, null);
bool bFirstTime = true;
foreach (SqlColumn sc in tColumns)
{
if (bFirstTime)
{
bFirstTime = false;
tNode.FirstNode.Text = sc.Name;
}
else
tNode.Nodes.Add(sc.Name);
}
tvTablesColumns.EndUpdate();
}
private void tbSQL_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text)) // only accept text
e.Effect = DragDropEffects.Copy;
}
private void tbSQL_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
tbSQL.SelectedText = (string)e.Data.GetData(DataFormats.Text);
}
private void tvTablesColumns_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
TreeNode node = tvTablesColumns.GetNodeAt(e.X, e.Y);
if (node == null || node.Parent == null)
return;
string dragText;
if (tbSQL.Text == "")
{
if (node.Parent.Parent == null)
{ // select table; generate full select for table
tvTablesColumns_ExpandTable(node); // make sure we've obtained the columns
dragText = "SELECT ";
TreeNode next = node.FirstNode;
while (true)
{
dragText += DesignerUtility.NormalizeSqlName(next.Text);
next = next.NextNode;
if (next == null)
break;
dragText += ", ";
}
dragText += (" FROM " + DesignerUtility.NormalizeSqlName(node.Text));
}
else
{ // select column; generate select of that column
dragText = "SELECT " + DesignerUtility.NormalizeSqlName(node.Text) + " FROM " + DesignerUtility.NormalizeSqlName(node.Parent.Text);
}
}
else
dragText = node.Text;
tvTablesColumns.DoDragDrop(dragText, DragDropEffects.Copy);
}
private void DialogDatabase_Closed(object sender, System.EventArgs e)
{
if (_TempFileName != null)
File.Delete(_TempFileName);
}
private void tbSQL_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
_ColumnList = null; // get rid of any column list as well
cbColumnList.Items.Clear(); // and clear out other places where columns show
cbColumnList.Text = "";
clbSubtotal.Items.Clear();
}
private void tbReportName_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void tbReportDescription_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void tbReportAuthor_TextChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void rbTable_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
if (rbTable.Checked)
{
TabularGroup.Enabled = true;
}
else
{
TabularGroup.Enabled = false;
}
}
private void rbList_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void rbMatrix_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
private void rbChart_CheckedChanged(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
}
//private void bAdd_Click(object sender, System.EventArgs e)
//{
// ReportParm rp = new ReportParm("newparm");
// int cur = reportParameterCtl1.lbParameters.Items.Add(rp);
// reportParameterCtl1.lbParameters.SelectedIndex = cur;
// this.tbParmName.Focus();
//}
//private void bRemove_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// lbParameters.Items.RemoveAt(cur);
// if (lbParameters.Items.Count <= 0)
// return;
// cur--;
// if (cur < 0)
// cur = 0;
// lbParameters.SelectedIndex = cur;
//}
//private void lbParameters_SelectedIndexChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// tbParmName.Text = rp.Name;
// cbParmType.Text = rp.DataType;
// tbParmPrompt.Text = rp.Prompt;
// tbParmDefaultValue.Text = rp.DefaultValueDisplay;
// ckbParmAllowBlank.Checked = rp.AllowBlank;
// tbParmValidValues.Text = rp.ValidValuesDisplay;
// ckbParmAllowNull.Checked = rp.AllowNull;
//}
//private void lbParameters_MoveItem(int curloc, int newloc)
//{
// ReportParm rp = lbParameters.Items[curloc] as ReportParm;
// if (rp == null)
// return;
// lbParameters.BeginUpdate();
// lbParameters.Items.RemoveAt(curloc);
// lbParameters.Items.Insert(newloc, rp);
// lbParameters.SelectedIndex = newloc;
// lbParameters.EndUpdate();
//}
//private void tbParmName_TextChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// if (rp.Name == tbParmName.Text)
// return;
// rp.Name = tbParmName.Text;
// // text doesn't change in listbox; force change by removing and re-adding item
// lbParameters_MoveItem(cur, cur);
//}
//private void cbParmType_SelectedIndexChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.DataType = cbParmType.Text;
//}
//private void tbParmPrompt_TextChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.Prompt = tbParmPrompt.Text;
//}
//private void ckbParmAllowNull_CheckedChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.AllowNull = ckbParmAllowNull.Checked;
//}
//private void ckbParmAllowBlank_CheckedChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// rp.AllowBlank = ckbParmAllowBlank.Checked;
//}
//private void bParmUp_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur <= 0)
// return;
// lbParameters_MoveItem(cur, cur - 1);
//}
//private void bParmDown_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur + 1 >= lbParameters.Items.Count)
// return;
// lbParameters_MoveItem(cur, cur + 1);
//}
//private void tbParmDefaultValue_TextChanged(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// if (tbParmDefaultValue.Text.Length > 0)
// {
// if (rp.DefaultValue == null)
// rp.DefaultValue = new List<string>();
// else
// rp.DefaultValue.Clear();
// rp.DefaultValue.Add(tbParmDefaultValue.Text);
// }
// else
// rp.DefaultValue = null;
//}
private void tbConnection_TextChanged(object sender, System.EventArgs e)
{
tvTablesColumns.Nodes.Clear();
}
private void emptyReportSyntax(object sender, System.EventArgs e)
{
tbReportSyntax.Text = ""; // need to generate another report
}
private void bMove_Click(object sender, System.EventArgs e)
{
if (tvTablesColumns.SelectedNode == null ||
tvTablesColumns.SelectedNode.Parent == null)
return; // this is the Tables/Views node
TreeNode node = tvTablesColumns.SelectedNode;
string t = node.Text;
if (tbSQL.Text == "")
{
if (node.Parent.Parent == null)
{ // select table; generate full select for table
tvTablesColumns_ExpandTable(node); // make sure we've obtained the columns
StringBuilder sb = new StringBuilder("SELECT ");
TreeNode next = node.FirstNode;
while (true)
{
sb.Append(DesignerUtility.NormalizeSqlName(next.Text));
next = next.NextNode;
if (next == null)
break;
sb.Append(", ");
}
sb.Append(" FROM ");
sb.Append(DesignerUtility.NormalizeSqlName(node.Text));
t = sb.ToString();
}
else
{ // select column; generate select of that column
t = "SELECT " + DesignerUtility.NormalizeSqlName(node.Text) + " FROM " + DesignerUtility.NormalizeSqlName(node.Parent.Text);
}
}
tbSQL.SelectedText = t;
}
//private void bValidValues_Click(object sender, System.EventArgs e)
//{
// int cur = lbParameters.SelectedIndex;
// if (cur < 0)
// return;
// ReportParm rp = lbParameters.Items[cur] as ReportParm;
// if (rp == null)
// return;
// DialogValidValues dvv = new DialogValidValues(rp.ValidValues);
// try
// {
// if (dvv.ShowDialog() != DialogResult.OK)
// return;
// rp.ValidValues = dvv.ValidValues;
// this.tbParmValidValues.Text = rp.ValidValuesDisplay;
// }
// finally
// {
// dvv.Dispose();
// }
//}
private void cbConnectionTypes_SelectedIndexChanged(object sender, System.EventArgs e)
{
groupBoxSqlServer.Visible = false;
buttonSqliteSelectDatabase.Visible = false;
if (cbConnectionTypes.Text == SHARED_CONNECTION)
{
lConnection.Text = Strings.DialogDatabase_cbConnectionTypes_SelectedIndexChanged_Shared_Data_Source_File;
bShared.Visible = true;
}
else
{
lConnection.Text = Strings.DialogDatabase_cbConnectionTypes_SelectedIndexChanged_Connection;
bShared.Visible = false;
}
if (cbConnectionTypes.Text == "ODBC")
{
lODBC.Visible = cbOdbcNames.Visible = true;
DesignerUtility.FillOdbcNames(cbOdbcNames);
}
else
{
lODBC.Visible = cbOdbcNames.Visible = false;
}
// this is only for ease of testing
switch (cbConnectionTypes.Text)
{
case "SQL":
tbConnection.Text = "Server=(local)\\ServerInstance;DataBase=DatabaseName;User Id=myUsername;Password=myPassword;Connect Timeout=5";
groupBoxSqlServer.Visible = true;
break;
case "ODBC":
tbConnection.Text = "dsn=world;UID=user;PWD=password;";
break;
case "Oracle":
tbConnection.Text = "User Id=SYSTEM;Password=password;Data Source=server";
break;
case "Firebird.NET":
tbConnection.Text = @"Dialect=3;User Id=SYSDBA;Database=daabaseFile.fdb;Data Source=localhost;Password=password";
break;
case "MySQL.NET":
tbConnection.Text = "database=world;user id=user;password=password;";
break;
case "iAnywhere.NET":
tbConnection.Text = "Data Source=ASA 9.0 Sample;UID=DBA;PWD=password";
break;
case "SQLite":
tbConnection.Text = "Data Source=filename;Version=3;Password=myPassword;Pooling=True;Max Pool Size=100;";
buttonSqliteSelectDatabase.Visible = true;
break;
case "PostgreSQL":
case "PostgreSQL_Devart":
tbConnection.Text = "Server=127.0.0.1;Port=5432;Database=myDataBase;User Id=myUsername;Password=myPassword;";
break;
default:
tbConnection.Text = "";
break;
}
}
private void cbOdbcNames_SelectedIndexChanged(object sender, System.EventArgs e)
{
string name = "dsn=" + cbOdbcNames.Text + ";";
this.tbConnection.Text = name;
}
private void bTestConnection_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrEmpty(tbConnection.Text))
{
MessageBox.Show(Strings.DialogDatabase_ShowD_SelectDataProvider, Strings.DesignerUtility_Show_TestConnection, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string cType = GetDataProvider();
if (cType == null)
return;
if (DesignerUtility.TestConnection(cType, GetDataConnection()))
MessageBox.Show(Strings.DialogDatabase_Show_ConnectionSuccessful, Strings.DesignerUtility_Show_TestConnection);
}
private void DBConnection_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!DesignerUtility.TestConnection(this.GetDataConnection(), GetDataConnection()))
e.Cancel = true;
}
private void bShared_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = Strings.DialogDatabase_bShared_Click_DSRFilter;
ofd.FilterIndex = 1;
if (tbConnection.Text.Length > 0)
ofd.FileName = tbConnection.Text;
else
ofd.FileName = "*.dsr";
ofd.Title = Strings.DialogDatabase_bShared_Click_DSRTitle;
ofd.CheckFileExists = true;
ofd.DefaultExt = "dsr";
ofd.AddExtension = true;
try
{
if (ofd.ShowDialog() == DialogResult.OK)
tbConnection.Text = ofd.FileName;
}
finally
{
ofd.Dispose();
}
}
private void buttonSqliteSelectDatabase_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
try
{
ofd.Filter = Strings.DialogDatabase_buttonSqliteSelectDatabase_Click_AllFilesFilter;
ofd.CheckFileExists = true;
try
{
if (ofd.ShowDialog(this) != DialogResult.OK)
{
return;
}
if (tbConnection.Text.Trim() == "")
{
tbConnection.Text = "Data Source=" + ofd.FileName;
}
else
{
string[] sections = tbConnection.Text.Split(';');
foreach (string section in sections)
{
if (section.ToLower().Contains("data source"))
{
string dataSource = string.Format("Data Source={0}", ofd.FileName);
tbConnection.Text = tbConnection.Text.Replace(section, dataSource);
break;
}
}
}
}
finally
{
ofd.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSearchSqlServers_Click(object sender, EventArgs e)
{
try
{
System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
DataTable dt;
dt = instance.GetDataSources();
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (System.Data.DataRow row in dt.Rows)
{
string server = row["ServerName"].ToString();
if (row["InstanceName"].ToString() != "")
{
server = server + @"\" + row["InstanceName"].ToString();
}
dict.Add(server, server);
}
comboServerList.ValueMember = "Value";
comboServerList.DisplayMember = "Key";
comboServerList.DataSource = new BindingSource(dict, null);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonDatabaseSearch_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter da;
DataTable dt = new DataTable();
string connectionString = string.Format("server={0}; Database={1};User ID={2}; Password={3}; Trusted_Connection=False;",
comboServerList.SelectedValue.ToString(), "master", textBoxSqlUser.Text, textBoxSqlPassword.Text);
SqlConnection cn = new System.Data.SqlClient.SqlConnection(connectionString); ;
try
{
cn.Open();
cmd.Connection = cn;
cmd.CommandText = "sp_databases";
cmd.CommandType = CommandType.StoredProcedure;
da = new System.Data.SqlClient.SqlDataAdapter(cmd);
da.Fill(dt);
dt.TableName = "master";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
cn.Close();
}
try
{
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (System.Data.DataRow row in dt.Rows)
{
string database = row["DATABASE_NAME"].ToString();
dict.Add(database, database);
}
comboDatabaseList.ValueMember = "Value";
comboDatabaseList.DisplayMember = "Key";
comboDatabaseList.DataSource = new BindingSource(dict, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogDatabase_ShowD_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void tbSQL_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
tbSQL.SelectAll();
}
}
private void DialogDatabase_Load(object sender, EventArgs e)
{
}
private void comboServerList_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboServerList.Items.Count == 0)
{
return;
}
string[] sections = tbConnection.Text.Split(';');
foreach (string section in sections)
{
if (section.ToLower().Contains("server="))
{
string dataSource = string.Format("server={0}", comboServerList.SelectedValue.ToString());
tbConnection.Text = tbConnection.Text.Replace(section, dataSource);
break;
}
}
}
private void comboDatabaseList_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboDatabaseList.Items.Count == 0)
{
return;
}
string[] sections = tbConnection.Text.Split(';');
foreach (string section in sections)
{
if (section.ToLower().Contains("database="))
{
string dataSource = string.Format("database={0}", comboDatabaseList.SelectedValue.ToString());
tbConnection.Text = tbConnection.Text.Replace(section, dataSource);
break;
}
}
}
private void rbEmpty_CheckedChanged(object sender, EventArgs e)
{
tbReportSyntax.Text = ""; // when SQL changes get rid of report syntax
TabularGroup.Enabled = !rbEmpty.Checked;
DBConnection.Enabled = !rbEmpty.Checked;
DBSql.Enabled= !rbEmpty.Checked;
}
}
}
| |
using NetApp.Tests.Helpers;
using Microsoft.Azure.Management.NetApp;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Xunit;
using System;
using Microsoft.Azure.Management.NetApp.Models;
using System.Collections.Generic;
namespace NetApp.Tests.ResourceTests
{
public class PoolTests : TestBase
{
[Fact]
public void CreateDeletePool()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account
var resource = ResourceUtils.CreateAccount(netAppMgmtClient);
Assert.Null(resource.Tags);
// create the pool, get all pools and check
ResourceUtils.CreatePool(netAppMgmtClient, ResourceUtils.poolName1, ResourceUtils.accountName1, poolOnly: true);
var poolsBefore = netAppMgmtClient.Pools.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Single(poolsBefore);
// delete the pool and check again
netAppMgmtClient.Pools.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
var poolsAfter = netAppMgmtClient.Pools.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Empty(poolsAfter);
// cleanup - remove the account
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void ListPools()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create two pools under same account
// throw in a quick check on tags on the first
var dict = new Dictionary<string, string>();
dict.Add("Tag2", "Value2");
var resource = ResourceUtils.CreatePool(netAppMgmtClient, tags: dict);
Assert.True(resource.Tags.ContainsKey("Tag2"));
Assert.Equal("Value2", resource.Tags["Tag2"]);
ResourceUtils.CreatePool(netAppMgmtClient, ResourceUtils.poolName2, poolOnly: true);
// get the account list and check
var pools = netAppMgmtClient.Pools.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Equal(pools.ElementAt(0).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1);
Assert.Equal(pools.ElementAt(1).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName2);
Assert.Equal(2, pools.Count());
// clean up - delete the two pools and the account
ResourceUtils.DeletePool(netAppMgmtClient, ResourceUtils.poolName2);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetPoolByName()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account and pool
ResourceUtils.CreatePool(netAppMgmtClient);
// get and check the pool
var pool = netAppMgmtClient.Pools.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.Equal(pool.Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1);
// clean up - delete the pool and account
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetPoolByNameNotFound()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create an account
ResourceUtils.CreateAccount(netAppMgmtClient);
// try and get the non-existent pool
try
{
var pool = netAppMgmtClient.Pools.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
Assert.Contains("was not found", ex.Message);
}
// cleanup - remove the account
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetPoolByNameAccountNotFound()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create an account and pool
ResourceUtils.CreatePool(netAppMgmtClient);
// get and check the pool in a non-existent account
try
{
var pool = netAppMgmtClient.Pools.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName2, ResourceUtils.poolName1);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
Assert.Contains("was not found", ex.Message);
}
// cleanup - remove pool and account
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void DeleteAccountWithPoolPresent()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account and pool
ResourceUtils.CreatePool(netAppMgmtClient);
var poolsBefore = netAppMgmtClient.Pools.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Single(poolsBefore);
// try and delete the account
try
{
netAppMgmtClient.Accounts.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
// Conflict
Assert.Equal("Can not delete resource before nested resources are deleted.", ex.Message);
}
// clean up
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void UpdatePool()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the pool
var pool = ResourceUtils.CreatePool(netAppMgmtClient);
Assert.Equal("Premium", pool.ServiceLevel);
Assert.Null(pool.Tags);
// update. Add tags and change service level
// size is already present in the object
// and must also be provided otherwise Bad Request
var dict = new Dictionary<string, string>();
dict.Add("Tag3", "Value3");
pool.Tags = dict;
var updatedPool = netAppMgmtClient.Pools.CreateOrUpdate(pool, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.True(updatedPool.Tags.ContainsKey("Tag3"));
Assert.Equal("Value3", updatedPool.Tags["Tag3"]);
// cleanup
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void PatchPool()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the pool
var pool = ResourceUtils.CreatePool(netAppMgmtClient);
Assert.Equal("Premium", pool.ServiceLevel);
Assert.Null(pool.Tags);
var dict = new Dictionary<string, string>();
dict.Add("Tag1", "Value1");
// Now try and modify it
// set only two of the three possibles
// size should remain unchanged
var poolPatch = new CapacityPoolPatch()
{
Tags = dict,
};
var resource = netAppMgmtClient.Pools.Update(poolPatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.True(resource.Tags.ContainsKey("Tag1"));
Assert.Equal("Value1", resource.Tags["Tag1"]);
// cleanup
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
private static string GetSessionsDirectoryPath()
{
string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.PoolTests).GetTypeInfo().Assembly.Location;
return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel.Design;
namespace System.ComponentModel
{
/// <summary>
/// Provides properties and methods to add a license
/// to a component and to manage a <see cref='System.ComponentModel.LicenseProvider'/>. This class cannot be inherited.
/// </summary>
public sealed class LicenseManager
{
private static readonly object s_selfLock = new object();
private static volatile LicenseContext s_context;
private static object s_contextLockHolder;
private static volatile Hashtable s_providers;
private static volatile Hashtable s_providerInstances;
private static readonly object s_internalSyncObject = new object();
// not creatable...
private LicenseManager()
{
}
/// <summary>
/// Gets or sets the current <see cref='System.ComponentModel.LicenseContext'/> which specifies when the licensed object can be
/// used.
/// </summary>
public static LicenseContext CurrentContext
{
get
{
if (s_context == null)
{
lock (s_internalSyncObject)
{
if (s_context == null)
{
s_context = new RuntimeLicenseContext();
}
}
}
return s_context;
}
set
{
lock (s_internalSyncObject)
{
if (s_contextLockHolder != null)
{
throw new InvalidOperationException(SR.LicMgrContextCannotBeChanged);
}
s_context = value;
}
}
}
/// <summary>
/// Gets the <see cref='System.ComponentModel.LicenseUsageMode'/> that
/// specifies when the licensed object can be used, for the <see cref='System.ComponentModel.LicenseManager.CurrentContext'/>.
/// </summary>
public static LicenseUsageMode UsageMode
{
get
{
if (s_context != null)
{
return s_context.UsageMode;
}
return LicenseUsageMode.Runtime;
}
}
/// <summary>
/// Caches the provider, both in the instance cache, and the type
/// cache.
/// </summary>
private static void CacheProvider(Type type, LicenseProvider provider)
{
if (s_providers == null)
{
s_providers = new Hashtable();
}
s_providers[type] = provider;
if (provider != null)
{
if (s_providerInstances == null)
{
s_providerInstances = new Hashtable();
}
s_providerInstances[provider.GetType()] = provider;
}
}
/// <summary>
/// Creates an instance of the specified type, using
/// creationContext
/// as the context in which the licensed instance can be used.
/// </summary>
public static object CreateWithContext(Type type, LicenseContext creationContext)
{
return CreateWithContext(type, creationContext, Array.Empty<object>());
}
/// <summary>
/// Creates an instance of the specified type with the
/// specified arguments, using creationContext as the context in which the licensed
/// instance can be used.
/// </summary>
public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args)
{
object created = null;
lock (s_internalSyncObject)
{
LicenseContext normal = CurrentContext;
try
{
CurrentContext = creationContext;
LockContext(s_selfLock);
try
{
created = Activator.CreateInstance(type, args);
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
finally
{
UnlockContext(s_selfLock);
CurrentContext = normal;
}
}
return created;
}
/// <summary>
/// Determines if type was actually cached to have _no_ provider,
/// as opposed to not being cached.
/// </summary>
private static bool GetCachedNoLicenseProvider(Type type)
{
if (s_providers != null)
{
return s_providers.ContainsKey(type);
}
return false;
}
/// <summary>
/// Retrieves a cached instance of the provider associated with the
/// specified type.
/// </summary>
private static LicenseProvider GetCachedProvider(Type type)
{
return (LicenseProvider)s_providers?[type];
}
/// <summary>
/// Retrieves a cached instance of the provider of the specified
/// type.
/// </summary>
private static LicenseProvider GetCachedProviderInstance(Type providerType)
{
Debug.Assert(providerType != null, "Type cannot ever be null");
return (LicenseProvider) s_providerInstances?[providerType];
}
/// <summary>
/// Determines if the given type has a valid license or not.
/// </summary>
public static bool IsLicensed(Type type)
{
Debug.Assert(type != null, "IsValid Type cannot ever be null");
bool value = ValidateInternal(type, null, false, out License license);
if (license != null)
{
license.Dispose();
license = null;
}
return value;
}
/// <summary>
/// Determines if a valid license can be granted for the specified type.
/// </summary>
public static bool IsValid(Type type)
{
Debug.Assert(type != null, "IsValid Type cannot ever be null");
bool value = ValidateInternal(type, null, false, out License license);
if (license != null)
{
license.Dispose();
license = null;
}
return value;
}
/// <summary>
/// Determines if a valid license can be granted for the
/// specified instance of the type. This method creates a valid <see cref='System.ComponentModel.License'/>.
/// </summary>
public static bool IsValid(Type type, object instance, out License license)
{
return ValidateInternal(type, instance, false, out license);
}
public static void LockContext(object contextUser)
{
lock (s_internalSyncObject)
{
if (s_contextLockHolder != null)
{
throw new InvalidOperationException(SR.LicMgrAlreadyLocked);
}
s_contextLockHolder = contextUser;
}
}
public static void UnlockContext(object contextUser)
{
lock (s_internalSyncObject)
{
if (s_contextLockHolder != contextUser)
{
throw new ArgumentException(SR.LicMgrDifferentUser);
}
s_contextLockHolder = null;
}
}
/// <summary>
/// Internal validation helper.
/// </summary>
private static bool ValidateInternal(Type type, object instance, bool allowExceptions, out License license)
{
return ValidateInternalRecursive(CurrentContext,
type,
instance,
allowExceptions,
out license,
out string licenseKey);
}
/// <summary>
/// Since we want to walk up the entire inheritance change, when not
/// give an instance, we need another helper method to walk up
/// the chain...
/// </summary>
private static bool ValidateInternalRecursive(LicenseContext context, Type type, object instance, bool allowExceptions, out License license, out string licenseKey)
{
LicenseProvider provider = GetCachedProvider(type);
if (provider == null && !GetCachedNoLicenseProvider(type))
{
// NOTE : Must look directly at the class, we want no inheritance.
LicenseProviderAttribute attr = (LicenseProviderAttribute)Attribute.GetCustomAttribute(type, typeof(LicenseProviderAttribute), false);
if (attr != null)
{
Type providerType = attr.LicenseProvider;
provider = GetCachedProviderInstance(providerType) ?? (LicenseProvider)Activator.CreateInstance(providerType);
}
CacheProvider(type, provider);
}
license = null;
bool isValid = true;
licenseKey = null;
if (provider != null)
{
license = provider.GetLicense(context, type, instance, allowExceptions);
if (license == null)
{
isValid = false;
}
else
{
// For the case where a COM client is calling "RequestLicKey",
// we try to squirrel away the first found license key
licenseKey = license.LicenseKey;
}
}
// When looking only at a type, we need to recurse up the inheritence
// chain, however, we can't give out the license, since this may be
// from more than one provider.
if (isValid && instance == null)
{
Type baseType = type.BaseType;
if (baseType != typeof(object) && baseType != null)
{
if (license != null)
{
license.Dispose();
license = null;
}
string temp;
isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out temp);
if (license != null)
{
license.Dispose();
license = null;
}
}
}
return isValid;
}
/// <summary>
/// Determines if a license can be granted for the specified type.
/// </summary>
public static void Validate(Type type)
{
if (!ValidateInternal(type, null, true, out License lic))
{
throw new LicenseException(type);
}
if (lic != null)
{
lic.Dispose();
lic = null;
}
}
/// <summary>
/// Determines if a license can be granted for the instance of the specified type.
/// </summary>
public static License Validate(Type type, object instance)
{
if (!ValidateInternal(type, instance, true, out License lic))
{
throw new LicenseException(type, instance);
}
return lic;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using Topshelf.Logging;
using Topshelf.ServiceConfigurators;
namespace Topshelf.FileSystemWatcher
{
public static class ServiceConfiguratorExtensions
{
private static readonly ICollection<System.IO.FileSystemWatcher> _watchers =
new Collection<System.IO.FileSystemWatcher>();
public static ServiceConfigurator<T> WhenFileSystemRenamed<T>(this ServiceConfigurator<T> configurator,
Action<FileSystemWatcherConfigurator> fileSystemWatcherConfigurator,
Action<TopshelfFileSystemEventArgs> fileSystemRenamed)
where T : class
{
return WhenFileSystemChanged(configurator, fileSystemWatcherConfigurator, null, null, fileSystemRenamed, null, fileSystemRenamed);
}
public static ServiceConfigurator<T> WhenFileSystemChanged<T>(this ServiceConfigurator<T> configurator,
Action<FileSystemWatcherConfigurator> fileSystemWatcherConfigurator,
Action<TopshelfFileSystemEventArgs> fileSystemChanged)
where T : class
{
return WhenFileSystemChanged(configurator, fileSystemWatcherConfigurator, fileSystemChanged, null, null, null, fileSystemChanged);
}
public static ServiceConfigurator<T> WhenFileSystemCreated<T>(this ServiceConfigurator<T> configurator,
Action<FileSystemWatcherConfigurator> fileSystemWatcherConfigurator,
Action<TopshelfFileSystemEventArgs> fileSystemCreated)
where T : class
{
return WhenFileSystemChanged(configurator, fileSystemWatcherConfigurator, null, fileSystemCreated, null, null, fileSystemCreated);
}
public static ServiceConfigurator<T> WhenFileSystemDeleted<T>(this ServiceConfigurator<T> configurator,
Action<FileSystemWatcherConfigurator> fileSystemWatcherConfigurator,
Action<TopshelfFileSystemEventArgs> fileSystemDeleted)
where T : class
{
return WhenFileSystemChanged(configurator, fileSystemWatcherConfigurator, null, null, null, fileSystemDeleted, fileSystemDeleted);
}
public static ServiceConfigurator<T> WhenFileSystemChanged<T>(this ServiceConfigurator<T> configurator,
Action<FileSystemWatcherConfigurator> fileSystemWatcherConfigurator,
Action<TopshelfFileSystemEventArgs> fileSystemChanged,
Action<TopshelfFileSystemEventArgs> fileSystemCreated,
Action<TopshelfFileSystemEventArgs> fileSystemRenamed,
Action<TopshelfFileSystemEventArgs> fileSystemDeleted,
Action<TopshelfFileSystemEventArgs> fileSystemInitialState)
where T : class
{
var log = HostLogger.Get(typeof(ServiceConfiguratorExtensions));
var fileSystemWatcherConfig = new FileSystemWatcherConfigurator();
fileSystemWatcherConfigurator(fileSystemWatcherConfig);
var configs = new Collection<FileSystemWatcherConfigurator.DirectoryConfiguration>();
foreach (Action<FileSystemWatcherConfigurator.DirectoryConfiguration> action in
fileSystemWatcherConfig.DirectoryConfigurationAction)
{
var config = new FileSystemWatcherConfigurator.DirectoryConfiguration();
action(config);
configs.Add(config);
}
FileSystemEventHandler watcherOnChanged = CreateEventHandler(fileSystemChanged);
FileSystemEventHandler watcherOnCreated = CreateEventHandler(fileSystemCreated);
RenamedEventHandler watcherOnRenamed = CreateRenamedEventHandler(fileSystemRenamed);
FileSystemEventHandler watcherOnDeleted = CreateEventHandler(fileSystemDeleted);
if (configs.Any())
{
BeforeStartingService(configurator, configs, log, watcherOnChanged, watcherOnCreated, watcherOnRenamed, watcherOnDeleted);
AfterStartingService(configurator, configs, log, fileSystemInitialState);
BeforeStoppingService(configurator, log, watcherOnChanged);
}
return configurator;
}
private static FileSystemEventHandler CreateEventHandler(Action<TopshelfFileSystemEventArgs> fileSystemAction)
{
FileSystemEventHandler eventHandler = null;
if (fileSystemAction != null)
{
eventHandler =
(sender, args) => fileSystemAction(FileSystemEventFactory.CreateNormalFileSystemEvent(args));
}
return eventHandler;
}
private static RenamedEventHandler CreateRenamedEventHandler(Action<TopshelfFileSystemEventArgs> fileSystemAction)
{
RenamedEventHandler eventHandler = null;
if (fileSystemAction != null)
{
eventHandler =
(sender, args) => fileSystemAction(FileSystemEventFactory.CreateRenamedFileSystemEvent(args));
}
return eventHandler;
}
private static void BeforeStartingService<T>(ServiceConfigurator<T> configurator,
IEnumerable<FileSystemWatcherConfigurator.DirectoryConfiguration> configs, LogWriter log,
FileSystemEventHandler watcherOnChanged,
FileSystemEventHandler watcherOnCreated,
RenamedEventHandler watcherOnRenamed,
FileSystemEventHandler watcherOnDeleted) where T : class
{
configurator.BeforeStartingService(() =>
{
foreach (FileSystemWatcherConfigurator.DirectoryConfiguration config in configs)
{
if (!Directory.Exists(config.Path))
{
if (config.CreateDir)
{
log.Debug($"[Topshelf.FileSystemWatcher] Path ({config.Path}) does not exist. Creating...");
Directory.CreateDirectory(config.Path);
}
else
{
throw new DirectoryNotFoundException($"{config.Path} does not exist. Please call CreateDir in the FileSystemWatcherConfigurator, or make sure the dirs exist in the FileSystem");
}
}
var fileSystemWatcher = CreateFileSystemWatcher(config.Path, config.NotifyFilters, config.FileFilter, config.IncludeSubDirectories, config.InternalBufferSize);
if (config.ExcludeDuplicateEvents)
{
if (watcherOnChanged != null)
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
h => fileSystemWatcher.Changed += h,
h => fileSystemWatcher.Changed -= h).
Window(config.ExcludeDuplicateEventsWindowTime).
SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
Subscribe(pattern => { lock (_watchers) { watcherOnChanged(pattern.Sender, pattern.EventArgs); } });
if (watcherOnCreated != null)
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
h => { fileSystemWatcher.Created += h; fileSystemWatcher.Changed += h; },
h => { fileSystemWatcher.Created -= h; fileSystemWatcher.Changed += h; }).
Window(config.ExcludeDuplicateEventsWindowTime).
SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
Subscribe(pattern => { lock (_watchers) { watcherOnCreated(pattern.Sender, pattern.EventArgs); } });
if (watcherOnRenamed != null)
Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>(
h => fileSystemWatcher.Renamed += h,
h => fileSystemWatcher.Renamed -= h).
Window(config.ExcludeDuplicateEventsWindowTime).
SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
Subscribe(pattern => { lock (_watchers) { watcherOnRenamed(pattern.Sender, pattern.EventArgs); } });
if (watcherOnDeleted != null)
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
h => fileSystemWatcher.Deleted += h,
h => fileSystemWatcher.Deleted -= h).
Window(config.ExcludeDuplicateEventsWindowTime).
SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
Subscribe(pattern => { lock (_watchers) { watcherOnDeleted(pattern.Sender, pattern.EventArgs); } });
}
else
{
if (watcherOnChanged != null)
fileSystemWatcher.Changed += watcherOnChanged;
if (watcherOnCreated != null)
fileSystemWatcher.Created += watcherOnCreated;
if (watcherOnRenamed != null)
fileSystemWatcher.Renamed += watcherOnRenamed;
if (watcherOnDeleted != null)
fileSystemWatcher.Deleted += watcherOnDeleted;
}
_watchers.Add(fileSystemWatcher);
log.Info($"[Topshelf.FileSystemWatcher] configured to listen for events in {config.Path}");
//foreach (System.IO.FileSystemWatcher watcher in _watchers)
//{
// watcher.EnableRaisingEvents = true;
//}
//log.Info("[Topshelf.FileSystemWatcher] listening for events");
}
});
}
private static void AfterStartingService<T>(ServiceConfigurator<T> configurator,
IEnumerable<FileSystemWatcherConfigurator.DirectoryConfiguration> configs, LogWriter log,
Action<TopshelfFileSystemEventArgs> fileSystemChanged) where T : class
{
configurator.AfterStartingService(() =>
{
foreach (FileSystemWatcherConfigurator.DirectoryConfiguration config in configs)
{
if (config.GetInitialStateEvent)
{
log.Info("[Topshelf.FileSystemWatcher] Checking for InitialState Events");
string[] paths;
if (!string.IsNullOrWhiteSpace(config.FileFilter))
{
paths = Directory.GetFiles(config.Path, config.FileFilter);
}
else
{
paths = Directory.GetFiles(config.Path);
}
if (paths.Any())
{
foreach (string path in paths)
{
fileSystemChanged(FileSystemEventFactory.CreateCurrentStateFileSystemEvent(Path.GetDirectoryName(path), Path.GetFileName(path)));
}
}
}
}
});
}
private static void BeforeStoppingService<T>(ServiceConfigurator<T> configurator, LogWriter log, FileSystemEventHandler watcherOnChanged) where T : class
{
configurator.BeforeStoppingService(() =>
{
if (_watchers != null && _watchers.Any())
{
foreach (System.IO.FileSystemWatcher fileSystemWatcher in _watchers)
{
fileSystemWatcher.EnableRaisingEvents = false;
fileSystemWatcher.Changed -= watcherOnChanged;
fileSystemWatcher.Created -= watcherOnChanged;
fileSystemWatcher.Deleted -= watcherOnChanged;
fileSystemWatcher.Dispose();
log.Info("[Topshelf.FileSystemWatcher] Unsubscribed for FileSystemChange events");
}
}
});
}
private static System.IO.FileSystemWatcher CreateFileSystemWatcher(string path, NotifyFilters notifyFilters, string fileFilter, bool includeSubDirectories, int internalBufferSize)
{
System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher
{
Path = path,
EnableRaisingEvents = true,
IncludeSubdirectories = includeSubDirectories,
NotifyFilter = notifyFilters,
Filter = fileFilter,
};
if (internalBufferSize > 0)
{
watcher.InternalBufferSize = internalBufferSize;
}
return watcher;
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Transport.Client;
using tutorial;
using shared;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
namespace Client
{
public class Program
{
private static ServiceCollection ServiceCollection = new ServiceCollection();
private static ILogger Logger;
private static readonly TConfiguration Configuration = null; // new TConfiguration() if needed
private static void DisplayHelp()
{
Logger.LogInformation(@"
Usage:
Client.exe -help
will diplay help information
Client.exe -tr:<transport> -bf:<buffering> -pr:<protocol> -mc:<numClients>
will run client with specified arguments (tcp transport and binary protocol by default) and with 1 client
Options:
-tr (transport):
tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
namedpipe - namedpipe transport will be used (pipe address - "".test"")
http - http transport will be used (address - ""http://localhost:9090"")
tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090)
-bf (buffering):
none - (default) no buffering will be used
buffered - buffered transport will be used
framed - framed transport will be used
-pr (protocol):
binary - (default) binary protocol will be used
compact - compact protocol will be used
json - json protocol will be used
multiplexed - multiplexed protocol will be used
-mc (multiple clients):
<numClients> - number of multiple clients to connect to server (max 100, default 1)
Sample:
Client.exe -tr:tcp -p:binary
");
}
public static void Main(string[] args)
{
args = args ?? new string[0];
ServiceCollection.AddLogging(logging => ConfigureLogging(logging));
Logger = ServiceCollection.BuildServiceProvider().GetService<ILoggerFactory>().CreateLogger(nameof(Client));
if (args.Any(x => x.StartsWith("-help", StringComparison.OrdinalIgnoreCase)))
{
DisplayHelp();
return;
}
Logger.LogInformation("Starting client...");
using (var source = new CancellationTokenSource())
{
RunAsync(args, source.Token).GetAwaiter().GetResult();
}
}
private static void ConfigureLogging(ILoggingBuilder logging)
{
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddConsole();
logging.AddDebug();
}
private static async Task RunAsync(string[] args, CancellationToken cancellationToken)
{
var numClients = GetNumberOfClients(args);
Logger.LogInformation($"Selected # of clients: {numClients}");
var transports = new TTransport[numClients];
for (int i = 0; i < numClients; i++)
{
var t = GetTransport(args);
transports[i] = t;
}
Logger.LogInformation($"Selected client transport: {transports[0]}");
var protocols = new Tuple<Protocol, TProtocol>[numClients];
for (int i = 0; i < numClients; i++)
{
var p = GetProtocol(args, transports[i]);
protocols[i] = p;
}
Logger.LogInformation($"Selected client protocol: {protocols[0].Item1}");
var tasks = new Task[numClients];
for (int i = 0; i < numClients; i++)
{
var task = RunClientAsync(protocols[i], cancellationToken);
tasks[i] = task;
}
Task.WaitAll(tasks);
await Task.CompletedTask;
}
private static TTransport GetTransport(string[] args)
{
TTransport transport = new TSocketTransport(IPAddress.Loopback, 9090, Configuration);
// construct endpoint transport
var transportArg = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];
if (Enum.TryParse(transportArg, true, out Transport selectedTransport))
{
switch (selectedTransport)
{
case Transport.Tcp:
transport = new TSocketTransport(IPAddress.Loopback, 9090, Configuration);
break;
case Transport.NamedPipe:
transport = new TNamedPipeTransport(".test", Configuration);
break;
case Transport.Http:
transport = new THttpTransport(new Uri("http://localhost:9090"), Configuration);
break;
case Transport.TcpTls:
transport = new TTlsSocketTransport(IPAddress.Loopback, 9090, Configuration,
GetCertificate(), CertValidator, LocalCertificateSelectionCallback);
break;
default:
Debug.Assert(false, "unhandled case");
break;
}
}
// optionally add layered transport(s)
var bufferingArg = args.FirstOrDefault(x => x.StartsWith("-bf"))?.Split(':')?[1];
if (Enum.TryParse<Buffering>(bufferingArg, out var selectedBuffering))
{
switch (selectedBuffering)
{
case Buffering.Buffered:
transport = new TBufferedTransport(transport);
break;
case Buffering.Framed:
transport = new TFramedTransport(transport);
break;
default: // layered transport(s) are optional
Debug.Assert(selectedBuffering == Buffering.None, "unhandled case");
break;
}
}
return transport;
}
private static int GetNumberOfClients(string[] args)
{
var numClients = args.FirstOrDefault(x => x.StartsWith("-mc"))?.Split(':')?[1];
Logger.LogInformation($"Selected # of clients: {numClients}");
int c;
if( int.TryParse(numClients, out c) && (0 < c) && (c <= 100))
return c;
else
return 1;
}
private static X509Certificate2 GetCertificate()
{
// due to files location in net core better to take certs from top folder
var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory()));
return new X509Certificate2(certFile, "ThriftTest");
}
private static string GetCertPath(DirectoryInfo di, int maxCount = 6)
{
var topDir = di;
var certFile =
topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories)
.FirstOrDefault();
if (certFile == null)
{
if (maxCount == 0)
throw new FileNotFoundException("Cannot find file in directories");
return GetCertPath(di.Parent, maxCount - 1);
}
return certFile.FullName;
}
private static X509Certificate LocalCertificateSelectionCallback(object sender,
string targetHost, X509CertificateCollection localCertificates,
X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return GetCertificate();
}
private static bool CertValidator(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private static Tuple<Protocol, TProtocol> GetProtocol(string[] args, TTransport transport)
{
var protocol = args.FirstOrDefault(x => x.StartsWith("-pr"))?.Split(':')?[1];
Protocol selectedProtocol;
if (Enum.TryParse(protocol, true, out selectedProtocol))
{
switch (selectedProtocol)
{
case Protocol.Binary:
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TBinaryProtocol(transport));
case Protocol.Compact:
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TCompactProtocol(transport));
case Protocol.Json:
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TJsonProtocol(transport));
case Protocol.Multiplexed:
// it returns BinaryProtocol to avoid making wrapped protocol as public in TProtocolDecorator (in RunClientAsync it will be wrapped into Multiplexed protocol)
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TBinaryProtocol(transport));
default:
Debug.Assert(false, "unhandled case");
break;
}
}
return new Tuple<Protocol, TProtocol>(selectedProtocol, new TBinaryProtocol(transport));
}
private static async Task RunClientAsync(Tuple<Protocol, TProtocol> protocolTuple, CancellationToken cancellationToken)
{
try
{
var protocol = protocolTuple.Item2;
var protocolType = protocolTuple.Item1;
TBaseClient client = null;
try
{
if (protocolType != Protocol.Multiplexed)
{
client = new Calculator.Client(protocol);
await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client);
}
else
{
// it uses binary protocol there to create Multiplexed protocols
var multiplex = new TMultiplexedProtocol(protocol, nameof(Calculator));
client = new Calculator.Client(multiplex);
await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client);
multiplex = new TMultiplexedProtocol(protocol, nameof(SharedService));
client = new SharedService.Client(multiplex);
await ExecuteSharedServiceClientOperations(cancellationToken, (SharedService.Client)client);
}
}
catch (Exception ex)
{
Logger.LogError($"{client?.ClientId} " + ex);
}
finally
{
protocol.Transport.Close();
}
}
catch (TApplicationException x)
{
Logger.LogError(x.ToString());
}
}
private static async Task ExecuteCalculatorClientOperations(CancellationToken cancellationToken, Calculator.Client client)
{
await client.OpenTransportAsync(cancellationToken);
// Async version
Logger.LogInformation($"{client.ClientId} PingAsync()");
await client.pingAsync(cancellationToken);
Logger.LogInformation($"{client.ClientId} AddAsync(1,1)");
var sum = await client.addAsync(1, 1, cancellationToken);
Logger.LogInformation($"{client.ClientId} AddAsync(1,1)={sum}");
var work = new Work
{
Op = Operation.DIVIDE,
Num1 = 1,
Num2 = 0
};
try
{
Logger.LogInformation($"{client.ClientId} CalculateAsync(1)");
await client.calculateAsync(1, work, cancellationToken);
Logger.LogInformation($"{client.ClientId} Whoa we can divide by 0");
}
catch (InvalidOperation io)
{
Logger.LogInformation($"{client.ClientId} Invalid operation: " + io);
}
work.Op = Operation.SUBTRACT;
work.Num1 = 15;
work.Num2 = 10;
try
{
Logger.LogInformation($"{client.ClientId} CalculateAsync(1)");
var diff = await client.calculateAsync(1, work, cancellationToken);
Logger.LogInformation($"{client.ClientId} 15-10={diff}");
}
catch (InvalidOperation io)
{
Logger.LogInformation($"{client.ClientId} Invalid operation: " + io);
}
Logger.LogInformation($"{client.ClientId} GetStructAsync(1)");
var log = await client.getStructAsync(1, cancellationToken);
Logger.LogInformation($"{client.ClientId} Check log: {log.Value}");
Logger.LogInformation($"{client.ClientId} ZipAsync() with delay 100mc on server side");
await client.zipAsync(cancellationToken);
}
private static async Task ExecuteSharedServiceClientOperations(CancellationToken cancellationToken, SharedService.Client client)
{
await client.OpenTransportAsync(cancellationToken);
// Async version
Logger.LogInformation($"{client.ClientId} SharedService GetStructAsync(1)");
var log = await client.getStructAsync(1, cancellationToken);
Logger.LogInformation($"{client.ClientId} SharedService Value: {log.Value}");
}
private enum Transport
{
Tcp,
NamedPipe,
Http,
TcpBuffered,
Framed,
TcpTls
}
private enum Protocol
{
Binary,
Compact,
Json,
Multiplexed
}
private enum Buffering
{
None,
Buffered,
Framed
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
namespace BitPool.Cryptography.BouncyCastle.IO
{
public class CipherStream : Stream
{
internal Stream stream;
internal IBufferedCipher inCipher, outCipher;
private byte[] mInBuf;
private int mInPos;
private bool inStreamEnded;
public CipherStream(
Stream stream,
IBufferedCipher readCipher,
IBufferedCipher writeCipher)
{
this.stream = stream;
if (readCipher != null)
{
this.inCipher = readCipher;
mInBuf = null;
}
if (writeCipher != null)
{
this.outCipher = writeCipher;
}
}
public IBufferedCipher ReadCipher
{
get { return inCipher; }
}
public IBufferedCipher WriteCipher
{
get { return outCipher; }
}
public override int ReadByte()
{
if (inCipher == null)
return stream.ReadByte();
if (mInBuf == null || mInPos >= mInBuf.Length)
{
if (!FillInBuf())
return -1;
}
return mInBuf[mInPos++];
}
public override int Read(
byte[] buffer,
int offset,
int count)
{
if (inCipher == null)
return stream.Read(buffer, offset, count);
int num = 0;
while (num < count)
{
if (mInBuf == null || mInPos >= mInBuf.Length)
{
if (!FillInBuf())
break;
}
int numToCopy = System.Math.Min(count - num, mInBuf.Length - mInPos);
Array.Copy(mInBuf, mInPos, buffer, offset + num, numToCopy);
mInPos += numToCopy;
num += numToCopy;
}
return num;
}
private bool FillInBuf()
{
if (inStreamEnded)
return false;
mInPos = 0;
do
{
mInBuf = ReadAndProcessBlock();
}
while (!inStreamEnded && mInBuf == null);
return mInBuf != null;
}
private byte[] ReadAndProcessBlock()
{
int blockSize = inCipher.GetBlockSize();
int readSize = (blockSize == 0) ? 256 : blockSize;
byte[] block = new byte[readSize];
int numRead = 0;
do
{
int count = stream.Read(block, numRead, block.Length - numRead);
if (count < 1)
{
inStreamEnded = true;
break;
}
numRead += count;
}
while (numRead < block.Length);
Debug.Assert(inStreamEnded || numRead == block.Length);
byte[] bytes = inStreamEnded
? inCipher.DoFinal(block, 0, numRead)
: inCipher.ProcessBytes(block);
if (bytes != null && bytes.Length == 0)
{
bytes = null;
}
return bytes;
}
public override void Write(
byte[] buffer,
int offset,
int count)
{
Debug.Assert(buffer != null);
Debug.Assert(0 <= offset && offset <= buffer.Length);
Debug.Assert(count >= 0);
int end = offset + count;
Debug.Assert(0 <= end && end <= buffer.Length);
if (outCipher == null)
{
stream.Write(buffer, offset, count);
return;
}
byte[] data = outCipher.ProcessBytes(buffer, offset, count);
if (data != null)
{
stream.Write(data, 0, data.Length);
}
}
public override void WriteByte(
byte b)
{
if (outCipher == null)
{
stream.WriteByte(b);
return;
}
byte[] data = outCipher.ProcessByte(b);
if (data != null)
{
stream.Write(data, 0, data.Length);
}
}
public override bool CanRead
{
get { return stream.CanRead && (inCipher != null); }
}
public override bool CanWrite
{
get { return stream.CanWrite && (outCipher != null); }
}
public override bool CanSeek
{
get { return false; }
}
public sealed override long Length
{
get { throw new NotSupportedException(); }
}
public sealed override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override void Close()
{
if (outCipher != null)
{
byte[] data = outCipher.DoFinal();
stream.Write(data, 0, data.Length);
stream.Flush();
}
stream.Close();
}
public override void Flush()
{
// Note: outCipher.DoFinal is only called during Close()
stream.Flush();
}
public sealed override long Seek(
long offset,
SeekOrigin origin)
{
throw new NotSupportedException();
}
public sealed override void SetLength(
long length)
{
throw new NotSupportedException();
}
}
}
| |
// 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.Threading.Tasks;
using System.Threading;
namespace System.Net.NetworkInformation
{
// Linux implementation of NetworkChange
public partial class NetworkChange
{
private static volatile int s_socket = 0;
// Lock controlling access to delegate subscriptions, socket initialization, availability-changed state and timer.
private static readonly object s_gate = new object();
private static readonly Interop.Sys.NetworkChangeEvent s_networkChangeCallback = ProcessEvent;
// The "leniency" window for NetworkAvailabilityChanged socket events.
// All socket events received within this duration will be coalesced into a
// single event. Generally, many route changed events are fired in succession,
// and we are not interested in all of them, just the fact that network availability
// has potentially changed as a result.
private const int AvailabilityTimerWindowMilliseconds = 150;
private static readonly TimerCallback s_availabilityTimerFiredCallback = OnAvailabilityTimerFired;
private static Timer s_availabilityTimer;
private static bool s_availabilityHasChanged;
public static event NetworkAddressChangedEventHandler NetworkAddressChanged
{
add
{
if (value != null)
{
lock (s_gate)
{
if (s_socket == 0)
{
CreateSocket();
}
s_addressChangedSubscribers.TryAdd(value, ExecutionContext.Capture());
}
}
}
remove
{
if (value != null)
{
lock (s_gate)
{
if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0)
{
Debug.Assert(s_socket == 0,
"s_socket != 0, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged.");
return;
}
s_addressChangedSubscribers.Remove(value);
if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0)
{
CloseSocket();
}
}
}
}
}
public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged
{
add
{
if (value != null)
{
lock (s_gate)
{
if (s_socket == 0)
{
CreateSocket();
}
if (s_availabilityTimer == null)
{
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
bool restoreFlow = false;
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
ExecutionContext.SuppressFlow();
restoreFlow = true;
}
s_availabilityTimer = new Timer(s_availabilityTimerFiredCallback, null, Timeout.Infinite, Timeout.Infinite);
}
finally
{
// Restore the current ExecutionContext
if (restoreFlow)
ExecutionContext.RestoreFlow();
}
}
s_availabilityChangedSubscribers.TryAdd(value, ExecutionContext.Capture());
}
}
}
remove
{
if (value != null)
{
lock (s_gate)
{
if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0)
{
Debug.Assert(s_socket == 0,
"s_socket != 0, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged.");
return;
}
s_availabilityChangedSubscribers.Remove(value);
if (s_availabilityChangedSubscribers.Count == 0)
{
if (s_availabilityTimer != null)
{
s_availabilityTimer.Dispose();
s_availabilityTimer = null;
s_availabilityHasChanged = false;
}
if (s_addressChangedSubscribers.Count == 0)
{
CloseSocket();
}
}
}
}
}
}
private static void CreateSocket()
{
Debug.Assert(s_socket == 0, "s_socket != 0, must close existing socket before opening another.");
int newSocket;
Interop.Error result = Interop.Sys.CreateNetworkChangeListenerSocket(out newSocket);
if (result != Interop.Error.SUCCESS)
{
string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage();
throw new NetworkInformationException(message);
}
s_socket = newSocket;
Task.Factory.StartNew(s => LoopReadSocket((int)s), s_socket,
CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
private static void CloseSocket()
{
Debug.Assert(s_socket != 0, "s_socket was 0 when CloseSocket was called.");
Interop.Error result = Interop.Sys.CloseNetworkChangeListenerSocket(s_socket);
if (result != Interop.Error.SUCCESS)
{
string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage();
throw new NetworkInformationException(message);
}
s_socket = 0;
}
private static void LoopReadSocket(int socket)
{
while (socket == s_socket)
{
Interop.Sys.ReadEvents(socket, s_networkChangeCallback);
}
}
private static void ProcessEvent(int socket, Interop.Sys.NetworkChangeKind kind)
{
if (kind != Interop.Sys.NetworkChangeKind.None)
{
lock (s_gate)
{
if (socket == s_socket)
{
OnSocketEvent(kind);
}
}
}
}
private static void OnSocketEvent(Interop.Sys.NetworkChangeKind kind)
{
switch (kind)
{
case Interop.Sys.NetworkChangeKind.AddressAdded:
case Interop.Sys.NetworkChangeKind.AddressRemoved:
OnAddressChanged();
break;
case Interop.Sys.NetworkChangeKind.AvailabilityChanged:
lock (s_gate)
{
if (s_availabilityTimer != null)
{
if (!s_availabilityHasChanged)
{
s_availabilityTimer.Change(AvailabilityTimerWindowMilliseconds, -1);
}
s_availabilityHasChanged = true;
}
}
break;
}
}
private static void OnAddressChanged()
{
Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null;
lock (s_gate)
{
if (s_addressChangedSubscribers.Count > 0)
{
addressChangedSubscribers = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers);
}
}
if (addressChangedSubscribers != null)
{
foreach (KeyValuePair<NetworkAddressChangedEventHandler, ExecutionContext>
subscriber in addressChangedSubscribers)
{
NetworkAddressChangedEventHandler handler = subscriber.Key;
ExecutionContext ec = subscriber.Value;
if (ec == null) // Flow supressed
{
handler(null, EventArgs.Empty);
}
else
{
ExecutionContext.Run(ec, s_runAddressChangedHandler, handler);
}
}
}
}
private static void OnAvailabilityTimerFired(object state)
{
Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> availabilityChangedSubscribers = null;
lock (s_gate)
{
if (s_availabilityHasChanged)
{
s_availabilityHasChanged = false;
if (s_availabilityChangedSubscribers.Count > 0)
{
availabilityChangedSubscribers =
new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(
s_availabilityChangedSubscribers);
}
}
}
if (availabilityChangedSubscribers != null)
{
bool isAvailable = NetworkInterface.GetIsNetworkAvailable();
NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs;
ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable;
foreach (KeyValuePair<NetworkAvailabilityChangedEventHandler, ExecutionContext>
subscriber in availabilityChangedSubscribers)
{
NetworkAvailabilityChangedEventHandler handler = subscriber.Key;
ExecutionContext ec = subscriber.Value;
if (ec == null) // Flow supressed
{
handler(null, args);
}
else
{
ExecutionContext.Run(ec, callbackContext, handler);
}
}
}
}
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// 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.Collections.Generic;
using Yaapii.Atoms.Enumerable;
using Yaapii.Atoms.Scalar;
namespace Yaapii.Atoms.Map
{
/// <summary>
/// Joined map.
/// Since 9.9.2019
/// </summary>
public sealed class Joined : MapEnvelope
{
/// <summary>
/// Joined map.
/// </summary>
public Joined(IKvp kvp, IDictionary<string, string> origin) : this(
new MapOf(kvp),
origin
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(IMapInput input, IDictionary<string, string> origin) : this(
new MapOf(input),
origin
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(params IDictionary<string, string>[] dicts) : this(
new LiveMany<IDictionary<string, string>>(dicts)
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(IEnumerable<IDictionary<string, string>> dicts, bool rejectBuildingAllValues = true) : base(
() =>
new LazyDict(
new Enumerable.Joined<IKvp>(
new Mapped<IDictionary<string, string>, IEnumerable<IKvp>>(dict =>
new ManyOf<IKvp>(
new ScalarOf<IEnumerator<IKvp>>(() =>
{
IEnumerable<IKvp> list = new ManyOf<IKvp>();
foreach (var key in dict.Keys)
{
list = new Enumerable.Joined<IKvp>(list, new KvpOf(key, () => dict[key]));
}
return list.GetEnumerator();
})
),
dicts
)
)
),
rejectBuildingAllValues
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<string,Value> New<Value>(IKvp<Value> kvp, IDictionary<string, Value> origin, bool live = false)
=> new Joined<Value>(kvp, origin, live);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<string,Value> New<Value>(IMapInput<Value> input, IDictionary<string, Value> origin, bool live = false)
=> new Joined<Value>(input, origin);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<string,Value> New<Value>(params IDictionary<string, Value>[] dicts)
=> new Joined<Value>(dicts);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<string,Value> New<Value>(bool live, params IDictionary<string, Value>[] dicts)
=> new Joined<Value>(live, dicts);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<string,Value> New<Value>(IEnumerable<IDictionary<string, Value>> dicts, bool live = false)
=> new Joined<Value>(dicts, live);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<Key, Value> New<Key, Value>(IKvp<Key, Value> kvp, IDictionary<Key, Value> origin, bool live = false)
=> new Joined<Key, Value>(kvp, origin, live);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<Key, Value> New<Key, Value>(IMapInput<Key, Value> input, IDictionary<Key, Value> origin, bool live = false)
=> new Joined<Key, Value>(input, origin, live);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<Key, Value> New<Key, Value>(bool live, params IDictionary<Key, Value>[] dicts)
=> new Joined<Key, Value>(live, dicts);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<Key, Value> New<Key, Value>(params IDictionary<Key, Value>[] dicts)
=> new Joined<Key, Value>(dicts);
/// <summary>
/// Joined map.
/// </summary>
public static IDictionary<Key, Value> New<Key, Value>(IEnumerable<IDictionary<Key, Value>> dicts, bool live = false)
=> new Joined<Key, Value>(dicts, live);
}
/// <summary>
/// Joined map.
/// Since 9.9.2019
/// </summary>
public sealed class Joined<Value> : MapEnvelope<Value>
{
/// <summary>
/// Joined map.
/// </summary>
public Joined(IKvp<Value> kvp, IDictionary<string, Value> origin, bool live = false) : this(
live,
new MapOf<Value>(kvp), origin
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(IMapInput<Value> input, IDictionary<string, Value> origin, bool live = false) : this(
live,
new MapOf<Value>(input), origin
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(params IDictionary<string, Value>[] dicts) : this(
false,
dicts
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(bool live, params IDictionary<string, Value>[] dicts) : this(
new LiveMany<IDictionary<string, Value>>(dicts),
live
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(IEnumerable<IDictionary<string, Value>> dicts, bool live = false) : base(
() =>
new LazyDict<string, Value>(
new Enumerable.Joined<IKvp<string, Value>>(
new Mapped<IDictionary<string, Value>, IEnumerable<IKvp<string, Value>>>(dict =>
new LiveMany<IKvp<string, Value>>(() =>
{
IEnumerable<IKvp<string, Value>> list = new ManyOf<IKvp<string, Value>>();
foreach (var key in dict.Keys)
{
list = new Enumerable.Joined<IKvp<string, Value>>(list, new KvpOf<string, Value>(key, () => dict[key]));
}
return list.GetEnumerator();
}
),
dicts
)
)
)
,
live
)
{ }
}
/// <summary>
/// Joined map.
/// Since 9.9.2019
/// </summary>
public sealed class Joined<Key, Value> : MapEnvelope<Key, Value>
{
/// <summary>
/// Joined map.
/// </summary>
public Joined(IKvp<Key, Value> kvp, IDictionary<Key, Value> origin, bool live = false) : this(
live,
new MapOf<Key, Value>(kvp), origin
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(IMapInput<Key, Value> input, IDictionary<Key, Value> origin, bool live = false) : this(
live,
new MapOf<Key, Value>(input), origin
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(bool live, params IDictionary<Key, Value>[] dicts) : this(
new LiveMany<IDictionary<Key, Value>>(dicts),
live
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(params IDictionary<Key, Value>[] dicts) : this(
new LiveMany<IDictionary<Key, Value>>(dicts),
false
)
{ }
/// <summary>
/// Joined map.
/// </summary>
public Joined(IEnumerable<IDictionary<Key, Value>> dicts, bool live = false) : base(
() =>
new LazyDict<Key, Value>(
new Enumerable.Joined<IKvp<Key, Value>>(
new Mapped<IDictionary<Key, Value>, IEnumerable<IKvp<Key, Value>>>(dict =>
new LiveMany<IKvp<Key, Value>>(() =>
{
IEnumerable<IKvp<Key, Value>> list = new ManyOf<IKvp<Key, Value>>();
foreach (var key in dict.Keys)
{
list = new Enumerable.Joined<IKvp<Key, Value>>(list, new KvpOf<Key, Value>(key, () => dict[key]));
}
return list.GetEnumerator();
}
),
dicts
)
)
)
,
live
)
{ }
}
}
| |
/*
** Copyright (c) Microsoft. All rights reserved.
** Licensed under the MIT license.
** See LICENSE file in the project root for full license information.
**
** This program was translated to C# and adapted for xunit-performance.
** New variants of several tests were added to compare class versus
** struct and to compare jagged arrays vs multi-dimensional arrays.
*/
// Captures contents of NNET.DAT as a string
// to simplfy testing in CoreCLR.
internal class NeuralData
{
public static string Input =
"5 7 8 \n"
+ "26 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "0 1 0 0 0 0 1 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 0 0 1 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "0 1 0 0 0 1 0 0 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 1 1 \n"
+ "0 1 0 0 0 1 0 1 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "0 1 0 0 0 1 1 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 1 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 0 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 0 0 0 \n"
+ "0 1 1 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 1 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 1 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 1 0 \n"
+ "1 0 1 0 0 \n"
+ "1 1 0 0 0 \n"
+ "1 0 1 0 0 \n"
+ "1 0 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 0 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 1 1 1 1 \n"
+ "0 1 0 0 1 1 0 0 \n"
+ "1 0 0 0 1 \n"
+ "1 1 0 1 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 1 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 0 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 0 1 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 0 1 1 1 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 0 1 1 1 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "0 1 0 1 0 0 0 0 \n"
+ "0 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 0 1 1 \n"
+ "0 1 1 1 1 \n"
+ "0 1 0 1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "1 0 1 0 0 \n"
+ "1 0 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 0 1 0 \n"
+ "0 1 1 1 1 \n"
+ "1 0 0 0 0 \n"
+ "1 0 0 0 0 \n"
+ "0 1 1 1 0 \n"
+ "0 0 0 0 1 \n"
+ "0 0 0 0 1 \n"
+ "1 1 1 1 0 \n"
+ "0 1 0 1 0 0 1 1 \n"
+ "1 1 1 1 1 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 1 0 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 1 1 0 \n"
+ "0 1 0 1 0 1 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 1 1 0 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 0 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "1 0 1 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 1 1 1 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 1 0 0 0 \n"
+ "1 0 0 0 1 \n"
+ "0 1 0 1 0 \n"
+ "0 1 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 1 1 0 0 1 \n"
+ "1 1 1 1 1 \n"
+ "0 0 0 1 0 \n"
+ "0 0 0 1 0 \n"
+ "0 0 1 0 0 \n"
+ "0 1 0 0 0 \n"
+ "0 1 0 0 0 \n"
+ "1 1 1 1 1 \n"
+ "0 1 0 1 1 0 1 0 \n"
+ " \n";
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* 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.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Globalization;
using System.IO;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Interfaces;
using OpenMetaverse.Messages.Linden;
namespace OpenMetaverse
{
/// <summary>
/// NetworkManager is responsible for managing the network layer of
/// OpenMetaverse. It tracks all the server connections, serializes
/// outgoing traffic and deserializes incoming traffic, and provides
/// instances of delegates for network-related events.
/// </summary>
public partial class NetworkManager
{
#region Enums
/// <summary>
/// Explains why a simulator or the grid disconnected from us
/// </summary>
public enum DisconnectType
{
/// <summary>The client requested the logout or simulator disconnect</summary>
ClientInitiated,
/// <summary>The server notified us that it is disconnecting</summary>
ServerInitiated,
/// <summary>Either a socket was closed or network traffic timed out</summary>
NetworkTimeout,
/// <summary>The last active simulator shut down</summary>
SimShutdown
}
#endregion Enums
#region Structs
/// <summary>
/// Holds a simulator reference and a decoded packet, these structs are put in
/// the packet inbox for event handling
/// </summary>
public struct IncomingPacket
{
/// <summary>Reference to the simulator that this packet came from</summary>
public Simulator Simulator;
/// <summary>Packet that needs to be processed</summary>
public Packet Packet;
public IncomingPacket(Simulator simulator, Packet packet)
{
Simulator = simulator;
Packet = packet;
}
}
/// <summary>
/// Holds a simulator reference and a serialized packet, these structs are put in
/// the packet outbox for sending
/// </summary>
public class OutgoingPacket
{
/// <summary>Reference to the simulator this packet is destined for</summary>
public readonly Simulator Simulator;
/// <summary>Packet that needs to be sent</summary>
public readonly UDPPacketBuffer Buffer;
/// <summary>Sequence number of the wrapped packet</summary>
public uint SequenceNumber;
/// <summary>Number of times this packet has been resent</summary>
public int ResendCount;
/// <summary>Environment.TickCount when this packet was last sent over the wire</summary>
public int TickCount;
/// <summary>Type of the packet</summary>
public PacketType Type;
public OutgoingPacket(Simulator simulator, UDPPacketBuffer buffer, PacketType type)
{
Simulator = simulator;
Buffer = buffer;
this.Type = type;
}
}
#endregion Structs
#region Delegates
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<PacketSentEventArgs> m_PacketSent;
///<summary>Raises the PacketSent Event</summary>
/// <param name="e">A PacketSentEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnPacketSent(PacketSentEventArgs e)
{
EventHandler<PacketSentEventArgs> handler = m_PacketSent;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_PacketSentLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<PacketSentEventArgs> PacketSent
{
add { lock (m_PacketSentLock) { m_PacketSent += value; } }
remove { lock (m_PacketSentLock) { m_PacketSent -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<LoggedOutEventArgs> m_LoggedOut;
///<summary>Raises the LoggedOut Event</summary>
/// <param name="e">A LoggedOutEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnLoggedOut(LoggedOutEventArgs e)
{
EventHandler<LoggedOutEventArgs> handler = m_LoggedOut;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_LoggedOutLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<LoggedOutEventArgs> LoggedOut
{
add { lock (m_LoggedOutLock) { m_LoggedOut += value; } }
remove { lock (m_LoggedOutLock) { m_LoggedOut -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<SimConnectingEventArgs> m_SimConnecting;
///<summary>Raises the SimConnecting Event</summary>
/// <param name="e">A SimConnectingEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnSimConnecting(SimConnectingEventArgs e)
{
EventHandler<SimConnectingEventArgs> handler = m_SimConnecting;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_SimConnectingLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<SimConnectingEventArgs> SimConnecting
{
add { lock (m_SimConnectingLock) { m_SimConnecting += value; } }
remove { lock (m_SimConnectingLock) { m_SimConnecting -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<SimConnectedEventArgs> m_SimConnected;
///<summary>Raises the SimConnected Event</summary>
/// <param name="e">A SimConnectedEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnSimConnected(SimConnectedEventArgs e)
{
EventHandler<SimConnectedEventArgs> handler = m_SimConnected;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_SimConnectedLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<SimConnectedEventArgs> SimConnected
{
add { lock (m_SimConnectedLock) { m_SimConnected += value; } }
remove { lock (m_SimConnectedLock) { m_SimConnected -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<SimDisconnectedEventArgs> m_SimDisconnected;
///<summary>Raises the SimDisconnected Event</summary>
/// <param name="e">A SimDisconnectedEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnSimDisconnected(SimDisconnectedEventArgs e)
{
EventHandler<SimDisconnectedEventArgs> handler = m_SimDisconnected;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_SimDisconnectedLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<SimDisconnectedEventArgs> SimDisconnected
{
add { lock (m_SimDisconnectedLock) { m_SimDisconnected += value; } }
remove { lock (m_SimDisconnectedLock) { m_SimDisconnected -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<DisconnectedEventArgs> m_Disconnected;
///<summary>Raises the Disconnected Event</summary>
/// <param name="e">A DisconnectedEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnDisconnected(DisconnectedEventArgs e)
{
EventHandler<DisconnectedEventArgs> handler = m_Disconnected;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_DisconnectedLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<DisconnectedEventArgs> Disconnected
{
add { lock (m_DisconnectedLock) { m_Disconnected += value; } }
remove { lock (m_DisconnectedLock) { m_Disconnected -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<SimChangedEventArgs> m_SimChanged;
///<summary>Raises the SimChanged Event</summary>
/// <param name="e">A SimChangedEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnSimChanged(SimChangedEventArgs e)
{
EventHandler<SimChangedEventArgs> handler = m_SimChanged;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_SimChangedLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<SimChangedEventArgs> SimChanged
{
add { lock (m_SimChangedLock) { m_SimChanged += value; } }
remove { lock (m_SimChangedLock) { m_SimChanged -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<EventQueueRunningEventArgs> m_EventQueueRunning;
///<summary>Raises the EventQueueRunning Event</summary>
/// <param name="e">A EventQueueRunningEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnEventQueueRunning(EventQueueRunningEventArgs e)
{
EventHandler<EventQueueRunningEventArgs> handler = m_EventQueueRunning;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_EventQueueRunningLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<EventQueueRunningEventArgs> EventQueueRunning
{
add { lock (m_EventQueueRunningLock) { m_EventQueueRunning += value; } }
remove { lock (m_EventQueueRunningLock) { m_EventQueueRunning -= value; } }
}
#endregion Delegates
#region Properties
/// <summary>Unique identifier associated with our connections to
/// simulators</summary>
public uint CircuitCode
{
get { return _CircuitCode; }
set { _CircuitCode = value; }
}
/// <summary>The simulator that the logged in avatar is currently
/// occupying</summary>
public Simulator CurrentSim
{
get { return _CurrentSim; }
set { _CurrentSim = value; }
}
/// <summary>Shows whether the network layer is logged in to the
/// grid or not</summary>
public bool Connected { get { return connected; } }
/// <summary>Number of packets in the incoming queue</summary>
public int InboxCount { get { return PacketInbox.Count; } }
/// <summary>Number of packets in the outgoing queue</summary>
public int OutboxCount { get { return PacketOutbox.Count; } }
#endregion Properties
/// <summary>All of the simulators we are currently connected to</summary>
public List<Simulator> Simulators = new List<Simulator>();
/// <summary>Handlers for incoming capability events</summary>
internal CapsEventDictionary CapsEvents;
/// <summary>Handlers for incoming packets</summary>
internal PacketEventDictionary PacketEvents;
/// <summary>Incoming packets that are awaiting handling</summary>
internal BlockingQueue<IncomingPacket> PacketInbox = new BlockingQueue<IncomingPacket>(Settings.PACKET_INBOX_SIZE);
/// <summary>Outgoing packets that are awaiting handling</summary>
internal BlockingQueue<OutgoingPacket> PacketOutbox = new BlockingQueue<OutgoingPacket>(Settings.PACKET_INBOX_SIZE);
private GridClient Client;
private Timer DisconnectTimer;
private uint _CircuitCode;
private Simulator _CurrentSim = null;
private bool connected = false;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="client">Reference to the GridClient object</param>
public NetworkManager(GridClient client)
{
Client = client;
PacketEvents = new PacketEventDictionary(client);
CapsEvents = new CapsEventDictionary(client);
// Register internal CAPS callbacks
RegisterEventCallback("EnableSimulator", new Caps.EventQueueCallback(EnableSimulatorHandler));
// Register the internal callbacks
RegisterCallback(PacketType.RegionHandshake, RegionHandshakeHandler);
RegisterCallback(PacketType.StartPingCheck, StartPingCheckHandler, false);
RegisterCallback(PacketType.DisableSimulator, DisableSimulatorHandler);
RegisterCallback(PacketType.KickUser, KickUserHandler);
RegisterCallback(PacketType.LogoutReply, LogoutReplyHandler);
RegisterCallback(PacketType.CompletePingCheck, CompletePingCheckHandler, false);
RegisterCallback(PacketType.SimStats, SimStatsHandler, false);
// GLOBAL SETTING: Don't force Expect-100: Continue headers on HTTP POST calls
ServicePointManager.Expect100Continue = false;
}
/// <summary>
/// Register an event handler for a packet. This is a low level event
/// interface and should only be used if you are doing something not
/// supported in the library
/// </summary>
/// <param name="type">Packet type to trigger events for</param>
/// <param name="callback">Callback to fire when a packet of this type
/// is received</param>
public void RegisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback)
{
RegisterCallback(type, callback, true);
}
/// <summary>
/// Register an event handler for a packet. This is a low level event
/// interface and should only be used if you are doing something not
/// supported in the library
/// </summary>
/// <param name="type">Packet type to trigger events for</param>
/// <param name="callback">Callback to fire when a packet of this type
/// is received</param>
/// <param name="isAsync">True if the callback should be ran
/// asynchronously. Only set this to false (synchronous for callbacks
/// that will always complete quickly)</param>
/// <remarks>If any callback for a packet type is marked as
/// asynchronous, all callbacks for that packet type will be fired
/// asynchronously</remarks>
public void RegisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback, bool isAsync)
{
PacketEvents.RegisterEvent(type, callback, isAsync);
}
/// <summary>
/// Unregister an event handler for a packet. This is a low level event
/// interface and should only be used if you are doing something not
/// supported in the library
/// </summary>
/// <param name="type">Packet type this callback is registered with</param>
/// <param name="callback">Callback to stop firing events for</param>
public void UnregisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback)
{
PacketEvents.UnregisterEvent(type, callback);
}
/// <summary>
/// Register a CAPS event handler. This is a low level event interface
/// and should only be used if you are doing something not supported in
/// the library
/// </summary>
/// <param name="capsEvent">Name of the CAPS event to register a handler for</param>
/// <param name="callback">Callback to fire when a CAPS event is received</param>
public void RegisterEventCallback(string capsEvent, Caps.EventQueueCallback callback)
{
CapsEvents.RegisterEvent(capsEvent, callback);
}
/// <summary>
/// Unregister a CAPS event handler. This is a low level event interface
/// and should only be used if you are doing something not supported in
/// the library
/// </summary>
/// <param name="capsEvent">Name of the CAPS event this callback is
/// registered with</param>
/// <param name="callback">Callback to stop firing events for</param>
public void UnregisterEventCallback(string capsEvent, Caps.EventQueueCallback callback)
{
CapsEvents.UnregisterEvent(capsEvent, callback);
}
/// <summary>
/// Send a packet to the simulator the avatar is currently occupying
/// </summary>
/// <param name="packet">Packet to send</param>
public void SendPacket(Packet packet)
{
// try CurrentSim, however directly after login this will
// be null, so if it is, we'll try to find the first simulator
// we're connected to in order to send the packet.
Simulator simulator = CurrentSim;
if (simulator == null && Client.Network.Simulators.Count >= 1)
{
Logger.DebugLog("CurrentSim object was null, using first found connected simulator", Client);
simulator = Client.Network.Simulators[0];
}
if (simulator != null && simulator.Connected)
{
simulator.SendPacket(packet);
}
else
{
//throw new NotConnectedException("Packet received before simulator packet processing threads running, make certain you are completely logged in");
Logger.Log("Packet received before simulator packet processing threads running, make certain you are completely logged in.", Helpers.LogLevel.Error);
}
}
/// <summary>
/// Send a packet to a specified simulator
/// </summary>
/// <param name="packet">Packet to send</param>
/// <param name="simulator">Simulator to send the packet to</param>
public void SendPacket(Packet packet, Simulator simulator)
{
if (simulator != null)
{
simulator.SendPacket(packet);
}
else
{
Logger.Log("Packet received before simulator packet processing threads running, make certain you are completely logged in", Helpers.LogLevel.Error);
}
}
/// <summary>
/// Connect to a simulator
/// </summary>
/// <param name="ip">IP address to connect to</param>
/// <param name="port">Port to connect to</param>
/// <param name="handle">Handle for this simulator, to identify its
/// location in the grid</param>
/// <param name="setDefault">Whether to set CurrentSim to this new
/// connection, use this if the avatar is moving in to this simulator</param>
/// <param name="seedcaps">URL of the capabilities server to use for
/// this sim connection</param>
/// <returns>A Simulator object on success, otherwise null</returns>
public Simulator Connect(IPAddress ip, ushort port, ulong handle, bool setDefault, string seedcaps)
{
IPEndPoint endPoint = new IPEndPoint(ip, (int)port);
return Connect(endPoint, handle, setDefault, seedcaps);
}
/// <summary>
/// Connect to a simulator
/// </summary>
/// <param name="endPoint">IP address and port to connect to</param>
/// <param name="handle">Handle for this simulator, to identify its
/// location in the grid</param>
/// <param name="setDefault">Whether to set CurrentSim to this new
/// connection, use this if the avatar is moving in to this simulator</param>
/// <param name="seedcaps">URL of the capabilities server to use for
/// this sim connection</param>
/// <returns>A Simulator object on success, otherwise null</returns>
public Simulator Connect(IPEndPoint endPoint, ulong handle, bool setDefault, string seedcaps)
{
Simulator simulator = FindSimulator(endPoint);
if (simulator == null)
{
// We're not tracking this sim, create a new Simulator object
simulator = new Simulator(Client, endPoint, handle);
// Immediately add this simulator to the list of current sims. It will be removed if the
// connection fails
lock (Simulators) Simulators.Add(simulator);
}
if (!simulator.Connected)
{
if (!connected)
{
// Mark that we are connecting/connected to the grid
//
connected = true;
// Open the queues in case this is a reconnect and they were shut down
PacketInbox.Open();
PacketOutbox.Open();
// Start the packet decoding thread
Thread decodeThread = new Thread(new ThreadStart(IncomingPacketHandler));
decodeThread.Name = "Incoming UDP packet dispatcher";
decodeThread.Start();
// Start the packet sending thread
Thread sendThread = new Thread(new ThreadStart(OutgoingPacketHandler));
sendThread.Name = "Outgoing UDP packet dispatcher";
sendThread.Start();
}
// raise the SimConnecting event and allow any event
// subscribers to cancel the connection
if (m_SimConnecting != null)
{
SimConnectingEventArgs args = new SimConnectingEventArgs(simulator);
OnSimConnecting(args);
if (args.Cancel)
{
// Callback is requesting that we abort this connection
lock (Simulators)
{
Simulators.Remove(simulator);
}
return null;
}
}
// Attempt to establish a connection to the simulator
if (simulator.Connect(setDefault))
{
if (DisconnectTimer == null)
{
// Start a timer that checks if we've been disconnected
DisconnectTimer = new Timer(new TimerCallback(DisconnectTimer_Elapsed), null,
Client.Settings.SIMULATOR_TIMEOUT, Client.Settings.SIMULATOR_TIMEOUT);
}
if (setDefault)
{
SetCurrentSim(simulator, seedcaps);
}
// Raise the SimConnected event
if (m_SimConnected != null)
{
OnSimConnected(new SimConnectedEventArgs(simulator));
}
// If enabled, send an AgentThrottle packet to the server to increase our bandwidth
if (Client.Settings.SEND_AGENT_THROTTLE)
{
Client.Throttle.Set(simulator);
}
return simulator;
}
else
{
// Connection failed, remove this simulator from our list and destroy it
lock (Simulators)
{
Simulators.Remove(simulator);
}
return null;
}
}
else if (setDefault)
{
// Move in to this simulator
simulator.handshakeComplete = false;
simulator.UseCircuitCode(true);
Client.Self.CompleteAgentMovement(simulator);
// We're already connected to this server, but need to set it to the default
SetCurrentSim(simulator, seedcaps);
// Send an initial AgentUpdate to complete our movement in to the sim
if (Client.Settings.SEND_AGENT_UPDATES)
{
Client.Self.Movement.SendUpdate(true, simulator);
}
return simulator;
}
else
{
// Already connected to this simulator and wasn't asked to set it as the default,
// just return a reference to the existing object
return simulator;
}
}
/// <summary>
/// Begins the non-blocking logout. Makes sure that the LoggedOut event is
/// called even if the server does not send a logout reply, and Shutdown()
/// is properly called.
/// </summary>
public void BeginLogout()
{
// Wait for a logout response (by way of the LoggedOut event. If the
// response is received, shutdown will be fired in the callback.
// Otherwise we fire it manually with a NetworkTimeout type after LOGOUT_TIMEOUT
System.Timers.Timer timeout = new System.Timers.Timer();
EventHandler<LoggedOutEventArgs> callback = delegate(object sender, LoggedOutEventArgs e) {
Shutdown(DisconnectType.ClientInitiated);
timeout.Stop();
};
LoggedOut += callback;
timeout.Interval = Client.Settings.LOGOUT_TIMEOUT;
timeout.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) {
timeout.Stop();
Shutdown(DisconnectType.NetworkTimeout);
OnLoggedOut(new LoggedOutEventArgs(new List<UUID>()));
};
timeout.Start();
// Send the packet requesting a clean logout
RequestLogout();
LoggedOut -= callback;
}
/// <summary>
/// Initiate a blocking logout request. This will return when the logout
/// handshake has completed or when <code>Settings.LOGOUT_TIMEOUT</code>
/// has expired and the network layer is manually shut down
/// </summary>
public void Logout()
{
AutoResetEvent logoutEvent = new AutoResetEvent(false);
EventHandler<LoggedOutEventArgs> callback = delegate(object sender, LoggedOutEventArgs e) { logoutEvent.Set(); };
LoggedOut += callback;
// Send the packet requesting a clean logout
RequestLogout();
// Wait for a logout response. If the response is received, shutdown
// will be fired in the callback. Otherwise we fire it manually with
// a NetworkTimeout type
if (!logoutEvent.WaitOne(Client.Settings.LOGOUT_TIMEOUT, false))
Shutdown(DisconnectType.NetworkTimeout);
LoggedOut -= callback;
}
/// <summary>
/// Initiate the logout process. The <code>Shutdown()</code> function
/// needs to be manually called.
/// </summary>
public void RequestLogout()
{
// No need to run the disconnect timer any more
if (DisconnectTimer != null)
{
DisconnectTimer.Dispose();
DisconnectTimer = null;
}
// This will catch a Logout when the client is not logged in
if (CurrentSim == null || !connected)
{
Logger.Log("Ignoring RequestLogout(), client is already logged out", Helpers.LogLevel.Warning, Client);
return;
}
Logger.Log("Logging out", Helpers.LogLevel.Info, Client);
// Send a logout request to the current sim
LogoutRequestPacket logout = new LogoutRequestPacket();
logout.AgentData.AgentID = Client.Self.AgentID;
logout.AgentData.SessionID = Client.Self.SessionID;
SendPacket(logout);
}
/// <summary>
/// Close a connection to the given simulator
/// </summary>
/// <param name="simulator"></param>
/// <param name="sendCloseCircuit"></param>
public void DisconnectSim(Simulator simulator, bool sendCloseCircuit)
{
if (simulator != null)
{
simulator.Disconnect(sendCloseCircuit);
// Fire the SimDisconnected event if a handler is registered
if (m_SimDisconnected != null)
{
OnSimDisconnected(new SimDisconnectedEventArgs(simulator, DisconnectType.NetworkTimeout));
}
lock (Simulators) Simulators.Remove(simulator);
if (Simulators.Count == 0) Shutdown(DisconnectType.SimShutdown);
}
else
{
Logger.Log("DisconnectSim() called with a null Simulator reference", Helpers.LogLevel.Warning, Client);
}
}
/// <summary>
/// Shutdown will disconnect all the sims except for the current sim
/// first, and then kill the connection to CurrentSim. This should only
/// be called if the logout process times out on <code>RequestLogout</code>
/// </summary>
/// <param name="type">Type of shutdown</param>
public void Shutdown(DisconnectType type)
{
Shutdown(type, type.ToString());
}
/// <summary>
/// Shutdown will disconnect all the sims except for the current sim
/// first, and then kill the connection to CurrentSim. This should only
/// be called if the logout process times out on <code>RequestLogout</code>
/// </summary>
/// <param name="type">Type of shutdown</param>
/// <param name="message">Shutdown message</param>
public void Shutdown(DisconnectType type, string message)
{
Logger.Log("NetworkManager shutdown initiated", Helpers.LogLevel.Info, Client);
// Send a CloseCircuit packet to simulators if we are initiating the disconnect
bool sendCloseCircuit = (type == DisconnectType.ClientInitiated || type == DisconnectType.NetworkTimeout);
lock (Simulators)
{
// Disconnect all simulators except the current one
for (int i = 0; i < Simulators.Count; i++)
{
if (Simulators[i] != null && Simulators[i] != CurrentSim)
{
Simulators[i].Disconnect(sendCloseCircuit);
// Fire the SimDisconnected event if a handler is registered
if (m_SimDisconnected != null)
{
OnSimDisconnected(new SimDisconnectedEventArgs(Simulators[i], type));
}
}
}
Simulators.Clear();
}
if (CurrentSim != null)
{
// Kill the connection to the curent simulator
CurrentSim.Disconnect(sendCloseCircuit);
// Fire the SimDisconnected event if a handler is registered
if (m_SimDisconnected != null)
{
OnSimDisconnected(new SimDisconnectedEventArgs(CurrentSim, type));
}
}
// Clear out all of the packets that never had time to process
PacketInbox.Close();
PacketOutbox.Close();
connected = false;
// Fire the disconnected callback
if (m_Disconnected != null)
{
OnDisconnected(new DisconnectedEventArgs(type, message));
}
}
/// <summary>
/// Searches through the list of currently connected simulators to find
/// one attached to the given IPEndPoint
/// </summary>
/// <param name="endPoint">IPEndPoint of the Simulator to search for</param>
/// <returns>A Simulator reference on success, otherwise null</returns>
public Simulator FindSimulator(IPEndPoint endPoint)
{
lock (Simulators)
{
for (int i = 0; i < Simulators.Count; i++)
{
if (Simulators[i].IPEndPoint.Equals(endPoint))
return Simulators[i];
}
}
return null;
}
internal void RaisePacketSentEvent(byte[] data, int bytesSent, Simulator simulator)
{
if (m_PacketSent != null)
{
OnPacketSent(new PacketSentEventArgs(data, bytesSent, simulator));
}
}
/// <summary>
/// Fire an event when an event queue connects for capabilities
/// </summary>
/// <param name="simulator">Simulator the event queue is attached to</param>
internal void RaiseConnectedEvent(Simulator simulator)
{
if (m_EventQueueRunning != null)
{
OnEventQueueRunning(new EventQueueRunningEventArgs(simulator));
}
}
private void OutgoingPacketHandler()
{
OutgoingPacket outgoingPacket = null;
Simulator simulator;
// FIXME: This is kind of ridiculous. Port the HTB code from Simian over ASAP!
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
while (connected)
{
if (PacketOutbox.Dequeue(100, ref outgoingPacket))
{
simulator = outgoingPacket.Simulator;
// Very primitive rate limiting, keeps a fixed buffer of time between each packet
stopwatch.Stop();
if (stopwatch.ElapsedMilliseconds < 10)
{
//Logger.DebugLog(String.Format("Rate limiting, last packet was {0}ms ago", ms));
Thread.Sleep(10 - (int)stopwatch.ElapsedMilliseconds);
}
simulator.SendPacketFinal(outgoingPacket);
stopwatch.Start();
}
}
}
private void IncomingPacketHandler()
{
IncomingPacket incomingPacket = new IncomingPacket();
Packet packet = null;
Simulator simulator = null;
while (connected)
{
// Reset packet to null for the check below
packet = null;
if (PacketInbox.Dequeue(100, ref incomingPacket))
{
packet = incomingPacket.Packet;
simulator = incomingPacket.Simulator;
if (packet != null)
{
// Skip blacklisted packets
if (UDPBlacklist.Contains(packet.Type.ToString()))
{
Logger.Log(String.Format("Discarding Blacklisted packet {0} from {1}",
packet.Type, simulator.IPEndPoint), Helpers.LogLevel.Warning);
return;
}
// Fire the callback(s), if any
PacketEvents.RaiseEvent(packet.Type, packet, simulator);
}
}
}
}
private void SetCurrentSim(Simulator simulator, string seedcaps)
{
if (simulator != CurrentSim)
{
Simulator oldSim = CurrentSim;
lock (Simulators) CurrentSim = simulator; // CurrentSim is synchronized against Simulators
simulator.SetSeedCaps(seedcaps);
// If the current simulator changed fire the callback
if (m_SimChanged != null && simulator != oldSim)
{
OnSimChanged(new SimChangedEventArgs(oldSim));
}
}
}
#region Timers
private void DisconnectTimer_Elapsed(object obj)
{
if (!connected || CurrentSim == null)
{
if (DisconnectTimer != null)
{
DisconnectTimer.Dispose();
DisconnectTimer = null;
}
connected = false;
}
else if (CurrentSim.DisconnectCandidate)
{
// The currently occupied simulator hasn't sent us any traffic in a while, shutdown
Logger.Log("Network timeout for the current simulator (" +
CurrentSim.ToString() + "), logging out", Helpers.LogLevel.Warning, Client);
if (DisconnectTimer != null)
{
DisconnectTimer.Dispose();
DisconnectTimer = null;
}
connected = false;
// Shutdown the network layer
Shutdown(DisconnectType.NetworkTimeout);
}
else
{
// Mark the current simulator as potentially disconnected each time this timer fires.
// If the timer is fired again before any packets are received, an actual disconnect
// sequence will be triggered
CurrentSim.DisconnectCandidate = true;
}
}
#endregion Timers
#region Packet Callbacks
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void LogoutReplyHandler(object sender, PacketReceivedEventArgs e)
{
LogoutReplyPacket logout = (LogoutReplyPacket)e.Packet;
if ((logout.AgentData.SessionID == Client.Self.SessionID) && (logout.AgentData.AgentID == Client.Self.AgentID))
{
Logger.DebugLog("Logout reply received", Client);
// Deal with callbacks, if any
if (m_LoggedOut != null)
{
List<UUID> itemIDs = new List<UUID>();
foreach (LogoutReplyPacket.InventoryDataBlock InventoryData in logout.InventoryData)
{
itemIDs.Add(InventoryData.ItemID);
}
OnLoggedOut(new LoggedOutEventArgs(itemIDs));
}
// If we are receiving a LogoutReply packet assume this is a client initiated shutdown
Shutdown(DisconnectType.ClientInitiated);
}
else
{
Logger.Log("Invalid Session or Agent ID received in Logout Reply... ignoring", Helpers.LogLevel.Warning, Client);
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void StartPingCheckHandler(object sender, PacketReceivedEventArgs e)
{
StartPingCheckPacket incomingPing = (StartPingCheckPacket)e.Packet;
CompletePingCheckPacket ping = new CompletePingCheckPacket();
ping.PingID.PingID = incomingPing.PingID.PingID;
ping.Header.Reliable = false;
// TODO: We can use OldestUnacked to correct transmission errors
// I don't think that's right. As far as I can tell, the Viewer
// only uses this to prune its duplicate-checking buffer. -bushing
SendPacket(ping, e.Simulator);
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void CompletePingCheckHandler(object sender, PacketReceivedEventArgs e)
{
CompletePingCheckPacket pong = (CompletePingCheckPacket)e.Packet;
//String retval = "Pong2: " + (Environment.TickCount - e.Simulator.Stats.LastPingSent);
//if ((pong.PingID.PingID - e.Simulator.Stats.LastPingID + 1) != 0)
// retval += " (gap of " + (pong.PingID.PingID - e.Simulator.Stats.LastPingID + 1) + ")";
e.Simulator.Stats.LastLag = Environment.TickCount - e.Simulator.Stats.LastPingSent;
e.Simulator.Stats.ReceivedPongs++;
// Client.Log(retval, Helpers.LogLevel.Info);
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void SimStatsHandler(object sender, PacketReceivedEventArgs e)
{
if (!Client.Settings.ENABLE_SIMSTATS)
{
return;
}
SimStatsPacket stats = (SimStatsPacket)e.Packet;
for (int i = 0; i < stats.Stat.Length; i++)
{
SimStatsPacket.StatBlock s = stats.Stat[i];
switch (s.StatID)
{
case 0:
e.Simulator.Stats.Dilation = s.StatValue;
break;
case 1:
e.Simulator.Stats.FPS = Convert.ToInt32(s.StatValue);
break;
case 2:
e.Simulator.Stats.PhysicsFPS = s.StatValue;
break;
case 3:
e.Simulator.Stats.AgentUpdates = s.StatValue;
break;
case 4:
e.Simulator.Stats.FrameTime = s.StatValue;
break;
case 5:
e.Simulator.Stats.NetTime = s.StatValue;
break;
case 6:
e.Simulator.Stats.OtherTime = s.StatValue;
break;
case 7:
e.Simulator.Stats.PhysicsTime = s.StatValue;
break;
case 8:
e.Simulator.Stats.AgentTime = s.StatValue;
break;
case 9:
e.Simulator.Stats.ImageTime = s.StatValue;
break;
case 10:
e.Simulator.Stats.ScriptTime = s.StatValue;
break;
case 11:
e.Simulator.Stats.Objects = Convert.ToInt32(s.StatValue);
break;
case 12:
e.Simulator.Stats.ScriptedObjects = Convert.ToInt32(s.StatValue);
break;
case 13:
e.Simulator.Stats.Agents = Convert.ToInt32(s.StatValue);
break;
case 14:
e.Simulator.Stats.ChildAgents = Convert.ToInt32(s.StatValue);
break;
case 15:
e.Simulator.Stats.ActiveScripts = Convert.ToInt32(s.StatValue);
break;
case 16:
e.Simulator.Stats.LSLIPS = Convert.ToInt32(s.StatValue);
break;
case 17:
e.Simulator.Stats.INPPS = Convert.ToInt32(s.StatValue);
break;
case 18:
e.Simulator.Stats.OUTPPS = Convert.ToInt32(s.StatValue);
break;
case 19:
e.Simulator.Stats.PendingDownloads = Convert.ToInt32(s.StatValue);
break;
case 20:
e.Simulator.Stats.PendingUploads = Convert.ToInt32(s.StatValue);
break;
case 21:
e.Simulator.Stats.VirtualSize = Convert.ToInt32(s.StatValue);
break;
case 22:
e.Simulator.Stats.ResidentSize = Convert.ToInt32(s.StatValue);
break;
case 23:
e.Simulator.Stats.PendingLocalUploads = Convert.ToInt32(s.StatValue);
break;
case 24:
e.Simulator.Stats.UnackedBytes = Convert.ToInt32(s.StatValue);
break;
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void RegionHandshakeHandler(object sender, PacketReceivedEventArgs e)
{
RegionHandshakePacket handshake = (RegionHandshakePacket)e.Packet;
Simulator simulator = e.Simulator;
e.Simulator.ID = handshake.RegionInfo.CacheID;
simulator.IsEstateManager = handshake.RegionInfo.IsEstateManager;
simulator.Name = Utils.BytesToString(handshake.RegionInfo.SimName);
simulator.SimOwner = handshake.RegionInfo.SimOwner;
simulator.TerrainBase0 = handshake.RegionInfo.TerrainBase0;
simulator.TerrainBase1 = handshake.RegionInfo.TerrainBase1;
simulator.TerrainBase2 = handshake.RegionInfo.TerrainBase2;
simulator.TerrainBase3 = handshake.RegionInfo.TerrainBase3;
simulator.TerrainDetail0 = handshake.RegionInfo.TerrainDetail0;
simulator.TerrainDetail1 = handshake.RegionInfo.TerrainDetail1;
simulator.TerrainDetail2 = handshake.RegionInfo.TerrainDetail2;
simulator.TerrainDetail3 = handshake.RegionInfo.TerrainDetail3;
simulator.TerrainHeightRange00 = handshake.RegionInfo.TerrainHeightRange00;
simulator.TerrainHeightRange01 = handshake.RegionInfo.TerrainHeightRange01;
simulator.TerrainHeightRange10 = handshake.RegionInfo.TerrainHeightRange10;
simulator.TerrainHeightRange11 = handshake.RegionInfo.TerrainHeightRange11;
simulator.TerrainStartHeight00 = handshake.RegionInfo.TerrainStartHeight00;
simulator.TerrainStartHeight01 = handshake.RegionInfo.TerrainStartHeight01;
simulator.TerrainStartHeight10 = handshake.RegionInfo.TerrainStartHeight10;
simulator.TerrainStartHeight11 = handshake.RegionInfo.TerrainStartHeight11;
simulator.WaterHeight = handshake.RegionInfo.WaterHeight;
simulator.Flags = (RegionFlags)handshake.RegionInfo.RegionFlags;
simulator.BillableFactor = handshake.RegionInfo.BillableFactor;
simulator.Access = (SimAccess)handshake.RegionInfo.SimAccess;
simulator.RegionID = handshake.RegionInfo2.RegionID;
simulator.ColoLocation = Utils.BytesToString(handshake.RegionInfo3.ColoName);
simulator.CPUClass = handshake.RegionInfo3.CPUClassID;
simulator.CPURatio = handshake.RegionInfo3.CPURatio;
simulator.ProductName = Utils.BytesToString(handshake.RegionInfo3.ProductName);
simulator.ProductSku = Utils.BytesToString(handshake.RegionInfo3.ProductSKU);
if (handshake.RegionInfo4 != null && handshake.RegionInfo4.Length > 0)
{
simulator.Protocols = (RegionProtocols)handshake.RegionInfo4[0].RegionProtocols;
// Yes, overwrite region flags if we have extended version of them
simulator.Flags = (RegionFlags)handshake.RegionInfo4[0].RegionFlagsExtended;
}
// Send a RegionHandshakeReply
RegionHandshakeReplyPacket reply = new RegionHandshakeReplyPacket();
reply.AgentData.AgentID = Client.Self.AgentID;
reply.AgentData.SessionID = Client.Self.SessionID;
reply.RegionInfo.Flags = (uint)RegionProtocols.SelfAppearanceSupport;
SendPacket(reply, simulator);
// We're officially connected to this sim
simulator.connected = true;
simulator.handshakeComplete = true;
simulator.ConnectedEvent.Set();
}
protected void EnableSimulatorHandler(string capsKey, IMessage message, Simulator simulator)
{
if (!Client.Settings.MULTIPLE_SIMS) return;
EnableSimulatorMessage msg = (EnableSimulatorMessage)message;
for (int i = 0; i < msg.Simulators.Length; i++)
{
IPAddress ip = msg.Simulators[i].IP;
ushort port = (ushort)msg.Simulators[i].Port;
ulong handle = msg.Simulators[i].RegionHandle;
IPEndPoint endPoint = new IPEndPoint(ip, port);
if (FindSimulator(endPoint) != null) return;
if (Connect(ip, port, handle, false, null) == null)
{
Logger.Log("Unabled to connect to new sim " + ip + ":" + port,
Helpers.LogLevel.Error, Client);
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void DisableSimulatorHandler(object sender, PacketReceivedEventArgs e)
{
DisconnectSim(e.Simulator, false);
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void KickUserHandler(object sender, PacketReceivedEventArgs e)
{
string message = Utils.BytesToString(((KickUserPacket)e.Packet).UserInfo.Reason);
// Shutdown the network layer
Shutdown(DisconnectType.ServerInitiated, message);
}
#endregion Packet Callbacks
}
#region EventArgs
public class PacketReceivedEventArgs : EventArgs
{
private readonly Packet m_Packet;
private readonly Simulator m_Simulator;
public Packet Packet { get { return m_Packet; } }
public Simulator Simulator { get { return m_Simulator; } }
public PacketReceivedEventArgs(Packet packet, Simulator simulator)
{
this.m_Packet = packet;
this.m_Simulator = simulator;
}
}
public class LoggedOutEventArgs : EventArgs
{
private readonly List<UUID> m_InventoryItems;
public List<UUID> InventoryItems;
public LoggedOutEventArgs(List<UUID> inventoryItems)
{
this.m_InventoryItems = inventoryItems;
}
}
public class PacketSentEventArgs : EventArgs
{
private readonly byte[] m_Data;
private readonly int m_SentBytes;
private readonly Simulator m_Simulator;
public byte[] Data { get { return m_Data; } }
public int SentBytes { get { return m_SentBytes; } }
public Simulator Simulator { get { return m_Simulator; } }
public PacketSentEventArgs(byte[] data, int bytesSent, Simulator simulator)
{
this.m_Data = data;
this.m_SentBytes = bytesSent;
this.m_Simulator = simulator;
}
}
public class SimConnectingEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
private bool m_Cancel;
public Simulator Simulator { get { return m_Simulator; } }
public bool Cancel
{
get { return m_Cancel; }
set { m_Cancel = value; }
}
public SimConnectingEventArgs(Simulator simulator)
{
this.m_Simulator = simulator;
this.m_Cancel = false;
}
}
public class SimConnectedEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
public Simulator Simulator { get { return m_Simulator; } }
public SimConnectedEventArgs(Simulator simulator)
{
this.m_Simulator = simulator;
}
}
public class SimDisconnectedEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
private readonly NetworkManager.DisconnectType m_Reason;
public Simulator Simulator { get { return m_Simulator; } }
public NetworkManager.DisconnectType Reason { get { return m_Reason; } }
public SimDisconnectedEventArgs(Simulator simulator, NetworkManager.DisconnectType reason)
{
this.m_Simulator = simulator;
this.m_Reason = reason;
}
}
public class DisconnectedEventArgs : EventArgs
{
private readonly NetworkManager.DisconnectType m_Reason;
private readonly String m_Message;
public NetworkManager.DisconnectType Reason { get { return m_Reason; } }
public String Message { get { return m_Message; } }
public DisconnectedEventArgs(NetworkManager.DisconnectType reason, String message)
{
this.m_Reason = reason;
this.m_Message = message;
}
}
public class SimChangedEventArgs : EventArgs
{
private readonly Simulator m_PreviousSimulator;
public Simulator PreviousSimulator { get { return m_PreviousSimulator; } }
public SimChangedEventArgs(Simulator previousSimulator)
{
this.m_PreviousSimulator = previousSimulator;
}
}
public class EventQueueRunningEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
public Simulator Simulator { get { return m_Simulator; } }
public EventQueueRunningEventArgs(Simulator simulator)
{
this.m_Simulator = simulator;
}
}
#endregion
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Provisioning.Cloud.Workflow.AppWebWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* [The "BSD licence"]
* Copyright (c) 2005-2008 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Antlr.Runtime.Tree {
using System.Collections.Generic;
using IList = System.Collections.IList;
/** <summary>
* A generic list of elements tracked in an alternative to be used in
* a -> rewrite rule. We need to subclass to fill in the next() method,
* which returns either an AST node wrapped around a token payload or
* an existing subtree.
* </summary>
*
* <remarks>
* Once you start next()ing, do not try to add more elements. It will
* break the cursor tracking I believe.
*
* TODO: add mechanism to detect/puke on modification after reading from stream
* </remarks>
*
* <see cref="RewriteRuleSubtreeStream"/>
* <see cref="RewriteRuleTokenStream"/>
*/
[System.Serializable]
public abstract class RewriteRuleElementStream {
/** <summary>
* Cursor 0..n-1. If singleElement!=null, cursor is 0 until you next(),
* which bumps it to 1 meaning no more elements.
* </summary>
*/
protected int cursor = 0;
/** <summary>Track single elements w/o creating a list. Upon 2nd add, alloc list */
protected object singleElement;
/** <summary>The list of tokens or subtrees we are tracking */
protected IList elements;
/** <summary>Once a node / subtree has been used in a stream, it must be dup'd
* from then on. Streams are reset after subrules so that the streams
* can be reused in future subrules. So, reset must set a dirty bit.
* If dirty, then next() always returns a dup.
*
* I wanted to use "naughty bit" here, but couldn't think of a way
* to use "naughty".
*/
protected bool dirty = false;
/** <summary>The element or stream description; usually has name of the token or
* rule reference that this list tracks. Can include rulename too, but
* the exception would track that info.
*/
protected string elementDescription;
protected ITreeAdaptor adaptor;
public RewriteRuleElementStream(ITreeAdaptor adaptor, string elementDescription) {
this.elementDescription = elementDescription;
this.adaptor = adaptor;
}
/** <summary>Create a stream with one element</summary> */
public RewriteRuleElementStream(ITreeAdaptor adaptor, string elementDescription, object oneElement)
: this(adaptor, elementDescription) {
Add(oneElement);
}
/** <summary>Create a stream, but feed off an existing list</summary> */
public RewriteRuleElementStream(ITreeAdaptor adaptor, string elementDescription, IList elements)
: this(adaptor, elementDescription) {
this.singleElement = null;
this.elements = elements;
}
/** <summary>
* Reset the condition of this stream so that it appears we have
* not consumed any of its elements. Elements themselves are untouched.
* Once we reset the stream, any future use will need duplicates. Set
* the dirty bit.
* </summary>
*/
public virtual void Reset() {
cursor = 0;
dirty = true;
}
public virtual void Add(object el) {
//System.out.println("add '"+elementDescription+"' is "+el);
if (el == null) {
return;
}
if (elements != null) { // if in list, just add
elements.Add(el);
return;
}
if (singleElement == null) { // no elements yet, track w/o list
singleElement = el;
return;
}
// adding 2nd element, move to list
elements = new List<object>(5);
elements.Add(singleElement);
singleElement = null;
elements.Add(el);
}
/** <summary>
* Return the next element in the stream. If out of elements, throw
* an exception unless size()==1. If size is 1, then return elements[0].
* Return a duplicate node/subtree if stream is out of elements and
* size==1. If we've already used the element, dup (dirty bit set).
* </summary>
*/
public virtual object NextTree() {
int n = Count;
if (dirty || (cursor >= n && n == 1)) {
// if out of elements and size is 1, dup
object el = NextCore();
return Dup(el);
}
// test size above then fetch
object el2 = NextCore();
return el2;
}
/** <summary>
* Do the work of getting the next element, making sure that it's
* a tree node or subtree. Deal with the optimization of single-
* element list versus list of size > 1. Throw an exception
* if the stream is empty or we're out of elements and size>1.
* protected so you can override in a subclass if necessary.
* </summary>
*/
protected virtual object NextCore() {
int n = Count;
if (n == 0) {
throw new RewriteEmptyStreamException(elementDescription);
}
if (cursor >= n) { // out of elements?
if (n == 1) { // if size is 1, it's ok; return and we'll dup
return ToTree(singleElement);
}
// out of elements and size was not 1, so we can't dup
throw new RewriteCardinalityException(elementDescription);
}
// we have elements
if (singleElement != null) {
cursor++; // move cursor even for single element list
return ToTree(singleElement);
}
// must have more than one in list, pull from elements
object o = ToTree(elements[cursor]);
cursor++;
return o;
}
/** <summary>
* When constructing trees, sometimes we need to dup a token or AST
* subtree. Dup'ing a token means just creating another AST node
* around it. For trees, you must call the adaptor.dupTree() unless
* the element is for a tree root; then it must be a node dup.
* </summary>
*/
protected abstract object Dup(object el);
/** <summary>
* Ensure stream emits trees; tokens must be converted to AST nodes.
* AST nodes can be passed through unmolested.
* </summary>
*/
protected virtual object ToTree(object el) {
return el;
}
public virtual bool HasNext {
get {
return (singleElement != null && cursor < 1) ||
(elements != null && cursor < elements.Count);
}
}
public virtual int Count {
get {
int n = 0;
if (singleElement != null) {
n = 1;
}
if (elements != null) {
return elements.Count;
}
return n;
}
}
public virtual string Description {
get {
return elementDescription;
}
}
}
}
| |
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.CertificateRevocationListFileBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonTimeStamp))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonULong64))]
public partial class SystemCertificateRevocationListFile : iControlInterface {
public SystemCertificateRevocationListFile() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
public void create(
string [] files,
string [] paths
) {
this.Invoke("create", new object [] {
files,
paths});
}
public System.IAsyncResult Begincreate(string [] files,string [] paths, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
files,
paths}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_certificate_revocation_list_files
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
public void delete_all_certificate_revocation_list_files(
) {
this.Invoke("delete_all_certificate_revocation_list_files", new object [0]);
}
public System.IAsyncResult Begindelete_all_certificate_revocation_list_files(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_certificate_revocation_list_files", new object[0], callback, asyncState);
}
public void Enddelete_all_certificate_revocation_list_files(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_certificate_revocation_list_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
public void delete_certificate_revocation_list_file(
string [] files
) {
this.Invoke("delete_certificate_revocation_list_file", new object [] {
files});
}
public System.IAsyncResult Begindelete_certificate_revocation_list_file(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_certificate_revocation_list_file", new object[] {
files}, callback, asyncState);
}
public void Enddelete_certificate_revocation_list_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_cache_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_cache_path(
string [] files
) {
object [] results = this.Invoke("get_cache_path", new object [] {
files});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_cache_path(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cache_path", new object[] {
files}, callback, asyncState);
}
public string [] Endget_cache_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_checksum
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_checksum(
string [] files
) {
object [] results = this.Invoke("get_checksum", new object [] {
files});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_checksum(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_checksum", new object[] {
files}, callback, asyncState);
}
public string [] Endget_checksum(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_creation_time
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonTimeStamp [] get_creation_time(
string [] files
) {
object [] results = this.Invoke("get_creation_time", new object [] {
files});
return ((CommonTimeStamp [])(results[0]));
}
public System.IAsyncResult Beginget_creation_time(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_creation_time", new object[] {
files}, callback, asyncState);
}
public CommonTimeStamp [] Endget_creation_time(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonTimeStamp [])(results[0]));
}
//-----------------------------------------------------------------------
// get_creator
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_creator(
string [] files
) {
object [] results = this.Invoke("get_creator", new object [] {
files});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_creator(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_creator", new object[] {
files}, callback, asyncState);
}
public string [] Endget_creator(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_dynamic_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_dynamic_state(
string [] files
) {
object [] results = this.Invoke("get_dynamic_state", new object [] {
files});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_dynamic_state(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_dynamic_state", new object[] {
files}, callback, asyncState);
}
public CommonEnabledState [] Endget_dynamic_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mode
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_mode(
string [] files
) {
object [] results = this.Invoke("get_mode", new object [] {
files});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_mode(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mode", new object[] {
files}, callback, asyncState);
}
public long [] Endget_mode(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_modification_time
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonTimeStamp [] get_modification_time(
string [] files
) {
object [] results = this.Invoke("get_modification_time", new object [] {
files});
return ((CommonTimeStamp [])(results[0]));
}
public System.IAsyncResult Beginget_modification_time(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_modification_time", new object[] {
files}, callback, asyncState);
}
public CommonTimeStamp [] Endget_modification_time(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonTimeStamp [])(results[0]));
}
//-----------------------------------------------------------------------
// get_modifier
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_modifier(
string [] files
) {
object [] results = this.Invoke("get_modifier", new object [] {
files});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_modifier(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_modifier", new object[] {
files}, callback, asyncState);
}
public string [] Endget_modifier(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_revision
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_revision(
string [] files
) {
object [] results = this.Invoke("get_revision", new object [] {
files});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_revision(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_revision", new object[] {
files}, callback, asyncState);
}
public long [] Endget_revision(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonULong64 [] get_size(
string [] files
) {
object [] results = this.Invoke("get_size", new object [] {
files});
return ((CommonULong64 [])(results[0]));
}
public System.IAsyncResult Beginget_size(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_size", new object[] {
files}, callback, asyncState);
}
public CommonULong64 [] Endget_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonULong64 [])(results[0]));
}
//-----------------------------------------------------------------------
// get_source_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_source_path(
string [] files
) {
object [] results = this.Invoke("get_source_path", new object [] {
files});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_source_path(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_source_path", new object[] {
files}, callback, asyncState);
}
public string [] Endget_source_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_system_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_system_path(
string [] files
) {
object [] results = this.Invoke("get_system_path", new object [] {
files});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_system_path(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_system_path", new object[] {
files}, callback, asyncState);
}
public string [] Endget_system_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_system_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_system_state(
string [] files
) {
object [] results = this.Invoke("get_system_state", new object [] {
files});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_system_state(string [] files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_system_state", new object[] {
files}, callback, asyncState);
}
public CommonEnabledState [] Endget_system_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
[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]));
}
//-----------------------------------------------------------------------
// set_local_path
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/CertificateRevocationListFile",
RequestNamespace="urn:iControl:System/CertificateRevocationListFile", ResponseNamespace="urn:iControl:System/CertificateRevocationListFile")]
public void set_local_path(
string [] files,
string [] paths
) {
this.Invoke("set_local_path", new object [] {
files,
paths});
}
public System.IAsyncResult Beginset_local_path(string [] files,string [] paths, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_local_path", new object[] {
files,
paths}, callback, asyncState);
}
public void Endset_local_path(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.BigQuery.DataTransfer.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.BigQuery.DataTransfer.V1.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedDataTransferServiceClientSnippets
{
/// <summary>Snippet for GetDataSourceAsync</summary>
public async Task GetDataSourceAsync()
{
// Snippet: GetDataSourceAsync(DataSourceNameOneof,CallSettings)
// Additional: GetDataSourceAsync(DataSourceNameOneof,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
DataSourceNameOneof name = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]"));
// Make the request
DataSource response = await dataTransferServiceClient.GetDataSourceAsync(name);
// End snippet
}
/// <summary>Snippet for GetDataSource</summary>
public void GetDataSource()
{
// Snippet: GetDataSource(DataSourceNameOneof,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
DataSourceNameOneof name = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]"));
// Make the request
DataSource response = dataTransferServiceClient.GetDataSource(name);
// End snippet
}
/// <summary>Snippet for GetDataSourceAsync</summary>
public async Task GetDataSourceAsync_RequestObject()
{
// Snippet: GetDataSourceAsync(GetDataSourceRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
GetDataSourceRequest request = new GetDataSourceRequest
{
DataSourceNameOneof = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]")),
};
// Make the request
DataSource response = await dataTransferServiceClient.GetDataSourceAsync(request);
// End snippet
}
/// <summary>Snippet for GetDataSource</summary>
public void GetDataSource_RequestObject()
{
// Snippet: GetDataSource(GetDataSourceRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
GetDataSourceRequest request = new GetDataSourceRequest
{
DataSourceNameOneof = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]")),
};
// Make the request
DataSource response = dataTransferServiceClient.GetDataSource(request);
// End snippet
}
/// <summary>Snippet for ListDataSourcesAsync</summary>
public async Task ListDataSourcesAsync()
{
// Snippet: ListDataSourcesAsync(ParentNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]"));
// Make the request
PagedAsyncEnumerable<ListDataSourcesResponse, DataSource> response =
dataTransferServiceClient.ListDataSourcesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((DataSource item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListDataSourcesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (DataSource item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<DataSource> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (DataSource item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListDataSources</summary>
public void ListDataSources()
{
// Snippet: ListDataSources(ParentNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]"));
// Make the request
PagedEnumerable<ListDataSourcesResponse, DataSource> response =
dataTransferServiceClient.ListDataSources(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (DataSource item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListDataSourcesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (DataSource item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<DataSource> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (DataSource item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListDataSourcesAsync</summary>
public async Task ListDataSourcesAsync_RequestObject()
{
// Snippet: ListDataSourcesAsync(ListDataSourcesRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ListDataSourcesRequest request = new ListDataSourcesRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]")),
};
// Make the request
PagedAsyncEnumerable<ListDataSourcesResponse, DataSource> response =
dataTransferServiceClient.ListDataSourcesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((DataSource item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListDataSourcesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (DataSource item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<DataSource> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (DataSource item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListDataSources</summary>
public void ListDataSources_RequestObject()
{
// Snippet: ListDataSources(ListDataSourcesRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ListDataSourcesRequest request = new ListDataSourcesRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]")),
};
// Make the request
PagedEnumerable<ListDataSourcesResponse, DataSource> response =
dataTransferServiceClient.ListDataSources(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (DataSource item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListDataSourcesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (DataSource item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<DataSource> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (DataSource item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CreateTransferConfigAsync</summary>
public async Task CreateTransferConfigAsync()
{
// Snippet: CreateTransferConfigAsync(ParentNameOneof,TransferConfig,CallSettings)
// Additional: CreateTransferConfigAsync(ParentNameOneof,TransferConfig,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]"));
TransferConfig transferConfig = new TransferConfig();
// Make the request
TransferConfig response = await dataTransferServiceClient.CreateTransferConfigAsync(parent, transferConfig);
// End snippet
}
/// <summary>Snippet for CreateTransferConfig</summary>
public void CreateTransferConfig()
{
// Snippet: CreateTransferConfig(ParentNameOneof,TransferConfig,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]"));
TransferConfig transferConfig = new TransferConfig();
// Make the request
TransferConfig response = dataTransferServiceClient.CreateTransferConfig(parent, transferConfig);
// End snippet
}
/// <summary>Snippet for CreateTransferConfigAsync</summary>
public async Task CreateTransferConfigAsync_RequestObject()
{
// Snippet: CreateTransferConfigAsync(CreateTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
CreateTransferConfigRequest request = new CreateTransferConfigRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]")),
TransferConfig = new TransferConfig(),
};
// Make the request
TransferConfig response = await dataTransferServiceClient.CreateTransferConfigAsync(request);
// End snippet
}
/// <summary>Snippet for CreateTransferConfig</summary>
public void CreateTransferConfig_RequestObject()
{
// Snippet: CreateTransferConfig(CreateTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
CreateTransferConfigRequest request = new CreateTransferConfigRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]")),
TransferConfig = new TransferConfig(),
};
// Make the request
TransferConfig response = dataTransferServiceClient.CreateTransferConfig(request);
// End snippet
}
/// <summary>Snippet for UpdateTransferConfigAsync</summary>
public async Task UpdateTransferConfigAsync()
{
// Snippet: UpdateTransferConfigAsync(TransferConfig,FieldMask,CallSettings)
// Additional: UpdateTransferConfigAsync(TransferConfig,FieldMask,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
TransferConfig transferConfig = new TransferConfig();
FieldMask updateMask = new FieldMask();
// Make the request
TransferConfig response = await dataTransferServiceClient.UpdateTransferConfigAsync(transferConfig, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateTransferConfig</summary>
public void UpdateTransferConfig()
{
// Snippet: UpdateTransferConfig(TransferConfig,FieldMask,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
TransferConfig transferConfig = new TransferConfig();
FieldMask updateMask = new FieldMask();
// Make the request
TransferConfig response = dataTransferServiceClient.UpdateTransferConfig(transferConfig, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateTransferConfigAsync</summary>
public async Task UpdateTransferConfigAsync_RequestObject()
{
// Snippet: UpdateTransferConfigAsync(UpdateTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateTransferConfigRequest request = new UpdateTransferConfigRequest
{
TransferConfig = new TransferConfig(),
UpdateMask = new FieldMask(),
};
// Make the request
TransferConfig response = await dataTransferServiceClient.UpdateTransferConfigAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateTransferConfig</summary>
public void UpdateTransferConfig_RequestObject()
{
// Snippet: UpdateTransferConfig(UpdateTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
UpdateTransferConfigRequest request = new UpdateTransferConfigRequest
{
TransferConfig = new TransferConfig(),
UpdateMask = new FieldMask(),
};
// Make the request
TransferConfig response = dataTransferServiceClient.UpdateTransferConfig(request);
// End snippet
}
/// <summary>Snippet for DeleteTransferConfigAsync</summary>
public async Task DeleteTransferConfigAsync()
{
// Snippet: DeleteTransferConfigAsync(TransferConfigNameOneof,CallSettings)
// Additional: DeleteTransferConfigAsync(TransferConfigNameOneof,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
TransferConfigNameOneof name = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
// Make the request
await dataTransferServiceClient.DeleteTransferConfigAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteTransferConfig</summary>
public void DeleteTransferConfig()
{
// Snippet: DeleteTransferConfig(TransferConfigNameOneof,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
TransferConfigNameOneof name = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
// Make the request
dataTransferServiceClient.DeleteTransferConfig(name);
// End snippet
}
/// <summary>Snippet for DeleteTransferConfigAsync</summary>
public async Task DeleteTransferConfigAsync_RequestObject()
{
// Snippet: DeleteTransferConfigAsync(DeleteTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteTransferConfigRequest request = new DeleteTransferConfigRequest
{
TransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
};
// Make the request
await dataTransferServiceClient.DeleteTransferConfigAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteTransferConfig</summary>
public void DeleteTransferConfig_RequestObject()
{
// Snippet: DeleteTransferConfig(DeleteTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
DeleteTransferConfigRequest request = new DeleteTransferConfigRequest
{
TransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
};
// Make the request
dataTransferServiceClient.DeleteTransferConfig(request);
// End snippet
}
/// <summary>Snippet for GetTransferConfigAsync</summary>
public async Task GetTransferConfigAsync()
{
// Snippet: GetTransferConfigAsync(TransferConfigNameOneof,CallSettings)
// Additional: GetTransferConfigAsync(TransferConfigNameOneof,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
TransferConfigNameOneof name = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
// Make the request
TransferConfig response = await dataTransferServiceClient.GetTransferConfigAsync(name);
// End snippet
}
/// <summary>Snippet for GetTransferConfig</summary>
public void GetTransferConfig()
{
// Snippet: GetTransferConfig(TransferConfigNameOneof,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
TransferConfigNameOneof name = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
// Make the request
TransferConfig response = dataTransferServiceClient.GetTransferConfig(name);
// End snippet
}
/// <summary>Snippet for GetTransferConfigAsync</summary>
public async Task GetTransferConfigAsync_RequestObject()
{
// Snippet: GetTransferConfigAsync(GetTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
GetTransferConfigRequest request = new GetTransferConfigRequest
{
TransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
};
// Make the request
TransferConfig response = await dataTransferServiceClient.GetTransferConfigAsync(request);
// End snippet
}
/// <summary>Snippet for GetTransferConfig</summary>
public void GetTransferConfig_RequestObject()
{
// Snippet: GetTransferConfig(GetTransferConfigRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
GetTransferConfigRequest request = new GetTransferConfigRequest
{
TransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
};
// Make the request
TransferConfig response = dataTransferServiceClient.GetTransferConfig(request);
// End snippet
}
/// <summary>Snippet for ListTransferConfigsAsync</summary>
public async Task ListTransferConfigsAsync()
{
// Snippet: ListTransferConfigsAsync(ParentNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]"));
// Make the request
PagedAsyncEnumerable<ListTransferConfigsResponse, TransferConfig> response =
dataTransferServiceClient.ListTransferConfigsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TransferConfig item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTransferConfigsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferConfig item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferConfig> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferConfig item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferConfigs</summary>
public void ListTransferConfigs()
{
// Snippet: ListTransferConfigs(ParentNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]"));
// Make the request
PagedEnumerable<ListTransferConfigsResponse, TransferConfig> response =
dataTransferServiceClient.ListTransferConfigs(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (TransferConfig item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTransferConfigsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferConfig item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferConfig> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferConfig item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferConfigsAsync</summary>
public async Task ListTransferConfigsAsync_RequestObject()
{
// Snippet: ListTransferConfigsAsync(ListTransferConfigsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ListTransferConfigsRequest request = new ListTransferConfigsRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]")),
};
// Make the request
PagedAsyncEnumerable<ListTransferConfigsResponse, TransferConfig> response =
dataTransferServiceClient.ListTransferConfigsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TransferConfig item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTransferConfigsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferConfig item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferConfig> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferConfig item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferConfigs</summary>
public void ListTransferConfigs_RequestObject()
{
// Snippet: ListTransferConfigs(ListTransferConfigsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ListTransferConfigsRequest request = new ListTransferConfigsRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new LocationName("[PROJECT]", "[LOCATION]")),
};
// Make the request
PagedEnumerable<ListTransferConfigsResponse, TransferConfig> response =
dataTransferServiceClient.ListTransferConfigs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TransferConfig item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTransferConfigsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferConfig item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferConfig> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferConfig item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ScheduleTransferRunsAsync</summary>
public async Task ScheduleTransferRunsAsync()
{
// Snippet: ScheduleTransferRunsAsync(TransferConfigNameOneof,Timestamp,Timestamp,CallSettings)
// Additional: ScheduleTransferRunsAsync(TransferConfigNameOneof,Timestamp,Timestamp,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
TransferConfigNameOneof parent = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
Timestamp startTime = new Timestamp();
Timestamp endTime = new Timestamp();
// Make the request
ScheduleTransferRunsResponse response = await dataTransferServiceClient.ScheduleTransferRunsAsync(parent, startTime, endTime);
// End snippet
}
/// <summary>Snippet for ScheduleTransferRuns</summary>
public void ScheduleTransferRuns()
{
// Snippet: ScheduleTransferRuns(TransferConfigNameOneof,Timestamp,Timestamp,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
TransferConfigNameOneof parent = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
Timestamp startTime = new Timestamp();
Timestamp endTime = new Timestamp();
// Make the request
ScheduleTransferRunsResponse response = dataTransferServiceClient.ScheduleTransferRuns(parent, startTime, endTime);
// End snippet
}
/// <summary>Snippet for ScheduleTransferRunsAsync</summary>
public async Task ScheduleTransferRunsAsync_RequestObject()
{
// Snippet: ScheduleTransferRunsAsync(ScheduleTransferRunsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ScheduleTransferRunsRequest request = new ScheduleTransferRunsRequest
{
ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
StartTime = new Timestamp(),
EndTime = new Timestamp(),
};
// Make the request
ScheduleTransferRunsResponse response = await dataTransferServiceClient.ScheduleTransferRunsAsync(request);
// End snippet
}
/// <summary>Snippet for ScheduleTransferRuns</summary>
public void ScheduleTransferRuns_RequestObject()
{
// Snippet: ScheduleTransferRuns(ScheduleTransferRunsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ScheduleTransferRunsRequest request = new ScheduleTransferRunsRequest
{
ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
StartTime = new Timestamp(),
EndTime = new Timestamp(),
};
// Make the request
ScheduleTransferRunsResponse response = dataTransferServiceClient.ScheduleTransferRuns(request);
// End snippet
}
/// <summary>Snippet for GetTransferRunAsync</summary>
public async Task GetTransferRunAsync()
{
// Snippet: GetTransferRunAsync(RunNameOneof,CallSettings)
// Additional: GetTransferRunAsync(RunNameOneof,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
RunNameOneof name = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]"));
// Make the request
TransferRun response = await dataTransferServiceClient.GetTransferRunAsync(name);
// End snippet
}
/// <summary>Snippet for GetTransferRun</summary>
public void GetTransferRun()
{
// Snippet: GetTransferRun(RunNameOneof,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
RunNameOneof name = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]"));
// Make the request
TransferRun response = dataTransferServiceClient.GetTransferRun(name);
// End snippet
}
/// <summary>Snippet for GetTransferRunAsync</summary>
public async Task GetTransferRunAsync_RequestObject()
{
// Snippet: GetTransferRunAsync(GetTransferRunRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
GetTransferRunRequest request = new GetTransferRunRequest
{
RunNameOneof = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]")),
};
// Make the request
TransferRun response = await dataTransferServiceClient.GetTransferRunAsync(request);
// End snippet
}
/// <summary>Snippet for GetTransferRun</summary>
public void GetTransferRun_RequestObject()
{
// Snippet: GetTransferRun(GetTransferRunRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
GetTransferRunRequest request = new GetTransferRunRequest
{
RunNameOneof = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]")),
};
// Make the request
TransferRun response = dataTransferServiceClient.GetTransferRun(request);
// End snippet
}
/// <summary>Snippet for DeleteTransferRunAsync</summary>
public async Task DeleteTransferRunAsync()
{
// Snippet: DeleteTransferRunAsync(RunNameOneof,CallSettings)
// Additional: DeleteTransferRunAsync(RunNameOneof,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
RunNameOneof name = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]"));
// Make the request
await dataTransferServiceClient.DeleteTransferRunAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteTransferRun</summary>
public void DeleteTransferRun()
{
// Snippet: DeleteTransferRun(RunNameOneof,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
RunNameOneof name = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]"));
// Make the request
dataTransferServiceClient.DeleteTransferRun(name);
// End snippet
}
/// <summary>Snippet for DeleteTransferRunAsync</summary>
public async Task DeleteTransferRunAsync_RequestObject()
{
// Snippet: DeleteTransferRunAsync(DeleteTransferRunRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteTransferRunRequest request = new DeleteTransferRunRequest
{
RunNameOneof = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]")),
};
// Make the request
await dataTransferServiceClient.DeleteTransferRunAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteTransferRun</summary>
public void DeleteTransferRun_RequestObject()
{
// Snippet: DeleteTransferRun(DeleteTransferRunRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
DeleteTransferRunRequest request = new DeleteTransferRunRequest
{
RunNameOneof = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]")),
};
// Make the request
dataTransferServiceClient.DeleteTransferRun(request);
// End snippet
}
/// <summary>Snippet for ListTransferRunsAsync</summary>
public async Task ListTransferRunsAsync()
{
// Snippet: ListTransferRunsAsync(TransferConfigNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
TransferConfigNameOneof parent = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
// Make the request
PagedAsyncEnumerable<ListTransferRunsResponse, TransferRun> response =
dataTransferServiceClient.ListTransferRunsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TransferRun item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTransferRunsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferRun item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferRun> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferRun item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferRuns</summary>
public void ListTransferRuns()
{
// Snippet: ListTransferRuns(TransferConfigNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
TransferConfigNameOneof parent = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]"));
// Make the request
PagedEnumerable<ListTransferRunsResponse, TransferRun> response =
dataTransferServiceClient.ListTransferRuns(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (TransferRun item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTransferRunsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferRun item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferRun> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferRun item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferRunsAsync</summary>
public async Task ListTransferRunsAsync_RequestObject()
{
// Snippet: ListTransferRunsAsync(ListTransferRunsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ListTransferRunsRequest request = new ListTransferRunsRequest
{
ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
};
// Make the request
PagedAsyncEnumerable<ListTransferRunsResponse, TransferRun> response =
dataTransferServiceClient.ListTransferRunsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TransferRun item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTransferRunsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferRun item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferRun> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferRun item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferRuns</summary>
public void ListTransferRuns_RequestObject()
{
// Snippet: ListTransferRuns(ListTransferRunsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ListTransferRunsRequest request = new ListTransferRunsRequest
{
ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new LocationTransferConfigName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]")),
};
// Make the request
PagedEnumerable<ListTransferRunsResponse, TransferRun> response =
dataTransferServiceClient.ListTransferRuns(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TransferRun item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTransferRunsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferRun item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferRun> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferRun item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferLogsAsync</summary>
public async Task ListTransferLogsAsync()
{
// Snippet: ListTransferLogsAsync(RunNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
RunNameOneof parent = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]"));
// Make the request
PagedAsyncEnumerable<ListTransferLogsResponse, TransferMessage> response =
dataTransferServiceClient.ListTransferLogsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TransferMessage item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTransferLogsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferMessage item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferMessage> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferMessage item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferLogs</summary>
public void ListTransferLogs()
{
// Snippet: ListTransferLogs(RunNameOneof,string,int?,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
RunNameOneof parent = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]"));
// Make the request
PagedEnumerable<ListTransferLogsResponse, TransferMessage> response =
dataTransferServiceClient.ListTransferLogs(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (TransferMessage item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTransferLogsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferMessage item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferMessage> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferMessage item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferLogsAsync</summary>
public async Task ListTransferLogsAsync_RequestObject()
{
// Snippet: ListTransferLogsAsync(ListTransferLogsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
ListTransferLogsRequest request = new ListTransferLogsRequest
{
ParentAsRunNameOneof = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]")),
};
// Make the request
PagedAsyncEnumerable<ListTransferLogsResponse, TransferMessage> response =
dataTransferServiceClient.ListTransferLogsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TransferMessage item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTransferLogsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferMessage item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferMessage> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferMessage item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTransferLogs</summary>
public void ListTransferLogs_RequestObject()
{
// Snippet: ListTransferLogs(ListTransferLogsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
ListTransferLogsRequest request = new ListTransferLogsRequest
{
ParentAsRunNameOneof = RunNameOneof.From(new LocationRunName("[PROJECT]", "[LOCATION]", "[TRANSFER_CONFIG]", "[RUN]")),
};
// Make the request
PagedEnumerable<ListTransferLogsResponse, TransferMessage> response =
dataTransferServiceClient.ListTransferLogs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TransferMessage item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTransferLogsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TransferMessage item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TransferMessage> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TransferMessage item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CheckValidCredsAsync</summary>
public async Task CheckValidCredsAsync()
{
// Snippet: CheckValidCredsAsync(DataSourceNameOneof,CallSettings)
// Additional: CheckValidCredsAsync(DataSourceNameOneof,CancellationToken)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
DataSourceNameOneof name = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]"));
// Make the request
CheckValidCredsResponse response = await dataTransferServiceClient.CheckValidCredsAsync(name);
// End snippet
}
/// <summary>Snippet for CheckValidCreds</summary>
public void CheckValidCreds()
{
// Snippet: CheckValidCreds(DataSourceNameOneof,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
DataSourceNameOneof name = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]"));
// Make the request
CheckValidCredsResponse response = dataTransferServiceClient.CheckValidCreds(name);
// End snippet
}
/// <summary>Snippet for CheckValidCredsAsync</summary>
public async Task CheckValidCredsAsync_RequestObject()
{
// Snippet: CheckValidCredsAsync(CheckValidCredsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
CheckValidCredsRequest request = new CheckValidCredsRequest
{
DataSourceNameOneof = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]")),
};
// Make the request
CheckValidCredsResponse response = await dataTransferServiceClient.CheckValidCredsAsync(request);
// End snippet
}
/// <summary>Snippet for CheckValidCreds</summary>
public void CheckValidCreds_RequestObject()
{
// Snippet: CheckValidCreds(CheckValidCredsRequest,CallSettings)
// Create client
DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.Create();
// Initialize request argument(s)
CheckValidCredsRequest request = new CheckValidCredsRequest
{
DataSourceNameOneof = DataSourceNameOneof.From(new LocationDataSourceName("[PROJECT]", "[LOCATION]", "[DATA_SOURCE]")),
};
// Make the request
CheckValidCredsResponse response = dataTransferServiceClient.CheckValidCreds(request);
// End snippet
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
namespace Microsoft.VisualStudio.Pug
{
/// <summary>
/// A collection of text ranges or objects that implement <seealso cref="ITextRange"/>.
/// Ranges must not overlap. Can be sorted by range start positions. Can be searched
/// in order to locate range that contains given position or range that starts
/// at a given position. The search is a binary search. Collection implements
/// <seealso cref="ITextRangeCollection"/>
/// </summary>
/// <typeparam name="T">A class or an interface that derives from <seealso cref="ITextRange"/></typeparam>
[DebuggerDisplay("Count={Count}")]
internal class TextRangeCollection<T> : IEnumerable<T>, ITextRangeCollection<T> where T : ITextRange
{
private static readonly IList<T> _emptyList = Array.Empty<T>();
private List<T> _items = new List<T>();
#region Construction
public TextRangeCollection()
{
}
public TextRangeCollection(IEnumerable<T> ranges)
{
Add(ranges);
Sort();
}
#endregion
#region ITextRange
public int Start => this.Count > 0 ? this[0].Start : 0;
public int End => this.Count > 0 ? this[this.Count - 1].End : 0;
public int Length => this.End - this.Start;
public virtual bool Contains(int position)
{
return TextRange.Contains(this, position);
}
public void Shift(int offset)
{
foreach (var ct in this._items)
{
ct.Shift(offset);
}
}
#endregion
#region ITextRangeCollection
/// <summary>
/// Number of comments in the collection.
/// </summary>
public int Count => this._items.Count;
/// <summary>
/// Sorted list of comment tokens in the document.
/// </summary>
public IList<T> Items => this._items;
/// <summary>
/// Retrieves Nth item in the collection
/// </summary>
public T this[int index] { get { return this._items[index]; } }
/// <summary>
/// Adds item to collection.
/// </summary>
/// <param name="item">Item to add</param>
public virtual void Add(T item)
{
this._items.Add(item);
}
/// <summary>
/// Add a range of items to the collection
/// </summary>
/// <param name="items">Items to add</param>
public void Add(IEnumerable<T> items)
{
this._items.AddRange(items);
}
/// <summary>
/// Returns index of item that starts at the given position if exists, -1 otherwise.
/// </summary>
/// <param name="position">Position in a text buffer</param>
/// <returns>Item index or -1 if not found</returns>
public virtual int GetItemAtPosition(int position)
{
if (this.Count == 0)
{
return -1;
}
if (position < this[0].Start)
{
return -1;
}
if (position >= this[this.Count - 1].End)
{
return -1;
}
var min = 0;
var max = this.Count - 1;
while (min <= max)
{
var mid = min + (max - min) / 2;
var item = this[mid];
if (item.Start == position)
{
return mid;
}
if (position < item.Start)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
return -1;
}
/// <summary>
/// Returns index of items that contains given position if exists, -1 otherwise.
/// </summary>
/// <param name="position">Position in a text buffer</param>
/// <returns>Item index or -1 if not found</returns>
public virtual int GetItemContaining(int position)
{
if (this.Count == 0)
{
return -1;
}
if (position < this[0].Start)
{
return -1;
}
if (position > this[this.Count - 1].End)
{
return -1;
}
var min = 0;
var max = this.Count - 1;
while (min <= max)
{
var mid = min + (max - min) / 2;
var item = this[mid];
if (item.Contains(position))
{
return mid;
}
if (mid < this.Count - 1 && item.End <= position && position < this[mid + 1].Start)
{
return -1;
}
if (position < item.Start)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
return -1;
}
/// <summary>
/// Retrieves first item that is after a given position
/// </summary>
/// <param name="position">Position in a text buffer</param>
/// <returns>Item index or -1 if not found</returns>
public virtual int GetFirstItemAfterPosition(int position)
{
if (this.Count == 0 || position > this[this.Count - 1].End)
{
return -1;
}
if (position < this[0].Start)
{
return 0;
}
var min = 0;
var max = this.Count - 1;
while (min <= max)
{
var mid = min + (max - min) / 2;
var item = this[mid];
if (item.Contains(position))
{
// Note that there may be multiple items with the same range.
// To be sure we do pick the first one, walk back until we include
// all elements containing passed position
return GetFirstElementContainingPosition(mid, position);
}
if (mid > 0 && this[mid - 1].End <= position && item.Start >= position)
{
return mid;
}
if (position < item.Start)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
return -1;
}
private int GetFirstElementContainingPosition(int index, int position)
{
for (var i = index - 1; i >= 0; i--)
{
var item = this[i];
if (!item.Contains(position))
{
index = i + 1;
break;
}
else if (i == 0)
{
return 0;
}
}
return index;
}
// assuming the item at index already contains the position
private int GetLastElementContainingPosition(int index, int position)
{
for (var i = index; i < this.Count; i++)
{
var item = this[i];
if (!item.Contains(position))
{
return i - 1;
}
}
return this.Count - 1;
}
/// <summary>
/// Retrieves first item that is after a given position
/// </summary>
/// <param name="position">Position in a text buffer</param>
/// <returns>Item index or -1 if not found</returns>
public virtual int GetLastItemBeforeOrAtPosition(int position)
{
if (this.Count == 0 || position < this[0].Start)
{
return -1;
}
if (position >= this[this.Count - 1].End)
{
return this.Count - 1;
}
var min = 0;
var max = this.Count - 1;
while (min <= max)
{
var mid = min + (max - min) / 2;
var item = this[mid];
if (item.Contains(position))
{
// Note that there may be multiple items with the same range.
// To be sure we do pick the first one, walk back until we include
// all elements containing passed position
return GetLastElementContainingPosition(mid, position);
}
// position is in between two tokens
if (mid > 0 && this[mid - 1].End <= position && item.Start >= position)
{
return mid - 1;
}
if (position < item.Start)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
return -1;
}
/// <summary>
/// Retrieves first item that is before a given position, not intersecting or touching with position
/// </summary>
/// <param name="position">Position in a text buffer</param>
/// <returns>Item index or -1 if not found</returns>
public virtual int GetFirstItemBeforePosition(int position)
{
if (this.Count == 0 || position < this[0].End)
{
return -1;
}
var min = 0;
var lastIndex = this.Count - 1;
var max = this.Count - 1;
if (position >= this[lastIndex].End)
{
return max;
}
while (min <= max)
{
var mid = min + (max - min) / 2;
var item = this[mid];
if (item.Contains(position)) // guaranteed not to be negative by the first if in this method
{
return mid - 1;
}
if (mid < lastIndex && this[mid + 1].Start >= position && item.End <= position)
{
return mid;
}
if (position < item.Start)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
return -1;
}
/// <summary>
/// Returns index of items that contains given position if exists, -1 otherwise.
/// </summary>
/// <param name="position">Position in a text buffer</param>
/// <returns>Item index or -1 if not found</returns>
public virtual IList<int> GetItemsContainingInclusiveEnd(int position)
{
IList<int> list = new List<int>();
if (this.Count > 0 &&
position >= this[0].Start &&
position <= this[this.Count - 1].End)
{
var min = 0;
var max = this.Count - 1;
while (min <= max)
{
var mid = min + (max - min) / 2;
var item = this[mid];
if (item.Contains(position) || item.End == position)
{
list = GetItemsContainingInclusiveEndLinearFromAPoint(mid, position);
break;
}
if (mid < this.Count - 1 && item.End <= position && position < this[mid + 1].Start)
{
break;
}
if (position < item.Start)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
}
return list;
}
private IList<int> GetItemsContainingInclusiveEndLinearFromAPoint(int startingPoint, int position)
{
Debug.Assert(this.Count > 0 && startingPoint < this.Count, "Starting point not in token list");
var list = new List<int>();
for (var i = startingPoint; i >= 0; i--)
{
var item = this[i];
if (item.Contains(position) || item.End == position)
{
list.Insert(0, i);
}
else
{
break;
}
}
if (startingPoint + 1 < this.Count)
{
for (var i = startingPoint + 1; i < this.Count; i++)
{
var item = this[i];
if (item.Contains(position) || item.End == position)
{
list.Add(i);
}
else
{
break;
}
}
}
return list;
}
#region ICompositeTextRange
/// <summary>
/// Shifts all tokens at of below given position by the specified offset.
/// </summary>
public virtual void ShiftStartingFrom(int position, int offset)
{
var min = 0;
var max = this.Count - 1;
if (this.Count == 0)
{
return;
}
if (position <= this[0].Start)
{
// all children are below the shifting point
Shift(offset);
}
else
{
while (min <= max)
{
var mid = min + (max - min) / 2;
if (this[mid].Contains(position))
{
// Found: item contains start position
var composite = this[mid] as ICompositeTextRange;
if (composite != null)
{
composite.ShiftStartingFrom(position, offset);
}
else
{
var expandable = this[mid] as IExpandableTextRange;
if (expandable != null)
{
expandable.Expand(0, offset);
}
}
// Now shift all remaining siblings that are below this one
for (var i = mid + 1; i < this.Count; i++)
{
this[i].Shift(offset);
}
return;
}
else if (mid < this.Count - 1 && this[mid].End <= position && position <= this[mid + 1].Start)
{
// Between this item and the next sibling. Shift siblings
for (var i = mid + 1; i < this.Count; i++)
{
this[i].Shift(offset);
}
return;
}
// Position does not belong to this item and is not between item end and next item start
if (position < this[mid].Start)
{
// Item is after the given position. There may be better items
// before this one so limit search to the range ending in this item.
max = mid - 1;
}
else
{
// Proceed forward
min = mid + 1;
}
}
}
}
#endregion
/// <summary>
/// Finds out items that overlap a text range
/// </summary>
/// <param name="range">Text range</param>
/// <returns>List of items that overlap the range</returns>
public virtual IList<T> ItemsInRange(ITextRange range)
{
var list = _emptyList;
var first = GetItemContaining(range.Start);
if (first < 0)
{
first = GetFirstItemAfterPosition(range.Start);
}
if (first >= 0)
{
for (var i = first; i < this.Count; i++)
{
if (this._items[i].Start >= range.End)
{
break;
}
if (TextRange.Intersect(this._items[i], range))
{
if (list == _emptyList)
{
list = new List<T>();
}
list.Add(this._items[i]);
}
}
}
return list;
}
/// <summary>
/// Removes items that overlap given text range
/// </summary>
/// <param name="range">Range to remove items in</param>
/// <returns>Collection of removed items</returns>
public ICollection<T> RemoveInRange(ITextRange range)
{
return RemoveInRange(range, false);
}
/// <summary>
/// Removes items that overlap given text range
/// </summary>
/// <param name="range">Range to remove items in</param>
/// <param name="inclusiveEnds">True if range end is inclusive</param>
/// <returns>Collection of removed items</returns>
public virtual ICollection<T> RemoveInRange(ITextRange range, bool inclusiveEnds)
{
var removed = _emptyList;
var first = GetFirstItemAfterPosition(range.Start);
if (first < 0 || (!inclusiveEnds && this[first].Start >= range.End) || (inclusiveEnds && this[first].Start > range.End))
{
return removed;
}
var lastCandidate = GetLastItemBeforeOrAtPosition(range.End);
var last = -1;
if (lastCandidate < first)
{
lastCandidate = first;
}
if (!inclusiveEnds && first >= 0)
{
for (var i = lastCandidate; i >= first; i--)
{
var item = this._items[i];
if (item.Start < range.End)
{
last = i;
break;
}
}
}
else
{
last = lastCandidate;
}
if (first >= 0 && last >= 0)
{
if (removed == _emptyList)
{
removed = new List<T>();
}
for (var i = first; i <= last; i++)
{
removed.Add(this._items[i]);
}
this._items.RemoveRange(first, last - first + 1);
}
return removed;
}
/// <summary>
/// Reflects multiple changes in text to the collection
/// Items are expanded and/or shifted according to the changes
/// passed. If change affects more than one range then affected items are removed
/// </summary>
/// <param name="changes">Collection of changes. Must be non-overlapping and sorted by position.</param>
/// <param name="startInclusive">True if insertion at range start falls inside the range rather than outside.</param>
/// <returns>Collection or removed blocks</returns>
public ICollection<T> ReflectTextChange(IEnumerable<TextChangeEventArgs> changes, bool startInclusive = false)
{
var list = new List<T>();
foreach (var change in changes)
{
var removed = ReflectTextChange(change.Start, change.OldLength, change.NewLength, startInclusive);
list.AddRange(removed);
}
return list;
}
/// <summary>
/// Reflects changes in text to the collection. Items are expanded and/or
/// shifted according to the change. If change affects more than one
/// range then affected items are removed.
/// </summary>
/// <param name="start">Starting position of the change.</param>
/// <param name="oldLength">Length of the changed fragment before the change.</param>
/// <param name="newLength">Length of text fragment after the change.</param>
/// <returns>Collection or removed blocks</returns>
public ICollection<T> ReflectTextChange(int start, int oldLength, int newLength)
{
return ReflectTextChange(start, oldLength, newLength, false);
}
/// <summary>
/// Reflects changes in text to the collection. Items are expanded and/or
/// shifted according to the change. If change affects more than one
/// range then affected items are removed.
/// </summary>
/// <param name="start">Starting position of the change.</param>
/// <param name="oldLength">Length of the changed fragment before the change.</param>
/// <param name="newLength">Length of text fragment after the change.</param>
/// <param name="startInclusive">True if insertion at range start falls inside the range rather than outside.</param>
/// <returns>Collection or removed blocks</returns>
public virtual ICollection<T> ReflectTextChange(int start, int oldLength, int newLength, bool startInclusive)
{
var indexStart = GetItemContaining(start);
var indexEnd = GetItemContaining(start + oldLength);
ICollection<T> removed = _emptyList;
// Make sure that end of the deleted range is not simply touching start
// of an existing range since deleting span that is touching an existing
// range does not invalidate the existing range: |__r1__|deleted|__r2__|
if (indexEnd > indexStart && indexStart >= 0)
{
if (this[indexEnd].Start == start + oldLength)
{
indexEnd--;
}
}
if (indexStart != indexEnd || (indexStart < 0 && indexEnd < 0))
{
removed = RemoveInRange(new TextRange(start, oldLength));
}
if (this.Count > 0)
{
var offset = newLength - oldLength;
if (removed != _emptyList && removed.Count > 0)
{
indexStart = GetItemContaining(start);
}
if (indexStart >= 0)
{
// If range length is 0 it still contains the position.
// Don't try and shrink zero length ranges and instead
// shift them.
var range = this[indexStart];
if (range.Length == 0 && offset < 0)
{
range.Shift(offset);
}
else if (!startInclusive && oldLength == 0 && start == range.Start)
{
// range.Contains(start) is true but we don't want to expand
// the range if change is actually an insert right before
// the existing range like in {some text inserted}|__r1__|
range.Shift(offset);
}
else
{
// In Razor ranges may have end-inclusive set which
// may cause us to try and shrink zero-length ranges.
if (range.Length > 0 || offset > 0)
{
// In the case when range is end-inclusive as in Razor,
// and change is right at the end of the range, we may end up
// trying to shrink range that is really must be deleted.
// If offset is bigger than the range length, delete it instead.
if ((range is IExpandableTextRange) && (range.Length + offset >= 0))
{
var expandable = range as IExpandableTextRange;
expandable.Expand(0, offset);
}
else if (range is ICompositeTextRange)
{
var composite = range as ICompositeTextRange;
composite.ShiftStartingFrom(start, offset);
}
else
{
RemoveAt(indexStart);
indexStart--;
if (removed == _emptyList)
{
removed = new List<T>();
}
removed.Add(range);
}
}
}
for (var i = indexStart + 1; i < this.Count; i++)
{
this[i].Shift(offset);
}
}
else
{
ShiftStartingFrom(start, offset);
}
}
return removed;
}
public bool IsEqual(IEnumerable<T> other)
{
var otherCount = 0;
foreach (var item in other)
{
otherCount++;
}
if (this.Count != otherCount)
{
return false;
}
var i = 0;
foreach (var item in other)
{
if (this[i].Start != item.Start)
{
return false;
}
if (this[i].Length != item.Length)
{
return false;
}
i++;
}
return true;
}
public virtual void RemoveAt(int index)
{
this.Items.RemoveAt(index);
}
public virtual void RemoveRange(int startIndex, int count)
{
this._items.RemoveRange(startIndex, count);
}
public virtual void Clear()
{
this._items.Clear();
}
public virtual void ReplaceAt(int index, T newItem)
{
this._items[index] = newItem;
}
/// <summary>
/// Sorts comment collection by token start positions.
/// </summary>
public void Sort()
{
this._items.Sort(new RangeItemComparer());
}
#endregion
/// <summary>
/// Returns collection of items in an array
/// </summary>
public T[] ToArray()
{
return this._items.ToArray();
}
/// <summary>
/// Returns collection of items in a list
/// </summary>
public IList<T> ToList()
{
var list = new List<T>();
list.AddRange(this._items);
return list;
}
/// <summary>
/// Compares two collections and calculates 'changed' range. In case this collection
/// or comparand are empty, uses lowerBound and upperBound values as range
/// delimiters. Typically lowerBound is 0 and upperBound is lentgh of the file.
/// </summary>
/// <param name="otherCollection">Collection to compare to</param>
public virtual ITextRange RangeDifference(IEnumerable<ITextRange> otherCollection, int lowerBound, int upperBound)
{
if (otherCollection == null)
{
return TextRange.FromBounds(lowerBound, upperBound);
}
var other = new TextRangeCollection<ITextRange>(otherCollection);
if (this.Count == 0 && other.Count == 0)
{
return TextRange.EmptyRange;
}
if (this.Count == 0)
{
return TextRange.FromBounds(lowerBound, upperBound);
}
if (other.Count == 0)
{
return TextRange.FromBounds(lowerBound, upperBound);
}
var minCount = Math.Min(this.Count, other.Count);
var start = 0;
var end = 0;
int i, j;
for (i = 0; i < minCount; i++)
{
start = Math.Min(this[i].Start, other[i].Start);
if (this[i].Start != other[i].Start || this[i].Length != other[i].Length)
{
break;
}
}
if (i == minCount)
{
if (this.Count == other.Count)
{
return TextRange.EmptyRange;
}
if (this.Count > other.Count)
{
return TextRange.FromBounds(Math.Min(upperBound, other[minCount - 1].Start), upperBound);
}
else
{
return TextRange.FromBounds(Math.Min(this[minCount - 1].Start, upperBound), upperBound);
}
}
for (i = this.Count - 1, j = other.Count - 1; i >= 0 && j >= 0; i--, j--)
{
end = Math.Max(this[i].End, other[j].End);
if (this[i].Start != other[j].Start || this[i].Length != other[j].Length)
{
break;
}
}
if (start < end)
{
return TextRange.FromBounds(start, end);
}
return TextRange.FromBounds(lowerBound, upperBound);
}
/// <summary>
/// Merges another collection into existing one. Only adds elements
/// that are not present in this collection. Both collections must
/// be sorted by position for the method to work properly.
/// </summary>
/// <param name="other"></param>
public void Merge(TextRangeCollection<T> other)
{
var i = 0;
var j = 0;
var count = this.Count;
while (true)
{
if (i > count - 1)
{
// Add elements remaining in the other collection
for (; j < other.Count; j++)
{
this.Add(other[j]);
}
break;
}
if (j > other.Count - 1)
{
break;
}
if (this[i].Start < other[j].Start)
{
i++;
}
else if (other[j].Start < this[i].Start)
{
this.Add(other[j++]);
}
else
{
// Element is already in the collection
j++;
}
}
this.Sort();
}
private class RangeItemComparer : IComparer<T>
{
#region IComparer<T> Members
public int Compare(T x, T y)
{
return x.Start - y.Start;
}
#endregion
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return this._items.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this._items.GetEnumerator();
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Utilities.Common
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.Threading;
using ServiceManagement;
public abstract class ServiceManagementBaseCmdlet : CloudBaseCmdlet<IServiceManagement>
{
protected override IServiceManagement CreateChannel()
{
// If ShareChannel is set by a unit test, use the same channel that
// was passed into out constructor. This allows the test to submit
// a mock that we use for all network calls.
if (ShareChannel)
{
return Channel;
}
var messageInspectors = new List<IClientMessageInspector>
{
new ServiceManagementClientOutputMessageInspector(),
new HttpRestMessageInspector(this.WriteDebug)
};
var clientOptions = new ServiceManagementClientOptions(null, null, null, 0, RetryPolicy.NoRetryPolicy, ServiceManagementClientOptions.DefaultOptions.WaitTimeForOperationToComplete, messageInspectors);
var smClient = new ServiceManagementClient(new Uri(this.ServiceEndpoint), CurrentSubscription.SubscriptionId, CurrentSubscription.Certificate, clientOptions);
Type serviceManagementClientType = typeof(ServiceManagementClient);
PropertyInfo propertyInfo = serviceManagementClientType.GetProperty("SyncService", BindingFlags.Instance | BindingFlags.NonPublic);
var syncService = (IServiceManagement)propertyInfo.GetValue(smClient, null);
return syncService;
}
/// <summary>
/// Invoke the given operation within an OperationContextScope if the
/// channel supports it.
/// </summary>
/// <param name="action">The action to invoke.</param>
protected override void InvokeInOperationContext(Action action)
{
IContextChannel contextChannel = ToContextChannel();
if (contextChannel != null)
{
using (new OperationContextScope(contextChannel))
{
action();
}
}
else
{
action();
}
}
protected virtual IContextChannel ToContextChannel()
{
try
{
return Channel.ToContextChannel();
}
catch (Exception)
{
return null;
}
}
protected void ExecuteClientAction(object input, string operationDescription, Action<string> action)
{
Operation operation = null;
WriteVerboseWithTimestamp(string.Format("Begin Operation: {0}", operationDescription));
RetryCall(action);
operation = GetOperation();
WriteVerboseWithTimestamp(string.Format("Completed Operation: {0}", operationDescription));
if (operation != null)
{
var context = new ManagementOperationContext
{
OperationDescription = operationDescription,
OperationId = operation.OperationTrackingId,
OperationStatus = operation.Status
};
WriteObject(context, true);
}
}
protected void ExecuteClientActionInOCS(object input, string operationDescription, Action<string> action)
{
IContextChannel contextChannel = null;
try
{
contextChannel = Channel.ToContextChannel();
}
catch (Exception)
{
// Do nothing, proceed.
}
if (contextChannel != null)
{
using (new OperationContextScope(contextChannel))
{
Operation operation = null;
WriteVerboseWithTimestamp(string.Format("Begin Operation: {0}", operationDescription));
try
{
RetryCall(action);
operation = GetOperation();
}
catch (ServiceManagementClientException ex)
{
WriteErrorDetails(ex);
}
WriteVerboseWithTimestamp(string.Format("Completed Operation: {0}", operationDescription));
if (operation != null)
{
var context = new ManagementOperationContext
{
OperationDescription = operationDescription,
OperationId = operation.OperationTrackingId,
OperationStatus = operation.Status
};
WriteObject(context, true);
}
}
}
else
{
RetryCall(action);
}
}
protected virtual void WriteErrorDetails(ServiceManagementClientException exception)
{
if (CommandRuntime != null)
{
WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
}
}
protected void ExecuteClientActionInOCS<TResult>(object input, string operationDescription, Func<string, TResult> action, Func<Operation, TResult, object> contextFactory) where TResult : class
{
IContextChannel contextChannel = null;
try
{
contextChannel = Channel.ToContextChannel();
}
catch (Exception)
{
// Do nothing, proceed.
}
if (contextChannel != null)
{
using (new OperationContextScope(contextChannel))
{
TResult result = null;
Operation operation = null;
WriteVerboseWithTimestamp(string.Format("Begin Operation: {0}", operationDescription));
try
{
result = RetryCall(action);
operation = GetOperation();
}
catch (ServiceManagementClientException ex)
{
WriteErrorDetails(ex);
}
WriteVerboseWithTimestamp(string.Format("Completed Operation: {0}", operationDescription));
if (result != null && operation != null)
{
object context = contextFactory(operation, result);
WriteObject(context, true);
}
}
}
else
{
TResult result = RetryCall(action);
if (result != null)
{
WriteObject(result, true);
}
}
}
protected Operation GetOperation()
{
Operation operation = null;
try
{
string operationId = RetrieveOperationId();
if (!string.IsNullOrEmpty(operationId))
{
operation = RetryCall(s => GetOperationStatus(this.CurrentSubscription.SubscriptionId, operationId));
if (string.Compare(operation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
{
var errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", operation.Status, operation.Error.Message);
var exception = new Exception(errorMessage);
WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
}
}
else
{
operation = new Operation
{
OperationTrackingId = string.Empty,
Status = OperationState.Failed
};
}
}
catch (ServiceManagementClientException ex)
{
WriteErrorDetails(ex);
}
return operation;
}
protected override Operation GetOperationStatus(string subscriptionId, string operationId)
{
var channel = (IServiceManagement)Channel;
return channel.GetOperationStatus(subscriptionId, operationId);
}
}
}
| |
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using Spark.Compiler;
using NUnit.Framework;
using Spark.Compiler.VisualBasic;
using Spark.Tests.Models;
using Spark.Tests.Stubs;
namespace Spark.Tests.Compiler
{
[TestFixture]
public class VisualBasicViewCompilerTester
{
[SetUp]
public void Init()
{
}
private static void DoCompileView(ViewCompiler compiler, IList<Chunk> chunks)
{
compiler.CompileView(new[] { chunks }, new[] { chunks });
}
[Test]
public void MakeAndCompile()
{
var compiler = CreateCompiler();
DoCompileView(compiler, new[] { new SendLiteralChunk { Text = "hello world" } });
var instance = compiler.CreateInstance();
string contents = instance.RenderView();
Assert.That(contents.Contains("hello world"));
}
[Test]
public void StronglyTypedBase()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.Tests.Stubs.StubSparkView" };
DoCompileView(compiler, new Chunk[]
{
new SendLiteralChunk { Text = "hello world" },
new ViewDataModelChunk { TModel="Global.System.String"}
});
var instance = compiler.CreateInstance();
string contents = instance.RenderView();
Assert.That(contents.Contains("hello world"));
}
[Test]
public void UnsafeLiteralCharacters()
{
var text = "hello\t\r\n\"world";
var compiler = CreateCompiler();
DoCompileView(compiler, new[] { new SendLiteralChunk { Text = text } });
Assert.That(compiler.SourceCode.Contains("Write(\"hello"));
var instance = compiler.CreateInstance();
string contents = instance.RenderView();
Assert.That(contents, Is.EqualTo(text));
}
private static VisualBasicViewCompiler CreateCompiler()
{
return new VisualBasicViewCompiler
{
BaseClass = "Spark.AbstractSparkView",
UseAssemblies = new[] { "Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" },
UseNamespaces = new[] { "Microsoft.VisualBasic" }
};
}
[Test]
public void SimpleOutput()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "3 + 4" } });
var instance = compiler.CreateInstance();
string contents = instance.RenderView();
Assert.AreEqual("7", contents);
}
[Test]
public void LenientNullBehavior()
{
var compiler = CreateCompiler();
DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length" } });
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.That(contents, Is.EqualTo("${CType(Nothing, String).Length}"));
}
[Test]
public void SilentNullBehavior()
{
var compiler = CreateCompiler();
DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length", SilentNulls = true } });
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.That(contents, Is.EqualTo(""));
}
[Test]
public void RethrowNullBehavior()
{
var compiler = CreateCompiler();
compiler.NullBehaviour = NullBehaviour.Strict;
DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "CType(Nothing, String).Length" } });
var instance = compiler.CreateInstance();
Assert.That(() => instance.RenderView(), Throws.TypeOf<ArgumentNullException>());
}
[Test]
public void LocalVariableDecl()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
DoCompileView(compiler, new Chunk[]
{
new LocalVariableChunk { Name = "i", Value = "5" },
new SendExpressionChunk { Code = "i" }
});
var instance = compiler.CreateInstance();
string contents = instance.RenderView();
Assert.AreEqual("5", contents);
}
[Test]
public void ForEachLoop()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
DoCompileView(compiler, new Chunk[]
{
new LocalVariableChunk {Name = "data", Value = "new Integer(){3,4,5}"},
new SendLiteralChunk {Text = "<ul>"},
new ForEachChunk
{
Code = "item As Integer in data",
Body = new Chunk[]
{
new SendLiteralChunk {Text = "<li>"},
new SendExpressionChunk {Code = "item"},
new SendLiteralChunk {Text = "</li>"}
}
},
new SendLiteralChunk {Text = "</ul>"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("<ul><li>3</li><li>4</li><li>5</li></ul>", contents);
}
[Test]
public void ForEachAutoVariables()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
DoCompileView(compiler, new Chunk[]
{
new LocalVariableChunk {Name = "data", Value = "new Integer(){3,4,5}"},
new SendLiteralChunk {Text = "<ul>"},
new ForEachChunk
{
Code = "item As Integer in data",
Body = new Chunk[]
{
new SendLiteralChunk {Text = "<li>"},
new SendExpressionChunk {Code = "item"},
new SendExpressionChunk {Code = "itemIsFirst"},
new SendExpressionChunk {Code = "itemIsLast"},
new SendExpressionChunk {Code = "itemIndex"},
new SendExpressionChunk {Code = "itemCount"},
new SendLiteralChunk {Text = "</li>"}
}
},
new SendLiteralChunk {Text = "</ul>"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("<ul><li>3TrueFalse03</li><li>4FalseFalse13</li><li>5FalseTrue23</li></ul>", contents);
}
[Test]
public void GlobalVariables()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
DoCompileView(compiler, new Chunk[]
{
new SendExpressionChunk{Code="title"},
new AssignVariableChunk{ Name="item", Value="8"},
new SendLiteralChunk{ Text=":"},
new SendExpressionChunk{Code="item"},
new GlobalVariableChunk{ Name="title", Value="\"hello world\""},
new GlobalVariableChunk{ Name="item", Value="3"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("hello world:8", contents);
}
[Test]
[Platform(Exclude = "Mono", Reason = "Problems with Mono-2.10+/Linux and the VB compiler prevent this from running.")]
public void TargetNamespace()
{
var compiler = new VisualBasicViewCompiler
{
BaseClass = "Spark.AbstractSparkView",
Descriptor = new SparkViewDescriptor { TargetNamespace = "Testing.Target.Namespace" }
};
DoCompileView(compiler, new Chunk[] { new SendLiteralChunk { Text = "Hello" } });
var instance = compiler.CreateInstance();
Assert.AreEqual("Testing.Target.Namespace", instance.GetType().Namespace);
}
[Test]
public void ProvideFullException()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
Assert.That(() =>
DoCompileView(compiler, new Chunk[]
{
new SendExpressionChunk {Code = "NoSuchVariable"}
}),
Throws.TypeOf<BatchCompilerException>());
}
[Test]
public void IfTrueCondition()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } };
DoCompileView(compiler, new Chunk[]
{
new SendLiteralChunk {Text = "<p>"},
new LocalVariableChunk{Name="arg", Value="5"},
new ConditionalChunk{Type=ConditionalType.If, Condition="arg=5", Body=trueChunks},
new SendLiteralChunk {Text = "</p>"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("<p>wastrue</p>", contents);
}
[Test]
public void IfFalseCondition()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } };
DoCompileView(compiler, new Chunk[]
{
new SendLiteralChunk {Text = "<p>"},
new LocalVariableChunk{Name="arg", Value="5"},
new ConditionalChunk{Type=ConditionalType.If, Condition="arg=6", Body=trueChunks},
new SendLiteralChunk {Text = "</p>"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("<p></p>", contents);
}
[Test]
public void IfElseFalseCondition()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } };
var falseChunks = new Chunk[] { new SendLiteralChunk { Text = "wasfalse" } };
DoCompileView(compiler, new Chunk[]
{
new SendLiteralChunk {Text = "<p>"},
new LocalVariableChunk{Name="arg", Value="5"},
new ConditionalChunk{Type=ConditionalType.If, Condition="arg=6", Body=trueChunks},
new ConditionalChunk{Type=ConditionalType.Else, Body=falseChunks},
new SendLiteralChunk {Text = "</p>"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("<p>wasfalse</p>", contents);
}
[Test]
public void UnlessTrueCondition()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } };
DoCompileView(compiler, new Chunk[]
{
new SendLiteralChunk {Text = "<p>"},
new LocalVariableChunk{Name="arg", Value="5"},
new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg=5", Body=trueChunks},
new SendLiteralChunk {Text = "</p>"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("<p></p>", contents);
}
[Test]
public void UnlessFalseCondition()
{
var compiler = new VisualBasicViewCompiler { BaseClass = "Spark.AbstractSparkView" };
var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } };
DoCompileView(compiler, new Chunk[]
{
new SendLiteralChunk {Text = "<p>"},
new LocalVariableChunk{Name="arg", Value="5"},
new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg=6", Body=trueChunks},
new SendLiteralChunk {Text = "</p>"}
});
var instance = compiler.CreateInstance();
var contents = instance.RenderView();
Assert.AreEqual("<p>wastrue</p>", contents);
}
[Test]
public void StrictNullUsesException()
{
var compiler = new VisualBasicViewCompiler()
{
BaseClass = "Spark.Tests.Stubs.StubSparkView",
NullBehaviour = NullBehaviour.Strict
};
var chunks = new Chunk[]
{
new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"},
new SendExpressionChunk {Code = "comment.Text", SilentNulls = false}
};
compiler.CompileView(new[] { chunks }, new[] { chunks });
Assert.That(compiler.SourceCode.Contains("Catch ex As Global.System.NullReferenceException"));
Assert.That(compiler.SourceCode.Contains("ArgumentNullException("));
Assert.That(compiler.SourceCode.Contains(", ex)"));
}
[Test]
public void PageBaseTypeOverridesBaseClass()
{
var compiler = new VisualBasicViewCompiler()
{
BaseClass = "Spark.Tests.Stubs.StubSparkView",
NullBehaviour = NullBehaviour.Strict
};
DoCompileView(compiler, new Chunk[]
{
new PageBaseTypeChunk { BaseClass="Spark.Tests.Stubs.StubSparkView2"},
new SendLiteralChunk{ Text = "Hello world"}
});
var instance = compiler.CreateInstance();
Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2)));
}
[Test]
public void PageBaseTypeWorksWithOptionalModel()
{
var compiler = new VisualBasicViewCompiler()
{
BaseClass = "Spark.Tests.Stubs.StubSparkView",
NullBehaviour = NullBehaviour.Strict
};
DoCompileView(compiler, new Chunk[]
{
new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView2"},
new ViewDataModelChunk {TModel = "Spark.Tests.Models.Comment"},
new SendLiteralChunk {Text = "Hello world"}
});
var instance = compiler.CreateInstance();
Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2)));
Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2<Comment>)));
}
[Test]
public void PageBaseTypeWorksWithGenericParametersIncluded()
{
var compiler = new VisualBasicViewCompiler()
{
BaseClass = "Spark.Tests.Stubs.StubSparkView",
NullBehaviour = NullBehaviour.Strict
};
DoCompileView(compiler, new Chunk[]
{
new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView3(Of Spark.Tests.Models.Comment, string)"},
new SendLiteralChunk {Text = "Hello world"}
});
var instance = compiler.CreateInstance();
Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2)));
Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2<Comment>)));
Assert.That(instance, Is.InstanceOf(typeof(StubSparkView3<Comment, string>)));
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Options;
namespace NUnit.Common
{
/// <summary>
/// ConsoleOptions encapsulates the option settings for
/// the nunit-console program. It inherits from the Mono
/// Options OptionSet class and provides a central location
/// for defining and parsing options.
/// </summary>
public class ConsoleOptions : OptionSet
{
private bool validated;
private bool noresult;
#region Constructor
internal ConsoleOptions(IDefaultOptionsProvider defaultOptionsProvider, params string[] args)
{
// Apply default oprions
if (defaultOptionsProvider == null) throw new ArgumentNullException("defaultOptionsProvider");
TeamCity = defaultOptionsProvider.TeamCity;
ConfigureOptions();
if (args != null)
Parse(args);
}
public ConsoleOptions(params string[] args)
{
ConfigureOptions();
if (args != null)
Parse(args);
}
#endregion
#region Properties
// Action to Perform
public bool Explore { get; private set; }
public bool ShowHelp { get; private set; }
// Select tests
private List<string> inputFiles = new List<string>();
public IList<string> InputFiles { get { return inputFiles; } }
private List<string> testList = new List<string>();
public IList<string> TestList { get { return testList; } }
public string Include { get; private set; }
public string Exclude { get; private set; }
public string ActiveConfig { get; private set; }
// Where to Run Tests
public string ProcessModel { get; private set; }
public string DomainUsage { get; private set; }
// How to Run Tests
public string Framework { get; private set; }
public bool RunAsX86 { get; private set; }
public bool DisposeRunners { get; private set; }
public bool ShadowCopyFiles { get; private set; }
private int defaultTimeout = -1;
public int DefaultTimeout { get { return defaultTimeout; } }
private int randomSeed = -1;
public int RandomSeed { get { return randomSeed; } }
private int numWorkers = -1;
public int NumWorkers { get { return numWorkers; } }
private int maxAgents = -1;
public int MaxAgents { get { return maxAgents; } }
public bool StopOnError { get; private set; }
public bool WaitBeforeExit { get; private set; }
public bool DebugTests { get; private set; }
public bool DebugAgent { get; private set; }
// Output Control
public bool NoHeader { get; private set; }
public bool NoColor { get; private set; }
public bool Verbose { get; private set; }
public bool TeamCity { get; private set; }
public string OutFile { get; private set; }
public string ErrFile { get; private set; }
public string DisplayTestLabels { get; private set; }
private string workDirectory = NUnit.Env.DefaultWorkDirectory;
public string WorkDirectory
{
get { return workDirectory; }
}
public string InternalTraceLevel { get; private set; }
/// <summary>Indicates whether a full report should be displayed.</summary>
public bool Full { get; private set; }
private List<OutputSpecification> resultOutputSpecifications = new List<OutputSpecification>();
public IList<OutputSpecification> ResultOutputSpecifications
{
get
{
if (noresult)
return new OutputSpecification[0];
if (resultOutputSpecifications.Count == 0)
resultOutputSpecifications.Add(new OutputSpecification("TestResult.xml"));
return resultOutputSpecifications;
}
}
private List<OutputSpecification> exploreOutputSpecifications = new List<OutputSpecification>();
public IList<OutputSpecification> ExploreOutputSpecifications { get { return exploreOutputSpecifications; } }
// Error Processing
public List<string> errorMessages = new List<string>();
public IList<string> ErrorMessages { get { return errorMessages; } }
#endregion
#region Public Methods
public bool Validate()
{
if (!validated)
{
// Additional Checks here
validated = true;
}
return ErrorMessages.Count == 0;
}
#endregion
#region Helper Methods
/// <summary>
/// Case is ignored when val is compared to validValues. When a match is found, the
/// returned value will be in the canonical case from validValues.
/// </summary>
private string RequiredValue(string val, string option, params string[] validValues)
{
if (string.IsNullOrEmpty(val))
ErrorMessages.Add("Missing required value for option '" + option + "'.");
bool isValid = true;
if (validValues != null && validValues.Length > 0)
{
isValid = false;
foreach (string valid in validValues)
if (string.Compare(valid, val, StringComparison.InvariantCultureIgnoreCase) == 0)
return valid;
}
if (!isValid)
ErrorMessages.Add(string.Format("The value '{0}' is not valid for option '{1}'.", val, option));
return val;
}
private int RequiredInt(string val, string option)
{
// We have to return something even though the value will
// be ignored if an error is reported. The -1 value seems
// like a safe bet in case it isn't ignored due to a bug.
int result = -1;
if (string.IsNullOrEmpty(val))
ErrorMessages.Add("Missing required value for option '" + option + "'.");
else
{
#if NETCF // NETCF: Create compatibility method for TryParse
try
{
result = int.Parse(val);
}
catch (Exception)
{
ErrorMessages.Add("An int value was expected for option '{0}' but a value of '{1}' was used");
}
#else
int r;
if (int.TryParse(val, out r))
result = r;
else
ErrorMessages.Add("An int value was expected for option '{0}' but a value of '{1}' was used");
#endif
}
return result;
}
private string ExpandToFullPath(string path)
{
if (path == null) return null;
#if NETCF
return Path.Combine(NUnit.Env.DocumentFolder, path);
#else
return Path.GetFullPath(path);
#endif
}
private void ConfigureOptions()
{
// NOTE: The order in which patterns are added
// determines the display order for the help.
// Old Options no longer supported:
// fixture
// xmlConsole
// noshadow
// nothread
// nodots
// Select Tests
this.Add("test=", "Comma-separated list of {NAMES} of tests to run or explore. This option may be repeated.",
v => ((List<string>)TestList).AddRange(TestNameParser.Parse(RequiredValue(v, "--test"))));
this.Add("testlist=", "File {PATH} containing a list of tests to run, one per line. This option may be repeated.",
v =>
{
string testListFile = RequiredValue(v, "--testlist");
var fullTestListPath = ExpandToFullPath(testListFile);
if (!File.Exists(fullTestListPath))
ErrorMessages.Add("Unable to locate file: " + testListFile);
else
{
try
{
using (var rdr = new StreamReader(fullTestListPath))
{
while (!rdr.EndOfStream)
{
var line = rdr.ReadLine().Trim();
if (line[0] != '#')
((List<string>)TestList).Add(line);
}
}
}
catch (IOException)
{
ErrorMessages.Add("Unable to read file: " + testListFile);
}
}
});
this.Add("include=", "Test {CATEGORIES} to be included. May be a single category, a comma-separated list of categories or a category expression.",
v => Include = RequiredValue(v, "--include"));
this.Add("exclude=", "Test {CATEGORIES} to be excluded. May be a single category, a comma-separated list of categories or a category expression.",
v => Exclude = RequiredValue(v, "--exclude"));
#if !NUNITLITE
this.Add("config=", "{NAME} of a project configuration to load (e.g.: Debug).",
v => ActiveConfig = RequiredValue(v, "--config"));
// Where to Run Tests
this.Add("process=", "{PROCESS} isolation for test assemblies.\nValues: Single, Separate, Multiple. If not specified, defaults to Separate for a single assembly or Multiple for more than one.",
v => ProcessModel = RequiredValue(v, "--process", "Single", "Separate", "Multiple"));
this.Add("domain=", "{DOMAIN} isolation for test assemblies.\nValues: None, Single, Multiple. If not specified, defaults to Single for a single assembly or Multiple for more than one.",
v => DomainUsage = RequiredValue(v, "--domain", "None", "Single", "Multiple"));
// How to Run Tests
this.Add("framework=", "{FRAMEWORK} type/version to use for tests.\nExamples: mono, net-3.5, v4.0, 2.0, mono-4.0. If not specified, tests will run under the framework they are compiled with.",
v => Framework = RequiredValue(v, "--framework"));
this.Add("x86", "Run tests in an x86 process on 64 bit systems",
v => RunAsX86 = v != null);
this.Add("dispose-runners", "Dispose each test runner after it has finished running its tests.",
v => DisposeRunners = v != null);
this.Add("shadowcopy", "Shadow copy test files",
v => ShadowCopyFiles = v != null);
this.Add("debug", "Launch debugger to debug tests.",
v => DebugTests = v != null);
#if DEBUG
this.Add("debug-agent", "Launch debugger in nunit-agent when it starts.",
v => DebugAgent = v != null);
#endif
#endif
this.Add("timeout=", "Set timeout for each test case in {MILLISECONDS}.",
v => defaultTimeout = RequiredInt(v, "--timeout"));
this.Add("seed=", "Set the random {SEED} used to generate test cases.",
v => randomSeed = RequiredInt(v, "--seed"));
this.Add("agents=", "Specify the maximum {NUMBER} of test assembly agents to run at one time. If not specified, there is no limit.",
v => maxAgents = RequiredInt(v, "--agents"));
this.Add("workers=", "Specify the {NUMBER} of worker threads to be used in running tests. If not specified, defaults to 2 or the number of processors, whichever is greater.",
v => numWorkers = RequiredInt(v, "--workers"));
this.Add("stoponerror", "Stop run immediately upon any test failure or error.",
v => StopOnError = v != null);
this.Add("wait", "Wait for input before closing console window.",
v => WaitBeforeExit = v != null);
// Output Control
this.Add("work=", "{PATH} of the directory to use for output files. If not specified, defaults to the current directory.",
v => workDirectory = RequiredValue(v, "--work"));
this.Add("output|out=", "File {PATH} to contain text output from the tests.",
v => OutFile = RequiredValue(v, "--output"));
this.Add("err=", "File {PATH} to contain error output from the tests.",
v => ErrFile = RequiredValue(v, "--err"));
this.Add("full", "Prints full report of all test results.",
v => Full = v != null);
this.Add("result=", "An output {SPEC} for saving the test results.\nThis option may be repeated.",
v => resultOutputSpecifications.Add(new OutputSpecification(RequiredValue(v, "--resultxml"))));
this.Add("explore:", "Display or save test info rather than running tests. Optionally provide an output {SPEC} for saving the test info. This option may be repeated.", v =>
{
Explore = true;
if (v != null)
ExploreOutputSpecifications.Add(new OutputSpecification(v));
});
this.Add("noresult", "Don't save any test results.",
v => noresult = v != null);
this.Add("labels=", "Specify whether to write test case names to the output. Values: Off, On, All",
v => DisplayTestLabels = RequiredValue(v, "--labels", "Off", "On", "All"));
this.Add("trace=", "Set internal trace {LEVEL}.\nValues: Off, Error, Warning, Info, Verbose (Debug)",
v => InternalTraceLevel = RequiredValue(v, "--trace", "Off", "Error", "Warning", "Info", "Verbose", "Debug"));
#if !NETCF
this.Add("teamcity", "Turns on use of TeamCity service messages.",
v => TeamCity = v != null);
#endif
this.Add("noheader|noh", "Suppress display of program information at start of run.",
v => NoHeader = v != null);
this.Add("nocolor|noc", "Displays console output without color.",
v => NoColor = v != null);
this.Add("verbose|v", "Display additional information as the test runs.",
v => Verbose = v != null);
this.Add("help|h", "Display this message and exit.",
v => ShowHelp = v != null);
// Default
this.Add("<>", v =>
{
if (v.StartsWith("-") || v.StartsWith("/") && Path.DirectorySeparatorChar != '/')
ErrorMessages.Add("Invalid argument: " + v);
else
InputFiles.Add(v);
});
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using odatav4webapi.Areas.HelpPage.ModelDescriptions;
using odatav4webapi.Areas.HelpPage.Models;
namespace odatav4webapi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CodeGeneration;
using System.Runtime.Serialization;
using System.IO;
namespace XUnitConverter
{
public sealed class MSTestToXUnitConverter : ConverterBase
{
private static object s_lockObject = new object();
private static HashSet<string> s_mstestNamespaces;
private static UsingDirectiveSyntax RemoveLeadingAndTrailingCompilerDirectives(UsingDirectiveSyntax usingSyntax)
{
UsingDirectiveSyntax usingDirectiveToUse = usingSyntax;
if (usingDirectiveToUse.HasLeadingTrivia)
{
if (usingDirectiveToUse.HasLeadingTrivia)
{
var newLeadingTrivia = RemoveCompilerDirectives(usingDirectiveToUse.GetLeadingTrivia());
usingDirectiveToUse = usingDirectiveToUse.WithLeadingTrivia(newLeadingTrivia);
}
if (usingDirectiveToUse.HasTrailingTrivia)
{
var newTrailingTrivia = RemoveCompilerDirectives(usingDirectiveToUse.GetTrailingTrivia());
usingDirectiveToUse = usingDirectiveToUse.WithTrailingTrivia(newTrailingTrivia);
}
}
return usingDirectiveToUse;
}
protected override async Task<Solution> ProcessAsync(Document document, SyntaxNode syntaxNode, CancellationToken cancellationToken)
{
var root = syntaxNode as CompilationUnitSyntax;
if (root == null)
return document.Project.Solution;
if (!LoadMSTestNamespaces())
{
return document.Project.Solution;
}
var originalRoot = root;
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
List<UsingDirectiveSyntax> newUsings = new List<UsingDirectiveSyntax>();
bool needsChanges = false;
foreach (var usingSyntax in root.Usings)
{
var symbolInfo = semanticModel.GetSymbolInfo(usingSyntax.Name);
if (symbolInfo.Symbol != null)
{
string namespaceDocID = symbolInfo.Symbol.GetDocumentationCommentId();
if (s_mstestNamespaces.Contains(namespaceDocID))
{
needsChanges = true;
}
else
{
newUsings.Add(RemoveLeadingAndTrailingCompilerDirectives(usingSyntax));
}
}
else
{
newUsings.Add(RemoveLeadingAndTrailingCompilerDirectives(usingSyntax));
}
}
if (!needsChanges)
{
return document.Project.Solution;
}
TransformationTracker transformationTracker = new TransformationTracker();
RemoveTestClassAttributes(root, semanticModel, transformationTracker);
RemoveContractsRequiredAttributes(root, semanticModel, transformationTracker);
ChangeTestMethodAttributesToFact(root, semanticModel, transformationTracker);
ChangeAssertCalls(root, semanticModel, transformationTracker);
root = transformationTracker.TransformRoot(root);
// Remove compiler directives before the first member of the file (e.g. an #endif after the using statements)
var firstMember = root.Members.FirstOrDefault();
if (firstMember != null)
{
if (firstMember.HasLeadingTrivia)
{
var newLeadingTrivia = RemoveCompilerDirectives(firstMember.GetLeadingTrivia());
root = root.ReplaceNode(firstMember, firstMember.WithLeadingTrivia(newLeadingTrivia));
}
}
var xUnitUsing = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("Xunit")).NormalizeWhitespace();
newUsings.Add(xUnitUsing);
// Apply trailing trivia from original last using statement to new last using statement
SyntaxTriviaList usingTrailingTrivia = RemoveCompilerDirectives(originalRoot.Usings.Last().GetTrailingTrivia());
newUsings[newUsings.Count - 1] = newUsings.Last().WithTrailingTrivia(usingTrailingTrivia);
root = root.WithUsings(SyntaxFactory.List<UsingDirectiveSyntax>(newUsings));
return document.WithSyntaxRoot(root).Project.Solution;
}
private void RemoveContractsRequiredAttributes(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker)
{
RemoveTestAttributes(root, semanticModel, transformationTracker, "ContractsRequiredAttribute");
}
private void RemoveTestClassAttributes(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker)
{
RemoveTestAttributes(root, semanticModel, transformationTracker, "TestClassAttribute");
}
private void RemoveTestAttributes(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker, string attributeName)
{
List<AttributeSyntax> nodesToRemove = new List<AttributeSyntax>();
foreach (var attributeListSyntax in root.DescendantNodes().OfType<AttributeListSyntax>())
{
var attributesToRemove = attributeListSyntax.Attributes.Where(attributeSyntax =>
{
var typeInfo = semanticModel.GetTypeInfo(attributeSyntax);
if (typeInfo.Type != null)
{
string attributeTypeDocID = typeInfo.Type.GetDocumentationCommentId();
if (IsTestNamespaceType(attributeTypeDocID, attributeName))
{
return true;
}
}
return false;
}).ToList();
nodesToRemove.AddRange(attributesToRemove);
}
transformationTracker.AddTransformation(nodesToRemove, (transformationRoot, rewrittenNodes, originalNodeMap) =>
{
foreach (AttributeSyntax rewrittenNode in rewrittenNodes)
{
var attributeListSyntax = (AttributeListSyntax)rewrittenNode.Parent;
var newSyntaxList = attributeListSyntax.Attributes.Remove(rewrittenNode);
if (newSyntaxList.Any())
{
transformationRoot = transformationRoot.ReplaceNode(attributeListSyntax, attributeListSyntax.WithAttributes(newSyntaxList));
}
else
{
transformationRoot = transformationRoot.RemoveNode(attributeListSyntax, SyntaxRemoveOptions.KeepLeadingTrivia);
}
}
return transformationRoot;
});
}
private void ChangeTestMethodAttributesToFact(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker)
{
List<AttributeSyntax> nodesToReplace = new List<AttributeSyntax>();
foreach (var attributeSyntax in root.DescendantNodes().OfType<AttributeSyntax>())
{
var typeInfo = semanticModel.GetTypeInfo(attributeSyntax);
if (typeInfo.Type != null)
{
string attributeTypeDocID = typeInfo.Type.GetDocumentationCommentId();
if (IsTestNamespaceType(attributeTypeDocID, "TestMethodAttribute"))
{
nodesToReplace.Add(attributeSyntax);
}
}
}
transformationTracker.AddTransformation(nodesToReplace, (transformationRoot, rewrittenNodes, originalNodeMap) =>
{
return transformationRoot.ReplaceNodes(rewrittenNodes, (originalNode, rewrittenNode) =>
{
return ((AttributeSyntax)rewrittenNode).WithName(SyntaxFactory.ParseName("Fact")).NormalizeWhitespace();
});
});
}
private void ChangeAssertCalls(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker)
{
Dictionary<string, string> assertMethodsToRename = new Dictionary<string, string>()
{
{ "AreEqual", "Equal" },
{ "AreNotEqual", "NotEqual" },
{ "IsNull", "Null" },
{ "IsNotNull", "NotNull" },
{ "AreSame", "Same" },
{ "AreNotSame", "NotSame" },
{ "IsTrue", "True" },
{ "IsFalse", "False" },
{ "IsInstanceOfType", "IsAssignableFrom" },
};
Dictionary<SimpleNameSyntax, string> nameReplacementsForNodes = new Dictionary<SimpleNameSyntax, string>();
List<InvocationExpressionSyntax> methodCallsToReverseArguments = new List<InvocationExpressionSyntax>();
foreach (var methodCallSyntax in root.DescendantNodes().OfType<MemberAccessExpressionSyntax>())
{
var expressionSyntax = methodCallSyntax.Expression;
var expressionTypeInfo = semanticModel.GetTypeInfo(expressionSyntax);
if (expressionTypeInfo.Type != null)
{
string expressionDocID = expressionTypeInfo.Type.GetDocumentationCommentId();
if (IsTestNamespaceType(expressionDocID, "Assert"))
{
string newMethodName;
if (assertMethodsToRename.TryGetValue(methodCallSyntax.Name.Identifier.Text, out newMethodName))
{
nameReplacementsForNodes.Add(methodCallSyntax.Name, newMethodName);
if (newMethodName == "IsAssignableFrom" && methodCallSyntax.Parent is InvocationExpressionSyntax)
{
// Parameter order is reversed between MSTest Assert.IsInstanceOfType and xUnit Assert.IsAssignableFrom
methodCallsToReverseArguments.Add((InvocationExpressionSyntax)methodCallSyntax.Parent);
}
}
}
}
}
if (nameReplacementsForNodes.Any())
{
transformationTracker.AddTransformation(nameReplacementsForNodes.Keys, (transformationRoot, rewrittenNodes, originalNodeMap) =>
{
return transformationRoot.ReplaceNodes(rewrittenNodes, (originalNode, rewrittenNode) =>
{
var realOriginalNode = (SimpleNameSyntax)originalNodeMap[originalNode];
string newName = nameReplacementsForNodes[realOriginalNode];
return SyntaxFactory.ParseName(newName);
});
});
transformationTracker.AddTransformation(methodCallsToReverseArguments, (transformationRoot, rewrittenNodes, originalNodeMap) =>
{
return transformationRoot.ReplaceNodes(rewrittenNodes, (originalNode, rewrittenNode) =>
{
var invocationExpression = (InvocationExpressionSyntax)rewrittenNode;
var oldArguments = invocationExpression.ArgumentList.Arguments;
var newArguments = new SeparatedSyntaxList<ArgumentSyntax>().AddRange(new[] { oldArguments[1], oldArguments[0] });
return invocationExpression.WithArgumentList(invocationExpression.ArgumentList.WithArguments(newArguments));
});
});
}
}
private static SyntaxTriviaList RemoveCompilerDirectives(SyntaxTriviaList stl)
{
foreach (var trivia in stl)
{
if (trivia.Kind() == SyntaxKind.IfDirectiveTrivia ||
trivia.Kind() == SyntaxKind.DisabledTextTrivia ||
trivia.Kind() == SyntaxKind.EndIfDirectiveTrivia ||
trivia.Kind() == SyntaxKind.ElifDirectiveTrivia ||
trivia.Kind() == SyntaxKind.ElseDirectiveTrivia)
{
stl = stl.Remove(trivia);
}
}
return stl;
}
private static bool IsTestNamespaceType(string docID, string simpleTypeName)
{
if (docID == null)
{
return false;
}
int lastPeriod = docID.LastIndexOf('.');
if (lastPeriod < 0)
{
return false;
}
string simpleTypeNameFromDocID = docID.Substring(lastPeriod + 1);
if (simpleTypeNameFromDocID != simpleTypeName)
{
return false;
}
string namespaceDocID = "N" + docID.Substring(1, lastPeriod - 1);
return s_mstestNamespaces.Contains(namespaceDocID);
}
private bool LoadMSTestNamespaces()
{
lock (s_lockObject)
{
if (s_mstestNamespaces != null)
{
return true;
}
var filePath = Path.Combine(
Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(typeof(MSTestToXUnitConverter).Assembly.CodeBase).Path)),
"MSTestNamespaces.txt");
if (!File.Exists(filePath))
{
Console.WriteLine("The MSTestNamespaces.txt file was not found.");
return false;
}
var lines = File.ReadAllLines(filePath);
s_mstestNamespaces = new HashSet<string>(lines);
return true;
}
}
private class TransformationTracker
{
private Dictionary<SyntaxAnnotation, Func<CompilationUnitSyntax, IEnumerable<SyntaxNode>, Dictionary<SyntaxNode, SyntaxNode>, CompilationUnitSyntax>> _annotationToTransformation = new Dictionary<SyntaxAnnotation, Func<CompilationUnitSyntax, IEnumerable<SyntaxNode>, Dictionary<SyntaxNode, SyntaxNode>, CompilationUnitSyntax>>();
private Dictionary<SyntaxNode, List<SyntaxAnnotation>> _nodeToAnnotations = new Dictionary<SyntaxNode, List<SyntaxAnnotation>>();
private Dictionary<SyntaxAnnotation, SyntaxNode> _originalNodeLookup = new Dictionary<SyntaxAnnotation, SyntaxNode>();
public void AddTransformation(IEnumerable<SyntaxNode> nodesToTransform, Func<CompilationUnitSyntax, IEnumerable<SyntaxNode>, Dictionary<SyntaxNode, SyntaxNode>, CompilationUnitSyntax> transformerFunc)
{
var annotation = new SyntaxAnnotation();
_annotationToTransformation[annotation] = transformerFunc;
foreach (var node in nodesToTransform)
{
List<SyntaxAnnotation> annotationsForNode;
if (!_nodeToAnnotations.TryGetValue(node, out annotationsForNode))
{
annotationsForNode = new List<SyntaxAnnotation>();
_nodeToAnnotations[node] = annotationsForNode;
}
annotationsForNode.Add(annotation);
var originalNodeAnnotation = new SyntaxAnnotation();
_originalNodeLookup[originalNodeAnnotation] = node;
annotationsForNode.Add(originalNodeAnnotation);
}
}
public CompilationUnitSyntax TransformRoot(CompilationUnitSyntax root)
{
root = root.ReplaceNodes(_nodeToAnnotations.Keys, (originalNode, rewrittenNode) =>
{
var ret = rewrittenNode.WithAdditionalAnnotations(_nodeToAnnotations[originalNode]);
return ret;
});
foreach (var kvp in _annotationToTransformation)
{
Dictionary<SyntaxNode, SyntaxNode> originalNodeMap = new Dictionary<SyntaxNode, SyntaxNode>();
foreach (var originalNodeKvp in _originalNodeLookup)
{
var annotatedNodes = root.GetAnnotatedNodes(originalNodeKvp.Key).ToList();
SyntaxNode annotatedNode = annotatedNodes.SingleOrDefault();
if (annotatedNode != null)
{
originalNodeMap[annotatedNode] = originalNodeKvp.Value;
}
}
var syntaxAnnotation = kvp.Key;
var transformation = kvp.Value;
var nodesToTransform = root.GetAnnotatedNodes(syntaxAnnotation);
root = transformation(root, nodesToTransform, originalNodeMap);
}
return root;
}
}
}
}
| |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.AdManager.v202108;
using System;
using System.Collections.Generic;
using System.Text;
using DateTime = Google.Api.Ads.AdManager.v202108.DateTime;
namespace Google.Api.Ads.AdManager.Util.v202108
{
/// <summary>
/// A utility class that allows for statements to be constructed in parts.
/// Typical usage is:
/// <code>
/// StatementBuilder statementBuilder = new StatementBuilder()
/// .Where("lastModifiedTime > :yesterday AND type = :type")
/// .OrderBy("name DESC")
/// .Limit(200)
/// .Offset(20)
/// .AddValue("yesterday",
/// DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(-1)))
/// .AddValue("type", "Type");
/// Statement statement = statementBuilder.ToStatement();
/// // ...
/// statementBuilder.increaseOffsetBy(20);
/// statement = statementBuilder.ToStatement();
/// </code>
/// </summary>
public class StatementBuilder
{
/// <summary>
/// The suggested default page size.
/// </summary>
public const int SUGGESTED_PAGE_LIMIT = 500;
private const string SELECT = "SELECT";
private const string FROM = "FROM";
private const string WHERE = "WHERE";
private const string LIMIT = "LIMIT";
private const string OFFSET = "OFFSET";
private const string ORDER_BY = "ORDER BY";
private string select;
private string from;
private string where;
private int? limit = null;
private int? offset = null;
private string orderBy;
/// <summary>
/// The list of query parameters.
/// </summary>
private List<String_ValueMapEntry> valueEntries;
/// <summary>
/// Constructs a statement builder for partial query building.
/// </summary>
public StatementBuilder()
{
valueEntries = new List<String_ValueMapEntry>();
}
/// <summary>
/// Removes a keyword from the start of a clause, if it exists.
/// </summary>
/// <param name="clause">The clause to remove the keyword from</param>
/// <param name="keyword">The keyword to remove</param>
/// <returns>The clause with the keyword removed</returns>
private static string RemoveKeyword(string clause, string keyword)
{
string formattedKeyword = keyword.Trim() + " ";
return clause.StartsWith(formattedKeyword, true, null)
? clause.Substring(formattedKeyword.Length)
: clause;
}
/// <summary>
/// Sets the statement SELECT clause in the form of "a,b".
/// Only necessary for statements being sent to the
/// <see cref="PublisherQueryLanguageService"/>.
/// The "SELECT " keyword will be ignored.
/// </summary>
/// <param name="columns">
/// The statement serlect clause without "SELECT".
/// </param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Select(String columns)
{
PreconditionUtilities.CheckArgumentNotNull(columns, "columns");
this.select = RemoveKeyword(columns, SELECT);
return this;
}
/// <summary>
/// Sets the statement FROM clause in the form of "table".
/// Only necessary for statements being sent to the
/// <see cref="PublisherQueryLanguageService"/>.
/// The "FROM " keyword will be ignored.
/// </summary>
/// <param name="table">The statement from clause without "FROM"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder From(String table)
{
PreconditionUtilities.CheckArgumentNotNull(table, "table");
this.from = RemoveKeyword(table, FROM);
return this;
}
/// <summary>
/// Sets the statement WHERE clause in the form of
/// <code>
/// "WHERE <condition> {[AND | OR] <condition> ...}"
/// </code>
/// e.g. "a = b OR b = c". The "WHERE " keyword will be ignored.
/// </summary>
/// <param name="conditions">The statement query without "WHERE"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Where(String conditions)
{
PreconditionUtilities.CheckArgumentNotNull(conditions, "conditions");
this.where = RemoveKeyword(conditions, WHERE);
return this;
}
/// <summary>
/// Sets the statement LIMIT clause in the form of
/// <code>"LIMIT <count>"</code>
/// </summary>
/// <param name="count">the statement limit</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Limit(Int32 count)
{
this.limit = count;
return this;
}
/// <summary>
/// Sets the statement OFFSET clause in the form of
/// <code>"OFFSET <count>"</code>
/// </summary>
/// <param name="count">the statement offset</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder Offset(Int32 count)
{
this.offset = count;
return this;
}
/// <summary>
/// Increases the offset by the given amount.
/// </summary>
/// <param name="amount">the amount to increase the offset</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder IncreaseOffsetBy(Int32 amount)
{
if (this.offset == null)
{
this.offset = 0;
}
this.offset += amount;
return this;
}
/// <summary>
/// Gets the curent offset
/// </summary>
/// <returns>The current offset</returns>
public int? GetOffset()
{
return this.offset;
}
/// <summary>
/// Removes the limit and offset from the query.
/// </summary>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder RemoveLimitAndOffset()
{
this.offset = null;
this.limit = null;
return this;
}
/// <summary>
/// Sets the statement ORDER BY clause in the form of
/// <code>"ORDER BY <property> [ASC | DESC]"</code>
/// e.g. "type ASC, lastModifiedDateTime DESC".
/// The "ORDER BY " keyword will be ignored.
/// </summary>
/// <param name="orderBy">the statement order by without "ORDER BY"</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder OrderBy(String orderBy)
{
PreconditionUtilities.CheckArgumentNotNull(orderBy, "orderBy");
this.orderBy = RemoveKeyword(orderBy, ORDER_BY);
return this;
}
/// <summary>
/// Adds a new string value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, string value)
{
TextValue queryValue = new TextValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new boolean value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, bool value)
{
BooleanValue queryValue = new BooleanValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new decimal value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, decimal value)
{
NumberValue queryValue = new NumberValue();
queryValue.value = value.ToString();
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new DateTime value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, DateTime value)
{
DateTimeValue queryValue = new DateTimeValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new Date value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
public StatementBuilder AddValue(string key, Date value)
{
DateValue queryValue = new DateValue();
queryValue.value = value;
return AddValue(key, queryValue);
}
/// <summary>
/// Adds a new value to the list of query parameters.
/// </summary>
/// <param name="key">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <returns>The statement builder, for chaining method calls.</returns>
private StatementBuilder AddValue(string key, Value value)
{
String_ValueMapEntry queryValue = new String_ValueMapEntry();
queryValue.key = key;
queryValue.value = value;
valueEntries.Add(queryValue);
return this;
}
private void ValidateQuery()
{
if (limit == null && offset != null)
{
throw new InvalidOperationException(AdManagerErrorMessages.InvalidOffsetAndLimit);
}
}
private String BuildQuery()
{
ValidateQuery();
StringBuilder stringBuilder = new StringBuilder();
if (!String.IsNullOrEmpty(select))
{
stringBuilder = stringBuilder.Append(SELECT).Append(" ").Append(select).Append(" ");
}
if (!String.IsNullOrEmpty(from))
{
stringBuilder = stringBuilder.Append(FROM).Append(" ").Append(from).Append(" ");
}
if (!String.IsNullOrEmpty(where))
{
stringBuilder = stringBuilder.Append(WHERE).Append(" ").Append(where).Append(" ");
}
if (!String.IsNullOrEmpty(orderBy))
{
stringBuilder = stringBuilder.Append(ORDER_BY).Append(" ").Append(orderBy)
.Append(" ");
}
if (limit != null)
{
stringBuilder = stringBuilder.Append(LIMIT).Append(" ").Append(limit).Append(" ");
}
if (offset != null)
{
stringBuilder = stringBuilder.Append(OFFSET).Append(" ").Append(offset).Append(" ");
}
return stringBuilder.ToString().Trim();
}
/// <summary>
/// Gets the <see cref="Statement"/> representing the state of this
/// statement builder.
/// </summary>
/// <returns>The statement.</returns>
public Statement ToStatement()
{
Statement statement = new Statement();
statement.query = BuildQuery();
statement.values = valueEntries.ToArray();
return statement;
}
}
}
| |
//
// AmpacheService.cs
//
// Author:
// John Moore <[email protected]>
//
// Copyright (c) 2011 John Moore
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel;
using Android.App;
using Android.Content;
using Android.OS;
using Environment = Android.OS.Environment;
using JohnMoore.AmpacheNet.Entities;
using JohnMoore.AmpacheNet.DataAccess;
using JohnMoore.AmpacheNet.Logic;
namespace JohnMoore.AmpacheNet
{
[Service]
public class AmpacheService : Background
{
private const string CONFIGURATION = "configuration";
private const string URL_KEY = "url";
private const string USER_NAME_KEY = "user";
private const string PASSWORD_KEY = "password";
private const string ALLOW_SEEKING_KEY = "allowSeeking";
private const string CACHE_ART_KEY = "cacheArt";
private const string PLAYLIST_CSV_KEY = "playlist";
private AndroidPlayer _player;
private AmpacheNotifications _notifications;
private PendingIntent _stopIntent;
private PendingIntent _pingIntent;
private int _intentId = 1;
#region implemented abstract members of Android.App.Service
public override IBinder OnBind (Intent intent)
{
return new Binder(_container);
}
public override void OnLowMemory ()
{
GC.Collect();
}
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
{
return StartCommandResult.NotSticky;
}
public override void OnCreate ()
{
base.OnCreate ();
Console.SetOut(new AndroidLogTextWriter());
DataAccess.Configurator.ArtLocalDirectory = CacheDir.AbsolutePath;
_container = new Athena.IoC.Container();
_model = new AmpacheModel();
_container.Register<AmpacheModel>().To(_model);
DataAccess.Configurator.Configure(_container);
var am = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
var ping = new Intent(PingReceiver.INTENT);
_pingIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, ping, PendingIntentFlags.UpdateCurrent);
am.SetRepeating(AlarmType.RtcWakeup, Java.Lang.JavaSystem.CurrentTimeMillis() + (long)TimeSpan.FromMinutes(5).TotalMilliseconds, (long)TimeSpan.FromMinutes(5).TotalMilliseconds, _pingIntent);
var stm = Resources.OpenRawResource(Resource.Drawable.ct_default_artwork);
var stream = new System.IO.MemoryStream();
stm.CopyTo(stream);
stream.Position = 0;
Start(stream);
_player = new AndroidPlayer(_model, ApplicationContext);
_notifications = new AmpacheNotifications(this.ApplicationContext, _model);
var telSvc = this.ApplicationContext.GetSystemService(Context.TelephonyService) as Android.Telephony.TelephonyManager;
if(telSvc != null) {
telSvc.Listen(new AmpachePhoneStateListener(_model), Android.Telephony.PhoneStateListenerFlags.CallState);
}
}
public override void OnDestroy ()
{
base.OnDestroy ();
_player.Dispose();
_loader.Dispose();
_notifications.Dispose();
Console.WriteLine ("So long and Thanks for all the fish!");
Java.Lang.JavaSystem.RunFinalizersOnExit(true);
Java.Lang.JavaSystem.Exit(0);
}
#endregion
#region implemented abstract members of JohnMoore.AmpacheNet.Logic.Background
public override void PlatformFinalize ()
{
StopForeground(true);
var am = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
am.Cancel(_pingIntent);
am.Cancel(_stopIntent);
StopSelf();
}
public override void StartAutoShutOff ()
{
StopForeground(false);
var am = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
am.Set(AlarmType.ElapsedRealtimeWakeup, Java.Lang.JavaSystem.CurrentTimeMillis() + (long)TimeSpan.FromMinutes(30).Milliseconds, _stopIntent);
var stop = new Intent(StopServiceReceiver.INTENT);
_stopIntent = PendingIntent.GetBroadcast(ApplicationContext, ++_intentId, stop, PendingIntentFlags.UpdateCurrent);
am.Set(AlarmType.RtcWakeup, Java.Lang.JavaSystem.CurrentTimeMillis() + (long)TimeSpan.FromMinutes(30).TotalMilliseconds , _stopIntent);
}
public override void StopAutoShutOff ()
{
StartForeground(AmpacheNotifications.NOTIFICATION_ID, _notifications.AmpacheNotification);
var am = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
am.Cancel(_stopIntent);
_stopIntent.Dispose();
_stopIntent = null;
}
#endregion
#region Binding Classes
public class Binder : Android.OS.Binder
{
public readonly Athena.IoC.Container Container;
public Binder (Athena.IoC.Container container)
{
Container = container;
}
}
public class Connection : Java.Lang.Object, IServiceConnection
{
public event EventHandler OnConnected;
private readonly IClient _client;
public Connection(IClient client) : base()
{
_client = client;
}
#region IServiceConnection implementation
public void OnServiceConnected (ComponentName name, IBinder service)
{
_client.Connected(((Binder)service).Container);
}
public void OnServiceDisconnected (ComponentName name)
{}
#endregion
}
public interface IClient
{
void Connected(Athena.IoC.Container container);
}
#endregion
#region Receiver Classes
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new string[] {StopServiceReceiver.INTENT})]
public class StopServiceReceiver : BroadcastReceiver
{
public const string INTENT = "JohnMoore.AmpacheNET.STOP";
public override void OnReceive (Context context, Intent intent)
{
Console.WriteLine ("Shutdown Broadcast Received");
if (!_model.IsPlaying) {
_model.Dispose ();
}
}
}
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new string[] {PingReceiver.INTENT})]
public class PingReceiver : BroadcastReceiver
{
public const string INTENT = "JohnMoore.AmpacheNET.PING";
public override void OnReceive (Context context, Intent intent)
{
Console.WriteLine ("Ping Broadcast Received");
if(_model.Factory != null) {
Task.Factory.StartNew(() => _model.Factory.Ping ())
.ContinueWith((t) => Console.WriteLine (t.Exception.Message),TaskContinuationOptions.OnlyOnFaulted);
}
}
}
#endregion
}
}
| |
using System;
/*
* $Id: Tree.cs,v 1.2 2008/05/10 09:35:40 bouncy Exp $
*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
namespace Org.BouncyCastle.Utilities.Zlib {
internal sealed class Tree{
private const int MAX_BITS=15;
private const int BL_CODES=19;
private const int D_CODES=30;
private const int LITERALS=256;
private const int LENGTH_CODES=29;
private const int L_CODES=(LITERALS+1+LENGTH_CODES);
private const int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
internal const int MAX_BL_BITS=7;
// end of block literal code
internal const int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
internal const int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
internal const int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
internal const int REPZ_11_138=18;
// extra bits for each length code
internal static readonly int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
internal static readonly int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
internal static readonly int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
internal static readonly byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
internal const int Buf_size=8*2;
// see definition of array dist_code below
internal const int DIST_CODE_LEN=512;
internal static readonly byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
internal static readonly byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
internal static readonly int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
internal static readonly int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
internal static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]);
}
internal short[] dyn_tree; // the dynamic tree
internal int max_code; // largest code with non zero frequency
internal StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
internal void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int based = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= based) xbits = extra[n-based];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += (int)(((long)bits - (long)tree[m*2+1])*(long)tree[m*2]);
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
internal void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(System.Math.Max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
internal static void gen_codes(short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count // number of codes at each bit length
){
short[] next_code=new short[MAX_BITS+1]; // next code value for each bit length
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
internal static int bi_reverse(int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>=1;
res<<=1;
}
while(--len>0);
return res>>1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T>
{
private IList<T> list;
[NonSerialized]
private Object _syncRoot;
public ReadOnlyCollection(IList<T> list)
{
if (list == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
this.list = list;
}
public int Count
{
get { return list.Count; }
}
public T this[int index]
{
get { return list[index]; }
}
public bool Contains(T value)
{
return list.Contains(value);
}
public void CopyTo(T[] array, int index)
{
list.CopyTo(array, index);
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
public int IndexOf(T value)
{
return list.IndexOf(value);
}
protected IList<T> Items
{
get
{
return list;
}
}
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
T IList<T>.this[int index]
{
get { return list[index]; }
set
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
void ICollection<T>.Add(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<T>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList<T>.Insert(int index, T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<T>.Remove(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
void IList<T>.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)list).GetEnumerator();
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = list as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] items = array as T[];
if (items != null)
{
list.CopyTo(items, index);
}
else
{
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = list.Count;
try
{
for (int i = 0; i < count; i++)
{
objects[index++] = list[i];
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool IList.IsFixedSize
{
get { return true; }
}
bool IList.IsReadOnly
{
get { return true; }
}
object IList.this[int index]
{
get { return list[index]; }
set
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
int IList.Add(object value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return -1;
}
void IList.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
private static bool IsCompatibleObject(object value)
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
return false;
}
int IList.IndexOf(object value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value);
}
return -1;
}
void IList.Insert(int index, object value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.Remove(object value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
/// <include file='doc\XmlSchemaObjectTable.uex' path='docs/doc[@for="XmlSchemaObjectTable"]/*' />
public class XmlSchemaObjectTable
{
private Dictionary<XmlQualifiedName, XmlSchemaObject> _table = new Dictionary<XmlQualifiedName, XmlSchemaObject>();
private List<XmlSchemaObjectEntry> _entries = new List<XmlSchemaObjectEntry>();
internal XmlSchemaObjectTable()
{
}
internal void Add(XmlQualifiedName name, XmlSchemaObject value)
{
Debug.Assert(!_table.ContainsKey(name), "XmlSchemaObjectTable.Add: entry already exists");
_table.Add(name, value);
_entries.Add(new XmlSchemaObjectEntry(name, value));
}
internal void Insert(XmlQualifiedName name, XmlSchemaObject value)
{
XmlSchemaObject oldValue = null;
if (_table.TryGetValue(name, out oldValue))
{
_table[name] = value; //set new value
Debug.Assert(oldValue != null);
int matchedIndex = FindIndexByValue(oldValue);
Debug.Assert(matchedIndex >= 0);
//set new entry
Debug.Assert(_entries[matchedIndex].qname == name);
_entries[matchedIndex] = new XmlSchemaObjectEntry(name, value);
}
else
{
Add(name, value);
}
}
internal void Replace(XmlQualifiedName name, XmlSchemaObject value)
{
XmlSchemaObject oldValue;
if (_table.TryGetValue(name, out oldValue))
{
_table[name] = value; //set new value
Debug.Assert(oldValue != null);
int matchedIndex = FindIndexByValue(oldValue);
Debug.Assert(_entries[matchedIndex].qname == name);
_entries[matchedIndex] = new XmlSchemaObjectEntry(name, value);
}
}
internal void Clear()
{
_table.Clear();
_entries.Clear();
}
internal void Remove(XmlQualifiedName name)
{
XmlSchemaObject value;
if (_table.TryGetValue(name, out value))
{
_table.Remove(name);
int matchedIndex = FindIndexByValue(value);
Debug.Assert(matchedIndex >= 0);
Debug.Assert(_entries[matchedIndex].qname == name);
_entries.RemoveAt(matchedIndex);
}
}
private int FindIndexByValue(XmlSchemaObject xso)
{
int index;
for (index = 0; index < _entries.Count; index++)
{
if ((object)_entries[index].xso == (object)xso)
{
return index;
}
}
return -1;
}
/// <include file='doc\XmlSchemaObjectTable.uex' path='docs/doc[@for="XmlSchemaObjectTable.Count"]/*' />
public int Count
{
get
{
Debug.Assert(_table.Count == _entries.Count);
return _table.Count;
}
}
/// <include file='doc\XmlSchemaObjectTable.uex' path='docs/doc[@for="XmlSchemaObjectTable.Contains"]/*' />
public bool Contains(XmlQualifiedName name)
{
return _table.ContainsKey(name);
}
/// <include file='doc\XmlSchemaObjectTable.uex' path='docs/doc[@for="XmlSchemaObjectTable.this"]/*' />
public XmlSchemaObject this[XmlQualifiedName name]
{
get
{
XmlSchemaObject value;
if (_table.TryGetValue(name, out value))
{
return value;
}
return null;
}
}
/// <include file='doc\XmlSchemaObjectTable.uex' path='docs/doc[@for="XmlSchemaObjectTable.Names"]/*' />
public ICollection Names
{
get
{
return new NamesCollection(_entries, _table.Count);
}
}
/// <include file='doc\XmlSchemaObjectTable.uex' path='docs/doc[@for="XmlSchemaObjectTable.Values"]/*' />
public ICollection Values
{
get
{
return new ValuesCollection(_entries, _table.Count);
}
}
/// <include file='doc\XmlSchemaObjectTable.uex' path='docs/doc[@for="XmlSchemaObjectTable.GetEnumerator"]/*' />
public IDictionaryEnumerator GetEnumerator()
{
return new XSODictionaryEnumerator(_entries, _table.Count, EnumeratorType.DictionaryEntry);
}
internal enum EnumeratorType
{
Keys,
Values,
DictionaryEntry,
}
internal struct XmlSchemaObjectEntry
{
internal XmlQualifiedName qname;
internal XmlSchemaObject xso;
public XmlSchemaObjectEntry(XmlQualifiedName name, XmlSchemaObject value)
{
qname = name;
xso = value;
}
public XmlSchemaObject IsMatch(string localName, string ns)
{
if (localName == qname.Name && ns == qname.Namespace)
{
return xso;
}
return null;
}
public void Reset()
{
qname = null;
xso = null;
}
}
internal class NamesCollection : ICollection
{
private List<XmlSchemaObjectEntry> _entries;
private int _size;
internal NamesCollection(List<XmlSchemaObjectEntry> entries, int size)
{
_entries = entries;
_size = size;
}
public int Count
{
get { return _size; }
}
public Object SyncRoot
{
get
{
return ((ICollection)_entries).SyncRoot;
}
}
public bool IsSynchronized
{
get
{
return ((ICollection)_entries).IsSynchronized;
}
}
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
Debug.Assert(array.Length >= _size, "array is not big enough to hold all the items in the ICollection");
for (int i = 0; i < _size; i++)
{
array.SetValue(_entries[i].qname, arrayIndex++);
}
}
public IEnumerator GetEnumerator()
{
return new XSOEnumerator(_entries, _size, EnumeratorType.Keys);
}
}
//ICollection for Values
internal class ValuesCollection : ICollection
{
private List<XmlSchemaObjectEntry> _entries;
private int _size;
internal ValuesCollection(List<XmlSchemaObjectEntry> entries, int size)
{
_entries = entries;
_size = size;
}
public int Count
{
get { return _size; }
}
public Object SyncRoot
{
get
{
return ((ICollection)_entries).SyncRoot;
}
}
public bool IsSynchronized
{
get
{
return ((ICollection)_entries).IsSynchronized;
}
}
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
Debug.Assert(array.Length >= _size, "array is not big enough to hold all the items in the ICollection");
for (int i = 0; i < _size; i++)
{
array.SetValue(_entries[i].xso, arrayIndex++);
}
}
public IEnumerator GetEnumerator()
{
return new XSOEnumerator(_entries, _size, EnumeratorType.Values);
}
}
internal class XSOEnumerator : IEnumerator
{
private List<XmlSchemaObjectEntry> _entries;
private EnumeratorType _enumType;
protected int currentIndex;
protected int size;
protected XmlQualifiedName currentKey;
protected XmlSchemaObject currentValue;
internal XSOEnumerator(List<XmlSchemaObjectEntry> entries, int size, EnumeratorType enumType)
{
_entries = entries;
this.size = size;
_enumType = enumType;
currentIndex = -1;
}
public Object Current
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
switch (_enumType)
{
case EnumeratorType.Keys:
return currentKey;
case EnumeratorType.Values:
return currentValue;
case EnumeratorType.DictionaryEntry:
return new DictionaryEntry(currentKey, currentValue);
default:
break;
}
return null;
}
}
public bool MoveNext()
{
if (currentIndex >= size - 1)
{
currentValue = null;
currentKey = null;
return false;
}
currentIndex++;
currentValue = _entries[currentIndex].xso;
currentKey = _entries[currentIndex].qname;
return true;
}
public void Reset()
{
currentIndex = -1;
currentValue = null;
currentKey = null;
}
}
internal class XSODictionaryEnumerator : XSOEnumerator, IDictionaryEnumerator
{
internal XSODictionaryEnumerator(List<XmlSchemaObjectEntry> entries, int size, EnumeratorType enumType) : base(entries, size, enumType)
{
}
//IDictionaryEnumerator members
public DictionaryEntry Entry
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
return new DictionaryEntry(currentKey, currentValue);
}
}
public object Key
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
return currentKey;
}
}
public object Value
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
return currentValue;
}
}
}
}
}
| |
using System;
using System.Data;
using Epi.Data;
using Epi.Data.Services;
using EpiInfo.Plugin;
namespace Epi.Fields
{
/// <summary>
/// Input Field Without Separate Prompt abstract class
/// </summary>
public abstract class InputFieldWithoutSeparatePrompt : FieldWithoutSeparatePrompt, IMirrorable, IInputField
{
#region Private Class Members
private bool isReadOnly = false;
private bool isRequired = false;
private bool shouldRepeatLast = false;
private string tableName = string.Empty;
private object currentRecordValueObject = null;
private string _Namespace;
#endregion Private Class Members
#region Protected class members
/// <summary>
/// Db column type
/// </summary>
protected GenericDbColumnType genericDbColumnType = GenericDbColumnType.String;
/// <summary>
/// dbColumnType
/// </summary>
protected DbType dbColumnType = DbType.String;
#endregion Protected class members
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">The page the field belongs to</param>
public InputFieldWithoutSeparatePrompt(Page page)
: base(page)
{
Construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">The view the field belongs to</param>
public InputFieldWithoutSeparatePrompt(View view)
: base(view)
{
Construct();
}
private void Construct()
{
}
/// <summary>
/// Load an Input Field without Separate Prompt from a
/// <see cref="System.Data.DataRow"/>
/// </summary>
/// <param name="row">Row containing InputFieldWIthouthSeparatePrompt data.</param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
isRequired = (bool)row[ColumnNames.IS_REQUIRED];
isReadOnly = (bool)row[ColumnNames.IS_READ_ONLY];
shouldRepeatLast = (bool)row[ColumnNames.SHOULD_REPEAT_LAST];
tableName = row[ColumnNames.DATA_TABLE_NAME].ToString();
}
public override void AssignMembers(Object field)
{
(field as InputFieldWithoutSeparatePrompt).isRequired = this.isRequired;
(field as InputFieldWithoutSeparatePrompt).isReadOnly = this.isReadOnly;
(field as InputFieldWithoutSeparatePrompt).shouldRepeatLast = this.shouldRepeatLast;
(field as InputFieldWithoutSeparatePrompt).tableName = this.tableName;
base.AssignMembers(field);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Retuns the datatype of the field.
/// </summary>
public DataType DataType
{
get
{
return (DataType)AppData.Instance.FieldTypesDataTable.GetDataTypeByFieldTypeId((int)FieldType);
}
set
{
//this.DataType = value;
return;
}
}
/// <summary>
/// Retuns the EpiInfo.Plugin.datatype of the field.
/// </summary>
EpiInfo.Plugin.DataType EpiInfo.Plugin.IVariable.DataType
{
get
{
return (EpiInfo.Plugin.DataType)AppData.Instance.FieldTypesDataTable.GetDataTypeByFieldTypeId((int)FieldType);
}
set
{
return;
}
}/**/
/// <summary>
/// The variable type of a field is always DataSourceField.
/// </summary>
public VariableType VarType
{
get
{
return VariableType.DataSource;
}
}
/// <summary>
/// The variable type of a field is always DataSourceField.
/// </summary>
public VariableScope VariableScope
{
get
{
return VariableScope.DataSource;
}
set { return; }
}
/// <summary>
/// Field namespace
/// </summary>
public string Namespace { get { return this._Namespace; } set { this._Namespace = value; } }
/// <summary>
/// Returns a string representation of Current Record Value
/// </summary>
public virtual string CurrentRecordValueString
{
get
{
if (CurrentRecordValueObject == null) return string.Empty;
else return CurrentRecordValueObject.ToString();
}
set
{
CurrentRecordValueObject = value;
}
}
/// <summary>
/// Returns current record value as a DB Query parameter.
/// </summary>
public QueryParameter CurrentRecordValueAsQueryParameter
{
get
{
object paramValue = DBNull.Value;
if (!Util.IsEmpty(CurrentRecordValueObject))
{
paramValue = this.CurrentRecordValueObject;
}
return new QueryParameter("@" + this.Name, this.dbColumnType, paramValue);
}
}
/// <summary>
/// Expression for the variable is the table name plus field name separated by a dot
/// </summary>
public string Expression
{
get
{
return GetProject().CollectedData.GetDatabase().InsertInEscape(tableName) + "." + this.Name;
}
set
{
throw new ApplicationException("Expression can't be set");
}
}
/// <summary>
/// Field's table name
/// </summary>
public string TableName
{
get
{
return tableName;
}
set
{
tableName = value;
}
}
/// <summary>
/// Gets/sets Read only flag
/// </summary>
public bool IsReadOnly
{
get
{
return (isReadOnly);
}
set
{
isReadOnly = value;
}
}
/// <summary>
/// Gets/sets Required flag.
/// </summary>
public bool IsRequired
{
get
{
return (isRequired);
}
set
{
isRequired = value;
}
}
/// <summary>
/// Gets/sets should repeat last flag
/// </summary>
public bool ShouldRepeatLast
{
get
{
return (shouldRepeatLast);
}
set
{
shouldRepeatLast = value;
}
}
/// <summary>
/// Gets/sets the data contents of the field
/// </summary>
public virtual object CurrentRecordValueObject
{
get
{
return currentRecordValueObject;
}
set
{
currentRecordValueObject = value;
}
}
/// <summary>
/// Gets the SQL Data type
/// </summary>
public virtual string GetDbSpecificColumnType()
{
if (genericDbColumnType != GenericDbColumnType.Unknown)
{
return GetProject().CollectedData.GetDatabase().GetDbSpecificColumnType(genericDbColumnType);
}
else
{
throw new GeneralException("genericDbColumnType is not set: " + this.FieldType.ToString());
}
}
public string Prompt { get { return this.Name; } set { return; } }
#endregion Public Properties
#region Public Methods
/// <summary>
/// Returns the Variable type enumeration value.
/// </summary>
/// <param name="typeCombination">Variable Type enum combination.</param>
/// <returns>True/False on variable type test.</returns>
public bool IsVarType(VariableType typeCombination)
{
return VariableBase.IsVarType(this.VarType, typeCombination);
}
/// <summary>
/// Returns the string value that is reflected my a mirror field.
/// </summary>
/// <returns>reflected value string</returns>
public virtual string GetReflectedValue()
{
return this.CurrentRecordValueString;
}
public void SetNewRecordValue()
{
if (shouldRepeatLast == false)
{
if (genericDbColumnType == GenericDbColumnType.String)
{
CurrentRecordValueString = string.Empty;
}
else
{
CurrentRecordValueObject = null;
}
}
}
#endregion Public Methods
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;
using Its.Recipes;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
namespace Its.Configuration.Tests
{
public class SettingsTests
{
[SetUp]
public void SetUp()
{
Settings.Reset();
Environment.SetEnvironmentVariable("Its.Configuration.Settings.Precedence", null);
Settings.CertificatePassword = null;
}
[TearDown]
public void TearDown()
{
Environment.SetEnvironmentVariable("Its.Configuration.Settings.Precedence", null);
}
[Test]
public void Settings_Get_T_deserializes_its_Value_from_config_source()
{
var settings = Settings.Get<LogDbConnection>();
settings.ConnectionString
.Should().Be("Data Source=(localdb)\\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
}
[Test]
public void Settings_Get_deserializes_its_Value_from_config_source()
{
dynamic settings = Settings.Get(typeof (LogDbConnection));
string connectionString = settings.ConnectionString;
connectionString
.Should().Be("Data Source=(localdb)\\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
}
[Test]
public void Default_values_can_be_declared_in_the_class_and_are_not_overwritten_when_the_value_is_not_present_in_the_config_source()
{
var settings = Settings.Get<LogDbConnection>();
settings.WriteRetries
.Should().Be(3);
}
[Test]
public void Uris_are_supported()
{
Settings.For<Widget<Uri>>.GetSerializedSetting = key => new
{
TheSetting = new Uri("http://blammo.com")
}.ToJson();
var settings = Settings.Get<Widget<Uri>>();
settings.TheSetting.ToString()
.Should().Be("http://blammo.com/");
}
[Test]
public void Parseable_DateTime_formats_are_supported()
{
Settings.For<Widget<DateTime>>.GetSerializedSetting = key => new
{
TheSetting = "2/20/2013"
}.ToJson();
var settings = Settings.Get<Widget<DateTime>>();
settings.TheSetting
.Should().Be(DateTime.Parse("2/20/2013"));
}
[Test]
public void Parseable_DateTimeOffset_formats_are_supported()
{
Settings.For<Widget<DateTimeOffset>>.GetSerializedSetting = key => new
{
TheSetting = "2/20/2013"
}.ToJson();
var settings = Settings.Get<Widget<DateTimeOffset>>();
settings.TheSetting
.Should().Be(DateTimeOffset.Parse("2/20/2013"));
}
[Test]
public void Settings_are_looked_up_by_file_name_by_default_from_json_files_in_the_root_of_the_config_folder()
{
Settings.Precedence = null;
var settings = Settings.Get<EnvironmentSettings>();
settings.Name.Should().Be("local");
settings.IsLocal.Should().BeTrue();
settings.IsTest.Should().BeTrue();
}
[Test]
public void Settings_can_be_resolved_from_a_file_name_that_does_not_match_the_class_name()
{
Settings.GetSerializedSetting = name =>
{
var fileInfo = Settings.GetFile(f =>
f.Name.Equals((name + ".json")
.Replace("NotNamed", ""),
StringComparison.InvariantCultureIgnoreCase));
return File.ReadAllText(fileInfo.FullName);
};
var settings = Settings.Get<NotNamedEnvironmentSettings>();
settings.Name.Should().Be("test");
settings.IsLocal.Should().BeFalse();
settings.IsTest.Should().BeTrue();
}
[Test]
public void Config_folder_selection_is_case_insensitive()
{
Settings.Precedence = new[] { "PRODUCTION" }; // the actual folder name is "production"
var settings = Settings.Get<EnvironmentSettings>();
settings.Name.Should().Be("production");
settings.IsLocal.Should().BeFalse();
settings.IsTest.Should().BeFalse();
}
[Test]
public void When_an_order_of_precedence_is_specified_then_settings_are_looked_up_by_file_name_from_json_files_in_the_environment_folder_under_the_config_folder()
{
Settings.Precedence = new[] { "production" };
var settings = Settings.Get<EnvironmentSettings>();
settings.Name.Should().Be("production");
settings.IsLocal.Should().BeFalse();
settings.IsTest.Should().BeFalse();
}
[Test]
public void GetFile_uses_stated_precedence()
{
var file = Settings.GetFile(f => f.Name == "EnvironmentSettings.json");
file.DirectoryName.Should().EndWith("test");
Settings.Reset();
Settings.Precedence = new[] { "production" };
file = Settings.GetFile(f => f.Name == "EnvironmentSettings.json");
file.DirectoryName.Should().EndWith("production");
}
[Test]
public void When_an_order_of_precedence_is_specified_then_each_folder_is_consulted_in_order_and_the_first_hit_wins()
{
Settings.Precedence = new[] { "test", "production" };
var settings = Settings.Get<EnvironmentSettings>();
settings.Name.Should().Be("test");
settings.IsLocal.Should().BeFalse();
settings.IsTest.Should().BeTrue();
}
[Test]
public void When_an_order_of_precedence_is_specified_then_nonexistent_subfolders_are_ignored()
{
Settings.Precedence = new[] { "nonexistent", "test" };
var settings = Settings.Get<EnvironmentSettings>();
settings.Name.Should().Be("test");
settings.IsLocal.Should().BeFalse();
settings.IsTest.Should().BeTrue();
}
[Test]
public void When_Settings_Set_is_used_to_set_a_value_for_a_type_then_Get_returns_that_value()
{
Func<EnvironmentSettings> settingsCreator = () => new EnvironmentSettings { IsLocal = true, IsTest = false, Name = "explicit_set" };
Settings.Set(settingsCreator());
var settings = Settings.Get<EnvironmentSettings>();
settings.ShouldBeEquivalentTo(settingsCreator());
}
[Test]
public void When_Settings_Set_is_used_to_set_a_value_for_a_type_and_precedence_is_also_configured_then_Get_returns_the_set_value_instead_of_the_one_found_in_the_precedence_specified_settings()
{
Settings.Precedence = new[] { "test" };
Func<EnvironmentSettings> settingsCreator = () => new EnvironmentSettings { IsLocal = true, IsTest = false, Name = "explicit_set" };
Settings.Set(settingsCreator());
var settings = Settings.Get<EnvironmentSettings>();
settings.ShouldBeEquivalentTo(settingsCreator());
}
[Test]
public void When_an_order_of_precedence_is_specified_then_setting_files_in_the_root_are_used_if_not_found_in_a_subfolder()
{
Settings.Precedence = new[] { "production" };
var settings = Settings.Get<OnlyConfiguredInRootFolder>();
settings.Value.Should().Be("correct");
}
[Test]
public void Trace_output_indicates_the_resolved_source_for_the_settings()
{
string log = "";
Settings.Precedence = new[] { "nonexistent", "test", "production" };
var listener = new TestTraceListener();
listener.OnTrace += (Action<string>) (s => log += s);
Trace.Listeners.Add(listener);
using (new AnonymousDisposable(() => Trace.Listeners.Remove(listener)))
{
Settings.Get<EnvironmentSettings>();
}
log.Should().Contain(string.Format("Resolved setting 'EnvironmentSettings' from settings folder ({0})", Path.Combine(Deployment.Directory, ".config", "test")));
}
[Test]
public void Settings_are_looked_up_from_environment_variables()
{
var name = Guid.NewGuid().ToString();
var json = new EnvironmentVariableTestSettings
{
Name = name
}.ToJson();
Environment.SetEnvironmentVariable("EnvironmentVariableTestSettings", json);
var settings = Settings.Get<EnvironmentVariableTestSettings>();
settings.Name.Should().Be(name);
}
[Test]
public void Settings_Get_returns_a_default_instance_if_no_settings_are_found()
{
var settings = Settings.Get<UnconfiguredSettings>();
settings.Value.Should().Be(new UnconfiguredSettings().Value);
}
[Test]
public void The_first_settings_source_to_return_a_non_null_or_empty_value_is_used()
{
Settings.Sources = new[]
{
Settings.CreateSource(key => null),
Settings.CreateSource(key => ""),
Settings.CreateSource(key => new { WriteRetries = 100 }.ToJson()),
Settings.CreateSource(key => new { WriteRetries = 200 }.ToJson())
};
var settings = Settings.Get<LogDbConnection>();
settings.WriteRetries.Should().Be(100);
}
[Test]
public void Settings_sources_later_in_the_sequence_than_the_first_to_return_a_value_are_ignored()
{
var secondSourceWasCalled = false;
Settings.Sources = new[]
{
Settings.CreateSource(key => new { WriteRetries = 100 }.ToJson()),
Settings.CreateSource(key =>
{
secondSourceWasCalled = true;
return new { WriteRetries = 200 }.ToJson();
})
};
secondSourceWasCalled.Should().BeFalse();
}
[Test]
public void Single_parameter_generic_settings_types_use_a_known_convention_to_look_up_corresponding_settings()
{
string requestKey = null;
Settings.For<Widget<SettingsTests>>.GetSerializedSetting = key =>
{
requestKey = key;
return null;
};
Settings.Get<Widget<SettingsTests>>();
requestKey.Should().Be("Widget(SettingsTests)");
}
[Test]
public void Multiple_parameter_generic_settings_types_use_a_known_convention_to_look_up_corresponding_settings()
{
string requestKey = null;
Settings.For<Dictionary<string, Widget<int>>>.GetSerializedSetting = key =>
{
requestKey = key;
return null;
};
Settings.Get<Dictionary<string, Widget<int>>>();
requestKey.Should().Be("Dictionary(String,Widget(Int32))");
}
[Test]
public void Abstract_settings_indicate_a_type_redirect_via_AppSettings()
{
var settings = Settings.Get<AbstractSettings>();
settings.Value.Should().Be("found me!"); // configured in app.config
}
[NUnit.Framework.Ignore("Scenario under development")]
[Test]
public void SettingsBase_maps_its_own_properties_from_serialized_values_on_construction()
{
// TODO: (SettingsBase_maps_its_own_properties_from_serialized_values_on_construction)
Settings.GetSerializedSetting = _ => new
{
String = "hello",
Int = 5
}.ToJson();
Assert.Fail("Broken: ctor never completes");
var settings = new DerivedFromSettingsBase();
settings.String.Should().Be("hello");
settings.Int.Should().Be(5);
}
[Test]
public void Configuration_folder_location_can_be_specified()
{
Settings.SettingsDirectory = Path.Combine(Deployment.Directory, ".alternateConfig");
Settings.Get<EnvironmentSettings>().Name.Should().Be("alternate");
}
[Test]
public void Settings_are_only_looked_up_and_deserializd_once_per_type()
{
int deserializeCount = 0;
int lookupCount = 0;
Settings.Sources = new[]
{
Settings.CreateSource(key =>
{
lookupCount++;
return "_";
})
};
Settings.Deserialize = (type, json) =>
{
deserializeCount++;
return new object();
};
Settings.Get<object>();
Settings.Get<object>();
Settings.Get<object>();
deserializeCount.Should().Be(1);
lookupCount.Should().Be(1);
}
[Test]
public void Settings_precedence_set_via_an_environment_variable_overrides_app_config()
{
// default behavior check...
var settings = Settings.Get<EnvironmentSettings>();
settings.Name.Should().Be("test");
Settings.Reset();
Environment.SetEnvironmentVariable("Its.Configuration.Settings.Precedence", "production");
settings = Settings.Get<EnvironmentSettings>();
settings.Name.Should().Be("production");
}
public class Credentials
{
public string Username { get; set; }
public string Password { get; set; }
}
public class LogDbConnection
{
public LogDbConnection()
{
WriteRetries = 3;
}
public virtual string ConnectionString { get; set; }
public virtual int WriteRetries { get; set; }
}
public class Widget<T>
{
public T TheSetting { get; set; }
}
public class EnvironmentVariableTestSettings
{
public string Name { get; set; }
}
public class UnconfiguredSettings
{
public UnconfiguredSettings()
{
Value = 42;
}
public int Value { get; set; }
}
internal class DerivedFromSettingsBase : SettingsBase
{
public string String { get; set; }
public int Int { get; set; }
}
internal abstract class SettingsBase
{
protected SettingsBase()
{
var myType = GetType();
var serialized = Settings.GetSerializedSetting(myType.Name);
var mapperType = typeof (MappingExpression.From<>).MakeGenericType(myType);
var map = mapperType
.GetMethod("ToExisting")
.MakeGenericMethod(myType).Invoke(null, null);
var deserialized = Settings.Deserialize(myType, serialized);
((dynamic) map)(deserialized, this);
}
}
public class OnlyConfiguredInRootFolder
{
public string Value { get; set; }
}
public abstract class AbstractSettings
{
public string Value { get; set; }
}
public class NotNamedEnvironmentSettings
{
public string Name { get; set; }
public bool IsLocal { get; set; }
public bool IsTest { get; set; }
}
public class DerivedFromAbstractSettings : AbstractSettings
{
}
public class TestTraceListener : TraceListener
{
public event Action<string> OnTrace;
public override void Write(string message)
{
WriteLine(message);
}
public override void WriteLine(string message)
{
var handler = OnTrace;
if (handler != null)
{
handler( message);
}
}
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Random = UnityEngine.Random;
//version one has meshFilter requirement HOWEVER, we will eventually make an enum selection to choose
// between a skinned mesh, mesh or some other thing.
[RequireComponent(typeof(ParticleSystem))]
[System.Serializable]
public class EmissiveParticleMesh : MonoBehaviour
{
//this is for the Baked Mesh Return data
[System.Serializable]
public class SampleData
{
public Vector3 position;
public Vector3 normal;
public SampleData()
{
}
public SampleData(Vector3 _POS, Vector3 _NORM)
{
position = _POS;
normal = _NORM;
}
}
//The Baked particle data
[System.Serializable]
public class TextureData
{
public Vector3 position;
public Vector3 normal;
public Vector2 UV;
public int index0;
public int index1;
public int index2;
public Color color;
public bool valid;
public TextureData()
{
position = Vector3.zero;
normal = Vector3.forward;
color = Color.white;
valid = false;
}
public TextureData(Vector3 _POSITION, Vector3 _NORMAL, Color _COLOR, Vector2 _UV, int _IND0, int _IND1, int _IND2)
{
index0 = _IND0;
index1 = _IND1;
index2 = _IND2;
UV = _UV;
position = _POSITION;
normal = _NORMAL;
color = _COLOR;
valid = true;
}
}
// Use this for initialization
//This is used to vary the type of load the computation will proceed at
public enum ComputationType
{
Light,
Medium,
Heavy
};
public ComputationType computationType = ComputationType.Light;
public bool useSkinnedMeshRenderer = false;
public bool Randomness = false;
public bool UseRandomPositioning = false;
public bool emitFromNormal = true;
public bool useSampledColor = true;
public bool playOnAwake = true;
public bool loop = true;
public bool playing = false;
public bool debuggingSpawns = false;
public bool useAlpha = false;
public bool finished = false;
public Vector3 MinVector3 = Vector3.one * -1;
public Vector3 MaxVector3 = Vector3.one;
public Vector2 Tiling = Vector2.one;
public Vector2 Offset = Vector2.zero;
public Texture2D spawnTex;
public int sampleWidth = 16;
public int computationProcess = 0;
private float currentSecond = 0.0f;
private float currentDuration = 0.0f;
public float randomPositioning = 1.0f;
[Range(0.0f, 1.0f)]
public float threshold = 0.5f;
//[SerializeField]
public List<TextureData> spawnData;
private Mesh mesh;
private SkinnedMeshRenderer smr;
public ParticleSystem ps;
private ParticleSystem.Particle[] particles;
private ParticleSystem.Burst[] bursts;
//this just samples the baked mesh based on hte precomputed indices, since they probably dont change... the vertex and normal however does.
public SampleData ResampleSkinnedMesh(TextureData data)
{
SampleData sample = new SampleData();
sample.position = Vector3.zero;
sample.normal = Vector3.zero;
Vector2 a = mesh.uv[data.index0], b = mesh.uv[data.index1], c = mesh.uv[data.index2];
Vector3 A = mesh.vertices[data.index0], B = mesh.vertices[data.index1], C = mesh.vertices[data.index2];
Vector3 AN = mesh.normals[data.index0], BN = mesh.normals[data.index1], CN = mesh.normals[data.index2];
float numer = Vector2.Angle((c - b).normalized, (data.UV - b).normalized);
float denom = Vector2.Angle((c - b).normalized, (a - b).normalized);
float CtoA = numer / denom;
Vector3 Start = B;
Vector3 End = Vector3.Lerp(C, A, CtoA);
Vector2 end2 = Vector3.Lerp(c, a, CtoA);
float dist = Vector2.Distance(b, data.UV) / Vector2.Distance(b, end2);
Vector3 finalPos = Vector3.Lerp(Start, End, dist);
Vector3 nEnd = Vector3.Lerp(CN, AN, CtoA);
Vector3 finalNormal = Vector3.Lerp(BN, nEnd, dist);
sample.position = finalPos;
sample.normal = finalNormal;
return sample;
}
//This function checks whether a point is within a UV coordinate given by the vertices at the provided indices
/*
This works by taking any given point in UV space given another ambiguous and projects a dot from the UV point of the vertex to the other UV points of hte other two vertex (assuming we have triangles).
then if the dot value of vertex1 - vertex0 and vertex2 - vertex0 is less than the dot from either (vertex1 or vertex2) - vertex0 and the UVpoint then the point is outside of the triangle projection where the opposite SIDE is infinitely large, repeat for other sides.
*/
private TextureData UVIntersectV1(int index1, int index2, int index3, Vector2 point)
{
//get all UVs
Vector2 a = mesh.uv[index1], b = mesh.uv[index2], c = mesh.uv[index3];
//UV direction 1
if (Vector2.Dot((point - a).normalized, (c - a).normalized) >= Vector2.Dot((b - a).normalized, (c - a).normalized))
{
//UV direction 2
if (Vector2.Dot((point - b).normalized, (a - b).normalized) >= Vector2.Dot((a - b).normalized, (c - b).normalized))
{
//UV direction 3
if (Vector2.Dot((point - c).normalized, (b - c).normalized) >= Vector2.Dot((b - c).normalized, (a - c).normalized))
{
//Get all vertices and normals
Vector3 A = mesh.vertices[index1], B = mesh.vertices[index2], C = mesh.vertices[index3];
Vector3 AN = mesh.normals[index1], BN = mesh.normals[index2], CN = mesh.normals[index3];
float numer = Vector2.Angle((b - a).normalized, (point - a).normalized);
float denom = Vector2.Angle((b - a).normalized, (c - a).normalized);
//part of the return value
//float BtoC = numer / denom;//not actually necessary in the calculations
numer = Vector2.Angle((c - b).normalized, (point - b).normalized);
denom = Vector2.Angle((c - b).normalized, (a - b).normalized);
float CtoA = numer / denom;
//numer = Vector2.Angle((a - c).normalized, (point - c).normalized);
//denom = Vector2.Angle((a - c).normalized, (b - c).normalized);
//float AtoB = numer / denom;//also not necessary
//position data
//project a point between the other two vertices based on the dot value then taking the distance ratio for the UV point and projecting that vertex to the interpolated position (original).
Vector3 Start = B;
Vector3 End = Vector3.Lerp(C, A, CtoA);
Vector2 end2 = Vector3.Lerp(c, a, CtoA);
float dist = Vector2.Distance(b, point) / Vector2.Distance(b, end2);
Vector3 finalPos = Vector3.Lerp(Start, End, dist);
Vector3 nEnd = Vector3.Lerp(CN,AN,CtoA);
Vector3 finalNormal = Vector3.Lerp(BN, nEnd, dist);
return new TextureData(finalPos, finalNormal, Color.white, point, index1, index2, index3);
}
}
}
//impossible lerp for our space, treat as false
return new TextureData();
}
//intermediate function that transforms UVs into indices
TextureData CalculateSpawns(float x, float y, int i)
{
//for each triangle in the mesh lets pass the values
TextureData data;
Vector2 uvPoint = new Vector2(x,y);
//0,1,2
int index0 = mesh.triangles[i], index1 = mesh.triangles[i+1], index2 = mesh.triangles[i+2];
data = UVIntersectV1(index0, index1,index2, uvPoint);
if (data.valid)
{
return data;
}
return new TextureData();
}
public IEnumerator CalculateTextureEmission()
{
finished = false;
spawnData = new List<TextureData>();
//this needs to be agnostic to MeshRenderer or SkinnedMeshRenderer;
MeshFilter MF = GetComponent<MeshFilter>();
if(MF != null)
{
mesh = MF.sharedMesh;
}
if (mesh == null)
{
useSkinnedMeshRenderer = true;
smr = GetComponent<SkinnedMeshRenderer>();
//mesh = new Mesh();
//smr.BakeMesh(mesh);
mesh = smr.sharedMesh;
//smr.BakeMesh(mesh);
}
sampleWidth = Mathf.Clamp(sampleWidth, 0, spawnTex.width - 1);
int totalWidth = (int)(spawnTex.width * Tiling.x);
int totalHeight = (int)(spawnTex.height * Tiling.y);
for (int i = 0; i < totalWidth; i += sampleWidth)
{
if(computationType == ComputationType.Medium)
yield return null;
for (int j = 0; j < totalHeight; j += sampleWidth)
{
if (computationType == ComputationType.Light)
yield return new WaitForSeconds(1.0f/60.0f);
computationProcess = (int)(spawnTex.width * i * Tiling.x + j);
Color c;
int UVX = (i%spawnTex.width), UVY = (j%spawnTex.height);
if (i > spawnTex.width)
UVX = (i + (int)(Offset.x * totalWidth / Tiling.x)) % spawnTex.width;
if (j > spawnTex.height)
UVY = (j + (int)(Offset.y * totalHeight / Tiling.y)) % spawnTex.height;
c = spawnTex.GetPixel(UVX, UVY);
if (((c.r + c.g + c.b) * ((useAlpha) ? c.a : 1.0f)) / 3 > threshold)
{
for (int index = 0; index < mesh.triangles.Length; index += 3)
{
//for now lets just spawn at 0
//spawnLocations.Add(new Vector3(i, j, 0) *(1.0f / spawnTex.height) - new Vector3(0.5f,0.5f,0));
//Multiply the point by 1/tiling.x or y
float xPos, yPos;
xPos = (float)i;
yPos = (float)j;
//Tiling
//xPos
//Offset
xPos = ((((float)i)) / (totalWidth)) - Offset.x / Tiling.x;
if (xPos > 1.0f)
xPos -= 1.0f;
if (xPos < 0.0f)
xPos += 1.0f;
yPos = ((((float)j)) /(totalHeight)) - Offset.y / Tiling.y;
if (yPos < 0.0f)
yPos += 1.0f;
if (yPos > 1.0f)
{
yPos -= 1.0f;
}
/////float uvX = ((xPos + dx) / (spawnTex.width * Tiling.x));
//float xOFFSETTILE = 1.0f / Tiling.x;
//float dx = 0;
//while (dx < Tiling.x)
//{
// dx += xOFFSETTILE;
// float uvX = ((xPos + dx)/ (spawnTex.width * Tiling.x));
// while (uvX >Tiling.x)
// uvX -= Tiling.x;
TextureData data = CalculateSpawns(xPos, yPos, index);
if (!data.valid)
{
continue;
}
data.color = c;
spawnData.Add(data);
}
}
}
}
computationProcess = (int)(spawnTex.width * spawnTex.height * Tiling.x * Tiling.y);
finished = true;
}
public void Play()
{
playing = true;
}
public void Stop()
{
playing = false;
}
void Start ()
{
//start just behind the start in order to get bursts of particles that occur at 0:00
currentDuration = 0.0f - float.Epsilon;
//get the current particle system
ps = GetComponent<ParticleSystem>();
//play now?!
if (playOnAwake)
{
playing = true;
}
//buggy af
//if(playOnAwake)
// ps.Play();
//stop playing default
ps.Stop();
smr = GetComponent<SkinnedMeshRenderer>();
if (smr == null)
{
useSkinnedMeshRenderer = false;
mesh = GetComponent<MeshFilter>().mesh;
}
else
useSkinnedMeshRenderer = true;
}
//for debugging purposes
void OnDrawGizmosSelected()
{
if (debuggingSpawns)
{
if (spawnData != null)
{
//calculate distance from each point to the camera and scale it by that maybe... TODO:::
SampleData nSD;
if (useSkinnedMeshRenderer)
{
if (smr == null)
{
smr = GetComponent<SkinnedMeshRenderer>();
if (smr == null)
useSkinnedMeshRenderer = false;
else
mesh = smr.sharedMesh;
}
}
for (int i = 0; i < spawnData.Count; ++i)
{
Vector3 spawnPos = spawnData[i].position;
if (useSkinnedMeshRenderer)
{
nSD = ResampleSkinnedMesh(spawnData[i]);
spawnPos = nSD.position;
}
Vector3 wPos = transform.TransformPoint(spawnPos);
float scalar = Vector3.Distance(Camera.current.transform.position, wPos);
Gizmos.color = spawnData[i].color;
//so we can have scaling on the debug spheres.
Gizmos.DrawSphere(wPos, 0.02f + 0.01f * transform.lossyScale.magnitude * (scalar));
}
}
}
}
//to stop looping.
public void Loop(bool b)
{
loop = b;
}
void FixedUpdate () {
//override emission of particles, due to an issue with one of Unity's functions we need to instead get and Set particles
//currently this does not emit via distance
if (playing)
{
currentSecond += Time.fixedDeltaTime;
currentDuration += Time.fixedDeltaTime;
if (currentDuration > ps.main.duration)
{
if (!loop)
playing = false;
}
//sampling curves
if (ps.emission.rateOverTime.mode == ParticleSystemCurveMode.Constant)
if (ps.emission.enabled)
{
if (currentSecond * ps.emission.rateOverTime.constant > 1)
{
ps.Emit((int)(1 * currentSecond * ps.emission.rateOverTime.constant));
currentSecond = 0.0f;
}
}
if (ps.emission.rateOverTime.mode == ParticleSystemCurveMode.Curve)
{
if (ps.emission.enabled)
{
if (currentSecond * ps.emission.rateOverTime.Evaluate(currentDuration / ps.main.duration) > 1)
{
ps.Emit((int)(currentSecond * ps.emission.rateOverTime.Evaluate(currentDuration / ps.main.duration)));
currentSecond = 0.0f;
}
}
}
//updated each call because new bursts could be added at any time...
bursts = new ParticleSystem.Burst[ps.emission.burstCount];
ps.emission.GetBursts(bursts);
for (int i = 0; i < bursts.Length; ++i)
{
//check for bursts using delta
if (currentDuration < bursts[i].time)
if (currentDuration + Time.fixedDeltaTime > bursts[i].time)
{
//emit
ps.Emit(Random.Range(bursts[i].minCount, bursts[i].maxCount));
}
//now perform the wrapping statement from end frame to beginning;
if (currentDuration > ((currentDuration + Time.fixedDeltaTime) % ps.main.duration))
{
if (bursts[i].time < ((currentDuration + Time.fixedDeltaTime) % ps.main.duration))
{
ps.Emit(Random.Range(bursts[i].minCount, bursts[i].maxCount));
}
}
}
currentDuration = currentDuration % ps.main.duration;
particles = new ParticleSystem.Particle[ps.particleCount];
ps.GetParticles(particles);
//make sure it has stopped (from the players perspective).
ps.Stop();
//ps.SetParticles(particles, particles.Length);
//OLD
//currentTime -= Time.fixedDeltaTime;
if (ps.particleCount > 0)
{
//generate a new mesh snapshot if required
//if we are skinned then we need to get the current skinned mesh renderer if we dont already have a reference to it then BAKE the mesh
if (useSkinnedMeshRenderer)
{
if (smr == null)
{
smr = GetComponent<SkinnedMeshRenderer>();
if (smr == null)
useSkinnedMeshRenderer = false;
}
if (mesh == null)
{
mesh = new Mesh();
}
smr.BakeMesh(mesh);
}
//currentTime = 1/(ps.emission.rate.constantMax/2);
if (spawnData.Count > 0)
{
SampleData nSD;
for (int i = 0; i < particles.Length; ++i)
{
if (particles[i].remainingLifetime >= particles[i].startLifetime - float.Epsilon)
{
//particles[i].remainingLifetime = particles[i].startLifetime;
//particles[i].startSize = 100;
int index = Random.Range(0, spawnData.Count);
Vector3 spawnPos = spawnData[index].position;
Vector3 spawnNorm = spawnData[index].normal;
if (useSkinnedMeshRenderer)
{
nSD = ResampleSkinnedMesh(spawnData[index]);
spawnPos = nSD.position;
spawnNorm = nSD.normal;
}
if (UseRandomPositioning)
{
spawnPos += Random.insideUnitSphere * randomPositioning;
}
//emitParams.position = (spawnPos);
particles[i].position = spawnPos;
spawnNorm = (spawnNorm + new Vector3(Random.Range(MinVector3.x, MaxVector3.x) * transform.lossyScale.x, Random.Range(MinVector3.y, MaxVector3.y) * transform.lossyScale.y, Random.Range(MinVector3.z, MaxVector3.z) * transform.lossyScale.z)).normalized;
//set simulation space
if (ps.main.simulationSpace == ParticleSystemSimulationSpace.World)
{
particles[i].position = transform.TransformPoint(spawnPos);
spawnNorm = transform.TransformDirection(spawnNorm);
}
if (ps.main.simulationSpace == ParticleSystemSimulationSpace.Custom)
{
particles[i].position = ps.main.customSimulationSpace.TransformPoint(spawnPos);
spawnNorm = ps.main.customSimulationSpace.TransformDirection(spawnNorm);
}
//use the sampled NORMAL of the mesh point
if (emitFromNormal)
{
//This may require reworking.
particles[i].velocity = (spawnNorm.normalized).normalized * ps.main.startSpeed.Evaluate(0.0f);
}
//use the sampled color of the texture guide
if (useSampledColor)
particles[i].startColor = spawnData[index].color;
}
}
}
}
//now set the particles back
ps.SetParticles(particles, particles.Length);
}
}
}
| |
//+-----------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation
//
// File: GenericTextProperties.cs
//
// Contents: Generic implementation of TextFormatter abstract classes
//
// Created: 3-9-2003 Worachai Chaoweeraprasit (wchao)
//
//------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using System.Globalization;
namespace MS.Internal.TextFormatting
{
/// <summary>
/// Generic implementation of TextRunProperties
/// </summary>
internal sealed class GenericTextRunProperties : TextRunProperties
{
/// <summary>
/// Constructing TextRunProperties
/// </summary>
/// <param name="typeface">typeface</param>
/// <param name="size">text size</param>
/// <param name="hintingSize">text size for Truetype hinting program</param>
/// <param name="culture">text culture info</param>
/// <param name="textDecorations">TextDecorations </param>
/// <param name="foregroundBrush">text foreground brush</param>
/// <param name="backgroundBrush">highlight background brush</param>
/// <param name="baselineAlignment">text vertical alignment to its container</param>
/// <param name="substitution">number substitution behavior to apply to the text; can be null,
/// in which case the default number substitution method for the text culture is used</param>
public GenericTextRunProperties(
Typeface typeface,
double size,
double hintingSize,
TextDecorationCollection textDecorations,
Brush foregroundBrush,
Brush backgroundBrush,
BaselineAlignment baselineAlignment,
CultureInfo culture,
NumberSubstitution substitution
)
{
_typeface = typeface;
_emSize = size;
_emHintingSize = hintingSize;
_textDecorations = textDecorations;
_foregroundBrush = foregroundBrush;
_backgroundBrush = backgroundBrush;
_baselineAlignment = baselineAlignment;
_culture = culture;
_numberSubstitution = substitution;
}
/// <summary>
/// Hash code generator
/// </summary>
/// <returns>TextRunProperties hash code</returns>
public override int GetHashCode()
{
return
_typeface.GetHashCode()
^ _emSize.GetHashCode()
^ _emHintingSize.GetHashCode()
^ ((_foregroundBrush == null) ? 0 : _foregroundBrush.GetHashCode())
^ ((_backgroundBrush == null) ? 0 : _backgroundBrush.GetHashCode())
^ ((_textDecorations == null) ? 0 : _textDecorations.GetHashCode())
^ ((int)_baselineAlignment << 3)
^ ((int)_culture.GetHashCode() << 6)
^ ((_numberSubstitution == null) ? 0 : _numberSubstitution.GetHashCode());
}
/// <summary>
/// Equality check
/// </summary>
/// <returns>objects equals</returns>
public override bool Equals(object o)
{
if ((o == null) || !(o is TextRunProperties))
{
return false;
}
TextRunProperties textRunProperties = (TextRunProperties)o;
return
_emSize == textRunProperties.FontRenderingEmSize
&& _emHintingSize == textRunProperties.FontHintingEmSize
&& _culture == textRunProperties.CultureInfo
&& _typeface.Equals(textRunProperties.Typeface)
&& ((_textDecorations == null) ? textRunProperties.TextDecorations == null : _textDecorations.ValueEquals(textRunProperties.TextDecorations))
&& _baselineAlignment == textRunProperties.BaselineAlignment
&& ((_foregroundBrush == null) ? (textRunProperties.ForegroundBrush == null) : (_foregroundBrush.Equals(textRunProperties.ForegroundBrush)))
&& ((_backgroundBrush == null) ? (textRunProperties.BackgroundBrush == null) : (_backgroundBrush.Equals(textRunProperties.BackgroundBrush)))
&& ((_numberSubstitution == null) ? (textRunProperties.NumberSubstitution == null) : (_numberSubstitution.Equals(textRunProperties.NumberSubstitution)));
}
/// <summary>
/// Run typeface
/// </summary>
public override Typeface Typeface
{
get { return _typeface; }
}
/// <summary>
/// Em size of font used to format and display text
/// </summary>
public override double FontRenderingEmSize
{
get { return _emSize; }
}
/// <summary>
/// Em size of font to determine subtle change in font hinting default value is 12pt
/// </summary>
public override double FontHintingEmSize
{
get { return _emHintingSize; }
}
/// <summary>
/// Run text decoration
/// </summary>
public override TextDecorationCollection TextDecorations
{
get { return _textDecorations; }
}
/// <summary>
/// Run text foreground brush
/// </summary>
public override Brush ForegroundBrush
{
get { return _foregroundBrush; }
}
/// <summary>
/// Run text highlight background brush
/// </summary>
public override Brush BackgroundBrush
{
get { return _backgroundBrush; }
}
/// <summary>
/// Run vertical box alignment
/// </summary>
public override BaselineAlignment BaselineAlignment
{
get { return _baselineAlignment; }
}
/// <summary>
/// Run text Culture Info
/// </summary>
public override CultureInfo CultureInfo
{
get { return _culture; }
}
/// <summary>
/// Run typography properties
/// </summary>
public override TextRunTypographyProperties TypographyProperties
{
get{return null;}
}
/// <summary>
/// Run Text effects
/// </summary>
public override TextEffectCollection TextEffects
{
get { return null; }
}
/// <summary>
/// Number substitution
/// </summary>
public override NumberSubstitution NumberSubstitution
{
get { return _numberSubstitution; }
}
private Typeface _typeface;
private double _emSize;
private double _emHintingSize;
private TextDecorationCollection _textDecorations;
private Brush _foregroundBrush;
private Brush _backgroundBrush;
private BaselineAlignment _baselineAlignment;
private CultureInfo _culture;
private NumberSubstitution _numberSubstitution;
}
/// <summary>
/// Generic implementation of TextParagraphProperties
/// </summary>
internal sealed class GenericTextParagraphProperties : TextParagraphProperties
{
/// <summary>
/// Constructing TextParagraphProperties
/// </summary>
/// <param name="flowDirection">text flow direction</param>
/// <param name="textAlignment">logical horizontal alignment</param>
/// <param name="firstLineInParagraph">true if the paragraph is the first line in the paragraph</param>
/// <param name="alwaysCollapsible">true if the line is always collapsible</param>
/// <param name="defaultTextRunProperties">default paragraph's default run properties</param>
/// <param name="textWrap">text wrap option</param>
/// <param name="lineHeight">Paragraph line height</param>
/// <param name="indent">line indentation</param>
public GenericTextParagraphProperties(
FlowDirection flowDirection,
TextAlignment textAlignment,
bool firstLineInParagraph,
bool alwaysCollapsible,
TextRunProperties defaultTextRunProperties,
TextWrapping textWrap,
double lineHeight,
double indent
)
{
_flowDirection = flowDirection;
_textAlignment = textAlignment;
_firstLineInParagraph = firstLineInParagraph;
_alwaysCollapsible = alwaysCollapsible;
_defaultTextRunProperties = defaultTextRunProperties;
_textWrap = textWrap;
_lineHeight = lineHeight;
_indent = indent;
}
/// <summary>
/// Constructing TextParagraphProperties from another one
/// </summary>
/// <param name="textParagraphProperties">source line props</param>
public GenericTextParagraphProperties(TextParagraphProperties textParagraphProperties)
{
_flowDirection = textParagraphProperties.FlowDirection;
_defaultTextRunProperties = textParagraphProperties.DefaultTextRunProperties;
_textAlignment = textParagraphProperties.TextAlignment;
_lineHeight = textParagraphProperties.LineHeight;
_firstLineInParagraph = textParagraphProperties.FirstLineInParagraph;
_alwaysCollapsible = textParagraphProperties.AlwaysCollapsible;
_textWrap = textParagraphProperties.TextWrapping;
_indent = textParagraphProperties.Indent;
}
/// <summary>
/// This property specifies whether the primary text advance
/// direction shall be left-to-right, right-to-left, or top-to-bottom.
/// </summary>
public override FlowDirection FlowDirection
{
get { return _flowDirection; }
}
/// <summary>
/// This property describes how inline content of a block is aligned.
/// </summary>
public override TextAlignment TextAlignment
{
get { return _textAlignment; }
}
/// <summary>
/// Paragraph's line height
/// </summary>
public override double LineHeight
{
get { return _lineHeight; }
}
/// <summary>
/// Indicates the first line of the paragraph.
/// </summary>
public override bool FirstLineInParagraph
{
get { return _firstLineInParagraph; }
}
/// <summary>
/// If true, the formatted line may always be collapsed. If false (the default),
/// only lines that overflow the paragraph width are collapsed.
/// </summary>
public override bool AlwaysCollapsible
{
get { return _alwaysCollapsible; }
}
/// <summary>
/// Paragraph's default run properties
/// </summary>
public override TextRunProperties DefaultTextRunProperties
{
get { return _defaultTextRunProperties; }
}
/// <summary>
/// This property controls whether or not text wraps when it reaches the flow edge
/// of its containing block box
/// </summary>
public override TextWrapping TextWrapping
{
get { return _textWrap; }
}
/// <summary>
/// This property specifies marker characteristics of the first line in paragraph
/// </summary>
public override TextMarkerProperties TextMarkerProperties
{
get { return null; }
}
/// <summary>
/// Line indentation
/// </summary>
public override double Indent
{
get { return _indent; }
}
/// <summary>
/// Set text flow direction
/// </summary>
internal void SetFlowDirection(FlowDirection flowDirection)
{
_flowDirection = flowDirection;
}
/// <summary>
/// Set text alignment
/// </summary>
internal void SetTextAlignment(TextAlignment textAlignment)
{
_textAlignment = textAlignment;
}
/// <summary>
/// Set line height
/// </summary>
internal void SetLineHeight(double lineHeight)
{
_lineHeight = lineHeight;
}
/// <summary>
/// Set text wrap
/// </summary>
internal void SetTextWrapping(TextWrapping textWrap)
{
_textWrap = textWrap;
}
private FlowDirection _flowDirection;
private TextAlignment _textAlignment;
private bool _firstLineInParagraph;
private bool _alwaysCollapsible;
private TextRunProperties _defaultTextRunProperties;
private TextWrapping _textWrap;
private double _indent;
private double _lineHeight;
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.CodeGeneration;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
[Reentrant]
public class ReentrantGrain : Grain, IReentrantGrain
{
private IReentrantGrain Self { get; set; }
public Task<string> One()
{
return Task.FromResult("one");
}
public async Task<string> Two()
{
return await Self.One() + " two";
}
public Task SetSelf(IReentrantGrain self)
{
Self = self;
return Task.CompletedTask;
}
}
public class NonRentrantGrain : Grain, INonReentrantGrain
{
private INonReentrantGrain Self { get; set; }
private ILogger logger;
public NonRentrantGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
return base.OnActivateAsync();
}
public Task<string> One()
{
logger.Info("Entering One");
string result = "one";
logger.Info("Exiting One");
return Task.FromResult(result);
}
public async Task<string> Two()
{
logger.Info("Entering Two");
string result = await Self.One();
result = result + " two";
logger.Info("Exiting Two");
return result;
}
public Task SetSelf(INonReentrantGrain self)
{
logger.Info("SetSelf {0}", self);
Self = self;
return Task.CompletedTask;
}
}
[MayInterleave(nameof(MayInterleave))]
public class MayInterleavePredicateGrain : Grain, IMayInterleavePredicateGrain
{
private readonly ILogger logger;
public MayInterleavePredicateGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public static bool MayInterleave(InvokeMethodRequest req)
{
// not interested
if (req.Arguments.Length == 0)
return false;
string arg = null;
// assume single argument message
if (req.Arguments.Length == 1)
arg = (string)UnwrapImmutable(req.Arguments[0]);
// assume stream message
if (req.Arguments.Length == 2)
arg = (string)UnwrapImmutable(req.Arguments[1]);
if (arg == "err")
throw new ApplicationException("boom");
return arg == "reentrant";
}
static object UnwrapImmutable(object item) => item is Immutable<object> ? ((Immutable<object>)item).Value : item;
private IMayInterleavePredicateGrain Self { get; set; }
// this interleaves only when arg == "reentrant"
// and test predicate will throw when arg = "err"
public Task<string> One(string arg)
{
return Task.FromResult("one");
}
public async Task<string> Two()
{
return await Self.One("") + " two";
}
public async Task<string> TwoReentrant()
{
return await Self.One("reentrant") + " two";
}
public Task Exceptional()
{
return Self.One("err");
}
public async Task SubscribeToStream()
{
var stream = GetStream();
await stream.SubscribeAsync((item, _) =>
{
logger.Info("Received stream item:" + item);
return Task.CompletedTask;
});
}
public Task PushToStream(string item)
{
return GetStream().OnNextAsync(item);
}
IAsyncStream<string> GetStream() =>
this.GetStreamProvider("sms").GetStream<string>(Guid.Empty, "test-stream-interleave");
public Task SetSelf(IMayInterleavePredicateGrain self)
{
Self = self;
return Task.CompletedTask;
}
}
public class UnorderedNonRentrantGrain : Grain, IUnorderedNonReentrantGrain
{
private IUnorderedNonReentrantGrain Self { get; set; }
public Task<string> One()
{
return Task.FromResult("one");
}
public async Task<string> Two()
{
return await Self.One() + " two";
}
public Task SetSelf(IUnorderedNonReentrantGrain self)
{
Self = self;
return Task.CompletedTask;
}
}
[Reentrant]
public class ReentrantSelfManagedGrain1 : Grain, IReentrantSelfManagedGrain
{
private long destination;
private ILogger logger;
public ReentrantSelfManagedGrain1(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetCounter()
{
return Task.FromResult(1);
}
public Task SetDestination(long id)
{
destination = id;
return Task.CompletedTask;
}
public Task Ping(int seconds)
{
logger.Info("Start Ping({0})", seconds);
var start = DateTime.UtcNow;
var end = start + TimeSpan.FromSeconds(seconds);
int foo = 0;
while (DateTime.UtcNow < end)
{
foo++;
if (foo > 100000)
foo = 0;
}
logger.Info("Before GetCounter - OtherId={0}", destination);
IReentrantSelfManagedGrain otherGrain = GrainFactory.GetGrain<IReentrantSelfManagedGrain>(destination);
var ctr = otherGrain.GetCounter();
logger.Info("After GetCounter() - returning promise");
return ctr;
}
}
public class NonReentrantSelfManagedGrain1 : Grain, INonReentrantSelfManagedGrain
{
private long destination;
private ILogger logger;
public NonReentrantSelfManagedGrain1(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetCounter()
{
return Task.FromResult(1);
}
public Task SetDestination(long id)
{
destination = id;
return Task.CompletedTask;
}
public Task Ping(int seconds)
{
logger.Info("Start Ping({0})", seconds);
var start = DateTime.UtcNow;
var end = start + TimeSpan.FromSeconds(seconds);
int foo = 0;
while (DateTime.UtcNow < end)
{
foo++;
if (foo > 100000)
foo = 0;
}
logger.Info("Before GetCounter - OtherId={0}", destination);
INonReentrantSelfManagedGrain otherGrain = GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(destination);
var ctr = otherGrain.GetCounter();
logger.Info("After GetCounter() - returning promise");
return ctr;
}
}
[Reentrant]
public class FanOutGrain : Grain, IFanOutGrain
{
private ILogger logger;
private static readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
public FanOutGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public async Task FanOutReentrant(int offset, int num)
{
IReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_Reentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
//Task promise = fanOutGrains[i].Ping(OneSecond);
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains with offset={2}", num, "reentrant", offset);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutNonReentrant(int offset, int num)
{
INonReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
//Task promise = fanOutGrains[i].Ping(OneSecond);
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutReentrant_Chain(int offset, int num)
{
IReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_Reentrant(offset, num);
logger.Info("Starting fan-out chain calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains with offset={2}", num, "reentrant", offset);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutNonReentrant_Chain(int offset, int num)
{
INonReentrantTaskGrain[] fanOutGrains = await InitTaskGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out chain calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
private async Task<IReentrantTaskGrain[]> InitTaskGrains_Reentrant(int offset, int num)
{
IReentrantTaskGrain[] fanOutGrains = new IReentrantTaskGrain[num];
logger.Info("Creating {0} fan-out {1} worker grains", num, "reentrant");
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
int idx = offset + i;
IReentrantTaskGrain grain = GrainFactory.GetGrain<IReentrantTaskGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
private async Task<INonReentrantTaskGrain[]> InitTaskGrains_NonReentrant(int offset, int num)
{
INonReentrantTaskGrain[] fanOutGrains = new INonReentrantTaskGrain[num];
logger.Info("Creating {0} fan-out {1} worker grains", num, "non-reentrant");
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
int idx = offset + i;
INonReentrantTaskGrain grain = GrainFactory.GetGrain<INonReentrantTaskGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
}
[Reentrant]
public class FanOutACGrain : Grain, IFanOutACGrain
{
private ILogger logger;
private static readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
public FanOutACGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public async Task FanOutACReentrant(int offset, int num)
{
IReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_Reentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutACNonReentrant(int offset, int num)
{
INonReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].GetCounter();
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutACReentrant_Chain(int offset, int num)
{
IReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_Reentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond.Seconds);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
public async Task FanOutACNonReentrant_Chain(int offset, int num)
{
INonReentrantSelfManagedGrain[] fanOutGrains = await InitACGrains_NonReentrant(offset, num);
logger.Info("Starting fan-out calls to {0} grains", num);
List<Task> promises = new List<Task>();
for (int i = 0; i < num; i++)
{
Task promise = fanOutGrains[i].Ping(OneSecond.Seconds);
promises.Add(promise);
}
logger.Info("Waiting for responses from {0} grains", num);
await Task.WhenAll(promises);
logger.Info("Received {0} responses", num);
}
private async Task<IReentrantSelfManagedGrain[]> InitACGrains_Reentrant(int offset, int num)
{
var fanOutGrains = new IReentrantSelfManagedGrain[num];
List<Task> promises = new List<Task>();
logger.Info("Creating {0} fan-out {1} worker grains with offset={2}", num, "reentrant", offset);
for (int i = 0; i < num; i++)
{
int idx = offset + i;
var grain = GrainFactory.GetGrain<IReentrantSelfManagedGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
private async Task<INonReentrantSelfManagedGrain[]> InitACGrains_NonReentrant(int offset, int num)
{
var fanOutGrains = new INonReentrantSelfManagedGrain[num];
List<Task> promises = new List<Task>();
logger.Info("Creating {0} fan-out {1} worker grains with offset={2}", num, "non-reentrant", offset);
for (int i = 0; i < num; i++)
{
int idx = offset + i;
var grain = GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(idx);
fanOutGrains[i] = grain;
int next = offset + ((i + 1) % num);
Task promise = grain.SetDestination(next);
promises.Add(promise);
}
await Task.WhenAll(promises);
return fanOutGrains;
}
}
[Reentrant]
public class ReentrantTaskGrain : Grain, IReentrantTaskGrain
{
private ILogger logger;
private long otherId;
private int count;
public ReentrantTaskGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task SetDestination(long id)
{
otherId = id;
return Task.CompletedTask;
}
public async Task Ping(TimeSpan wait)
{
logger.Info("Ping Delay={0}", wait);
await Task.Delay(wait);
logger.Info("Before GetCounter - OtherId={0}", otherId);
var otherGrain = GrainFactory.GetGrain<IReentrantTaskGrain>(otherId);
var ctr = await otherGrain.GetCounter();
logger.Info("After GetCounter() - got value={0}", ctr);
}
public Task<int> GetCounter()
{
return Task.FromResult(++count);
}
}
public class NonReentrantTaskGrain : Grain, INonReentrantTaskGrain
{
private ILogger logger;
private long otherId;
private int count;
public NonReentrantTaskGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task SetDestination(long id)
{
otherId = id;
return Task.CompletedTask;
}
public async Task Ping(TimeSpan wait)
{
logger.Info("Ping Delay={0}", wait);
await Task.Delay(wait);
logger.Info("Before GetCounter - OtherId={0}", otherId);
var otherGrain = GrainFactory.GetGrain<INonReentrantTaskGrain>(otherId);
var ctr = await otherGrain.GetCounter();
logger.Info("After GetCounter() - got value={0}", ctr);
}
public Task<int> GetCounter()
{
return Task.FromResult(++count);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeMock.ArrangeActAssert;
namespace Nucleo.Collections
{
[TestClass]
public class CollectionBaseTest
{
#region " Test Classes "
protected class Pair
{
public object First;
public object Second;
public Pair(object first, object second)
{
First = first;
Second = second;
}
}
protected class ObjectCollectionBase : CollectionBase<Pair> { }
protected class StringCollectionBase : CollectionBase<string>
{
public StringCollectionBase()
: base() { }
public StringCollectionBase(IEnumerable<string> items)
: base(items) { }
}
#endregion
#region " Tests "
[TestMethod]
public void AddingBulkItemsAddsOK()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.AddRange(new string[] { "1", "2", "3", "4", "5", "6" });
//Assert
Assert.AreEqual("1", strings[0]);
Assert.AreEqual("3", strings[2]);
Assert.AreEqual("5", strings[4]);
Assert.AreEqual("6", strings[5]);
}
[TestMethod]
public void AddingItemsAddsOK()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.Add("Test");
strings.Add("This is a test");
strings.Add("My name is Brian");
strings.Add("This is a test 2");
strings.Add("Test");
strings.Add("Double Test");
//Assert
Assert.AreEqual(6, strings.Count, "Count isn't 6");
Assert.AreEqual("Test", strings[0]);
Assert.AreEqual("This is a test", strings[1]);
Assert.AreEqual("My name is Brian", strings[2]);
Assert.AreEqual("This is a test 2", strings[3]);
Assert.AreEqual("Test", strings[4]);
Assert.AreEqual("Double Test", strings[5]);
}
[TestMethod]
public void AddingEnumerableListOfItemsAddsOK()
{
//Arrange
List<string> items = new List<string>();
items.Add("1");
items.Add("2");
items.Add("3");
items.Add("4");
items.Add("5");
items.Add("6");
items.Add("7");
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.AddRange((IEnumerable)items);
//Assert
Assert.AreEqual(7, strings.Count);
Assert.AreEqual("1", strings[0]);
Assert.AreEqual("3", strings[2]);
Assert.AreEqual("5", strings[4]);
Assert.AreEqual("7", strings[6]);
}
[TestMethod]
public void AddingGenericEnumerableListOfItemsAddsOK()
{
//Arrange
List<string> items = new List<string>();
items.Add("1");
items.Add("2");
items.Add("3");
items.Add("4");
items.Add("5");
items.Add("6");
items.Add("7");
StringCollectionBase strings = new StringCollectionBase();
//Act
strings.AddRange(items);
//Assert
Assert.AreEqual(7, strings.Count);
Assert.AreEqual("1", strings[0]);
Assert.AreEqual("3", strings[2]);
Assert.AreEqual("5", strings[4]);
Assert.AreEqual("7", strings[6]);
}
[TestMethod]
public void CheckingForExistingItemsReturnsFalse()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
//Act
bool c0 = strings.Contains("0");
bool c1 = strings.Contains("1");
bool c3 = strings.Contains("3");
bool c5 = strings.Contains("5");
bool c6 = strings.Contains("6");
//Assert
Assert.AreEqual(false, c0);
Assert.AreEqual(true, c1);
Assert.AreEqual(true, c3);
Assert.AreEqual(true, c5);
Assert.AreEqual(false, c6);
}
[TestMethod]
public void ClearingItemsFromListRemovesAllItems()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
//Act
int beforeCount = strings.Count;
strings.Clear();
int afterCount = strings.Count;
//Assert
Assert.AreEqual(5, beforeCount);
Assert.AreEqual(0, afterCount);
}
[TestMethod]
public void CopyingArraysToSecondList()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
string[] arr = new string[5];
//Act
strings.CopyTo(arr, 0);
//Assert
Assert.AreEqual(5, arr.Length);
}
[TestMethod]
public void CreatingWithExistingItemWorksOK()
{
//Arrange
//Act
var coll = Isolate.Fake.Instance<CollectionBase<string>>(Members.CallOriginal, ConstructorWillBe.Called, new[] { "X" });
//Assert
Assert.AreEqual(1, coll.Count);
}
[TestMethod]
public void GettingRangeOfStringsWorksCorrectly()
{
//Arrange
StringCollectionBase scoll = new StringCollectionBase();
scoll.Add("1");
scoll.Add("2");
scoll.Add("3");
scoll.Add("4");
scoll.Add("5");
scoll.Add("6");
scoll.Add("7");
scoll.Add("8");
scoll.Add("9");
scoll.Add("10");
//Act
string[] innerColl = scoll.GetRange(1, 3);
string[] innerColl2 = scoll.GetRange(9, 20);
//Assert
Assert.AreEqual(3, innerColl.Length);
Assert.AreEqual("2", innerColl[0]);
Assert.AreEqual("3", innerColl[1]);
Assert.AreEqual("4", innerColl[2]);
Assert.AreEqual(1, innerColl2.Length);
Assert.AreEqual("10", innerColl2[0]);
}
[TestMethod]
public void IndexOfItemsReturnsCorrectIndexes()
{
//Arrange
StringCollectionBase strings = new StringCollectionBase(new string[] { "1", "2", "3", "4", "5" });
//Act
int index = strings.IndexOf("3");
//Assert
Assert.AreEqual(2, index, "Item 3 isn't at position 2");
}
[TestMethod]
public void RemovingObjectItems()
{
ObjectCollectionBase ocoll = new ObjectCollectionBase();
ocoll.Add(new Pair(1, 2));
ocoll.Add(new Pair(3, 4));
ocoll.Add(new Pair(5, 6));
ocoll.Add(new Pair(7, 8));
ocoll.Add(new Pair(9, 10));
Assert.AreEqual(5, ocoll.Count);
ocoll.Remove(ocoll[3]);
Assert.AreEqual(4, ocoll.Count);
Assert.AreEqual(9, ocoll[3].First);
Assert.AreEqual(10, ocoll[3].Second);
ocoll.RemoveAt(0);
Assert.AreEqual(3, ocoll[0].First);
Assert.AreEqual(4, ocoll[0].Second);
try
{
ocoll.RemoveAt(6);
}
catch (ArgumentOutOfRangeException ex) { }
}
[TestMethod]
public void RemovingStringItems()
{
//Arrange
StringCollectionBase scoll = new StringCollectionBase();
scoll.Add("1");
scoll.Add("2");
scoll.Add("3");
scoll.Add("4");
scoll.Add("5");
Assert.AreEqual(5, scoll.Count);
scoll.Remove(scoll[3]);
Assert.AreEqual(4, scoll.Count);
Assert.AreEqual("5", scoll[3]);
scoll.RemoveAt(0);
Assert.AreEqual(3, scoll.Count);
Assert.AreEqual("2", scoll[0]);
try
{
scoll.RemoveAt(6);
}
catch (ArgumentOutOfRangeException ex) { }
}
#endregion
}
}
| |
// Copyright (c) 2013-2017 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Linq;
namespace Icu
{
/// <summary>
/// A subclass of BreakIterator whose behavior is specified using a list of rules.
/// Instances of this class are most commonly created by the factory methods
/// <see cref="BreakIterator.CreateWordInstance(Icu.Locale)"/>,
/// <see cref="BreakIterator.CreateLineInstance(Icu.Locale)"/>, etc.
/// and then used via the abstract API in class BreakIterator
/// </summary>
public class RuleBasedBreakIterator : BreakIterator
{
private readonly UBreakIteratorType _iteratorType;
/// <summary>
/// Sets the rules this break iterator uses
/// </summary>
protected string Rules;
private readonly Locale _locale = DefaultLocale;
private bool _disposingValue; // To detect redundant calls
private IntPtr _breakIterator = IntPtr.Zero;
private string _text;
private int _currentIndex;
private TextBoundary[] _textBoundaries = new TextBoundary[0];
/// <summary>
/// Default RuleStatus vector returns 0.
/// </summary>
protected static readonly int[] EmptyRuleStatusVector = new int[] { 0 };
/// <summary>
/// The default locale.
/// </summary>
protected static readonly Locale DefaultLocale = new Locale();
/// <summary>
/// Creates a BreakIterator with the given BreakIteratorType and Locale.
/// </summary>
/// <param name="iteratorType">Break type.</param>
/// <param name="locale">The locale.</param>
/// <remarks>
/// If iterator type is UBreakIteratorType.WORD, it will include
/// spaces and punctuation as boundaries for words. If this is
/// not desired <see cref="BreakIterator.GetBoundaries(BreakIterator.UBreakIteratorType, Icu.Locale, string, bool)"/>.
/// </remarks>
public RuleBasedBreakIterator(UBreakIteratorType iteratorType, Locale locale)
{
_locale = locale;
_iteratorType = iteratorType;
}
/// <summary>
/// Creates a RuleBasedBreakIterator with the given rules.
/// </summary>
public RuleBasedBreakIterator(string rules)
{
Rules = rules;
}
/// <summary>
/// Creates a copy of the given RuleBasedBreakIterator
/// </summary>
/// <param name="bi">break itrerator</param>
/// <exception cref="Exception">Throws an exception if we get an error cloning the native
/// break iterator</exception>
private RuleBasedBreakIterator(RuleBasedBreakIterator bi)
{
_iteratorType = bi._iteratorType;
Rules = bi.Rules;
_locale = bi._locale;
_text = bi._text;
_currentIndex = bi._currentIndex;
_textBoundaries = new TextBoundary[bi._textBoundaries.Length];
bi._textBoundaries.CopyTo(_textBoundaries, 0);
if (bi._breakIterator == IntPtr.Zero)
return;
ErrorCode errorCode;
_breakIterator = NativeMethods.ubrk_safeClone(bi._breakIterator, IntPtr.Zero, IntPtr.Zero, out errorCode);
if (errorCode.IsFailure())
throw new Exception($"BreakIterator.ubrk_safeClone() failed with code {errorCode}");
}
/// <summary>
/// Clones this RuleBasedBreakIterator
/// </summary>
public override BreakIterator Clone()
{
return new RuleBasedBreakIterator(this);
}
/// <summary>
/// Gets all of the boundaries for the given text.
/// </summary>
public override int[] Boundaries
{
get { return _textBoundaries.Select(x => x.Offset).ToArray(); }
}
/// <summary>
/// Gets the locale for this BreakIterator.
/// </summary>
public override Locale Locale => _locale;
/// <summary>
/// Gets the text being examined by this BreakIterator.
/// </summary>
public override string Text => _text;
/// <summary>
/// Determine the most recently-returned text boundary.
/// Returns <see cref="BreakIterator.DONE"/> if there are no boundaries left to return.
/// </summary>
public override int Current
{
get
{
if (string.IsNullOrEmpty(Text))
return 0;
return _textBoundaries[_currentIndex].Offset;
}
}
/// <summary>
/// Decrements the iterator and returns the previous boundary.
/// Returns DONE if the iterator moves past the first boundary.
/// </summary>
public override int MovePrevious()
{
// If we are trying to go into negative indices, return DONE.
if (_currentIndex == 0)
{
return DONE;
}
_currentIndex--;
return _textBoundaries[_currentIndex].Offset;
}
/// <summary>
/// Increments the iterator and returns the next boundary.
/// Returns DONE if there are no boundaries left to return.
/// </summary>
public override int MoveNext()
{
int nextIndex = _currentIndex + 1;
// If the next index is going to move this out of boundaries, do
// not incremement the index.
if (nextIndex >= _textBoundaries.Length)
{
return DONE;
}
else
{
_currentIndex = nextIndex;
}
return _textBoundaries[_currentIndex].Offset;
}
/// <summary>
/// Sets the iterator to the first boundary and returns it.
/// Returns DONE if there was no text set.
/// </summary>
public override int MoveFirst()
{
if (string.IsNullOrEmpty(Text))
return 0;
_currentIndex = 0;
return _textBoundaries[_currentIndex].Offset;
}
/// <summary>
/// Sets the iterator to the last boundary and returns the offset into
/// the text.
/// Returns DONE if there was no text set.
/// </summary>
public override int MoveLast()
{
if (Text == null)
{
return DONE;
}
else if (Text.Equals(string.Empty))
{
return 0;
}
_currentIndex = _textBoundaries.Length - 1;
return _textBoundaries[_currentIndex].Offset;
}
/// <summary>
/// Sets the iterator to refer to the first boundary position following
/// the specified position.
/// </summary>
/// <param name="offset">The position from which to begin searching for
/// a break position.</param>
/// <returns>The position of the first break after the current position.
/// The value returned is always greater than offset, or <see cref="BreakIterator.DONE"/>
/// </returns>
public override int MoveFollowing(int offset)
{
// if the offset passed in is already past the end of the text,
// just return DONE; if it's before the beginning, return the
// text's starting offset
if (Text == null || offset >= Text.Length)
{
MoveLast();
return MoveNext();
}
else if (offset < 0)
{
return MoveFirst();
}
if (offset == _textBoundaries[0].Offset)
{
_currentIndex = 0;
return MoveNext();
}
else if (offset == _textBoundaries[_textBoundaries.Length - 1].Offset)
{
_currentIndex = _textBoundaries.Length - 1;
return MoveNext();
}
else
{
int index = 1;
// We are guaranteed not to leave the array due to range test above
while (offset >= _textBoundaries[index].Offset)
{
index++;
}
_currentIndex = index;
return _textBoundaries[_currentIndex].Offset;
}
}
/// <summary>
/// Sets the iterator to refer to the last boundary position before the
/// specified position.
/// </summary>
/// <param name="offset">The position to begin searching for a break from.</param>
/// <returns>The position of the last boundary before the starting
/// position. The value returned is always smaller than the offset
/// or the value <see cref="BreakIterator.DONE"/></returns>
public override int MovePreceding(int offset)
{
if (Text == null || offset > Text.Length)
{
return MoveLast();
}
else if (offset < 0)
{
return MoveFirst();
}
// If the offset is less than the first boundary, return the first
// boundary. Else if, the offset is greater than the last boundary,
// return the last boundary.
// Otherwise, the offset is somewhere in the middle. So we start
// iterating through the boundaries until we get to a point where
// the current boundary we are at has a greater offset than the given
// one. So we return that.
if (_textBoundaries.Length == 0 || offset == _textBoundaries[0].Offset)
{
_currentIndex = 0;
return DONE;
}
else if (offset < _textBoundaries[0].Offset)
{
_currentIndex = 0;
}
else if (offset > _textBoundaries[_textBoundaries.Length - 1].Offset)
{
_currentIndex = _textBoundaries.Length - 1;
}
else
{
int index = 0;
while (index < _textBoundaries.Length
&& offset > _textBoundaries[index].Offset)
{
index++;
}
index--;
_currentIndex = index;
}
return _textBoundaries[_currentIndex].Offset;
}
/// <summary>
/// Returns true if the specified position is a boundary position and
/// false, otherwise. In addition, it leaves the iterator pointing to
/// the first boundary position at or after "offset".
/// </summary>
public override bool IsBoundary(int offset)
{
// When the text is null or empty, there are no boundaries
// The current offset is already at BreakIterator.DONE.
if (_textBoundaries.Length == 0)
{
return false;
}
// the beginning index of the iterator is always a boundary position by definition
if (offset == 0)
{
MoveFirst(); // For side effects on current position, tag values.
return true;
}
int lastOffset = _textBoundaries.Last().Offset;
if (offset == lastOffset)
{
MoveLast();
return true;
}
// out-of-range indexes are never boundary positions
if (offset < 0)
{
MoveFirst();
return false;
}
if (offset > lastOffset)
{
MoveLast();
return false;
}
var current = MoveFirst();
while (current != DONE)
{
if (current == offset)
return true;
if (current > offset)
return false;
current = MoveNext();
}
return false;
}
/// <summary>
/// Returns the status tag from the break rule that determined the
/// current position. For break iterator types that do not support a
/// rule status, a default value of 0 is returned.
/// </summary>
/// <remarks>
/// For more information, see
/// http://userguide.icu-project.org/boundaryanalysis#TOC-Rule-Status-Values
/// </remarks>
public override int GetRuleStatus()
{
if (string.IsNullOrEmpty(Text))
return 0;
return _textBoundaries[_currentIndex].RuleStatus;
}
/// <summary>
/// Get the statuses from the break rules that determined the most
/// recently returned break position.
///
/// The values appear in the rule source within brackets, {123}, for
/// example. The default status value for rules that do not explicitly
/// provide one is zero.
///
/// For word break iterators, the possible values are defined in enum
/// <see cref="BreakIterator.UWordBreak"/>.
/// </summary>
/// <remarks>
/// For more information, see
/// http://userguide.icu-project.org/boundaryanalysis#TOC-Rule-Status-Values
/// </remarks>
public override int[] GetRuleStatusVector()
{
if (string.IsNullOrEmpty(Text))
return EmptyRuleStatusVector;
return _textBoundaries[_currentIndex].RuleStatusVector;
}
/// <summary>
/// Sets an existing iterator to point to a new piece of text.
/// </summary>
/// <param name="text">New text</param>
public override void SetText(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
_text = text;
if (string.IsNullOrEmpty(Text))
{
_textBoundaries = new TextBoundary[0];
_currentIndex = 0;
return;
}
if (_breakIterator == IntPtr.Zero)
{
InitializeBreakIterator();
}
unsafe
{
// Need to lock down the pointer to _text between calls to the unmanaged ICU
// code in case the GC kicks in and moves it.
fixed (char* p = _text)
{
ErrorCode err;
NativeMethods.ubrk_setText(_breakIterator, Text, Text.Length, out err);
if (err.IsFailure())
throw new Exception(
"BreakIterator.ubrk_setText() failed with code " + err);
List<TextBoundary> textBoundaries = new List<TextBoundary>();
// Start at the the beginning of the text and iterate until all
// of the boundaries are consumed.
int cur = NativeMethods.ubrk_first(_breakIterator);
TextBoundary textBoundary;
if (!TryGetTextBoundaryFromOffset(cur, out textBoundary))
return;
textBoundaries.Add(textBoundary);
while (cur != DONE)
{
int next = NativeMethods.ubrk_next(_breakIterator);
if (!TryGetTextBoundaryFromOffset(next, out textBoundary))
break;
textBoundaries.Add(textBoundary);
cur = next;
}
_textBoundaries = textBoundaries.ToArray();
_currentIndex = 0;
}
}
}
/// <summary>
/// Checks if the offset is valid, gets the RuleStatus and
/// RuleStatusVector for the offset and returns that TextBoundary.
/// </summary>
/// <param name="offset">Offset to check in text.</param>
/// <param name="textBoundary">TextBoundary for the given offset.</param>
/// <returns>true if the offset is valid; false otherwise.</returns>
private bool TryGetTextBoundaryFromOffset(int offset, out TextBoundary textBoundary)
{
textBoundary = default(TextBoundary);
if (offset == DONE)
return false;
const int length = 128;
int[] vector = new int[length];
ErrorCode errorCode;
int actualLen = NativeMethods.ubrk_getRuleStatusVec(_breakIterator, vector, length, out errorCode);
if (errorCode.IsFailure())
throw new Exception("BreakIterator.GetRuleStatusVector failed! " + errorCode);
if (actualLen > length)
{
vector = new int[actualLen];
NativeMethods.ubrk_getRuleStatusVec(_breakIterator, vector, vector.Length, out errorCode);
if (errorCode.IsFailure())
throw new Exception("BreakIterator.GetRuleStatusVector failed! " + errorCode);
}
int[] ruleStatuses;
// Constrain the size of the array to actual number of elements
// that were returned.
if (actualLen < vector.Length)
{
ruleStatuses = new int[actualLen];
Array.Copy(vector, ruleStatuses, actualLen);
}
else
{
ruleStatuses = vector;
}
textBoundary = new TextBoundary(offset, ruleStatuses);
return true;
}
/// <summary>
/// Initialises or returns unmanaged pointer to BreakIterator
/// </summary>
/// <returns></returns>
private void InitializeBreakIterator()
{
if (_breakIterator != IntPtr.Zero)
{
return;
}
if (Rules != null)
{
ErrorCode errorCode;
ParseError parseError;
_breakIterator = NativeMethods.ubrk_openRules(Rules, Rules.Length, Text, Text.Length, out parseError, out errorCode);
if (errorCode.IsFailure())
{
throw new ParseErrorException("Couldn't create RuleBasedBreakIterator with the given rules!", parseError, Rules);
}
}
else
{
ErrorCode errorCode;
_breakIterator = NativeMethods.ubrk_open(_iteratorType, _locale.Id, Text, Text.Length, out errorCode);
if (errorCode.IsFailure())
{
throw new InvalidOperationException(
string.Format("Could not create a BreakIterator with locale [{0}], BreakIteratorType [{1}] and Text [{2}]", _locale.Id, _iteratorType, Text));
}
}
}
/// <summary>
/// If the RuleBasedBreakIterator was created using custom rules,
/// returns those rules as its string interpretation, otherwise,
/// returns the locale and BreakIteratorType.
/// </summary>
public override string ToString()
{
return Rules ?? $"Locale: {_locale}, BreakIteratorType: {_iteratorType}";
}
#region IDisposable Support
/// <summary>
/// Implementing IDisposable pattern to properly release unmanaged resources.
/// See https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.100).aspx
/// for more information.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (!_disposingValue)
{
if (disposing)
{
// Dispose managed state (managed objects), if any.
}
if (_breakIterator != IntPtr.Zero)
{
NativeMethods.ubrk_close(_breakIterator);
_breakIterator = IntPtr.Zero;
}
_disposingValue = true;
}
}
/// <summary>
/// Disposes of all unmanaged resources used by RulesBasedBreakIterator
/// </summary>
~RuleBasedBreakIterator()
{
Dispose(false);
}
#endregion
/// <summary>
/// Keeps track of each text boundary by containing its offset,
/// and the set of rules used to obtain that boundary.
/// </summary>
protected struct TextBoundary
{
/// <summary>
/// Gets the offset within the text of the boundary.
/// </summary>
public readonly int Offset;
/// <summary>
/// Gets the rule that was used to determine the boundary. Possible
/// values are from: <see cref="BreakIterator.ULineBreakTag"/>,
/// <see cref="BreakIterator.UWordBreak"/>, or <see cref="BreakIterator.USentenceBreakTag"/>
/// </summary>
/// <remarks>
/// If there are more than one rule that determined the boundary,
/// returns the numerically largest value from <see cref="RuleStatusVector"/>.
/// More information: http://userguide.icu-project.org/boundaryanalysis#TOC-Rule-Status-Values
/// </remarks>
public readonly int RuleStatus;
/// <summary>
/// Gets the set of rules used to determine the boundary. Possible
/// values are from: <see cref="BreakIterator.ULineBreakTag"/>,
/// <see cref="BreakIterator.UWordBreak"/>, or <see cref="BreakIterator.USentenceBreakTag"/>
/// </summary>
public readonly int[] RuleStatusVector;
/// <summary>
/// Creates a text boundary with the given offset and rule status vector.
/// </summary>
/// <param name="index">Offset in text of the boundary.</param>
/// <param name="ruleStatusVector">Rule status vector of boundary.</param>
public TextBoundary(int index, int[] ruleStatusVector)
{
Offset = index;
RuleStatusVector = ruleStatusVector;
// According to the documentation, in the event that there are
// multiple values in ubrk_getRuleStatusVec(), a call to
// ubrk_getRuleStatus() will return the numerically largest
// from the vector. We are saving a PInvoke by finding the max
// value.
// http://userguide.icu-project.org/boundaryanalysis#TOC-Rule-Status-Values
//int status = NativeMethods.ubrk_getRuleStatus(_breakIterator);
RuleStatus = ruleStatusVector.Max();
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using osu.Framework.Development;
using osu.Framework.IO.Network;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Framework.Threading;
using osu.Game.Database;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using SharpCompress.Compressors;
using SharpCompress.Compressors.BZip2;
namespace osu.Game.Beatmaps
{
/// <summary>
/// A component which handles population of online IDs for beatmaps using a two part lookup procedure.
/// </summary>
/// <remarks>
/// On creating the component, a copy of a database containing metadata for a large subset of beatmaps (stored to <see cref="cache_database_name"/>) will be downloaded if not already present locally.
/// This will always be checked before doing a second online query to get required metadata.
/// </remarks>
[ExcludeFromDynamicCompile]
public class BeatmapOnlineLookupQueue : IDisposable
{
private readonly IAPIProvider api;
private readonly Storage storage;
private const int update_queue_request_concurrency = 4;
private readonly ThreadedTaskScheduler updateScheduler = new ThreadedTaskScheduler(update_queue_request_concurrency, nameof(BeatmapOnlineLookupQueue));
private FileWebRequest cacheDownloadRequest;
private const string cache_database_name = "online.db";
public BeatmapOnlineLookupQueue(IAPIProvider api, Storage storage)
{
this.api = api;
this.storage = storage;
// avoid downloading / using cache for unit tests.
if (!DebugUtils.IsNUnitRunning && !storage.Exists(cache_database_name))
prepareLocalCache();
}
public Task UpdateAsync(BeatmapSetInfo beatmapSet, CancellationToken cancellationToken)
{
return Task.WhenAll(beatmapSet.Beatmaps.Select(b => UpdateAsync(beatmapSet, b, cancellationToken)).ToArray());
}
// todo: expose this when we need to do individual difficulty lookups.
protected Task UpdateAsync(BeatmapSetInfo beatmapSet, BeatmapInfo beatmapInfo, CancellationToken cancellationToken)
=> Task.Factory.StartNew(() => lookup(beatmapSet, beatmapInfo), cancellationToken, TaskCreationOptions.HideScheduler | TaskCreationOptions.RunContinuationsAsynchronously, updateScheduler);
private void lookup(BeatmapSetInfo set, BeatmapInfo beatmapInfo)
{
if (checkLocalCache(set, beatmapInfo))
return;
if (api?.State.Value != APIState.Online)
return;
var req = new GetBeatmapRequest(beatmapInfo);
req.Failure += fail;
try
{
// intentionally blocking to limit web request concurrency
api.Perform(req);
var res = req.Response;
if (res != null)
{
beatmapInfo.Status = res.Status;
beatmapInfo.BeatmapSet.Status = res.BeatmapSet?.Status ?? BeatmapOnlineStatus.None;
beatmapInfo.BeatmapSet.OnlineID = res.OnlineBeatmapSetID;
beatmapInfo.OnlineID = res.OnlineID;
if (beatmapInfo.Metadata != null)
beatmapInfo.Metadata.AuthorID = res.AuthorID;
if (beatmapInfo.BeatmapSet.Metadata != null)
beatmapInfo.BeatmapSet.Metadata.AuthorID = res.AuthorID;
logForModel(set, $"Online retrieval mapped {beatmapInfo} to {res.OnlineBeatmapSetID} / {res.OnlineID}.");
}
}
catch (Exception e)
{
fail(e);
}
void fail(Exception e)
{
beatmapInfo.OnlineID = null;
logForModel(set, $"Online retrieval failed for {beatmapInfo} ({e.Message})");
}
}
private void prepareLocalCache()
{
string cacheFilePath = storage.GetFullPath(cache_database_name);
string compressedCacheFilePath = $"{cacheFilePath}.bz2";
cacheDownloadRequest = new FileWebRequest(compressedCacheFilePath, $"https://assets.ppy.sh/client-resources/{cache_database_name}.bz2?{DateTimeOffset.UtcNow:yyyyMMdd}");
cacheDownloadRequest.Failed += ex =>
{
File.Delete(compressedCacheFilePath);
File.Delete(cacheFilePath);
Logger.Log($"{nameof(BeatmapOnlineLookupQueue)}'s online cache download failed: {ex}", LoggingTarget.Database);
};
cacheDownloadRequest.Finished += () =>
{
try
{
using (var stream = File.OpenRead(cacheDownloadRequest.Filename))
using (var outStream = File.OpenWrite(cacheFilePath))
using (var bz2 = new BZip2Stream(stream, CompressionMode.Decompress, false))
bz2.CopyTo(outStream);
// set to null on completion to allow lookups to begin using the new source
cacheDownloadRequest = null;
}
catch (Exception ex)
{
Logger.Log($"{nameof(BeatmapOnlineLookupQueue)}'s online cache extraction failed: {ex}", LoggingTarget.Database);
File.Delete(cacheFilePath);
}
finally
{
File.Delete(compressedCacheFilePath);
}
};
cacheDownloadRequest.PerformAsync();
}
private bool checkLocalCache(BeatmapSetInfo set, BeatmapInfo beatmapInfo)
{
// download is in progress (or was, and failed).
if (cacheDownloadRequest != null)
return false;
// database is unavailable.
if (!storage.Exists(cache_database_name))
return false;
if (string.IsNullOrEmpty(beatmapInfo.MD5Hash)
&& string.IsNullOrEmpty(beatmapInfo.Path)
&& beatmapInfo.OnlineID == null)
return false;
try
{
using (var db = new SqliteConnection(DatabaseContextFactory.CreateDatabaseConnectionString("online.db", storage)))
{
db.Open();
using (var cmd = db.CreateCommand())
{
cmd.CommandText = "SELECT beatmapset_id, beatmap_id, approved, user_id FROM osu_beatmaps WHERE checksum = @MD5Hash OR beatmap_id = @OnlineID OR filename = @Path";
cmd.Parameters.Add(new SqliteParameter("@MD5Hash", beatmapInfo.MD5Hash));
cmd.Parameters.Add(new SqliteParameter("@OnlineID", beatmapInfo.OnlineID ?? (object)DBNull.Value));
cmd.Parameters.Add(new SqliteParameter("@Path", beatmapInfo.Path));
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
var status = (BeatmapOnlineStatus)reader.GetByte(2);
beatmapInfo.Status = status;
beatmapInfo.BeatmapSet.Status = status;
beatmapInfo.BeatmapSet.OnlineID = reader.GetInt32(0);
beatmapInfo.OnlineID = reader.GetInt32(1);
if (beatmapInfo.Metadata != null)
beatmapInfo.Metadata.AuthorID = reader.GetInt32(3);
if (beatmapInfo.BeatmapSet.Metadata != null)
beatmapInfo.BeatmapSet.Metadata.AuthorID = reader.GetInt32(3);
logForModel(set, $"Cached local retrieval for {beatmapInfo}.");
return true;
}
}
}
}
}
catch (Exception ex)
{
logForModel(set, $"Cached local retrieval for {beatmapInfo} failed with {ex}.");
}
return false;
}
private void logForModel(BeatmapSetInfo set, string message) =>
ArchiveModelManager<BeatmapSetInfo, BeatmapSetFileInfo>.LogForModel(set, $"[{nameof(BeatmapOnlineLookupQueue)}] {message}");
public void Dispose()
{
cacheDownloadRequest?.Dispose();
updateScheduler?.Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using NFluidsynth.Native;
namespace NFluidsynth
{
public class Sequencer : FluidsynthObject
{
private readonly Dictionary<short, LibFluidsynth.fluid_event_callback_t> _clientCallbacks =
new Dictionary<short, LibFluidsynth.fluid_event_callback_t>();
public Sequencer(bool useSystemTimer) : base(LibFluidsynth.new_fluid_sequencer2(useSystemTimer ? 1 : 0))
{
}
protected override void Dispose(bool disposing)
{
if (!Disposed)
{
LibFluidsynth.delete_fluid_sequencer(Handle);
}
base.Dispose(disposing);
}
public bool UseSystemTimer
{
get
{
ThrowIfDisposed();
return LibFluidsynth.fluid_sequencer_get_use_system_timer(Handle) != 0;
}
}
public uint Tick
{
get
{
ThrowIfDisposed();
return LibFluidsynth.fluid_sequencer_get_tick(Handle);
}
}
public double TimeScale
{
get
{
ThrowIfDisposed();
return LibFluidsynth.fluid_sequencer_get_time_scale(Handle);
}
set
{
ThrowIfDisposed();
LibFluidsynth.fluid_sequencer_set_time_scale(Handle, value);
}
}
public int CountClients
{
get
{
ThrowIfDisposed();
return LibFluidsynth.fluid_sequencer_count_clients(Handle);
}
}
public unsafe SequencerClientId RegisterClient(string name, SequencerEventCallback callback)
{
ThrowIfDisposed();
LibFluidsynth.fluid_event_callback_t wrapper = null;
var callbackPtr = IntPtr.Zero;
if (callback != null)
{
wrapper = (time, @event, seq, data) =>
{
using (var ev = new SequencerEvent(@event))
{
callback(time, ev);
}
};
callbackPtr = Marshal.GetFunctionPointerForDelegate(wrapper);
}
var id = LibFluidsynth.fluid_sequencer_register_client(Handle, name, callbackPtr, null);
if (id == LibFluidsynth.FluidFailed)
{
throw new FluidSynthInteropException("fluid_sequencer_register_client failed");
}
if (wrapper != null)
{
_clientCallbacks.Add(id, wrapper);
}
return new SequencerClientId(id);
}
public void UnregisterClient(SequencerClientId id)
{
ThrowIfDisposed();
_clientCallbacks.Remove(id.Value);
LibFluidsynth.fluid_sequencer_unregister_client(Handle, id.Value);
}
public SequencerClientId GetClientId(int index)
{
ThrowIfDisposed();
var id = LibFluidsynth.fluid_sequencer_get_client_id(Handle, index);
if (id == LibFluidsynth.FluidFailed)
{
throw new ArgumentException("Sequencer client not found.");
}
return new SequencerClientId(id);
}
public unsafe string GetClientName(SequencerClientId id)
{
ThrowIfDisposed();
var ptr = LibFluidsynth.fluid_sequencer_get_client_name(Handle, id.Value);
return Utility.PtrToStringUTF8(ptr);
}
public bool ClientIsDestination(SequencerClientId id)
{
ThrowIfDisposed();
return LibFluidsynth.fluid_sequencer_client_is_dest(Handle, id.Value) != 0;
}
public void Process(uint msec)
{
ThrowIfDisposed();
LibFluidsynth.fluid_sequencer_process(Handle, msec);
}
public void SendNow(SequencerEvent evt)
{
ThrowIfDisposed();
evt.ThrowIfDisposed();
LibFluidsynth.fluid_sequencer_send_now(Handle, evt.Handle);
}
public void SendAt(SequencerEvent evt, uint time, bool absolute)
{
ThrowIfDisposed();
evt.ThrowIfDisposed();
var ret = LibFluidsynth.fluid_sequencer_send_at(Handle, evt.Handle, time, absolute ? 1 : 0);
if (ret == LibFluidsynth.FluidFailed)
{
throw new FluidSynthInteropException("fluid_sequencer_send_at failed");
}
}
public void RemoveEvents(SequencerClientId source, SequencerClientId dest, int type)
{
ThrowIfDisposed();
LibFluidsynth.fluid_sequencer_remove_events(Handle, source.Value, dest.Value, type);
}
public SequencerClientId RegisterFluidsynth(Synth synth)
{
ThrowIfDisposed();
synth.ThrowIfDisposed();
var id = LibFluidsynth.fluid_sequencer_register_fluidsynth(Handle, synth.Handle);
if (id == LibFluidsynth.FluidFailed)
{
throw new FluidSynthInteropException("fluid_sequencer_register_fluidsynth failed");
}
return new SequencerClientId(id);
}
public unsafe void AddMidiEventToBuffer(MidiEvent @event)
{
ThrowIfDisposed();
@event.ThrowIfDisposed();
var ret = LibFluidsynth.fluid_sequencer_add_midi_event_to_buffer((void*) Handle, @event.Handle);
if (ret == LibFluidsynth.FluidFailed)
{
throw new FluidSynthInteropException("fluid_sequencer_add_midi_event_to_buffer failed");
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
namespace Northwind.CSLA.Library
{
public delegate void ProductInfoEvent(object sender);
/// <summary>
/// ProductInfo Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(ProductInfoConverter))]
public partial class ProductInfo : ReadOnlyBase<ProductInfo>, IDisposable
{
public event ProductInfoEvent Changed;
private void OnChange()
{
if (Changed != null) Changed(this);
}
#region Collection
protected static List<ProductInfo> _AllList = new List<ProductInfo>();
private static Dictionary<string, ProductInfo> _AllByPrimaryKey = new Dictionary<string, ProductInfo>();
private static void ConvertListToDictionary()
{
List<ProductInfo> remove = new List<ProductInfo>();
foreach (ProductInfo tmp in _AllList)
{
_AllByPrimaryKey[tmp.ProductID.ToString()]=tmp; // Primary Key
remove.Add(tmp);
}
foreach (ProductInfo tmp in remove)
_AllList.Remove(tmp);
}
internal static void AddList(ProductInfoList lst)
{
foreach (ProductInfo item in lst) _AllList.Add(item);
}
public static ProductInfo GetExistingByPrimaryKey(int productID)
{
ConvertListToDictionary();
string key = productID.ToString();
if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key];
return null;
}
#endregion
#region Business Methods
private string _ErrorMessage = string.Empty;
public string ErrorMessage
{
get { return _ErrorMessage; }
}
protected Product _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _ProductID;
[System.ComponentModel.DataObjectField(true, true)]
public int ProductID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ProductID;
}
}
private string _ProductName = string.Empty;
public string ProductName
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ProductName;
}
}
private int? _SupplierID;
public int? SupplierID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MySupplier != null) _SupplierID = _MySupplier.SupplierID;
return _SupplierID;
}
}
private SupplierInfo _MySupplier;
public SupplierInfo MySupplier
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MySupplier == null && _SupplierID != null) _MySupplier = SupplierInfo.Get((int)_SupplierID);
return _MySupplier;
}
}
private int? _CategoryID;
public int? CategoryID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyCategory != null) _CategoryID = _MyCategory.CategoryID;
return _CategoryID;
}
}
private CategoryInfo _MyCategory;
public CategoryInfo MyCategory
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyCategory == null && _CategoryID != null) _MyCategory = CategoryInfo.Get((int)_CategoryID);
return _MyCategory;
}
}
private string _QuantityPerUnit = string.Empty;
public string QuantityPerUnit
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _QuantityPerUnit;
}
}
private decimal? _UnitPrice;
public decimal? UnitPrice
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _UnitPrice;
}
}
private Int16? _UnitsInStock;
public Int16? UnitsInStock
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _UnitsInStock;
}
}
private Int16? _UnitsOnOrder;
public Int16? UnitsOnOrder
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _UnitsOnOrder;
}
}
private Int16? _ReorderLevel;
public Int16? ReorderLevel
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ReorderLevel;
}
}
private bool _Discontinued;
public bool Discontinued
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Discontinued;
}
}
private int _ProductOrderDetailCount = 0;
/// <summary>
/// Count of ProductOrderDetails for this Product
/// </summary>
public int ProductOrderDetailCount
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ProductOrderDetailCount;
}
}
private OrderDetailInfoList _ProductOrderDetails = null;
[TypeConverter(typeof(OrderDetailInfoListConverter))]
public OrderDetailInfoList ProductOrderDetails
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_ProductOrderDetailCount > 0 && _ProductOrderDetails == null)
_ProductOrderDetails = OrderDetailInfoList.GetByProductID(_ProductID);
return _ProductOrderDetails;
}
}
// TODO: Replace base ProductInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current ProductInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// TODO: Check ProductInfo.GetIdValue to assure that the ID returned is unique
/// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary>
/// <returns>A Unique ID for the current ProductInfo</returns>
protected override object GetIdValue()
{
return _ProductID;
}
#endregion
#region Factory Methods
private ProductInfo()
{/* require use of factory methods */
_AllList.Add(this);
}
public void Dispose()
{
_AllList.Remove(this);
_AllByPrimaryKey.Remove(ProductID.ToString());
}
public virtual Product Get()
{
return _Editable = Product.Get(_ProductID);
}
public static void Refresh(Product tmp)
{
ProductInfo tmpInfo = GetExistingByPrimaryKey(tmp.ProductID);
if (tmpInfo == null) return;
tmpInfo.RefreshFields(tmp);
}
private void RefreshFields(Product tmp)
{
_ProductName = tmp.ProductName;
_SupplierID = tmp.SupplierID;
_CategoryID = tmp.CategoryID;
_QuantityPerUnit = tmp.QuantityPerUnit;
_UnitPrice = tmp.UnitPrice;
_UnitsInStock = tmp.UnitsInStock;
_UnitsOnOrder = tmp.UnitsOnOrder;
_ReorderLevel = tmp.ReorderLevel;
_Discontinued = tmp.Discontinued;
_ProductInfoExtension.Refresh(this);
_MySupplier = null;
_MyCategory = null;
OnChange();// raise an event
}
public static void Refresh(CategoryProduct tmp)
{
ProductInfo tmpInfo = GetExistingByPrimaryKey(tmp.ProductID);
if (tmpInfo == null) return;
tmpInfo.RefreshFields(tmp);
}
private void RefreshFields(CategoryProduct tmp)
{
_ProductName = tmp.ProductName;
_SupplierID = tmp.SupplierID;
_QuantityPerUnit = tmp.QuantityPerUnit;
_UnitPrice = tmp.UnitPrice;
_UnitsInStock = tmp.UnitsInStock;
_UnitsOnOrder = tmp.UnitsOnOrder;
_ReorderLevel = tmp.ReorderLevel;
_Discontinued = tmp.Discontinued;
_ProductInfoExtension.Refresh(this);
_MySupplier = null;
_MyCategory = null;
OnChange();// raise an event
}
public static void Refresh(SupplierProduct tmp)
{
ProductInfo tmpInfo = GetExistingByPrimaryKey(tmp.ProductID);
if (tmpInfo == null) return;
tmpInfo.RefreshFields(tmp);
}
private void RefreshFields(SupplierProduct tmp)
{
_ProductName = tmp.ProductName;
_CategoryID = tmp.CategoryID;
_QuantityPerUnit = tmp.QuantityPerUnit;
_UnitPrice = tmp.UnitPrice;
_UnitsInStock = tmp.UnitsInStock;
_UnitsOnOrder = tmp.UnitsOnOrder;
_ReorderLevel = tmp.ReorderLevel;
_Discontinued = tmp.Discontinued;
_ProductInfoExtension.Refresh(this);
_MySupplier = null;
_MyCategory = null;
OnChange();// raise an event
}
public static ProductInfo Get(int productID)
{
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Product");
try
{
ProductInfo tmp = GetExistingByPrimaryKey(productID);
if (tmp == null)
{
tmp = DataPortal.Fetch<ProductInfo>(new PKCriteria(productID));
_AllList.Add(tmp);
}
if (tmp.ErrorMessage == "No Record Found") tmp = null;
return tmp;
}
catch (Exception ex)
{
throw new DbCslaException("Error on ProductInfo.Get", ex);
}
}
#endregion
#region Data Access Portal
internal ProductInfo(SafeDataReader dr)
{
Database.LogInfo("ProductInfo.Constructor", GetHashCode());
try
{
ReadData(dr);
}
catch (Exception ex)
{
Database.LogException("ProductInfo.Constructor", ex);
throw new DbCslaException("ProductInfo.Constructor", ex);
}
}
[Serializable()]
protected class PKCriteria
{
private int _ProductID;
public int ProductID
{ get { return _ProductID; } }
public PKCriteria(int productID)
{
_ProductID = productID;
}
}
private void ReadData(SafeDataReader dr)
{
Database.LogInfo("ProductInfo.ReadData", GetHashCode());
try
{
_ProductID = dr.GetInt32("ProductID");
_ProductName = dr.GetString("ProductName");
_SupplierID = (int?)dr.GetValue("SupplierID");
_CategoryID = (int?)dr.GetValue("CategoryID");
_QuantityPerUnit = dr.GetString("QuantityPerUnit");
_UnitPrice = (decimal?)dr.GetValue("UnitPrice");
_UnitsInStock = (Int16?)dr.GetValue("UnitsInStock");
_UnitsOnOrder = (Int16?)dr.GetValue("UnitsOnOrder");
_ReorderLevel = (Int16?)dr.GetValue("ReorderLevel");
_Discontinued = dr.GetBoolean("Discontinued");
_ProductOrderDetailCount = dr.GetInt32("OrderDetailCount");
}
catch (Exception ex)
{
Database.LogException("ProductInfo.ReadData", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("ProductInfo.ReadData", ex);
}
}
private void DataPortal_Fetch(PKCriteria criteria)
{
Database.LogInfo("ProductInfo.DataPortal_Fetch", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
ApplicationContext.LocalContext["cn"] = cn;
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getProduct";
cm.Parameters.AddWithValue("@ProductID", criteria.ProductID);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
if (!dr.Read())
{
_ErrorMessage = "No Record Found";
return;
}
ReadData(dr);
}
}
// removing of item only needed for local data portal
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
ApplicationContext.LocalContext.Remove("cn");
}
}
catch (Exception ex)
{
Database.LogException("ProductInfo.DataPortal_Fetch", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("ProductInfo.DataPortal_Fetch", ex);
}
}
#endregion
// Standard Refresh
#region extension
ProductInfoExtension _ProductInfoExtension = new ProductInfoExtension();
[Serializable()]
partial class ProductInfoExtension : extensionBase {}
[Serializable()]
class extensionBase
{
// Default Refresh
public virtual void Refresh(ProductInfo tmp) { }
}
#endregion
} // Class
#region Converter
internal class ProductInfoConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is ProductInfo)
{
// Return the ToString value
return ((ProductInfo)value).ToString();
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
| |
// Copyright (c) 2013-2015 Robert Rouhani <[email protected]> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SharpNav.Geometry;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif
namespace SharpNav
{
/// <summary>
/// A Heightfield represents a "voxel" grid represented as a 2-dimensional grid of <see cref="Cell"/>s.
/// </summary>
public partial class Heightfield
{
private BBox3 bounds;
private int width, height, length;
private float cellSize, cellHeight;
private Cell[] cells;
/// <summary>
/// Initializes a new instance of the <see cref="Heightfield"/> class.
/// </summary>
/// <param name="b">The world-space bounds.</param>
/// <param name="settings">The settings to build with.</param>
public Heightfield(BBox3 b, NavMeshGenerationSettings settings)
: this(b, settings.CellSize, settings.CellHeight)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Heightfield"/> class.
/// </summary>
/// <param name="b">The world-space bounds.</param>
/// <param name="cellSize">The world-space size of each cell in the XZ plane.</param>
/// <param name="cellHeight">The world-space height of each cell.</param>
public Heightfield(BBox3 b, float cellSize, float cellHeight)
{
if (!BBox3.IsValid(ref bounds))
throw new ArgumentException("The bounds are considered invalid. See BBox3.IsValid for details.");
if (cellSize <= 0)
throw new ArgumentOutOfRangeException("cellSize", "Cell size must be greater than 0.");
if (cellHeight <= 0)
throw new ArgumentOutOfRangeException("cellHeight", "Cell height must be greater than 0.");
this.cellSize = cellSize;
this.cellHeight = cellHeight;
this.bounds = b;
//make sure the bbox contains all the possible voxels.
width = (int)Math.Ceiling((b.Max.X - b.Min.X) / cellSize);
height = (int)Math.Ceiling((b.Max.Y - b.Min.Y) / cellHeight);
length = (int)Math.Ceiling((b.Max.Z - b.Min.Z) / cellSize);
bounds.Max.X = bounds.Min.X + width * cellSize;
bounds.Max.Y = bounds.Min.Y + height * cellHeight;
bounds.Max.Z = bounds.Min.Z + length * cellSize;
cells = new Cell[width * length];
for (int i = 0; i < cells.Length; i++)
cells[i] = new Cell(height);
}
/// <summary>
/// Gets the bounding box of the heightfield.
/// </summary>
public BBox3 Bounds
{
get
{
return bounds;
}
}
/// <summary>
/// Gets the world-space minimum.
/// </summary>
/// <value>The minimum.</value>
public Vector3 Minimum
{
get
{
return bounds.Min;
}
}
/// <summary>
/// Gets the world-space maximum.
/// </summary>
/// <value>The maximum.</value>
public Vector3 Maximum
{
get
{
return bounds.Max;
}
}
/// <summary>
/// Gets the number of cells in the X direction.
/// </summary>
/// <value>The width.</value>
public int Width
{
get
{
return width;
}
}
/// <summary>
/// Gets the number of cells in the Y (up) direction.
/// </summary>
/// <value>The height.</value>
public int Height
{
get
{
return height;
}
}
/// <summary>
/// Gets the number of cells in the Z direction.
/// </summary>
/// <value>The length.</value>
public int Length
{
get
{
return length;
}
}
/// <summary>
/// Gets the size of a cell (voxel).
/// </summary>
/// <value>The size of the cell.</value>
public Vector3 CellSize
{
get
{
return new Vector3(cellSize, cellHeight, cellSize);
}
}
/// <summary>
/// Gets the size of a cell on the X and Z axes.
/// </summary>
public float CellSizeXZ
{
get
{
return cellSize;
}
}
/// <summary>
/// Gets the size of a cell on the Y axis.
/// </summary>
public float CellHeight
{
get
{
return cellHeight;
}
}
/// <summary>
/// Gets the total number of spans.
/// </summary>
public int SpanCount
{
get
{
int count = 0;
for (int i = 0; i < cells.Length; i++)
count += cells[i].WalkableSpanCount;
return count;
}
}
/// <summary>
/// Gets the <see cref="Cell"/> at the specified coordinate.
/// </summary>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <returns>The cell at [x, y].</returns>
public Cell this[int x, int y]
{
get
{
if (x < 0 || x >= width || y < 0 || y >= length)
throw new ArgumentOutOfRangeException();
return cells[y * width + x];
}
}
/// <summary>
/// Gets the <see cref="Cell"/> at the specified index.
/// </summary>
/// <param name="i">The index.</param>
/// <returns>The cell at index i.</returns>
public Cell this[int i]
{
get
{
if (i < 0 || i >= cells.Length)
throw new ArgumentOutOfRangeException();
return cells[i];
}
}
/// <summary>
/// Gets the <see cref="Span"/> at the reference.
/// </summary>
/// <param name="spanRef">A reference to a span.</param>
/// <returns>The span at the reference.</returns>
public Span this[SpanReference spanRef]
{
get
{
return cells[spanRef.Y * width + spanRef.X].Spans[spanRef.Index];
}
}
/// <summary>
/// Filters the heightmap to allow two neighboring spans have a small difference in maximum height (such as
/// stairs) to be walkable.
/// </summary>
/// <remarks>
/// This filter may override the results of <see cref="FilterLedgeSpans"/>.
/// </remarks>
/// <param name="walkableClimb">The maximum difference in height to filter.</param>
public void FilterLowHangingWalkableObstacles(int walkableClimb)
{
//Loop through every cell in the Heightfield
for (int i = 0; i < cells.Length; i++)
{
Cell c = cells[i];
List<Span> spans = c.MutableSpans;
//store the first span's data as the "previous" data
Area prevArea = Area.Null;
bool prevWalkable = prevArea != Area.Null;
int prevMax = 0;
//iterate over all the spans in the cell
for (int j = 0; j < spans.Count; j++)
{
Span s = spans[j];
bool walkable = s.Area != Area.Null;
//if the current span isn't walkable but there's a walkable span right below it,
//mark this span as walkable too.
if (!walkable && prevWalkable)
{
if (Math.Abs(s.Maximum - prevMax) < walkableClimb)
s.Area = prevArea;
}
//save changes back to the span list.
spans[j] = s;
//set the previous data for the next iteration
prevArea = s.Area;
prevWalkable = walkable;
prevMax = s.Maximum;
}
}
}
/// <summary>
/// If two spans have little vertical space in between them,
/// then span is considered unwalkable
/// </summary>
/// <param name="walkableHeight">The clearance.</param>
public void FilterWalkableLowHeightSpans(int walkableHeight)
{
for (int i = 0; i < cells.Length; i++)
{
Cell c = cells[i];
List<Span> spans = c.MutableSpans;
//Iterate over all spans
for (int j = 0; j < spans.Count - 1; j++)
{
Span currentSpan = spans[j];
//too low, not enough space to walk through
if ((spans[j + 1].Minimum - currentSpan.Maximum) <= walkableHeight)
{
currentSpan.Area = Area.Null;
spans[j] = currentSpan;
}
}
}
}
/// <summary>
/// A ledge is unwalkable because the difference between the maximum height of two spans
/// is too large of a drop (i.e. greater than walkableClimb).
/// </summary>
/// <param name="walkableHeight">The maximum walkable height to filter.</param>
/// <param name="walkableClimb">The maximum walkable climb to filter.</param>
public void FilterLedgeSpans(int walkableHeight, int walkableClimb)
{
//Mark border spans.
Parallel.For(0, length, y =>
{
//for (int y = 0; y < length; y++)
//{
for (int x = 0; x < width; x++)
{
Cell c = cells[x + y * width];
List<Span> spans = c.MutableSpans;
//Examine all the spans in each cell
for (int i = 0; i < spans.Count; i++)
{
Span currentSpan = spans[i];
// Skip non walkable spans.
if (currentSpan.Area == Area.Null)
continue;
int bottom = (int)currentSpan.Maximum;
int top = (i == spans.Count - 1) ? int.MaxValue : spans[i + 1].Minimum;
// Find neighbors minimum height.
int minHeight = int.MaxValue;
// Min and max height of accessible neighbors.
int accessibleMin = currentSpan.Maximum;
int accessibleMax = currentSpan.Maximum;
for (var dir = Direction.West; dir <= Direction.South; dir++)
{
int dx = x + dir.GetHorizontalOffset();
int dy = y + dir.GetVerticalOffset();
// Skip neighbors which are out of bounds.
if (dx < 0 || dy < 0 || dx >= width || dy >= length)
{
minHeight = Math.Min(minHeight, -walkableClimb - bottom);
continue;
}
// From minus infinity to the first span.
Cell neighborCell = cells[dy * width + dx];
List<Span> neighborSpans = neighborCell.MutableSpans;
int neighborBottom = -walkableClimb;
int neighborTop = neighborSpans.Count > 0 ? neighborSpans[0].Minimum : int.MaxValue;
// Skip neighbor if the gap between the spans is too small.
if (Math.Min(top, neighborTop) - Math.Max(bottom, neighborBottom) > walkableHeight)
minHeight = Math.Min(minHeight, neighborBottom - bottom);
// Rest of the spans.
for (int j = 0; j < neighborSpans.Count; j++)
{
Span currentNeighborSpan = neighborSpans[j];
neighborBottom = currentNeighborSpan.Maximum;
neighborTop = (j == neighborSpans.Count - 1) ? int.MaxValue : neighborSpans[j + 1].Minimum;
// Skip neighbor if the gap between the spans is too small.
if (Math.Min(top, neighborTop) - Math.Max(bottom, neighborBottom) > walkableHeight)
{
minHeight = Math.Min(minHeight, neighborBottom - bottom);
// Find min/max accessible neighbor height.
if (Math.Abs(neighborBottom - bottom) <= walkableClimb)
{
if (neighborBottom < accessibleMin) accessibleMin = neighborBottom;
if (neighborBottom > accessibleMax) accessibleMax = neighborBottom;
}
}
}
}
// The current span is close to a ledge if the drop to any
// neighbor span is less than the walkableClimb.
if (minHeight < -walkableClimb)
currentSpan.Area = Area.Null;
// If the difference between all neighbors is too large,
// we are at steep slope, mark the span as ledge.
if ((accessibleMax - accessibleMin) > walkableClimb)
currentSpan.Area = Area.Null;
//save span data
spans[i] = currentSpan;
}
}
//}
});
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Matthew Ward" email="[email protected]"/>
// <version>$Revision: 1965 $</version>
// </file>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.XPath;
using System.Linq;
namespace InnovatorAdmin.Editor
{
/// <summary>
/// Utility class that contains xml parsing routines used to determine
/// the currently selected element so we can provide intellisense.
/// </summary>
/// <remarks>
/// All of the routines return <see cref="XmlElementPath"/> objects
/// since we are interested in the complete path or tree to the
/// currently active element.
/// </remarks>
public class XmlParser
{
/// <summary>
/// Helper class. Holds the namespace URI and the prefix currently
/// in use for this namespace.
/// </summary>
class NamespaceURI
{
string namespaceURI = String.Empty;
string prefix = String.Empty;
public NamespaceURI()
{
}
public NamespaceURI(string namespaceURI, string prefix)
{
this.namespaceURI = namespaceURI;
this.prefix = prefix;
}
public string Namespace
{
get
{
return namespaceURI;
}
set
{
namespaceURI = value;
}
}
public string Prefix
{
get
{
return prefix;
}
set
{
prefix = value;
if (prefix == null)
{
prefix = String.Empty;
}
}
}
}
XmlParser()
{
}
/// <summary>
/// Gets path of the xml element start tag that the specified
/// <paramref name="index"/> is currently inside.
/// </summary>
/// <remarks>If the index outside the start tag then an empty path
/// is returned.</remarks>
public static XmlElementPath GetActiveElementStartPath(string xml, int index)
{
XmlElementPath path = new XmlElementPath();
string elementText = GetActiveElementStartText(xml, index);
if (elementText != null)
{
QualifiedName elementName = GetElementName(elementText);
NamespaceURI elementNamespace = GetElementNamespace(elementText);
path = GetParentElementPathCore(xml.Substring(0, index));
string namespaceUri;
if (elementNamespace.Namespace.Length == 0
&& !string.IsNullOrEmpty(elementName.Prefix)
&& path.Namespaces != null
&& path.Namespaces.TryGetValue(elementName.Prefix, out namespaceUri))
{
elementNamespace.Namespace = namespaceUri;
elementNamespace.Prefix = elementName.Prefix;
}
path.Elements.Add(new QualifiedName(elementName.Name, elementNamespace.Namespace, elementNamespace.Prefix));
path.Compact(elementNamespace.Namespace);
}
return path;
}
/// <summary>
/// Gets path of the xml element start tag that the specified
/// <paramref name="index"/> is currently located. This is different to the
/// GetActiveElementStartPath method since the index can be inside the element
/// name.
/// </summary>
/// <remarks>If the index outside the start tag then an empty path
/// is returned.</remarks>
public static XmlElementPath GetActiveElementStartPathAtIndex(string xml, int index)
{
// Find first non xml element name character to the right of the index.
index = GetCorrectedIndex(xml.Length, index);
int currentIndex = index;
for (; currentIndex < xml.Length; ++currentIndex)
{
char ch = xml[currentIndex];
if (!IsXmlNameChar(ch))
{
break;
}
}
string elementText = GetElementNameAtIndex(xml, currentIndex);
if (elementText != null)
{
return GetActiveElementStartPath(xml, currentIndex, elementText);
}
return new XmlElementPath();
}
public static IDictionary<string, string> GetNamespacesInScope(string xml)
{
try
{
var xmlReader = new XmlTextReader(new StringReader(xml));
xmlReader.XmlResolver = null;
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
return xmlReader.GetNamespacesInScope(XmlNamespaceScope.All);
}
}
}
catch (XmlException) { /* Do nothing. */ }
catch (WebException) { /* Do nothing. */ }
return null;
}
public static XmlElementPath GetParentElementPath(string xml)
{
var path = GetParentElementPathCore(xml);
path.Compact();
return path;
}
public static IEnumerable<XmlElementPath> GetParentElementPaths(string xml)
{
var path = GetParentElementPathCore(xml);
string lastNamespace = "";
var groups = new GroupedList<string, QualifiedName>();
foreach (QualifiedName qname in path.Elements)
{
groups.Add(qname.Namespace ?? "", qname);
lastNamespace = qname.Namespace;
}
var orderedList = groups.ToList();
orderedList.Sort((x, y) =>
{
if (x.Key == y.Key) return 0;
if (x.Key == lastNamespace) return -1;
if (y.Key == lastNamespace) return 1;
return x.Key.CompareTo(y.Key);
});
return orderedList.Select(g => new XmlElementPath(g.ToArray())
{
Namespaces = path.Namespaces
});
}
/// <summary>
/// Gets the last open element (if the last node is an open element)
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
[DebuggerStepThrough()]
public static string GetOpenElement(string xml)
{
var elements = new Stack<QualifiedName>();
var isOpenElement = false;
try
{
StringReader reader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(reader);
xmlReader.XmlResolver = null;
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
if (xmlReader.IsEmptyElement)
{
isOpenElement = false;
}
else
{
elements.Push(new QualifiedName(xmlReader.LocalName, xmlReader.NamespaceURI, xmlReader.Prefix));
isOpenElement = true;
}
break;
case XmlNodeType.EndElement:
elements.Pop();
isOpenElement = false;
break;
default:
isOpenElement = false;
break;
}
}
}
catch (XmlException)
{
// Do nothing.
}
catch (WebException)
{
// Do nothing.
}
return isOpenElement ? elements.Peek().ToString() : null;
}
/// <summary>
/// Gets the parent element path based on the index position.
/// </summary>
[DebuggerStepThrough()]
public static XmlElementPath GetParentElementPathCore(string xml)
{
XmlElementPath path = new XmlElementPath();
try
{
StringReader reader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(reader);
xmlReader.XmlResolver = null;
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
if (!xmlReader.IsEmptyElement)
{
QualifiedName elementName = new QualifiedName(xmlReader.LocalName, xmlReader.NamespaceURI, xmlReader.Prefix);
path.Elements.Add(elementName);
path.Namespaces = xmlReader.GetNamespacesInScope(XmlNamespaceScope.All);
}
break;
case XmlNodeType.EndElement:
path.Elements.RemoveLast();
break;
}
}
}
catch (XmlException)
{
// Do nothing.
}
catch (WebException)
{
// Do nothing.
}
return path;
}
/// <summary>
/// Checks whether the attribute at the end of the string is a
/// namespace declaration.
/// </summary>
public static bool IsNamespaceDeclaration(string xml, int index)
{
if (xml.Length == 0)
{
return false;
}
index = GetCorrectedIndex(xml.Length, index);
// Move back one character if the last character is an '='
if (xml[index] == '=')
{
xml = xml.Substring(0, xml.Length - 1);
--index;
}
// From the end of the string work backwards until we have
// picked out the last attribute and reached some whitespace.
StringBuilder reversedAttributeName = new StringBuilder();
bool ignoreWhitespace = true;
int currentIndex = index;
for (int i = 0; i < index; ++i)
{
char currentChar = xml[currentIndex];
if (Char.IsWhiteSpace(currentChar))
{
if (ignoreWhitespace == false)
{
// Reached the start of the attribute name.
break;
}
}
else if (Char.IsLetterOrDigit(currentChar) || (currentChar == ':'))
{
ignoreWhitespace = false;
reversedAttributeName.Append(currentChar);
}
else
{
// Invalid string.
break;
}
--currentIndex;
}
// Did we get a namespace?
bool isNamespace = false;
if ((reversedAttributeName.ToString() == "snlmx") || (reversedAttributeName.ToString().EndsWith(":snlmx")))
{
isNamespace = true;
}
return isNamespace;
}
/// <summary>
/// Gets the name of the attribute inside but before the specified
/// index.
/// </summary>
public static string GetAttributeName(string xml, int index)
{
if (xml.Length == 0)
{
return String.Empty;
}
index = GetCorrectedIndex(xml.Length, index);
return GetAttributeName(xml, index, true, true, true);
}
/// <summary>
/// Gets the name of the attribute at the specified index. The index
/// can be anywhere inside the attribute name or in the attribute value.
/// </summary>
public static string GetAttributeNameAtIndex(string xml, int index)
{
index = GetCorrectedIndex(xml.Length, index);
bool ignoreWhitespace = true;
bool ignoreEqualsSign = false;
bool ignoreQuote = false;
if (IsInsideAttributeValue(xml, index))
{
// Find attribute name start.
int elementStartIndex = GetActiveElementStartIndex(xml, index);
if (elementStartIndex == -1)
{
return String.Empty;
}
// Find equals sign.
for (int i = index; i > elementStartIndex; --i)
{
char ch = xml[i];
if (ch == '=')
{
index = i;
ignoreEqualsSign = true;
break;
}
}
}
else
{
// Find end of attribute name.
for (; index < xml.Length; ++index)
{
char ch = xml[index];
if (!Char.IsLetterOrDigit(ch))
{
if (ch == '\'' || ch == '\"')
{
ignoreQuote = true;
ignoreEqualsSign = true;
}
break;
}
}
--index;
}
return GetAttributeName(xml, index, ignoreWhitespace, ignoreQuote, ignoreEqualsSign);
}
/// <summary>
/// Checks for valid xml attribute value character
/// </summary>
public static bool IsAttributeValueChar(char ch)
{
if (Char.IsLetterOrDigit(ch) ||
(ch == ':') ||
(ch == '/') ||
(ch == '_') ||
(ch == '.') ||
(ch == '-') ||
(ch == '#') || (ch == ' '))
{
return true;
}
return false;
}
/// <summary>
/// Checks for valid xml element or attribute name character.
/// </summary>
public static bool IsXmlNameChar(char ch)
{
if (Char.IsLetterOrDigit(ch) ||
(ch == ':') ||
(ch == '/') ||
(ch == '_') ||
(ch == '.') ||
(ch == '-'))
{
return true;
}
return false;
}
/// <summary>
/// Determines whether the specified index is inside an attribute value.
/// </summary>
public static bool IsInsideAttributeValue(string xml, int index)
{
if (xml.Length == 0)
{
return false;
}
if (index > xml.Length)
{
index = xml.Length;
}
int elementStartIndex = GetActiveElementStartIndex(xml, index);
if (elementStartIndex == -1)
{
return false;
}
// Count the number of double quotes and single quotes that exist
// before the first equals sign encountered going backwards to
// the start of the active element.
bool foundEqualsSign = false;
int doubleQuotesCount = 0;
int singleQuotesCount = 0;
char lastQuoteChar = ' ';
for (int i = index - 1; i > elementStartIndex; --i)
{
char ch = xml[i];
if (ch == '=')
{
foundEqualsSign = true;
break;
}
else if (ch == '\"')
{
lastQuoteChar = ch;
++doubleQuotesCount;
}
else if (ch == '\'')
{
lastQuoteChar = ch;
++singleQuotesCount;
}
}
bool isInside = false;
if (foundEqualsSign)
{
// Odd number of quotes?
if ((lastQuoteChar == '\"') && ((doubleQuotesCount % 2) > 0))
{
isInside = true;
}
else if ((lastQuoteChar == '\'') && ((singleQuotesCount % 2) > 0))
{
isInside = true;
}
}
return isInside;
}
/// <summary>
/// Gets the attribute value at the specified index.
/// </summary>
/// <returns>An empty string if no attribute value can be found.</returns>
public static string GetAttributeValueAtIndex(string xml, int index)
{
if (!IsInsideAttributeValue(xml, index))
{
return String.Empty;
}
index = GetCorrectedIndex(xml.Length, index);
int elementStartIndex = GetActiveElementStartIndex(xml, index);
if (elementStartIndex == -1)
{
return String.Empty;
}
// Find equals sign.
int equalsSignIndex = -1;
for (int i = index; i > elementStartIndex; --i)
{
char ch = xml[i];
if (ch == '=')
{
equalsSignIndex = i;
break;
}
}
if (equalsSignIndex == -1)
{
return String.Empty;
}
// Find attribute value.
char quoteChar = ' ';
bool foundQuoteChar = false;
StringBuilder attributeValue = new StringBuilder();
for (int i = equalsSignIndex; i < xml.Length; ++i)
{
char ch = xml[i];
if (!foundQuoteChar)
{
if (ch == '\"' || ch == '\'')
{
quoteChar = ch;
foundQuoteChar = true;
}
}
else
{
if (ch == quoteChar)
{
// End of attribute value.
return attributeValue.ToString();
}
else if (IsAttributeValueChar(ch) || (ch == '\"' || ch == '\''))
{
attributeValue.Append(ch);
}
else
{
// Invalid character found.
return String.Empty;
}
}
}
return String.Empty;
}
/// <summary>
/// Gets the text of the xml element start tag that the index is
/// currently inside.
/// </summary>
/// <returns>
/// Returns the text up to and including the start tag < character.
/// </returns>
static string GetActiveElementStartText(string xml, int index)
{
int elementStartIndex = GetActiveElementStartIndex(xml, index);
if (elementStartIndex >= 0)
{
if (elementStartIndex < index)
{
int elementEndIndex = GetActiveElementEndIndex(xml, index);
if (elementEndIndex >= index)
{
return xml.Substring(elementStartIndex, elementEndIndex - elementStartIndex);
}
}
}
return null;
}
/// <summary>
/// Locates the index of the start tag < character.
/// </summary>
/// <returns>
/// Returns the index of the start tag character; otherwise
/// -1 if no start tag character is found or a end tag
/// > character is found first.
/// </returns>
static int GetActiveElementStartIndex(string xml, int index)
{
int elementStartIndex = -1;
int currentIndex = index - 1;
for (int i = 0; i < index; ++i)
{
char currentChar = xml[currentIndex];
if (currentChar == '<')
{
elementStartIndex = currentIndex;
break;
}
else if (currentChar == '>')
{
break;
}
--currentIndex;
}
return elementStartIndex;
}
/// <summary>
/// Locates the index of the end tag character.
/// </summary>
/// <returns>
/// Returns the index of the end tag character; otherwise
/// -1 if no end tag character is found or a start tag
/// character is found first.
/// </returns>
static int GetActiveElementEndIndex(string xml, int index)
{
int elementEndIndex = index;
for (int i = index; i < xml.Length; ++i)
{
char currentChar = xml[i];
if (currentChar == '>')
{
elementEndIndex = i;
break;
}
else if (currentChar == '<')
{
elementEndIndex = -1;
break;
}
}
return elementEndIndex;
}
/// <summary>
/// Gets the element name from the element start tag string.
/// </summary>
/// <param name="xml">This string must start at the
/// element we are interested in.</param>
static QualifiedName GetElementName(string xml)
{
string name = String.Empty;
// Find the end of the element name.
xml = xml.Replace("\r\n", " ");
int index = xml.IndexOf(' ');
if (index > 0)
{
name = xml.Substring(1, index - 1);
}
else
{
name = xml.Substring(1);
}
QualifiedName qualifiedName = new QualifiedName();
int prefixIndex = name.IndexOf(':');
if (prefixIndex > 0)
{
qualifiedName.Prefix = name.Substring(0, prefixIndex);
qualifiedName.Name = name.Substring(prefixIndex + 1);
}
else
{
qualifiedName.Name = name;
}
return qualifiedName;
}
/// <summary>
/// Gets the element namespace from the element start tag
/// string.
/// </summary>
/// <param name="xml">This string must start at the
/// element we are interested in.</param>
static NamespaceURI GetElementNamespace(string xml)
{
NamespaceURI namespaceURI = new NamespaceURI();
Match match = Regex.Match(xml, ".*?(xmlns\\s*?|xmlns:.*?)=\\s*?['\\\"](.*?)['\\\"]");
if (match.Success)
{
namespaceURI.Namespace = match.Groups[2].Value;
string xmlns = match.Groups[1].Value.Trim();
int prefixIndex = xmlns.IndexOf(':');
if (prefixIndex > 0)
{
namespaceURI.Prefix = xmlns.Substring(prefixIndex + 1);
}
}
return namespaceURI;
}
static string ReverseString(string text)
{
StringBuilder reversedString = new StringBuilder(text);
int index = text.Length;
foreach (char ch in text)
{
--index;
reversedString[index] = ch;
}
return reversedString.ToString();
}
/// <summary>
/// Ensures that the index is on the last character if it is
/// too large.
/// </summary>
/// <param name="length">The length of the string.</param>
/// <param name="index">The current index.</param>
/// <returns>The index unchanged if the index is smaller than the
/// length of the string; otherwise it returns length - 1.</returns>
static int GetCorrectedIndex(int length, int index)
{
if (index >= length)
{
index = length - 1;
}
return index;
}
/// <summary>
/// Gets the active element path given the element text.
/// </summary>
static XmlElementPath GetActiveElementStartPath(string xml, int index, string elementText)
{
QualifiedName elementName = GetElementName(elementText);
NamespaceURI elementNamespace = GetElementNamespace(elementText);
XmlElementPath path = GetParentElementPath(xml.Substring(0, index));
if (elementNamespace.Namespace.Length == 0)
{
if (path.Elements.Count > 0)
{
QualifiedName parentName = path.Elements[path.Elements.Count - 1];
elementNamespace.Namespace = parentName.Namespace;
elementNamespace.Prefix = parentName.Prefix;
}
}
path.Elements.Add(new QualifiedName(elementName.Name, elementNamespace.Namespace, elementNamespace.Prefix));
path.Compact();
return path;
}
static string GetAttributeName(string xml, int index, bool ignoreWhitespace, bool ignoreQuote, bool ignoreEqualsSign)
{
string name = String.Empty;
// From the end of the string work backwards until we have
// picked out the attribute name.
StringBuilder reversedAttributeName = new StringBuilder();
int currentIndex = index;
bool invalidString = true;
for (int i = 0; i <= index; ++i)
{
char currentChar = xml[currentIndex];
if (Char.IsLetterOrDigit(currentChar))
{
if (!ignoreEqualsSign)
{
ignoreWhitespace = false;
reversedAttributeName.Append(currentChar);
}
}
else if (Char.IsWhiteSpace(currentChar))
{
if (ignoreWhitespace == false)
{
// Reached the start of the attribute name.
invalidString = false;
break;
}
}
else if ((currentChar == '\'') || (currentChar == '\"'))
{
if (ignoreQuote)
{
ignoreQuote = false;
}
else
{
break;
}
}
else if (currentChar == '=')
{
if (ignoreEqualsSign)
{
ignoreEqualsSign = false;
}
else
{
break;
}
}
else if (IsAttributeValueChar(currentChar))
{
if (!ignoreQuote)
{
break;
}
}
else
{
break;
}
--currentIndex;
}
if (!invalidString)
{
name = ReverseString(reversedAttributeName.ToString());
}
return name;
}
/// <summary>
/// Gets the element name at the specified index.
/// </summary>
static string GetElementNameAtIndex(string xml, int index)
{
int elementStartIndex = GetActiveElementStartIndex(xml, index);
if (elementStartIndex >= 0 && elementStartIndex < index)
{
int elementEndIndex = GetActiveElementEndIndex(xml, index);
if (elementEndIndex == -1)
{
elementEndIndex = xml.IndexOf(' ', elementStartIndex);
}
if (elementEndIndex >= elementStartIndex)
{
return xml.Substring(elementStartIndex, elementEndIndex - elementStartIndex);
}
}
return null;
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.App.Analyst;
using Encog.Engine.Network.Activation;
using Encog.Neural.Flat;
using Encog.Util;
using Encog.Util.CSV;
using Encog.Util.File;
namespace Encog.App.Generate.Generators
{
/// <summary>
/// Provides a basic implementation of a template generator.
/// </summary>
public abstract class AbstractTemplateGenerator : ITemplateGenerator
{
/// <summary>
/// The contents of the generated file.
/// </summary>
private readonly StringBuilder contents = new StringBuilder();
/// <summary>
/// The Encog analyst that is being used.
/// </summary>
private EncogAnalyst analyst;
/// <summary>
/// The current indention level.
/// </summary>
public int IndentLevel { get; set; }
/// <summary>
/// The Encog analyst that we are using.
/// </summary>
public EncogAnalyst Analyst
{
get { return analyst; }
}
/// <summary>
/// A platform specific array set to null.
/// </summary>
public abstract String NullArray { get; }
/// <summary>
/// Get a resource path to the template that we are using.
/// </summary>
public abstract String TemplatePath { get; }
/// <summary>
/// Generate based on the provided Encog Analyst.
/// </summary>
/// <param name="theAnalyst">The Encog analyst to base this on.</param>
public void Generate(EncogAnalyst theAnalyst)
{
string fileContent = ResourceLoader.LoadString(TemplatePath);
using (var reader = new StringReader(fileContent))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("~~"))
{
ProcessToken(line.Substring(2).Trim());
}
else
{
contents.Append(line);
contents.Append("\n");
}
}
}
}
/// <summary>
/// The generated contents.
/// </summary>
public String Contents
{
get { return contents.ToString(); }
}
/// <summary>
/// Write the contents to the specified file.
/// </summary>
/// <param name="targetFile">The target file.</param>
public void WriteContents(FileInfo targetFile)
{
File.WriteAllText(targetFile.ToString(), contents.ToString());
}
/// <summary>
/// Add a line, with proper indention.
/// </summary>
/// <param name="line">The line to add.</param>
public void AddLine(String line)
{
for (int i = 0; i < IndentLevel; i++)
{
contents.Append("\t");
}
contents.Append(line);
contents.Append("\n");
}
/// <summary>
/// Add a name value definition, as a double array.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="data">THe data.</param>
public void AddNameValue(String name, double[] data)
{
var value = new StringBuilder();
if (data == null)
{
value.Append(name);
value.Append(" = " + NullArray + ";");
AddLine(value.ToString());
}
else
{
ToBrokenList(value, data);
AddNameValue(name, "{" + value + "}");
}
}
/// <summary>
/// Add a name-value as an int.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">THe value.</param>
public void AddNameValue(String name, int value)
{
AddNameValue(name, "" + value);
}
/// <summary>
/// Add a name-value array where the value is an int array.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="data">The value.</param>
public void AddNameValue(String name, int[] data)
{
var value = new StringBuilder();
if (data == null)
{
value.Append(name);
value.Append(" = " + NullArray + ";");
AddLine(value.ToString());
}
else
{
ToBrokenList(value, data);
AddNameValue(name, "{" + value + "}");
}
}
/// <summary>
/// Add a name-value where a string is the value.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
public void AddNameValue(String name, String value)
{
var line = new StringBuilder();
line.Append(name);
line.Append(" = ");
if (value == null)
{
line.Append(NullArray);
}
else
{
line.Append(value);
}
line.Append(";");
AddLine(line.ToString());
}
/// <summary>
/// Create an array of activations based on a flat network.
/// </summary>
/// <param name="flat">The flat network.</param>
/// <returns></returns>
public int[] CreateActivations(FlatNetwork flat)
{
var result = new int[flat.ActivationFunctions.Length];
for (int i = 0; i < flat.ActivationFunctions.Length; i++)
{
IActivationFunction af = flat.ActivationFunctions[i];
if (af is ActivationLinear)
{
result[i] = 0;
}
else if (af is ActivationTANH)
{
result[i] = 1;
}
if (af is ActivationSigmoid)
{
result[i] = 2;
}
if (af is ActivationElliottSymmetric)
{
result[i] = 3;
}
if (af is ActivationElliott)
{
result[i] = 4;
}
}
return result;
}
/// <summary>
/// Create an array of doubles to hold the specified flat network.
/// </summary>
/// <param name="flat">The flat network to use as a model.</param>
/// <returns>The new array.</returns>
public double[] CreateParams(FlatNetwork flat)
{
var result = new double[flat.ActivationFunctions.Length];
EngineArray.Fill(result, 1);
return result;
}
/// <summary>
/// Indent to the right one.
/// </summary>
public void IndentIn()
{
IndentLevel++;
}
/// <summary>
/// Indent to the left one.
/// </summary>
public void IndentOut()
{
IndentLevel--;
}
/// <summary>
/// Process the specified token.
/// </summary>
/// <param name="command">The token to process.</param>
public abstract void ProcessToken(String command);
/// <summary>
/// Create an array list broken into 10 columns. This prevents a very large
/// array from creating a very long single line.
/// </summary>
/// <param name="result">The string builder to add to.</param>
/// <param name="data">The data to convert.</param>
public void ToBrokenList(StringBuilder result, double[] data)
{
int lineCount = 0;
result.Length = 0;
for (int i = 0; i < data.Length; i++)
{
if (i != 0)
{
result.Append(',');
}
lineCount++;
if (lineCount > 10)
{
result.Append("\n");
lineCount = 0;
}
result.Append(CSVFormat.EgFormat.Format(data[i],
EncogFramework.DefaultPrecision));
}
}
/// <summary>
/// Create an array list broken into 10 columns. This prevents a very large
/// array from creating a very long single line.
/// </summary>
/// <param name="result">The string builder to add to.</param>
/// <param name="data">The data to convert.</param>
public void ToBrokenList(StringBuilder result, int[] data)
{
int lineCount = 0;
for (int i = 0; i < data.Length; i++)
{
if (i != 0)
{
result.Append(',');
}
lineCount++;
if (lineCount > 10)
{
result.Append("\n");
lineCount = 0;
}
result.Append("" + data[i]);
}
}
}
}
| |
using DevExpress.Mvvm.UI.Interactivity;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using DevExpress.Mvvm.Native;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using DevExpress.Mvvm.UI.Native;
using System.ComponentModel;
namespace DevExpress.Mvvm.UI {
public abstract class FunctionBindingBehaviorBase : Behavior<DependencyObject> {
#region error messages
protected const string Error_PropertyNotFound = "Cannot find property with name {1} in the {0} class.";
protected const string Error_SourceMethodNotFound = "FunctionBindingBehaviorBase error: Cannot find function with name {1} in the {0} class.";
protected const string Error_SourceMethodReturnVoid = "The return value of the '{0}.{1}' function can't be void.";
#endregion
#region Dependency Properties
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnSourceObjectChanged()));
public static readonly DependencyProperty Arg1Property =
DependencyProperty.Register("Arg1", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg2Property =
DependencyProperty.Register("Arg2", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg3Property =
DependencyProperty.Register("Arg3", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg4Property =
DependencyProperty.Register("Arg4", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg5Property =
DependencyProperty.Register("Arg5", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg6Property =
DependencyProperty.Register("Arg6", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg7Property =
DependencyProperty.Register("Arg7", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg8Property =
DependencyProperty.Register("Arg8", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg9Property =
DependencyProperty.Register("Arg9", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg10Property =
DependencyProperty.Register("Arg10", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg11Property =
DependencyProperty.Register("Arg11", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg12Property =
DependencyProperty.Register("Arg12", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg13Property =
DependencyProperty.Register("Arg13", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg14Property =
DependencyProperty.Register("Arg14", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public static readonly DependencyProperty Arg15Property =
DependencyProperty.Register("Arg15", typeof(object), typeof(FunctionBindingBehaviorBase),
new PropertyMetadata(null, (d, e) => ((FunctionBindingBehaviorBase)d).OnResultAffectedPropertyChanged()));
public object Source {
get { return GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public object Arg1 {
get { return GetValue(Arg1Property); }
set { SetValue(Arg1Property, value); }
}
public object Arg2 {
get { return GetValue(Arg2Property); }
set { SetValue(Arg2Property, value); }
}
public object Arg3 {
get { return GetValue(Arg3Property); }
set { SetValue(Arg3Property, value); }
}
public object Arg4 {
get { return GetValue(Arg4Property); }
set { SetValue(Arg4Property, value); }
}
public object Arg5 {
get { return GetValue(Arg5Property); }
set { SetValue(Arg5Property, value); }
}
public object Arg6 {
get { return GetValue(Arg6Property); }
set { SetValue(Arg6Property, value); }
}
public object Arg7 {
get { return GetValue(Arg7Property); }
set { SetValue(Arg7Property, value); }
}
public object Arg8 {
get { return GetValue(Arg8Property); }
set { SetValue(Arg8Property, value); }
}
public object Arg9 {
get { return GetValue(Arg9Property); }
set { SetValue(Arg9Property, value); }
}
public object Arg10 {
get { return GetValue(Arg10Property); }
set { SetValue(Arg10Property, value); }
}
public object Arg11 {
get { return GetValue(Arg11Property); }
set { SetValue(Arg11Property, value); }
}
public object Arg12 {
get { return GetValue(Arg12Property); }
set { SetValue(Arg12Property, value); }
}
public object Arg13 {
get { return GetValue(Arg13Property); }
set { SetValue(Arg13Property, value); }
}
public object Arg14 {
get { return GetValue(Arg14Property); }
set { SetValue(Arg14Property, value); }
}
public object Arg15 {
get { return GetValue(Arg15Property); }
set { SetValue(Arg15Property, value); }
}
#endregion
static readonly Regex regExp = new Regex(@"^Arg\d", RegexOptions.Compiled);
static readonly Regex numbers = new Regex(@"\d+", RegexOptions.Compiled);
protected object ActualSource { get; private set; }
protected abstract string ActualFunction { get; }
protected override void OnAttached() {
base.OnAttached();
(AssociatedObject as FrameworkElement).Do(x => x.DataContextChanged += OnAssociatedObjectDataContextChanged);
(AssociatedObject as FrameworkContentElement).Do(x => x.DataContextChanged += OnAssociatedObjectDataContextChanged);
UpdateActualSource();
OnResultAffectedPropertyChanged();
}
protected override void OnDetaching() {
(AssociatedObject as FrameworkElement).Do(x => x.DataContextChanged -= OnAssociatedObjectDataContextChanged);
(AssociatedObject as FrameworkContentElement).Do(x => x.DataContextChanged -= OnAssociatedObjectDataContextChanged);
(ActualSource as INotifyPropertyChanged).Do(x => x.PropertyChanged -= OnSourceObjectPropertyChanged);
ActualSource = null;
base.OnDetaching();
}
void OnAssociatedObjectDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
if(Source == null) {
UpdateActualSource();
OnResultAffectedPropertyChanged();
}
}
void OnSourceObjectChanged() {
UpdateActualSource();
OnResultAffectedPropertyChanged();
}
protected virtual void UpdateActualSource() {
(ActualSource as INotifyPropertyChanged).Do(x => x.PropertyChanged -= OnSourceObjectPropertyChanged);
ActualSource = Source ?? GetAssociatedObjectDataContext();
(ActualSource as INotifyPropertyChanged).Do(x => x.PropertyChanged += OnSourceObjectPropertyChanged);
}
object GetAssociatedObjectDataContext() {
object result = (AssociatedObject as FrameworkElement).Return(x => x.DataContext, () => null);
return result ?? (AssociatedObject as FrameworkContentElement).Return(x => x.DataContext, () => null);
}
void OnSourceObjectPropertyChanged(object sender, PropertyChangedEventArgs e) {
if(e.PropertyName == ActualFunction)
OnResultAffectedPropertyChanged();
}
protected virtual void OnResultAffectedPropertyChanged() { }
#region get method value
protected class ArgInfo {
public object Value { get; private set; }
public Type Type { get; private set; }
public bool IsUnsetValue { get; private set; }
public ArgInfo(DependencyObject obj, DependencyProperty prop) {
object value = obj.ReadLocalValue(prop);
IsUnsetValue = value == DependencyProperty.UnsetValue;
if(!IsUnsetValue) {
Value = value is BindingExpression ? obj.GetValue(prop) : value;
if(Value != null)
Type = Value.GetType();
}
}
public ArgInfo(object value) {
IsUnsetValue = value == DependencyProperty.UnsetValue;
if(!IsUnsetValue) {
Value = value;
if(Value != null)
Type = Value.GetType();
}
}
}
protected static List<ArgInfo> GetArgsInfo(FunctionBindingBehaviorBase instance) {
return typeof(FunctionBindingBehaviorBase).GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(x => regExp.IsMatch(x.Name)).OrderBy(x => int.Parse(numbers.Match(x.Name).Value))
.Select(x => new ArgInfo(instance, (DependencyProperty)x.GetValue(instance))).ToList();
}
protected static object InvokeSourceFunction(object source, string functionName, List<ArgInfo> argsInfo, Func<MethodInfo, Type, string, bool> functionChecker) {
if(argsInfo == null)
argsInfo = new List<ArgInfo>();
while(argsInfo.Count < 15)
argsInfo.Add(new ArgInfo(DependencyProperty.UnsetValue));
int argsCount = argsInfo.FindLastIndex(x => !x.IsUnsetValue) + 1;
Type targetType = (source as Type).Return(x => x.IsAbstract && x.IsSealed, () => false) ? source as Type : source.GetType();
MethodInfo info = GetMethodInfo(targetType, functionName, argsCount, argsInfo.Take(argsCount).Select(x => x.Type).ToArray());
if(!functionChecker(info, targetType, functionName))
return DependencyProperty.UnsetValue;
ParameterInfo[] paramsInfo = info.GetParameters();
argsCount = paramsInfo.Length;
int count = 0;
object[] param = argsInfo.Take(argsCount).Select(x => {
ParameterInfo parInfo = paramsInfo[count++];
if(x.IsUnsetValue && parInfo.IsOptional && parInfo.Attributes.HasFlag(ParameterAttributes.HasDefault))
return parInfo.RawDefaultValue;
else
return TypeCastHelper.TryCast(x.Value, parInfo.ParameterType);
}).ToArray();
return info.Invoke(source, param);
}
protected static bool DefaultMethodInfoChecker(MethodInfo info, Type targetType, string functionName) {
if(info == null) {
System.Diagnostics.Trace.WriteLine(string.Format(Error_SourceMethodNotFound, targetType.Name, functionName));
return false;
}
if(info.ReturnType == typeof(void))
throw new ArgumentException(string.Format(Error_SourceMethodReturnVoid, targetType.Name, info.Name));
return true;
}
protected static Action<object> GetObjectPropertySetter(object target, string property, bool? throwExcepctionOnNotFound = null) {
PropertyInfo targetPropertyInfo = ObjectPropertyHelper.GetPropertyInfoSetter(target, property);
targetPropertyInfo = targetPropertyInfo ?? ObjectPropertyHelper.GetPropertyInfo(target, property,
BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.NonPublic | BindingFlags.Static);
if(targetPropertyInfo != null)
return x => targetPropertyInfo.SetValue(target, x, null);
DependencyProperty targetDependencyProperty = ObjectPropertyHelper.GetDependencyProperty(target, property);
if(targetDependencyProperty != null)
return x => ((DependencyObject)target).SetValue(targetDependencyProperty, x);
if(throwExcepctionOnNotFound.HasValue) {
string message = string.Format(Error_PropertyNotFound, target.GetType().Name, property);
if(throwExcepctionOnNotFound.Value)
throw new ArgumentException(message);
else
System.Diagnostics.Trace.WriteLine(string.Format("MethodBindingBehaviorBase error: {0}", message));
}
return null;
}
static MethodInfo GetMethodInfo(Type objType, string methodName, int argsCount = -1, Type[] argsType = null) {
if(string.IsNullOrWhiteSpace(methodName) || objType == null)
return null;
MethodInfo result = null;
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
if(!argsType.Return(x => x.Length == 0 || x.Any(e => e == null), () => false))
result = objType.GetMethod(methodName, flags, Type.DefaultBinder, argsType, null);
return result ?? TryFindAmongMethods(objType, methodName, argsCount, argsType);
}
static MethodInfo TryFindAmongMethods(Type objType, string methodName, int argsCount, Type[] argsType) {
var appropriateMethods = objType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
.Where(e => e.Name == methodName).OrderBy(o => o.GetParameters().Length);
if(argsType != null && argsType.Length > 0 && appropriateMethods.Count() > 1) {
foreach(MethodInfo info in appropriateMethods) {
if(argsCount > -1 && info.GetParameters().Length < argsCount)
continue;
int count = 0;
if(argsType.All(x => x == null || info.GetParameters()[count++].ParameterType.Equals(x)))
return info;
}
}
return (argsCount > -1 ? appropriateMethods.FirstOrDefault(x => x.GetParameters().Length >= argsCount) : null) ?? appropriateMethods.FirstOrDefault();
}
#endregion
}
}
| |
//
// 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;
namespace DiscUtils.Streams
{
/// <summary>
/// Represents a range of bytes in a stream.
/// </summary>
/// <remarks>This is normally used to represent regions of a SparseStream that
/// are actually stored in the underlying storage medium (rather than implied
/// zero bytes). Extents are stored as a zero-based byte offset (from the
/// beginning of the stream), and a byte length.</remarks>
public sealed class StreamExtent : IEquatable<StreamExtent>, IComparable<StreamExtent>
{
/// <summary>
/// Initializes a new instance of the StreamExtent class.
/// </summary>
/// <param name="start">The start of the extent.</param>
/// <param name="length">The length of the extent.</param>
public StreamExtent(long start, long length)
{
Start = start;
Length = length;
}
/// <summary>
/// Gets the start of the extent (in bytes).
/// </summary>
public long Length { get; }
/// <summary>
/// Gets the start of the extent (in bytes).
/// </summary>
public long Start { get; }
/// <summary>
/// Compares this stream extent to another.
/// </summary>
/// <param name="other">The extent to compare.</param>
/// <returns>Value greater than zero if this extent starts after
/// <c>other</c>, zero if they start at the same position, else
/// a value less than zero.</returns>
public int CompareTo(StreamExtent other)
{
if (Start > other.Start)
{
return 1;
}
if (Start == other.Start)
{
return 0;
}
return -1;
}
/// <summary>
/// Indicates if this StreamExtent is equal to another.
/// </summary>
/// <param name="other">The extent to compare.</param>
/// <returns><c>true</c> if the extents are equal, else <c>false</c>.</returns>
public bool Equals(StreamExtent other)
{
if (other == null)
{
return false;
}
return Start == other.Start && Length == other.Length;
}
/// <summary>
/// Calculates the union of a list of extents with another extent.
/// </summary>
/// <param name="extents">The list of extents.</param>
/// <param name="other">The other extent.</param>
/// <returns>The union of the extents.</returns>
public static IEnumerable<StreamExtent> Union(IEnumerable<StreamExtent> extents, StreamExtent other)
{
List<StreamExtent> otherList = new List<StreamExtent>();
otherList.Add(other);
return Union(extents, otherList);
}
/// <summary>
/// Calculates the union of the extents of multiple streams.
/// </summary>
/// <param name="streams">The stream extents.</param>
/// <returns>The union of the extents from multiple streams.</returns>
/// <remarks>A typical use of this method is to calculate the combined set of
/// stored extents from a number of overlayed sparse streams.</remarks>
public static IEnumerable<StreamExtent> Union(params IEnumerable<StreamExtent>[] streams)
{
long extentStart = long.MaxValue;
long extentEnd = 0;
// Initialize enumerations and find first stored byte position
IEnumerator<StreamExtent>[] enums = new IEnumerator<StreamExtent>[streams.Length];
bool[] streamsValid = new bool[streams.Length];
int validStreamsRemaining = 0;
for (int i = 0; i < streams.Length; ++i)
{
enums[i] = streams[i].GetEnumerator();
streamsValid[i] = enums[i].MoveNext();
if (streamsValid[i])
{
++validStreamsRemaining;
if (enums[i].Current.Start < extentStart)
{
extentStart = enums[i].Current.Start;
extentEnd = enums[i].Current.Start + enums[i].Current.Length;
}
}
}
while (validStreamsRemaining > 0)
{
// Find the end of this extent
bool foundIntersection;
do
{
foundIntersection = false;
validStreamsRemaining = 0;
for (int i = 0; i < streams.Length; ++i)
{
while (streamsValid[i] && enums[i].Current.Start + enums[i].Current.Length <= extentEnd)
{
streamsValid[i] = enums[i].MoveNext();
}
if (streamsValid[i])
{
++validStreamsRemaining;
}
if (streamsValid[i] && enums[i].Current.Start <= extentEnd)
{
extentEnd = enums[i].Current.Start + enums[i].Current.Length;
foundIntersection = true;
streamsValid[i] = enums[i].MoveNext();
}
}
} while (foundIntersection && validStreamsRemaining > 0);
// Return the discovered extent
yield return new StreamExtent(extentStart, extentEnd - extentStart);
// Find the next extent start point
extentStart = long.MaxValue;
validStreamsRemaining = 0;
for (int i = 0; i < streams.Length; ++i)
{
if (streamsValid[i])
{
++validStreamsRemaining;
if (enums[i].Current.Start < extentStart)
{
extentStart = enums[i].Current.Start;
extentEnd = enums[i].Current.Start + enums[i].Current.Length;
}
}
}
}
}
/// <summary>
/// Calculates the intersection of the extents of a stream with another extent.
/// </summary>
/// <param name="extents">The stream extents.</param>
/// <param name="other">The extent to intersect.</param>
/// <returns>The intersection of the extents.</returns>
public static IEnumerable<StreamExtent> Intersect(IEnumerable<StreamExtent> extents, StreamExtent other)
{
List<StreamExtent> otherList = new List<StreamExtent>(1);
otherList.Add(other);
return Intersect(extents, otherList);
}
/// <summary>
/// Calculates the intersection of the extents of multiple streams.
/// </summary>
/// <param name="streams">The stream extents.</param>
/// <returns>The intersection of the extents from multiple streams.</returns>
/// <remarks>A typical use of this method is to calculate the extents in a
/// region of a stream..</remarks>
public static IEnumerable<StreamExtent> Intersect(params IEnumerable<StreamExtent>[] streams)
{
long extentStart = long.MinValue;
long extentEnd = long.MaxValue;
IEnumerator<StreamExtent>[] enums = new IEnumerator<StreamExtent>[streams.Length];
for (int i = 0; i < streams.Length; ++i)
{
enums[i] = streams[i].GetEnumerator();
if (!enums[i].MoveNext())
{
// Gone past end of one stream (in practice was empty), so no intersections
yield break;
}
}
int overlapsFound = 0;
while (true)
{
// We keep cycling round the streams, until we get streams.Length continuous overlaps
for (int i = 0; i < streams.Length; ++i)
{
// Move stream on past all extents that are earlier than our candidate start point
while (enums[i].Current.Length == 0
|| enums[i].Current.Start + enums[i].Current.Length <= extentStart)
{
if (!enums[i].MoveNext())
{
// Gone past end of this stream, no more intersections possible
yield break;
}
}
// If this stream has an extent that spans over the candidate start point
if (enums[i].Current.Start <= extentStart)
{
extentEnd = Math.Min(extentEnd, enums[i].Current.Start + enums[i].Current.Length);
overlapsFound++;
}
else
{
extentStart = enums[i].Current.Start;
extentEnd = extentStart + enums[i].Current.Length;
overlapsFound = 1;
}
// We've just done a complete loop of all streams, they overlapped this start position
// and we've cut the extent's end down to the shortest run.
if (overlapsFound == streams.Length)
{
yield return new StreamExtent(extentStart, extentEnd - extentStart);
extentStart = extentEnd;
extentEnd = long.MaxValue;
overlapsFound = 0;
}
}
}
}
/// <summary>
/// Calculates the subtraction of the extents of a stream by another extent.
/// </summary>
/// <param name="extents">The stream extents.</param>
/// <param name="other">The extent to subtract.</param>
/// <returns>The subtraction of <c>other</c> from <c>extents</c>.</returns>
public static IEnumerable<StreamExtent> Subtract(IEnumerable<StreamExtent> extents, StreamExtent other)
{
return Subtract(extents, new[] { other });
}
/// <summary>
/// Calculates the subtraction of the extents of a stream by another stream.
/// </summary>
/// <param name="a">The stream extents to subtract from.</param>
/// <param name="b">The stream extents to subtract.</param>
/// <returns>The subtraction of the extents of b from a.</returns>
public static IEnumerable<StreamExtent> Subtract(IEnumerable<StreamExtent> a, IEnumerable<StreamExtent> b)
{
return Intersect(a, Invert(b));
}
/// <summary>
/// Calculates the inverse of the extents of a stream.
/// </summary>
/// <param name="extents">The stream extents to inverse.</param>
/// <returns>The inverted extents.</returns>
/// <remarks>
/// This method assumes a logical stream addressable from <c>0</c> to <c>long.MaxValue</c>, and is undefined
/// should any stream extent start at less than 0. To constrain the extents to a specific range, use the
/// <c>Intersect</c> method.
/// </remarks>
public static IEnumerable<StreamExtent> Invert(IEnumerable<StreamExtent> extents)
{
StreamExtent last = new StreamExtent(0, 0);
foreach (StreamExtent extent in extents)
{
// Skip over any 'noise'
if (extent.Length == 0)
{
continue;
}
long lastEnd = last.Start + last.Length;
if (lastEnd < extent.Start)
{
yield return new StreamExtent(lastEnd, extent.Start - lastEnd);
}
last = extent;
}
long finalEnd = last.Start + last.Length;
if (finalEnd < long.MaxValue)
{
yield return new StreamExtent(finalEnd, long.MaxValue - finalEnd);
}
}
/// <summary>
/// Offsets the extents of a stream.
/// </summary>
/// <param name="stream">The stream extents.</param>
/// <param name="delta">The amount to offset the extents by.</param>
/// <returns>The stream extents, offset by delta.</returns>
public static IEnumerable<StreamExtent> Offset(IEnumerable<StreamExtent> stream, long delta)
{
foreach (StreamExtent extent in stream)
{
yield return new StreamExtent(extent.Start + delta, extent.Length);
}
}
/// <summary>
/// Returns the number of blocks containing stream data.
/// </summary>
/// <param name="stream">The stream extents.</param>
/// <param name="blockSize">The size of each block.</param>
/// <returns>The number of blocks containing stream data.</returns>
/// <remarks>This method logically divides the stream into blocks of a specified
/// size, then indicates how many of those blocks contain actual stream data.</remarks>
public static long BlockCount(IEnumerable<StreamExtent> stream, long blockSize)
{
long totalBlocks = 0;
long lastBlock = -1;
foreach (StreamExtent extent in stream)
{
if (extent.Length > 0)
{
long extentStartBlock = extent.Start / blockSize;
long extentNextBlock = MathUtilities.Ceil(extent.Start + extent.Length, blockSize);
long extentNumBlocks = extentNextBlock - extentStartBlock;
if (extentStartBlock == lastBlock)
{
extentNumBlocks--;
}
lastBlock = extentNextBlock - 1;
totalBlocks += extentNumBlocks;
}
}
return totalBlocks;
}
/// <summary>
/// Returns all of the blocks containing stream data.
/// </summary>
/// <param name="stream">The stream extents.</param>
/// <param name="blockSize">The size of each block.</param>
/// <returns>Ranges of blocks, as block indexes.</returns>
/// <remarks>This method logically divides the stream into blocks of a specified
/// size, then indicates ranges of blocks that contain stream data.</remarks>
public static IEnumerable<Range<long, long>> Blocks(IEnumerable<StreamExtent> stream, long blockSize)
{
long? rangeStart = null;
long rangeLength = 0;
foreach (StreamExtent extent in stream)
{
if (extent.Length > 0)
{
long extentStartBlock = extent.Start / blockSize;
long extentNextBlock = MathUtilities.Ceil(extent.Start + extent.Length, blockSize);
if (rangeStart != null && extentStartBlock > rangeStart + rangeLength)
{
// This extent is non-contiguous (in terms of blocks), so write out the last range and start new
yield return new Range<long, long>((long)rangeStart, rangeLength);
rangeStart = extentStartBlock;
}
else if (rangeStart == null)
{
// First extent, so start first range
rangeStart = extentStartBlock;
}
// Set the length of the current range, based on the end of this extent
rangeLength = extentNextBlock - (long)rangeStart;
}
}
// Final range (if any ranges at all) hasn't been returned yet, so do that now
if (rangeStart != null)
{
yield return new Range<long, long>((long)rangeStart, rangeLength);
}
}
/// <summary>
/// The equality operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether the two extents are equal.</returns>
public static bool operator ==(StreamExtent a, StreamExtent b)
{
if (ReferenceEquals(a, null))
{
return ReferenceEquals(b, null);
}
return a.Equals(b);
}
/// <summary>
/// The inequality operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether the two extents are different.</returns>
public static bool operator !=(StreamExtent a, StreamExtent b)
{
return !(a == b);
}
/// <summary>
/// The less-than operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether a is less than b.</returns>
public static bool operator <(StreamExtent a, StreamExtent b)
{
return a.CompareTo(b) < 0;
}
/// <summary>
/// The greater-than operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether a is greater than b.</returns>
public static bool operator >(StreamExtent a, StreamExtent b)
{
return a.CompareTo(b) > 0;
}
/// <summary>
/// Returns a string representation of the extent as [start:+length].
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return "[" + Start + ":+" + Length + "]";
}
/// <summary>
/// Indicates if this stream extent is equal to another object.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <c>obj</c> is equivalent, else <c>false</c>.</returns>
public override bool Equals(object obj)
{
return Equals(obj as StreamExtent);
}
/// <summary>
/// Gets a hash code for this extent.
/// </summary>
/// <returns>The extent's hash code.</returns>
public override int GetHashCode()
{
return Start.GetHashCode() ^ Length.GetHashCode();
}
}
}
| |
using UnityEngine;
namespace UnitySampleAssets.ImageEffects
{
public enum LensflareStyle34
{
Ghosting = 0,
Anamorphic = 1,
Combined = 2,
}
public enum TweakMode34
{
Basic = 0,
Complex = 1,
}
public enum HDRBloomMode
{
Auto = 0,
On = 1,
Off = 2,
}
public enum BloomScreenBlendMode
{
Screen = 0,
Add = 1,
}
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/BloomAndFlares (3.5, Deprecated)")]
public class BloomAndLensFlares : PostEffectsBase
{
public TweakMode34 tweakMode = 0;
public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add;
public HDRBloomMode hdr = HDRBloomMode.Auto;
private bool doHdr = false;
public float sepBlurSpread = 1.5f;
public float useSrcAlphaAsMask = 0.5f;
public float bloomIntensity = 1.0f;
public float bloomThreshhold = 0.5f;
public int bloomBlurIterations = 2;
public bool lensflares = false;
public int hollywoodFlareBlurIterations = 2;
public LensflareStyle34 lensflareMode = (LensflareStyle34)1;
public float hollyStretchWidth = 3.5f;
public float lensflareIntensity = 1.0f;
public float lensflareThreshhold = 0.3f;
public Color flareColorA = new Color(0.4f, 0.4f, 0.8f, 0.75f);
public Color flareColorB = new Color(0.4f, 0.8f, 0.8f, 0.75f);
public Color flareColorC = new Color(0.8f, 0.4f, 0.8f, 0.75f);
public Color flareColorD = new Color(0.8f, 0.4f, 0.0f, 0.75f);
public float blurWidth = 1.0f;
public Texture2D lensFlareVignetteMask;
public Shader lensFlareShader;
private Material lensFlareMaterial;
public Shader vignetteShader;
private Material vignetteMaterial;
public Shader separableBlurShader;
private Material separableBlurMaterial;
public Shader addBrightStuffOneOneShader;
private Material addBrightStuffBlendOneOneMaterial;
public Shader screenBlendShader;
private Material screenBlend;
public Shader hollywoodFlaresShader;
private Material hollywoodFlaresMaterial;
public Shader brightPassFilterShader;
private Material brightPassFilterMaterial;
protected override bool CheckResources()
{
CheckSupport(false);
screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend);
lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial);
vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial);
separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial);
addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial);
hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial);
brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);
if (!isSupported)
ReportAutoDisable();
return isSupported;
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit(source, destination);
return;
}
// screen blend is not supported when HDR is enabled (will cap values)
doHdr = false;
if (hdr == HDRBloomMode.Auto)
doHdr = source.format == RenderTextureFormat.ARGBHalf && camera.hdr;
else
{
doHdr = hdr == HDRBloomMode.On;
}
doHdr = doHdr && supportHDRTextures;
BloomScreenBlendMode realBlendMode = screenBlendMode;
if (doHdr)
realBlendMode = BloomScreenBlendMode.Add;
var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat);
RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
float oneOverBaseSize = 1.0f / 512.0f;
// downsample
Graphics.Blit(source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample
Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample
RenderTexture.ReleaseTemporary(halfRezColor);
// cut colors (threshholding)
BrightFilter(bloomThreshhold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor);
quarterRezColor.DiscardContents();
// blurring
if (bloomBlurIterations < 1) bloomBlurIterations = 1;
for (int iter = 0; iter < bloomBlurIterations; iter++)
{
float spreadForPass = (1.0f + (iter * 0.5f)) * sepBlurSpread;
separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f));
RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor;
Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial);
src.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
// lens flares: ghosting, anamorphic or a combination
if (lensflares)
{
if (lensflareMode == 0)
{
BrightFilter(lensflareThreshhold, 0.0f, quarterRezColor, thirdQuarterRezColor);
quarterRezColor.DiscardContents();
// smooth a little, this needs to be resolution dependent
/*
separableBlurMaterial.SetVector ("offsets", Vector4 (0.0f, (2.0f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f));
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
*/
// no ugly edges!
Vignette(0.975f, thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
BlendFlares(secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
// (b) hollywood/anamorphic flares?
else
{
// thirdQuarter has the brightcut unblurred colors
// quarterRezColor is the blurred, brightcut buffer that will end up as bloom
hollywoodFlaresMaterial.SetVector("_Threshhold", new Vector4(lensflareThreshhold, 1.0f / (1.0f - lensflareThreshhold), 0.0f, 0.0f));
hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2);
thirdQuarterRezColor.DiscardContents();
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f);
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
if (lensflareMode == (LensflareStyle34)1)
{
for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++)
{
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
else
{
// (c) combined
for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++)
{
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
Vignette(1.0f, secondQuarterRezColor, thirdQuarterRezColor);
secondQuarterRezColor.DiscardContents();
BlendFlares(thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
}
}
// screen blend bloom results to color buffer
screenBlend.SetFloat("_Intensity", bloomIntensity);
screenBlend.SetTexture("_ColorBuffer", source);
Graphics.Blit(quarterRezColor, destination, screenBlend, (int)realBlendMode);
RenderTexture.ReleaseTemporary(quarterRezColor);
RenderTexture.ReleaseTemporary(secondQuarterRezColor);
RenderTexture.ReleaseTemporary(thirdQuarterRezColor);
}
private void AddTo(float intensity_, RenderTexture from, RenderTexture to)
{
addBrightStuffBlendOneOneMaterial.SetFloat("_Intensity", intensity_);
Graphics.Blit(from, to, addBrightStuffBlendOneOneMaterial);
}
private void BlendFlares(RenderTexture from, RenderTexture to)
{
lensFlareMaterial.SetVector("colorA", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorB", new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorC", new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorD", new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity);
Graphics.Blit(from, to, lensFlareMaterial);
}
private void BrightFilter(float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to)
{
if (doHdr)
brightPassFilterMaterial.SetVector("threshhold", new Vector4(thresh, 1.0f, 0.0f, 0.0f));
else
brightPassFilterMaterial.SetVector("threshhold", new Vector4(thresh, 1.0f / (1.0f - thresh), 0.0f, 0.0f));
brightPassFilterMaterial.SetFloat("useSrcAlphaAsMask", useAlphaAsMask);
Graphics.Blit(from, to, brightPassFilterMaterial);
}
private void Vignette(float amount, RenderTexture from, RenderTexture to)
{
if (lensFlareVignetteMask)
{
screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask);
Graphics.Blit(from, to, screenBlend, 3);
}
else
{
vignetteMaterial.SetFloat("vignetteIntensity", amount);
Graphics.Blit(from, to, vignetteMaterial);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="JsonDataReader.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Stratus.OdinSerializer
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
/// <summary>
/// Reads json data from a stream that has been written by a <see cref="JsonDataWriter"/>.
/// </summary>
/// <seealso cref="BaseDataReader" />
public class JsonDataReader : BaseDataReader
{
private JsonTextReader reader;
private EntryType? peekedEntryType;
private string peekedEntryName;
private string peekedEntryContent;
private Dictionary<int, Type> seenTypes = new Dictionary<int, Type>(16);
private readonly Dictionary<Type, Delegate> primitiveArrayReaders;
public JsonDataReader() : this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonDataReader" /> class.
/// </summary>
/// <param name="stream">The base stream of the reader.</param>
/// <param name="context">The deserialization context to use.</param>
public JsonDataReader(Stream stream, DeserializationContext context) : base(stream, context)
{
this.primitiveArrayReaders = new Dictionary<Type, Delegate>()
{
{ typeof(char), (Func<char>)(() => { char v; this.ReadChar(out v); return v; }) },
{ typeof(sbyte), (Func<sbyte>)(() => { sbyte v; this.ReadSByte(out v); return v; }) },
{ typeof(short), (Func<short>)(() => { short v; this.ReadInt16(out v); return v; }) },
{ typeof(int), (Func<int>)(() => { int v; this.ReadInt32(out v); return v; }) },
{ typeof(long), (Func<long>)(() => { long v; this.ReadInt64(out v); return v; }) },
{ typeof(byte), (Func<byte>)(() => { byte v; this.ReadByte(out v); return v; }) },
{ typeof(ushort), (Func<ushort>)(() => { ushort v; this.ReadUInt16(out v); return v; }) },
{ typeof(uint), (Func<uint>)(() => { uint v; this.ReadUInt32(out v); return v; }) },
{ typeof(ulong), (Func<ulong>)(() => { ulong v; this.ReadUInt64(out v); return v; }) },
{ typeof(decimal), (Func<decimal>)(() => { decimal v; this.ReadDecimal(out v); return v; }) },
{ typeof(bool), (Func<bool>)(() => { bool v; this.ReadBoolean(out v); return v; }) },
{ typeof(float), (Func<float>)(() => { float v; this.ReadSingle(out v); return v; }) },
{ typeof(double), (Func<double>)(() => { double v; this.ReadDouble(out v); return v; }) },
{ typeof(Guid), (Func<Guid>)(() => { Guid v; this.ReadGuid(out v); return v; }) }
};
}
#if !UNITY_EDITOR // This causes a warning when using source in Unity
#pragma warning disable IDE0009 // Member access should be qualified.
#endif
/// <summary>
/// Gets or sets the base stream of the reader.
/// </summary>
/// <value>
/// The base stream of the reader.
/// </value>
public override Stream Stream
{
get
{
return base.Stream;
}
set
{
base.Stream = value;
this.reader = new JsonTextReader(base.Stream, this.Context);
}
}
#if !UNITY_EDITOR
#pragma warning restore IDE0009 // Member access should be qualified.
#endif
/// <summary>
/// Disposes all resources kept by the data reader, except the stream, which can be reused later.
/// </summary>
public override void Dispose()
{
this.reader.Dispose();
}
/// <summary>
/// Peeks ahead and returns the type of the next entry in the stream.
/// </summary>
/// <param name="name">The name of the next entry, if it has one.</param>
/// <returns>
/// The type of the next entry.
/// </returns>
public override EntryType PeekEntry(out string name)
{
if (this.peekedEntryType != null)
{
name = this.peekedEntryName;
return this.peekedEntryType.Value;
}
EntryType entry;
this.reader.ReadToNextEntry(out name, out this.peekedEntryContent, out entry);
this.peekedEntryName = name;
this.peekedEntryType = entry;
return entry;
}
/// <summary>
/// Tries to enter a node. This will succeed if the next entry is an <see cref="EntryType.StartOfNode" />.
/// <para />
/// This call MUST (eventually) be followed by a corresponding call to <see cref="IDataReader.ExitNode(DeserializationContext)" /><para />
/// This call will change the values of the <see cref="IDataReader.IsInArrayNode" />, <see cref="IDataReader.CurrentNodeName" />, <see cref="IDataReader.CurrentNodeId" /> and <see cref="IDataReader.CurrentNodeDepth" /> properties to the correct values for the current node.
/// </summary>
/// <param name="type">The type of the node. This value will be null if there was no metadata, or if the reader's serialization binder failed to resolve the type name.</param>
/// <returns>
/// <c>true</c> if entering a node succeeded, otherwise <c>false</c>
/// </returns>
public override bool EnterNode(out Type type)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.StartOfNode)
{
string nodeName = this.peekedEntryName;
int id = -1;
this.ReadToNextEntry();
if (this.peekedEntryName == JsonConfig.ID_SIG)
{
if (int.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out id) == false)
{
this.Context.Config.DebugContext.LogError("Failed to parse id: " + this.peekedEntryContent);
id = -1;
}
this.ReadToNextEntry();
}
if (this.peekedEntryName == JsonConfig.TYPE_SIG && this.peekedEntryContent != null && this.peekedEntryContent.Length > 0)
{
if (this.peekedEntryType == EntryType.Integer)
{
int typeID;
if (this.ReadInt32(out typeID))
{
if (this.seenTypes.TryGetValue(typeID, out type) == false)
{
this.Context.Config.DebugContext.LogError("Missing type id for node with reference id " + id + ": " + typeID);
}
}
else
{
this.Context.Config.DebugContext.LogError("Failed to read type id for node with reference id " + id);
type = null;
}
}
else
{
int typeNameStartIndex = 1;
int typeID = -1;
int idSplitIndex = this.peekedEntryContent.IndexOf('|');
if (idSplitIndex >= 0)
{
typeNameStartIndex = idSplitIndex + 1;
string idStr = this.peekedEntryContent.Substring(1, idSplitIndex - 1);
if (int.TryParse(idStr, NumberStyles.Any, CultureInfo.InvariantCulture, out typeID) == false)
{
typeID = -1;
}
}
type = this.Context.Binder.BindToType(this.peekedEntryContent.Substring(typeNameStartIndex, this.peekedEntryContent.Length - (1 + typeNameStartIndex)), this.Context.Config.DebugContext);
if (typeID >= 0)
{
this.seenTypes[typeID] = type;
}
this.peekedEntryType = null;
}
}
else
{
type = null;
}
this.PushNode(nodeName, id, type);
return true;
}
else
{
this.SkipEntry();
type = null;
return false;
}
}
/// <summary>
/// Exits the current node. This method will keep skipping entries using <see cref="IDataReader.SkipEntry(DeserializationContext)" /> until an <see cref="EntryType.EndOfNode" /> is reached, or the end of the stream is reached.
/// <para />
/// This call MUST have been preceded by a corresponding call to <see cref="IDataReader.EnterNode(out Type)" />.
/// <para />
/// This call will change the values of the <see cref="IDataReader.IsInArrayNode" />, <see cref="IDataReader.CurrentNodeName" />, <see cref="IDataReader.CurrentNodeId" /> and <see cref="IDataReader.CurrentNodeDepth" /> to the correct values for the node that was prior to the current node.
/// </summary>
/// <returns>
/// <c>true</c> if the method exited a node, <c>false</c> if it reached the end of the stream.
/// </returns>
public override bool ExitNode()
{
this.PeekEntry();
// Read to next end of node
while (this.peekedEntryType != EntryType.EndOfNode && this.peekedEntryType != EntryType.EndOfStream)
{
if (this.peekedEntryType == EntryType.EndOfArray)
{
this.Context.Config.DebugContext.LogError("Data layout mismatch; skipping past array boundary when exiting node.");
this.peekedEntryType = null;
//this.MarkEntryConsumed();
}
this.SkipEntry();
}
if (this.peekedEntryType == EntryType.EndOfNode)
{
this.peekedEntryType = null;
this.PopNode(this.CurrentNodeName);
return true;
}
return false;
}
/// <summary>
/// Tries to enters an array node. This will succeed if the next entry is an <see cref="EntryType.StartOfArray" />.
/// <para />
/// This call MUST (eventually) be followed by a corresponding call to <see cref="IDataReader.ExitArray(DeserializationContext)" /><para />
/// This call will change the values of the <see cref="IDataReader.IsInArrayNode" />, <see cref="IDataReader.CurrentNodeName" />, <see cref="IDataReader.CurrentNodeId" /> and <see cref="IDataReader.CurrentNodeDepth" /> properties to the correct values for the current array node.
/// </summary>
/// <param name="length">The length of the array that was entered.</param>
/// <returns>
/// <c>true</c> if an array was entered, otherwise <c>false</c>
/// </returns>
public override bool EnterArray(out long length)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.StartOfArray)
{
this.PushArray();
if (this.peekedEntryName != JsonConfig.REGULAR_ARRAY_LENGTH_SIG)
{
this.Context.Config.DebugContext.LogError("Array entry wasn't preceded by an array length entry!");
length = 0; // No array content for you!
return true;
}
else
{
int intLength;
if (int.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out intLength) == false)
{
this.Context.Config.DebugContext.LogError("Failed to parse array length: " + this.peekedEntryContent);
length = 0; // No array content for you!
return true;
}
length = intLength;
this.ReadToNextEntry();
if (this.peekedEntryName != JsonConfig.REGULAR_ARRAY_CONTENT_SIG)
{
this.Context.Config.DebugContext.LogError("Failed to find regular array content entry after array length entry!");
length = 0; // No array content for you!
return true;
}
this.peekedEntryType = null;
return true;
}
}
else
{
this.SkipEntry();
length = 0;
return false;
}
}
/// <summary>
/// Exits the closest array. This method will keep skipping entries using <see cref="IDataReader.SkipEntry(DeserializationContext)" /> until an <see cref="EntryType.EndOfArray" /> is reached, or the end of the stream is reached.
/// <para />
/// This call MUST have been preceded by a corresponding call to <see cref="IDataReader.EnterArray(out long)" />.
/// <para />
/// This call will change the values of the <see cref="IDataReader.IsInArrayNode" />, <see cref="IDataReader.CurrentNodeName" />, <see cref="IDataReader.CurrentNodeId" /> and <see cref="IDataReader.CurrentNodeDepth" /> to the correct values for the node that was prior to the exited array node.
/// </summary>
/// <returns>
/// <c>true</c> if the method exited an array, <c>false</c> if it reached the end of the stream.
/// </returns>
public override bool ExitArray()
{
this.PeekEntry();
// Read to next end of array
while (this.peekedEntryType != EntryType.EndOfArray && this.peekedEntryType != EntryType.EndOfStream)
{
if (this.peekedEntryType == EntryType.EndOfNode)
{
this.Context.Config.DebugContext.LogError("Data layout mismatch; skipping past node boundary when exiting array.");
this.peekedEntryType = null;
//this.MarkEntryConsumed();
}
this.SkipEntry();
}
if (this.peekedEntryType == EntryType.EndOfArray)
{
this.peekedEntryType = null;
this.PopArray();
return true;
}
return false;
}
/// <summary>
/// Reads a primitive array value. This call will succeed if the next entry is an <see cref="EntryType.PrimitiveArray" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <typeparam name="T">The element type of the primitive array. Valid element types can be determined using <see cref="FormatterUtilities.IsPrimitiveArrayType(Type)" />.</typeparam>
/// <param name="array">The resulting primitive array.</param>
/// <returns>
/// <c>true</c> if reading a primitive array succeeded, otherwise <c>false</c>
/// </returns>
/// <exception cref="System.ArgumentException">Type + typeof(T).Name + is not a valid primitive array type.</exception>
public override bool ReadPrimitiveArray<T>(out T[] array)
{
if (FormatterUtilities.IsPrimitiveArrayType(typeof(T)) == false)
{
throw new ArgumentException("Type " + typeof(T).Name + " is not a valid primitive array type.");
}
this.PeekEntry();
if (this.peekedEntryType == EntryType.PrimitiveArray)
{
this.PushArray();
if (this.peekedEntryName != JsonConfig.PRIMITIVE_ARRAY_LENGTH_SIG)
{
this.Context.Config.DebugContext.LogError("Array entry wasn't preceded by an array length entry!");
array = null; // No array content for you!
return false;
}
else
{
int intLength;
if (int.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out intLength) == false)
{
this.Context.Config.DebugContext.LogError("Failed to parse array length: " + this.peekedEntryContent);
array = null; // No array content for you!
return false;
}
this.ReadToNextEntry();
if (this.peekedEntryName != JsonConfig.PRIMITIVE_ARRAY_CONTENT_SIG)
{
this.Context.Config.DebugContext.LogError("Failed to find primitive array content entry after array length entry!");
array = null; // No array content for you!
return false;
}
this.peekedEntryType = null;
Func<T> reader = (Func<T>)this.primitiveArrayReaders[typeof(T)];
array = new T[intLength];
for (int i = 0; i < intLength; i++)
{
array[i] = reader();
}
this.ExitArray();
return true;
}
}
else
{
this.SkipEntry();
array = null;
return false;
}
}
/// <summary>
/// Reads a <see cref="bool" /> value. This call will succeed if the next entry is an <see cref="EntryType.Boolean" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadBoolean(out bool value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.Boolean)
{
try
{
value = this.peekedEntryContent == "true";
return true;
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = default(bool);
return false;
}
}
/// <summary>
/// Reads an internal reference id. This call will succeed if the next entry is an <see cref="EntryType.InternalReference" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="id">The internal reference id.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadInternalReference(out int id)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.InternalReference)
{
try
{
return this.ReadAnyIntReference(out id);
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
id = -1;
return false;
}
}
/// <summary>
/// Reads an external reference index. This call will succeed if the next entry is an <see cref="EntryType.ExternalReferenceByIndex" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="index">The external reference index.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadExternalReference(out int index)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.ExternalReferenceByIndex)
{
try
{
return this.ReadAnyIntReference(out index);
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
index = -1;
return false;
}
}
/// <summary>
/// Reads an external reference guid. This call will succeed if the next entry is an <see cref="EntryType.ExternalReferenceByGuid" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="guid">The external reference guid.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadExternalReference(out Guid guid)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.ExternalReferenceByGuid)
{
var guidStr = this.peekedEntryContent;
if (guidStr.StartsWith(JsonConfig.EXTERNAL_GUID_REF_SIG))
{
guidStr = guidStr.Substring(JsonConfig.EXTERNAL_GUID_REF_SIG.Length + 1);
}
try
{
guid = new Guid(guidStr);
return true;
}
catch (FormatException)
{
guid = Guid.Empty;
return false;
}
catch (OverflowException)
{
guid = Guid.Empty;
return false;
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
guid = Guid.Empty;
return false;
}
}
/// <summary>
/// Reads an external reference string. This call will succeed if the next entry is an <see cref="EntryType.ExternalReferenceByString" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="id">The external reference string.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadExternalReference(out string id)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.ExternalReferenceByString)
{
id = this.peekedEntryContent;
if (id.StartsWith(JsonConfig.EXTERNAL_STRING_REF_SIG))
{
id = id.Substring(JsonConfig.EXTERNAL_STRING_REF_SIG.Length + 1);
}
this.MarkEntryConsumed();
return true;
}
else
{
this.SkipEntry();
id = null;
return false;
}
}
/// <summary>
/// Reads a <see cref="char" /> value. This call will succeed if the next entry is an <see cref="EntryType.String" />.
/// <para />
/// If the string of the entry is longer than 1 character, the first character of the string will be taken as the result.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadChar(out char value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.String)
{
try
{
value = this.peekedEntryContent[1];
return true;
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = default(char);
return false;
}
}
/// <summary>
/// Reads a <see cref="string" /> value. This call will succeed if the next entry is an <see cref="EntryType.String" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadString(out string value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.String)
{
try
{
value = this.peekedEntryContent.Substring(1, this.peekedEntryContent.Length - 2);
return true;
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = null;
return false;
}
}
/// <summary>
/// Reads a <see cref="Guid" /> value. This call will succeed if the next entry is an <see cref="EntryType.Guid" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadGuid(out Guid value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.Guid)
{
try
{
try
{
value = new Guid(this.peekedEntryContent);
return true;
}
//// These exceptions can safely be swallowed - it just means the parse failed
catch (FormatException)
{
value = Guid.Empty;
return false;
}
catch (OverflowException)
{
value = Guid.Empty;
return false;
}
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = Guid.Empty;
return false;
}
}
/// <summary>
/// Reads an <see cref="sbyte" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="sbyte.MinValue" /> or larger than <see cref="sbyte.MaxValue" />, the result will be default(<see cref="sbyte" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadSByte(out sbyte value)
{
long longValue;
if (this.ReadInt64(out longValue))
{
checked
{
try
{
value = (sbyte)longValue;
}
catch (OverflowException)
{
value = default(sbyte);
}
}
return true;
}
value = default(sbyte);
return false;
}
/// <summary>
/// Reads a <see cref="short" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="short.MinValue" /> or larger than <see cref="short.MaxValue" />, the result will be default(<see cref="short" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadInt16(out short value)
{
long longValue;
if (this.ReadInt64(out longValue))
{
checked
{
try
{
value = (short)longValue;
}
catch (OverflowException)
{
value = default(short);
}
}
return true;
}
value = default(short);
return false;
}
/// <summary>
/// Reads an <see cref="int" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="int.MinValue" /> or larger than <see cref="int.MaxValue" />, the result will be default(<see cref="int" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadInt32(out int value)
{
long longValue;
if (this.ReadInt64(out longValue))
{
checked
{
try
{
value = (int)longValue;
}
catch (OverflowException)
{
value = default(int);
}
}
return true;
}
value = default(int);
return false;
}
/// <summary>
/// Reads a <see cref="long" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="long.MinValue" /> or larger than <see cref="long.MaxValue" />, the result will be default(<see cref="long" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadInt64(out long value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.Integer)
{
try
{
if (long.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return true;
}
else
{
this.Context.Config.DebugContext.LogError("Failed to parse long from: " + this.peekedEntryContent);
return false;
}
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = default(long);
return false;
}
}
/// <summary>
/// Reads a <see cref="byte" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="byte.MinValue" /> or larger than <see cref="byte.MaxValue" />, the result will be default(<see cref="byte" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadByte(out byte value)
{
ulong ulongValue;
if (this.ReadUInt64(out ulongValue))
{
checked
{
try
{
value = (byte)ulongValue;
}
catch (OverflowException)
{
value = default(byte);
}
}
return true;
}
value = default(byte);
return false;
}
/// <summary>
/// Reads an <see cref="ushort" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="ushort.MinValue" /> or larger than <see cref="ushort.MaxValue" />, the result will be default(<see cref="ushort" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadUInt16(out ushort value)
{
ulong ulongValue;
if (this.ReadUInt64(out ulongValue))
{
checked
{
try
{
value = (ushort)ulongValue;
}
catch (OverflowException)
{
value = default(ushort);
}
}
return true;
}
value = default(ushort);
return false;
}
/// <summary>
/// Reads an <see cref="uint" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="uint.MinValue" /> or larger than <see cref="uint.MaxValue" />, the result will be default(<see cref="uint" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadUInt32(out uint value)
{
ulong ulongValue;
if (this.ReadUInt64(out ulongValue))
{
checked
{
try
{
value = (uint)ulongValue;
}
catch (OverflowException)
{
value = default(uint);
}
}
return true;
}
value = default(uint);
return false;
}
/// <summary>
/// Reads an <see cref="ulong" /> value. This call will succeed if the next entry is an <see cref="EntryType.Integer" />.
/// <para />
/// If the value of the stored integer is smaller than <see cref="ulong.MinValue" /> or larger than <see cref="ulong.MaxValue" />, the result will be default(<see cref="ulong" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadUInt64(out ulong value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.Integer)
{
try
{
if (ulong.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return true;
}
else
{
this.Context.Config.DebugContext.LogError("Failed to parse ulong from: " + this.peekedEntryContent);
return false;
}
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = default(ulong);
return false;
}
}
/// <summary>
/// Reads a <see cref="decimal" /> value. This call will succeed if the next entry is an <see cref="EntryType.FloatingPoint" /> or an <see cref="EntryType.Integer" />.
/// <para />
/// If the stored integer or floating point value is smaller than <see cref="decimal.MinValue" /> or larger than <see cref="decimal.MaxValue" />, the result will be default(<see cref="decimal" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadDecimal(out decimal value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.FloatingPoint || this.peekedEntryType == EntryType.Integer)
{
try
{
if (decimal.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return true;
}
else
{
this.Context.Config.DebugContext.LogError("Failed to parse decimal from: " + this.peekedEntryContent);
return false;
}
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = default(decimal);
return false;
}
}
/// <summary>
/// Reads a <see cref="float" /> value. This call will succeed if the next entry is an <see cref="EntryType.FloatingPoint" /> or an <see cref="EntryType.Integer" />.
/// <para />
/// If the stored integer or floating point value is smaller than <see cref="float.MinValue" /> or larger than <see cref="float.MaxValue" />, the result will be default(<see cref="float" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadSingle(out float value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.FloatingPoint || this.peekedEntryType == EntryType.Integer)
{
try
{
if (float.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return true;
}
else
{
this.Context.Config.DebugContext.LogError("Failed to parse float from: " + this.peekedEntryContent);
return false;
}
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = default(float);
return false;
}
}
/// <summary>
/// Reads a <see cref="double" /> value. This call will succeed if the next entry is an <see cref="EntryType.FloatingPoint" /> or an <see cref="EntryType.Integer" />.
/// <para />
/// If the stored integer or floating point value is smaller than <see cref="double.MinValue" /> or larger than <see cref="double.MaxValue" />, the result will be default(<see cref="double" />).
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <param name="value">The value that has been read.</param>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadDouble(out double value)
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.FloatingPoint || this.peekedEntryType == EntryType.Integer)
{
try
{
if (double.TryParse(this.peekedEntryContent, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return true;
}
else
{
this.Context.Config.DebugContext.LogError("Failed to parse double from: " + this.peekedEntryContent);
return false;
}
}
finally
{
this.MarkEntryConsumed();
}
}
else
{
this.SkipEntry();
value = default(double);
return false;
}
}
/// <summary>
/// Reads a <c>null</c> value. This call will succeed if the next entry is an <see cref="EntryType.Null" />.
/// <para />
/// If the call fails (and returns <c>false</c>), it will skip the current entry value, unless that entry is an <see cref="EntryType.EndOfNode" /> or an <see cref="EntryType.EndOfArray" />.
/// </summary>
/// <returns>
/// <c>true</c> if reading the value succeeded, otherwise <c>false</c>
/// </returns>
public override bool ReadNull()
{
this.PeekEntry();
if (this.peekedEntryType == EntryType.Null)
{
this.MarkEntryConsumed();
return true;
}
else
{
this.SkipEntry();
return false;
}
}
/// <summary>
/// Tells the reader that a new serialization session is about to begin, and that it should clear all cached values left over from any prior serialization sessions.
/// This method is only relevant when the same reader is used to deserialize several different, unrelated values.
/// </summary>
public override void PrepareNewSerializationSession()
{
base.PrepareNewSerializationSession();
this.peekedEntryType = null;
this.peekedEntryContent = null;
this.peekedEntryName = null;
this.seenTypes.Clear();
this.reader.Reset();
}
public override string GetDataDump()
{
if (!this.Stream.CanSeek)
{
return "Json data stream cannot seek; cannot dump data.";
}
var oldPosition = this.Stream.Position;
var bytes = new byte[this.Stream.Length];
this.Stream.Position = 0;
this.Stream.Read(bytes, 0, bytes.Length);
this.Stream.Position = oldPosition;
return "Json: " + Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
/// <summary>
/// Peeks the current entry.
/// </summary>
/// <returns>The peeked entry.</returns>
protected override EntryType PeekEntry()
{
string name;
return this.PeekEntry(out name);
}
/// <summary>
/// Consumes the current entry, and reads to the next one.
/// </summary>
/// <returns>The next entry.</returns>
protected override EntryType ReadToNextEntry()
{
this.peekedEntryType = null;
string name;
return this.PeekEntry(out name);
}
private void MarkEntryConsumed()
{
// After a common read, we cannot skip EndOfArray and EndOfNode entries (meaning the read has failed),
// as only the ExitArray and ExitNode methods are allowed to exit nodes and arrays
if (this.peekedEntryType != EntryType.EndOfArray && this.peekedEntryType != EntryType.EndOfNode)
{
this.peekedEntryType = null;
}
}
private bool ReadAnyIntReference(out int value)
{
int separatorIndex = -1;
for (int i = 0; i < this.peekedEntryContent.Length; i++)
{
if (this.peekedEntryContent[i] == ':')
{
separatorIndex = i;
break;
}
}
if (separatorIndex == -1 || separatorIndex == this.peekedEntryContent.Length - 1)
{
this.Context.Config.DebugContext.LogError("Failed to parse id from: " + this.peekedEntryContent);
}
string idStr = this.peekedEntryContent.Substring(separatorIndex + 1);
if (int.TryParse(idStr, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return true;
}
else
{
this.Context.Config.DebugContext.LogError("Failed to parse id: " + idStr);
}
value = -1;
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Net.NetworkInformation
{
public enum DuplicateAddressDetectionState
{
Deprecated = 3,
Duplicate = 2,
Invalid = 0,
Preferred = 4,
Tentative = 1,
}
public abstract partial class GatewayIPAddressInformation
{
protected GatewayIPAddressInformation() { }
public abstract System.Net.IPAddress Address { get; }
}
public partial class GatewayIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.IEnumerable
{
protected internal GatewayIPAddressInformationCollection() { }
public virtual int Count { get { return default(int); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual System.Net.NetworkInformation.GatewayIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.GatewayIPAddressInformation); } }
public virtual void Add(System.Net.NetworkInformation.GatewayIPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.GatewayIPAddressInformation address) { return default(bool); }
public virtual void CopyTo(System.Net.NetworkInformation.GatewayIPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation>); }
public virtual bool Remove(System.Net.NetworkInformation.GatewayIPAddressInformation address) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public abstract partial class IcmpV4Statistics
{
protected IcmpV4Statistics() { }
public abstract long AddressMaskRepliesReceived { get; }
public abstract long AddressMaskRepliesSent { get; }
public abstract long AddressMaskRequestsReceived { get; }
public abstract long AddressMaskRequestsSent { get; }
public abstract long DestinationUnreachableMessagesReceived { get; }
public abstract long DestinationUnreachableMessagesSent { get; }
public abstract long EchoRepliesReceived { get; }
public abstract long EchoRepliesSent { get; }
public abstract long EchoRequestsReceived { get; }
public abstract long EchoRequestsSent { get; }
public abstract long ErrorsReceived { get; }
public abstract long ErrorsSent { get; }
public abstract long MessagesReceived { get; }
public abstract long MessagesSent { get; }
public abstract long ParameterProblemsReceived { get; }
public abstract long ParameterProblemsSent { get; }
public abstract long RedirectsReceived { get; }
public abstract long RedirectsSent { get; }
public abstract long SourceQuenchesReceived { get; }
public abstract long SourceQuenchesSent { get; }
public abstract long TimeExceededMessagesReceived { get; }
public abstract long TimeExceededMessagesSent { get; }
public abstract long TimestampRepliesReceived { get; }
public abstract long TimestampRepliesSent { get; }
public abstract long TimestampRequestsReceived { get; }
public abstract long TimestampRequestsSent { get; }
}
public abstract partial class IcmpV6Statistics
{
protected IcmpV6Statistics() { }
public abstract long DestinationUnreachableMessagesReceived { get; }
public abstract long DestinationUnreachableMessagesSent { get; }
public abstract long EchoRepliesReceived { get; }
public abstract long EchoRepliesSent { get; }
public abstract long EchoRequestsReceived { get; }
public abstract long EchoRequestsSent { get; }
public abstract long ErrorsReceived { get; }
public abstract long ErrorsSent { get; }
public abstract long MembershipQueriesReceived { get; }
public abstract long MembershipQueriesSent { get; }
public abstract long MembershipReductionsReceived { get; }
public abstract long MembershipReductionsSent { get; }
public abstract long MembershipReportsReceived { get; }
public abstract long MembershipReportsSent { get; }
public abstract long MessagesReceived { get; }
public abstract long MessagesSent { get; }
public abstract long NeighborAdvertisementsReceived { get; }
public abstract long NeighborAdvertisementsSent { get; }
public abstract long NeighborSolicitsReceived { get; }
public abstract long NeighborSolicitsSent { get; }
public abstract long PacketTooBigMessagesReceived { get; }
public abstract long PacketTooBigMessagesSent { get; }
public abstract long ParameterProblemsReceived { get; }
public abstract long ParameterProblemsSent { get; }
public abstract long RedirectsReceived { get; }
public abstract long RedirectsSent { get; }
public abstract long RouterAdvertisementsReceived { get; }
public abstract long RouterAdvertisementsSent { get; }
public abstract long RouterSolicitsReceived { get; }
public abstract long RouterSolicitsSent { get; }
public abstract long TimeExceededMessagesReceived { get; }
public abstract long TimeExceededMessagesSent { get; }
}
public abstract partial class IPAddressInformation
{
protected IPAddressInformation() { }
public abstract System.Net.IPAddress Address { get; }
public abstract bool IsDnsEligible { get; }
public abstract bool IsTransient { get; }
}
public partial class IPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.IEnumerable
{
internal IPAddressInformationCollection() { }
public virtual int Count { get { return default(int); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual System.Net.NetworkInformation.IPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.IPAddressInformation); } }
public virtual void Add(System.Net.NetworkInformation.IPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.IPAddressInformation address) { return default(bool); }
public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation>); }
public virtual bool Remove(System.Net.NetworkInformation.IPAddressInformation address) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public abstract partial class IPGlobalProperties
{
protected IPGlobalProperties() { }
public abstract string DhcpScopeName { get; }
public abstract string DomainName { get; }
public abstract string HostName { get; }
public abstract bool IsWinsProxy { get; }
public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; }
public abstract System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections();
public abstract System.Net.IPEndPoint[] GetActiveTcpListeners();
public abstract System.Net.IPEndPoint[] GetActiveUdpListeners();
public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics();
public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics();
public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { return default(System.Net.NetworkInformation.IPGlobalProperties); }
public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics();
public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics();
public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics();
public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics();
public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics();
public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics();
public virtual System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection> GetUnicastAddressesAsync() { return default(System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection>); }
}
public abstract partial class IPGlobalStatistics
{
protected IPGlobalStatistics() { }
public abstract int DefaultTtl { get; }
public abstract bool ForwardingEnabled { get; }
public abstract int NumberOfInterfaces { get; }
public abstract int NumberOfIPAddresses { get; }
public abstract int NumberOfRoutes { get; }
public abstract long OutputPacketRequests { get; }
public abstract long OutputPacketRoutingDiscards { get; }
public abstract long OutputPacketsDiscarded { get; }
public abstract long OutputPacketsWithNoRoute { get; }
public abstract long PacketFragmentFailures { get; }
public abstract long PacketReassembliesRequired { get; }
public abstract long PacketReassemblyFailures { get; }
public abstract long PacketReassemblyTimeout { get; }
public abstract long PacketsFragmented { get; }
public abstract long PacketsReassembled { get; }
public abstract long ReceivedPackets { get; }
public abstract long ReceivedPacketsDelivered { get; }
public abstract long ReceivedPacketsDiscarded { get; }
public abstract long ReceivedPacketsForwarded { get; }
public abstract long ReceivedPacketsWithAddressErrors { get; }
public abstract long ReceivedPacketsWithHeadersErrors { get; }
public abstract long ReceivedPacketsWithUnknownProtocol { get; }
}
public abstract partial class IPInterfaceProperties
{
protected IPInterfaceProperties() { }
public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; }
public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; }
public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; }
public abstract string DnsSuffix { get; }
public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; }
public abstract bool IsDnsEnabled { get; }
public abstract bool IsDynamicDnsEnabled { get; }
public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; }
public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; }
public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; }
public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties();
public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties();
}
public abstract partial class IPInterfaceStatistics
{
protected IPInterfaceStatistics() { }
public abstract long BytesReceived { get; }
public abstract long BytesSent { get; }
public abstract long IncomingPacketsDiscarded { get; }
public abstract long IncomingPacketsWithErrors { get; }
public abstract long IncomingUnknownProtocolPackets { get; }
public abstract long NonUnicastPacketsReceived { get; }
public abstract long NonUnicastPacketsSent { get; }
public abstract long OutgoingPacketsDiscarded { get; }
public abstract long OutgoingPacketsWithErrors { get; }
public abstract long OutputQueueLength { get; }
public abstract long UnicastPacketsReceived { get; }
public abstract long UnicastPacketsSent { get; }
}
public abstract partial class IPv4InterfaceProperties
{
protected IPv4InterfaceProperties() { }
public abstract int Index { get; }
public abstract bool IsAutomaticPrivateAddressingActive { get; }
public abstract bool IsAutomaticPrivateAddressingEnabled { get; }
public abstract bool IsDhcpEnabled { get; }
public abstract bool IsForwardingEnabled { get; }
public abstract int Mtu { get; }
public abstract bool UsesWins { get; }
}
public abstract partial class IPv6InterfaceProperties
{
protected IPv6InterfaceProperties() { }
public abstract int Index { get; }
public abstract int Mtu { get; }
public virtual long GetScopeId(System.Net.NetworkInformation.ScopeLevel scopeLevel) { return default(long); }
}
public abstract partial class MulticastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation
{
protected MulticastIPAddressInformation() { }
public abstract long AddressPreferredLifetime { get; }
public abstract long AddressValidLifetime { get; }
public abstract long DhcpLeaseLifetime { get; }
public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; }
public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; }
public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; }
}
public partial class MulticastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.IEnumerable
{
protected internal MulticastIPAddressInformationCollection() { }
public virtual int Count { get { return default(int); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual System.Net.NetworkInformation.MulticastIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.MulticastIPAddressInformation); } }
public virtual void Add(System.Net.NetworkInformation.MulticastIPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.MulticastIPAddressInformation address) { return default(bool); }
public virtual void CopyTo(System.Net.NetworkInformation.MulticastIPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation>); }
public virtual bool Remove(System.Net.NetworkInformation.MulticastIPAddressInformation address) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public enum NetBiosNodeType
{
Broadcast = 1,
Hybrid = 8,
Mixed = 4,
Peer2Peer = 2,
Unknown = 0,
}
public delegate void NetworkAddressChangedEventHandler(object sender, System.EventArgs e);
public static partial class NetworkChange
{
public static event System.Net.NetworkInformation.NetworkAddressChangedEventHandler NetworkAddressChanged { add { } remove { } }
}
public partial class NetworkInformationException : System.Exception
{
public NetworkInformationException() { }
public NetworkInformationException(int errorCode) { }
}
public abstract partial class NetworkInterface
{
protected NetworkInterface() { }
public virtual string Description { get { return default(string); } }
public virtual string Id { get { return default(string); } }
public static int IPv6LoopbackInterfaceIndex { get { return default(int); } }
public virtual bool IsReceiveOnly { get { return default(bool); } }
public static int LoopbackInterfaceIndex { get { return default(int); } }
public virtual string Name { get { return default(string); } }
public virtual System.Net.NetworkInformation.NetworkInterfaceType NetworkInterfaceType { get { return default(System.Net.NetworkInformation.NetworkInterfaceType); } }
public virtual System.Net.NetworkInformation.OperationalStatus OperationalStatus { get { return default(System.Net.NetworkInformation.OperationalStatus); } }
public virtual long Speed { get { return default(long); } }
public virtual bool SupportsMulticast { get { return default(bool); } }
public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { return default(System.Net.NetworkInformation.NetworkInterface[]); }
public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { return default(System.Net.NetworkInformation.IPInterfaceProperties); }
public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { return default(System.Net.NetworkInformation.IPInterfaceStatistics); }
public static bool GetIsNetworkAvailable() { return default(bool); }
public virtual System.Net.NetworkInformation.PhysicalAddress GetPhysicalAddress() { return default(System.Net.NetworkInformation.PhysicalAddress); }
public virtual bool Supports(System.Net.NetworkInformation.NetworkInterfaceComponent networkInterfaceComponent) { return default(bool); }
}
public enum NetworkInterfaceComponent
{
IPv4 = 0,
IPv6 = 1,
}
public enum NetworkInterfaceType
{
AsymmetricDsl = 94,
Atm = 37,
BasicIsdn = 20,
Ethernet = 6,
Ethernet3Megabit = 26,
FastEthernetFx = 69,
FastEthernetT = 62,
Fddi = 15,
GenericModem = 48,
GigabitEthernet = 117,
HighPerformanceSerialBus = 144,
IPOverAtm = 114,
Isdn = 63,
Loopback = 24,
MultiRateSymmetricDsl = 143,
Ppp = 23,
PrimaryIsdn = 21,
RateAdaptDsl = 95,
Slip = 28,
SymmetricDsl = 96,
TokenRing = 9,
Tunnel = 131,
Unknown = 1,
VeryHighSpeedDsl = 97,
Wireless80211 = 71,
Wman = 237,
Wwanpp = 243,
Wwanpp2 = 244,
}
public enum OperationalStatus
{
Dormant = 5,
Down = 2,
LowerLayerDown = 7,
NotPresent = 6,
Testing = 3,
Unknown = 4,
Up = 1,
}
public partial class PhysicalAddress
{
public static readonly System.Net.NetworkInformation.PhysicalAddress None;
public PhysicalAddress(byte[] address) { }
public override bool Equals(object comparand) { return default(bool); }
public byte[] GetAddressBytes() { return default(byte[]); }
public override int GetHashCode() { return default(int); }
public static System.Net.NetworkInformation.PhysicalAddress Parse(string address) { return default(System.Net.NetworkInformation.PhysicalAddress); }
public override string ToString() { return default(string); }
}
public enum PrefixOrigin
{
Dhcp = 3,
Manual = 1,
Other = 0,
RouterAdvertisement = 4,
WellKnown = 2,
}
public enum ScopeLevel
{
Admin = 4,
Global = 14,
Interface = 1,
Link = 2,
None = 0,
Organization = 8,
Site = 5,
Subnet = 3,
}
public enum SuffixOrigin
{
LinkLayerAddress = 4,
Manual = 1,
OriginDhcp = 3,
Other = 0,
Random = 5,
WellKnown = 2,
}
public abstract partial class TcpConnectionInformation
{
protected TcpConnectionInformation() { }
public abstract System.Net.IPEndPoint LocalEndPoint { get; }
public abstract System.Net.IPEndPoint RemoteEndPoint { get; }
public abstract System.Net.NetworkInformation.TcpState State { get; }
}
public enum TcpState
{
Closed = 1,
CloseWait = 8,
Closing = 9,
DeleteTcb = 12,
Established = 5,
FinWait1 = 6,
FinWait2 = 7,
LastAck = 10,
Listen = 2,
SynReceived = 4,
SynSent = 3,
TimeWait = 11,
Unknown = 0,
}
public abstract partial class TcpStatistics
{
protected TcpStatistics() { }
public abstract long ConnectionsAccepted { get; }
public abstract long ConnectionsInitiated { get; }
public abstract long CumulativeConnections { get; }
public abstract long CurrentConnections { get; }
public abstract long ErrorsReceived { get; }
public abstract long FailedConnectionAttempts { get; }
public abstract long MaximumConnections { get; }
public abstract long MaximumTransmissionTimeout { get; }
public abstract long MinimumTransmissionTimeout { get; }
public abstract long ResetConnections { get; }
public abstract long ResetsSent { get; }
public abstract long SegmentsReceived { get; }
public abstract long SegmentsResent { get; }
public abstract long SegmentsSent { get; }
}
public abstract partial class UdpStatistics
{
protected UdpStatistics() { }
public abstract long DatagramsReceived { get; }
public abstract long DatagramsSent { get; }
public abstract long IncomingDatagramsDiscarded { get; }
public abstract long IncomingDatagramsWithErrors { get; }
public abstract int UdpListeners { get; }
}
public abstract partial class UnicastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation
{
protected UnicastIPAddressInformation() { }
public abstract long AddressPreferredLifetime { get; }
public abstract long AddressValidLifetime { get; }
public abstract long DhcpLeaseLifetime { get; }
public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; }
public abstract System.Net.IPAddress IPv4Mask { get; }
public virtual int PrefixLength { get { return default(int); } }
public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; }
public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; }
}
public partial class UnicastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.IEnumerable
{
protected internal UnicastIPAddressInformationCollection() { }
public virtual int Count { get { return default(int); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual System.Net.NetworkInformation.UnicastIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.UnicastIPAddressInformation); } }
public virtual void Add(System.Net.NetworkInformation.UnicastIPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.UnicastIPAddressInformation address) { return default(bool); }
public virtual void CopyTo(System.Net.NetworkInformation.UnicastIPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation>); }
public virtual bool Remove(System.Net.NetworkInformation.UnicastIPAddressInformation address) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
}
| |
using System;
using QRCodeDecoder = MessagingToolkit.QRCode.Codec.QRCodeDecoder;
using MessagingToolkit.QRCode.Codec.Reader;
using AlignmentPatternNotFoundException = MessagingToolkit.QRCode.ExceptionHandler.AlignmentPatternNotFoundException;
using InvalidVersionException = MessagingToolkit.QRCode.ExceptionHandler.InvalidVersionException;
using MessagingToolkit.QRCode.Geom;
using MessagingToolkit.QRCode.Codec.Util;
namespace MessagingToolkit.QRCode.Codec.Reader.Pattern
{
public class AlignmentPattern
{
internal const int RIGHT = 1;
internal const int BOTTOM = 2;
internal const int LEFT = 3;
internal const int TOP = 4;
internal static DebugCanvas canvas;
internal Point[][] center;
internal int patternDistance;
virtual public int LogicalDistance
{
get
{
return patternDistance;
}
}
internal AlignmentPattern(Point[][] center, int patternDistance)
{
this.center = center;
this.patternDistance = patternDistance;
}
public static AlignmentPattern findAlignmentPattern(bool[][] image, FinderPattern finderPattern)
{
Point[][] logicalCenters = getLogicalCenter(finderPattern);
int logicalDistance = logicalCenters[1][0].X - logicalCenters[0][0].X;
//With it converts in order to handle in the same way
Point[][] centers = null;
centers = getCenter(image, finderPattern, logicalCenters);
return new AlignmentPattern(centers, logicalDistance);
}
public virtual Point[][] getCenter()
{
return center;
}
// for only trancparency access in version 1, which has no alignement pattern
public virtual void setCenter(Point[][] center)
{
this.center = center;
}
internal static Point[][] getCenter(bool[][] image, FinderPattern finderPattern, Point[][] logicalCenters)
{
int moduleSize = finderPattern.getModuleSize();
Axis axis = new Axis(finderPattern.getAngle(), moduleSize);
int sqrtCenters = logicalCenters.Length;
Point[][] centers = new Point[sqrtCenters][];
for (int i = 0; i < sqrtCenters; i++)
{
centers[i] = new Point[sqrtCenters];
}
axis.Origin = finderPattern.getCenter(FinderPattern.UL);
centers[0][0] = axis.translate(3, 3);
canvas.drawCross(centers[0][0], MessagingToolkit.QRCode.Codec.Util.Color_Fields.BLUE);
axis.Origin = finderPattern.getCenter(FinderPattern.UR);
centers[sqrtCenters - 1][0] = axis.translate(- 3, 3);
canvas.drawCross(centers[sqrtCenters - 1][0], MessagingToolkit.QRCode.Codec.Util.Color_Fields.BLUE);
axis.Origin = finderPattern.getCenter(FinderPattern.DL);
centers[0][sqrtCenters - 1] = axis.translate(3, - 3);
canvas.drawCross(centers[0][sqrtCenters - 1], MessagingToolkit.QRCode.Codec.Util.Color_Fields.BLUE);
Point tmpPoint = centers[0][0];
for (int y = 0; y < sqrtCenters; y++)
{
for (int x = 0; x < sqrtCenters; x++)
{
if ((x == 0 && y == 0) || (x == 0 && y == sqrtCenters - 1) || (x == sqrtCenters - 1 && y == 0))
{
// canvas.drawCross(centers[x][y], java.awt.Color.MAGENTA);
continue;
}
Point target = null;
if (y == 0)
{
if (x > 0 && x < sqrtCenters - 1)
{
target = axis.translate(centers[x - 1][y], logicalCenters[x][y].X - logicalCenters[x - 1][y].X, 0);
}
centers[x][y] = new Point(target.X, target.Y);
canvas.drawCross(centers[x][y], MessagingToolkit.QRCode.Codec.Util.Color_Fields.RED);
}
else if (x == 0)
{
if (y > 0 && y < sqrtCenters - 1)
{
target = axis.translate(centers[x][y - 1], 0, logicalCenters[x][y].Y - logicalCenters[x][y - 1].Y);
}
centers[x][y] = new Point(target.X, target.Y);
canvas.drawCross(centers[x][y], MessagingToolkit.QRCode.Codec.Util.Color_Fields.RED);
}
else
{
Point t1 = axis.translate(centers[x - 1][y], logicalCenters[x][y].X - logicalCenters[x - 1][y].X, 0);
Point t2 = axis.translate(centers[x][y - 1], 0, logicalCenters[x][y].Y - logicalCenters[x][y - 1].Y);
centers[x][y] = new Point((t1.X + t2.X) / 2, (t1.Y + t2.Y) / 2 + 1);
}
if (finderPattern.Version > 1)
{
Point precisionCenter = getPrecisionCenter(image, centers[x][y]);
if (centers[x][y].distanceOf(precisionCenter) < 6)
{
canvas.drawCross(centers[x][y], MessagingToolkit.QRCode.Codec.Util.Color_Fields.RED);
int dx = precisionCenter.X - centers[x][y].X;
int dy = precisionCenter.Y - centers[x][y].Y;
canvas.println("Adjust AP(" + x + "," + y + ") to d(" + dx + "," + dy + ")");
centers[x][y] = precisionCenter;
}
}
canvas.drawCross(centers[x][y], MessagingToolkit.QRCode.Codec.Util.Color_Fields.BLUE);
canvas.drawLine(new Line(tmpPoint, centers[x][y]), MessagingToolkit.QRCode.Codec.Util.Color_Fields.LIGHTBLUE);
tmpPoint = centers[x][y];
}
}
return centers;
}
internal static Point getPrecisionCenter(bool[][] image, Point targetPoint)
{
// find nearest dark point and update it as new rough center point
// when original rough center points light point
int tx = targetPoint.X, ty = targetPoint.Y;
if ((tx < 0 || ty < 0) || (tx > image.Length - 1 || ty > image[0].Length - 1))
throw new AlignmentPatternNotFoundException("Alignment Pattern finder exceeded out of image");
if (image[targetPoint.X][targetPoint.Y] == QRCodeImageReader.POINT_LIGHT)
{
int scope = 0;
bool found = false;
while (!found)
{
scope++;
for (int dy = scope; dy > - scope; dy--)
{
for (int dx = scope; dx > - scope; dx--)
{
int x = targetPoint.X + dx;
int y = targetPoint.Y + dy;
if ((x < 0 || y < 0) || (x > image.Length - 1 || y > image[0].Length - 1))
throw new AlignmentPatternNotFoundException("Alignment Pattern finder exceeded out of image");
if (image[x][y] == QRCodeImageReader.POINT_DARK)
{
targetPoint = new Point(targetPoint.X + dx, targetPoint.Y + dy);
found = true;
}
}
}
}
}
int x2, lx, rx, y2, uy, dy2;
x2 = lx = rx = targetPoint.X;
y2 = uy = dy2 = targetPoint.Y;
// GuoQing Hu's FIX
while (lx >= 1 && !targetPointOnTheCorner(image, lx, y2, lx - 1, y2))
lx--;
while (rx < image.Length - 1 && !targetPointOnTheCorner(image, rx, y2, rx + 1, y2))
rx++;
while (uy >= 1 && !targetPointOnTheCorner(image, x2, uy, x2, uy - 1))
uy--;
while (dy2 < image[0].Length - 1 && !targetPointOnTheCorner(image, x2, dy2, x2, dy2 + 1))
dy2++;
return new Point((lx + rx + 1) / 2, (uy + dy2 + 1) / 2);
}
internal static bool targetPointOnTheCorner(bool[][] image, int x, int y, int nx, int ny)
{
if (x < 0 || y < 0 || nx < 0 || ny < 0 || x > image.Length || y > image[0].Length || nx > image.Length || ny > image[0].Length)
{
// Console.out.println("Overflow: x="+x+", y="+y+" nx="+nx+" ny="+ny+" x.max="+image.length+", y.max="+image[0].length);
throw new AlignmentPatternNotFoundException("Alignment Pattern Finder exceeded image edge");
//return true;
}
else
{
return (image[x][y] == QRCodeImageReader.POINT_LIGHT && image[nx][ny] == QRCodeImageReader.POINT_DARK);
}
}
//get logical center coordinates of each alignment patterns
public static Point[][] getLogicalCenter(FinderPattern finderPattern)
{
int version = finderPattern.Version;
Point[][] logicalCenters = new Point[1][];
for (int i = 0; i < 1; i++)
{
logicalCenters[i] = new Point[1];
}
int[] logicalSeeds = new int[1];
//create "column(row)-coordinates" which based on relative coordinates
//int sqrtCenters = (version / 7) + 2;
//logicalSeeds = new int[sqrtCenters];
//for(int i=0 ; i<sqrtCenters ; i++) {
// logicalSeeds[i] = 6 + i * (4 + 4 * version) / (sqrtCenters - 1);
// logicalSeeds[i] -= (logicalSeeds[i] - 2) % 4;
//}
logicalSeeds = LogicalSeed.getSeed(version);
logicalCenters = new Point[logicalSeeds.Length][];
for (int i2 = 0; i2 < logicalSeeds.Length; i2++)
{
logicalCenters[i2] = new Point[logicalSeeds.Length];
}
//create real relative coordinates
for (int col = 0; col < logicalCenters.Length; col++)
{
for (int row = 0; row < logicalCenters.Length; row++)
{
logicalCenters[row][col] = new Point(logicalSeeds[row], logicalSeeds[col]);
}
}
return logicalCenters;
}
static AlignmentPattern()
{
canvas = QRCodeDecoder.Canvas;
}
}
}
| |
/* ====================================================================
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.XWPF.UserModel
{
using System;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using NPOI.XWPF.Util;
using NPOI.OpenXmlFormats.Dml;
using System.Xml.Serialization;
using NPOI.OpenXmlFormats.Dml.WordProcessing;
/**
* XWPFrun.object defines a region of text with a common Set of properties
*
* @author Yegor Kozlov
* @author Gregg Morris (gregg dot morris at gmail dot com) - added getColor(), setColor()
*/
public class XWPFRun
{
private CT_R run;
private String pictureText;
private XWPFParagraph paragraph;
private List<XWPFPicture> pictures;
/**
* @param r the CT_R bean which holds the run.attributes
* @param p the parent paragraph
*/
public XWPFRun(CT_R r, XWPFParagraph p)
{
this.run = r;
this.paragraph = p;
/**
* reserve already occupied Drawing ids, so reserving new ids later will
* not corrupt the document
*/
IList<CT_Drawing> drawingList = r.GetDrawingList();
foreach (CT_Drawing ctDrawing in drawingList)
{
List<CT_Anchor> anchorList = ctDrawing.GetAnchorList();
foreach (CT_Anchor anchor in anchorList)
{
if (anchor.docPr != null)
{
this.Document.DrawingIdManager.Reserve(anchor.docPr.id);
}
}
List<CT_Inline> inlineList = ctDrawing.GetInlineList();
foreach (CT_Inline inline in inlineList)
{
if (inline.docPr != null)
{
this.Document.DrawingIdManager.Reserve(inline.docPr.id);
}
}
}
//// Look for any text in any of our pictures or Drawings
StringBuilder text = new StringBuilder();
List<object> pictTextObjs = new List<object>();
foreach (CT_Picture pic in r.GetPictList())
pictTextObjs.Add(pic);
foreach (CT_Drawing draw in drawingList)
pictTextObjs.Add(draw);
//foreach (object o in pictTextObjs)
//{
//todo:: imlement this
//XmlObject[] t = o.SelectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");
//for (int m = 0; m < t.Length; m++)
//{
// NodeList kids = t[m].DomNode.ChildNodes;
// for (int n = 0; n < kids.Length; n++)
// {
// if (kids.Item(n) is Text)
// {
// if (text.Length > 0)
// text.Append("\n");
// text.Append(kids.Item(n).NodeValue);
// }
// }
//}
//}
pictureText = text.ToString();
// Do we have any embedded pictures?
// (They're a different CT_Picture, under the Drawingml namespace)
pictures = new List<XWPFPicture>();
foreach (object o in pictTextObjs)
{
foreach (OpenXmlFormats.Dml.Picture.CT_Picture pict in GetCTPictures(o))
{
XWPFPicture picture = new XWPFPicture(pict, this);
pictures.Add(picture);
}
}
}
private List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> GetCTPictures(object o)
{
List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> pictures = new List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture>();
//XmlObject[] picts = o.SelectPath("declare namespace pic='"+CT_Picture.type.Name.NamespaceURI+"' .//pic:pic");
//XmlElement[] picts = o.Any;
//foreach (XmlElement pict in picts)
//{
//if(pict is XmlAnyTypeImpl) {
// // Pesky XmlBeans bug - see Bugzilla #49934
// try {
// pict = CT_Picture.Factory.Parse( pict.ToString() );
// } catch(XmlException e) {
// throw new POIXMLException(e);
// }
//}
//if (pict is NPOI.OpenXmlFormats.Dml.CT_Picture)
//{
// pictures.Add((NPOI.OpenXmlFormats.Dml.CT_Picture)pict);
//}
//}
if (o is CT_Drawing)
{
CT_Drawing drawing = o as CT_Drawing;
if (drawing.inline!=null)
{
foreach (CT_Inline inline in drawing.inline)
{
GetPictures(inline.graphic.graphicData, pictures);
}
}
}
else if (o is CT_GraphicalObjectData)
{
GetPictures(o as CT_GraphicalObjectData, pictures);
}
return pictures;
}
private void GetPictures(CT_GraphicalObjectData god, List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> pictures)
{
XmlSerializer xmlse = new XmlSerializer(typeof(NPOI.OpenXmlFormats.Dml.Picture.CT_Picture));
foreach (string el in god.Any)
{
System.IO.StringReader stringReader = new System.IO.StringReader(el);
NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pict =
xmlse.Deserialize(System.Xml.XmlReader.Create(stringReader)) as NPOI.OpenXmlFormats.Dml.Picture.CT_Picture;
pictures.Add(pict);
}
}
/**
* Get the currently used CT_R object
* @return CT_R object
*/
public CT_R GetCTR()
{
return run;
}
/**
* Get the currenty referenced paragraph object
* @return current paragraph
*/
public XWPFParagraph Paragraph
{
get
{
return paragraph;
}
}
/**
* @return The {@link XWPFDocument} instance, this run.belongs to, or
* <code>null</code> if parent structure (paragraph > document) is not properly Set.
*/
public XWPFDocument Document
{
get
{
if (paragraph != null)
{
return paragraph.Document;
}
return null;
}
}
/**
* For isBold, isItalic etc
*/
private bool IsCTOnOff(CT_OnOff onoff)
{
if (!onoff.IsSetVal())
return true;
return onoff.val;
}
/**
* Whether the bold property shall be applied to all non-complex script
* characters in the contents of this run.when displayed in a document
*
* @return <code>true</code> if the bold property is applied
*/
public bool IsBold
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetB())
{
return false;
}
return IsCTOnOff(pr.b);
}
}
/**
* Whether the bold property shall be applied to all non-complex script
* characters in the contents of this run.when displayed in a document.
* <p>
* This formatting property is a toggle property, which specifies that its
* behavior differs between its use within a style defInition and its use as
* direct formatting. When used as part of a style defInition, Setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
* versa). Setting it to <code>false</code> (or an equivalent) shall
* result in the current Setting remaining unChanged. However, when used as
* direct formatting, Setting this property to true or false shall Set the
* absolute state of the resulting property.
* </p>
* <p>
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then bold shall not be
* applied to non-complex script characters.
* </p>
*
* @param value <code>true</code> if the bold property is applied to
* this run
*/
public void SetBold(bool value)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff bold = pr.IsSetB() ? pr.b : pr.AddNewB();
bold.val=value ;
}
/**
* Get text color. The returned value is a string in the hex form "RRGGBB".
*/
public String GetColor()
{
String color = null;
if (run.IsSetRPr())
{
CT_RPr pr = run.rPr;
if (pr.IsSetColor())
{
NPOI.OpenXmlFormats.Wordprocessing.CT_Color clr = pr.color;
color = clr.val; //clr.xgetVal().getStringValue();
}
}
return color;
}
/**
* Set text color.
* @param rgbStr - the desired color, in the hex form "RRGGBB".
*/
public void SetColor(String rgbStr)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
NPOI.OpenXmlFormats.Wordprocessing.CT_Color color = pr.IsSetColor() ? pr.color : pr.AddNewColor();
color.val = (rgbStr);
}
/**
* Return the string content of this text run
*
* @return the text of this text run.or <code>null</code> if not Set
*/
public String GetText(int pos)
{
return run.SizeOfTArray() == 0 ? null : run.GetTArray(pos).Value;
}
/**
* Returns text embedded in pictures
*/
public String PictureText
{
get
{
return pictureText;
}
}
public void ReplaceText(string oldText, string newText)
{
string text= this.Text.Replace(oldText, newText);
this.SetText(text);
}
/**
* Sets the text of this text run
*
* @param value the literal text which shall be displayed in the document
*/
public void SetText(String value)
{
StringBuilder sb = new StringBuilder();
run.Items.Clear();
run.ItemsElementName.Clear();
char[] chars= value.ToCharArray();
for (int i = 0; i < chars.Length;i++ )
{
if (chars[i] == '\n')
{
run.Items.Add(new CT_Text() { Value = sb.ToString() });
run.ItemsElementName.Add(RunItemsChoiceType.instrText);
sb=sb.Remove(0,sb.Length);
run.Items.Add(new CT_Br());
run.ItemsElementName.Add(RunItemsChoiceType.br);
}
else if (chars[i] == '\t')
{
run.Items.Add(new CT_Text() { Value = sb.ToString() });
run.ItemsElementName.Add(RunItemsChoiceType.instrText);
sb=sb.Remove(0, sb.Length);
run.Items.Add(new CT_PTab());
run.ItemsElementName.Add(RunItemsChoiceType.ptab);
}
else
{
sb.Append(chars[i]);
}
}
if (sb.Length > 0)
{
run.Items.Add(new CT_Text() { Value = sb.ToString() });
run.ItemsElementName.Add(RunItemsChoiceType.instrText);
}
}
public void AppendText(String value)
{
SetText(value, run.GetTList().Count);
}
/**
* Sets the text of this text run.in the
*
* @param value the literal text which shall be displayed in the document
* @param pos - position in the text array (NB: 0 based)
*/
public void SetText(String value, int pos)
{
int length = run.SizeOfTArray();
if (pos > length) throw new IndexOutOfRangeException("Value too large for the parameter position in XWPFrun.Text=(String value,int pos)");
CT_Text t = (pos < length && pos >= 0) ? run.GetTArray(pos) as CT_Text : run.AddNewT();
t.Value =(value);
preserveSpaces(t);
}
/**
* Whether the italic property should be applied to all non-complex script
* characters in the contents of this run.when displayed in a document.
*
* @return <code>true</code> if the italic property is applied
*/
public bool IsItalic
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetI())
return false;
return IsCTOnOff(pr.i);
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff italic = pr.IsSetI() ? pr.i : pr.AddNewI();
italic.val = value;
}
}
/**
* Specifies that the contents of this run.should be displayed along with an
* underline appearing directly below the character heigh
*
* @return the Underline pattern Applyed to this run
* @see UnderlinePatterns
*/
public UnderlinePatterns Underline
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetU()) ? EnumConverter.ValueOf<UnderlinePatterns, ST_Underline>(pr.u.val) : UnderlinePatterns.None;
}
}
internal void InsertText(CT_Text text, int textIndex)
{
run.GetTList().Insert(textIndex, text);
}
/// <summary>
/// insert text at start index in the run
/// </summary>
/// <param name="text">insert text</param>
/// <param name="startIndex">start index of the insertion in the run text</param>
public void InsertText(string text, int startIndex)
{
List<CT_Text> texts= run.GetTList();
int endPos = 0;
int startPos = 0;
for (int i = 0; i < texts.Count; i++)
{
startPos = endPos;
endPos += texts[i].Value.Length;
if (endPos > startIndex)
{
texts[i].Value = texts[i].Value.Insert(startIndex - startPos, text);
break;
}
}
}
public string Text
{
get {
StringBuilder text = new StringBuilder();
for (int i = 0; i < run.Items.Count;i++ )
{
object o = run.Items[i];
if (o is CT_Text)
{
if (!(run.ItemsElementName[i] == RunItemsChoiceType.instrText))
{
text.Append(((CT_Text)o).Value);
}
}
if (o is CT_PTab)
{
text.Append("\t");
}
if (o is CT_Br)
{
text.Append("\n");
}
if (o is CT_Empty)
{
// Some inline text elements Get returned not as
// themselves, but as CTEmpty, owing to some odd
// defInitions around line 5642 of the XSDs
// This bit works around it, and replicates the above
// rules for that case
if (run.ItemsElementName[i] == RunItemsChoiceType.tab)
{
text.Append("\t");
}
if (run.ItemsElementName[i] == RunItemsChoiceType.br)
{
text.Append("\n");
}
if (run.ItemsElementName[i] == RunItemsChoiceType.cr)
{
text.Append("\n");
}
}
}
return text.ToString();
}
}
/**
* Specifies that the contents of this run.should be displayed along with an
* underline appearing directly below the character heigh
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then an underline shall
* not be applied to the contents of this run.
*
* @param value -
* underline type
* @see UnderlinePatterns : all possible patterns that could be applied
*/
public void SetUnderline(UnderlinePatterns value)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_Underline underline = (pr.u == null) ? pr.AddNewU() : pr.u;
underline.val = EnumConverter.ValueOf<ST_Underline, UnderlinePatterns>(value);
}
/**
* Specifies that the contents of this run.shall be displayed with a single
* horizontal line through the center of the line.
*
* @return <code>true</code> if the strike property is applied
*/
public bool IsStrike
{
get
{
CT_RPr pr = run.rPr;
if (pr == null || !pr.IsSetStrike())
return false;
return IsCTOnOff(pr.strike);
}
}
/**
* Specifies that the contents of this run.shall be displayed with a single
* horizontal line through the center of the line.
* <p/>
* This formatting property is a toggle property, which specifies that its
* behavior differs between its use within a style defInition and its use as
* direct formatting. When used as part of a style defInition, Setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
* versa). Setting it to false (or an equivalent) shall result in the
* current Setting remaining unChanged. However, when used as direct
* formatting, Setting this property to true or false shall Set the absolute
* state of the resulting property.
* </p>
* <p/>
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then strikethrough shall
* not be applied to the contents of this run.
* </p>
*
* @param value <code>true</code> if the strike property is applied to
* this run
*/
public void SetStrike(bool value)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_OnOff strike = pr.IsSetStrike() ? pr.strike : pr.AddNewStrike();
strike.val = value ;
}
/**
* Specifies the alignment which shall be applied to the contents of this
* run.in relation to the default appearance of the run.s text.
* This allows the text to be repositioned as subscript or superscript without
* altering the font size of the run.properties.
*
* @return VerticalAlign
* @see VerticalAlign all possible value that could be Applyed to this run
*/
public VerticalAlign Subscript
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetVertAlign()) ?
EnumConverter.ValueOf<VerticalAlign, ST_VerticalAlignRun>(pr.vertAlign.val) : VerticalAlign.BASELINE;
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_VerticalAlignRun ctValign = pr.IsSetVertAlign() ? pr.vertAlign : pr.AddNewVertAlign();
ctValign.val = EnumConverter.ValueOf<ST_VerticalAlignRun, VerticalAlign>(value);
}
}
/**
* Specifies the fonts which shall be used to display the text contents of
* this run. Specifies a font which shall be used to format all characters
* in the ASCII range (0 - 127) within the parent run
*
* @return a string representing the font family
*/
public String FontFamily
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetRFonts()) ? pr.rFonts.ascii
: null;
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_Fonts fonts = pr.IsSetRFonts() ? pr.rFonts : pr.AddNewRFonts();
fonts.ascii = value;
}
}
/**
* Specifies the font size which shall be applied to all non complex script
* characters in the contents of this run.when displayed.
*
* @return value representing the font size
*/
public int FontSize
{
get
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetSz()) ? (int)pr.sz.val / 2 : -1;
}
set
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_HpsMeasure ctSize = pr.IsSetSz() ? pr.sz : pr.AddNewSz();
ctSize.val = (ulong)value * 2;
}
}
/**
* This element specifies the amount by which text shall be raised or
* lowered for this run.in relation to the default baseline of the
* surrounding non-positioned text. This allows the text to be repositioned
* without altering the font size of the contents.
*
* @return a big integer representing the amount of text shall be "moved"
*/
public int GetTextPosition()
{
CT_RPr pr = run.rPr;
return (pr != null && pr.IsSetPosition()) ? int.Parse(pr.position.val)
: -1;
}
/**
* This element specifies the amount by which text shall be raised or
* lowered for this run.in relation to the default baseline of the
* surrounding non-positioned text. This allows the text to be repositioned
* without altering the font size of the contents.
*
* If the val attribute is positive, then the parent run.shall be raised
* above the baseline of the surrounding text by the specified number of
* half-points. If the val attribute is negative, then the parent run.shall
* be lowered below the baseline of the surrounding text by the specified
* number of half-points.
* *
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then the text shall not
* be raised or lowered relative to the default baseline location for the
* contents of this run.
*/
public void SetTextPosition(int val)
{
CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr();
CT_SignedHpsMeasure position = pr.IsSetPosition() ? pr.position : pr.AddNewPosition();
position.val = (val.ToString());
}
/**
*
*/
public void RemoveBreak()
{
// TODO
}
/**
* Specifies that a break shall be placed at the current location in the run
* content.
* A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* @see #AddCarriageReturn()
*/
public void AddBreak()
{
run.AddNewBr();
}
/**
* Specifies that a break shall be placed at the current location in the run
* content.
* A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* <p>
* The behavior of this break character (the
* location where text shall be restarted After this break) shall be
* determined by its type values.
* </p>
* @see BreakType
*/
public void AddBreak(BreakType type)
{
CT_Br br=run.AddNewBr();
br.type = EnumConverter.ValueOf<ST_BrType, BreakType>(type);
}
/**
* Specifies that a break shall be placed at the current location in the run
* content. A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* <p>
* The behavior of this break character (the
* location where text shall be restarted After this break) shall be
* determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values.
* </p>
* @see BreakClear
*/
public void AddBreak(BreakClear Clear)
{
CT_Br br=run.AddNewBr();
br.type= EnumConverter.ValueOf<ST_BrType, BreakType>(BreakType.TEXTWRAPPING);
br.clear = EnumConverter.ValueOf<ST_BrClear, BreakClear>(Clear);
}
/**
* Specifies that a carriage return shall be placed at the
* current location in the run.content.
* A carriage return is used to end the current line of text in
* WordProcess.
* The behavior of a carriage return in run.content shall be
* identical to a break character with null type and clear attributes, which
* shall end the current line and find the next available line on which to
* continue.
* The carriage return character forced the following text to be
* restarted on the next available line in the document.
*/
public void AddCarriageReturn()
{
run.AddNewCr();
}
public void RemoveCarriageReturn(int i)
{
throw new NotImplementedException();
}
/**
* Adds a picture to the run. This method handles
* attaching the picture data to the overall file.
*
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_EMF
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_WMF
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PICT
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_JPEG
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PNG
* @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_DIB
*
* @param pictureData The raw picture data
* @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
* @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @throws NPOI.Openxml4j.exceptions.InvalidFormatException
* @throws IOException
*/
public XWPFPicture AddPicture(Stream pictureData, int pictureType, String filename, int width, int height)
{
XWPFDocument doc = paragraph.Document;
// Add the picture + relationship
String relationId = doc.AddPictureData(pictureData, pictureType);
XWPFPictureData picData = (XWPFPictureData)doc.GetRelationById(relationId);
// Create the Drawing entry for it
CT_Drawing Drawing = run.AddNewDrawing();
CT_Inline inline = Drawing.AddNewInline();
// Do the fiddly namespace bits on the inline
// (We need full control of what goes where and as what)
//CT_GraphicalObject tmp = new CT_GraphicalObject();
//String xml =
// "<a:graphic xmlns:a=\"" + "http://schemas.openxmlformats.org/drawingml/2006/main" + "\">" +
// "<a:graphicData uri=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\">" +
// "<pic:pic xmlns:pic=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\" />" +
// "</a:graphicData>" +
// "</a:graphic>";
//inline.Set((xml));
XmlDocument xmlDoc = new XmlDocument();
//XmlElement el = xmlDoc.CreateElement("pic", "pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
inline.graphic = new CT_GraphicalObject();
inline.graphic.graphicData = new CT_GraphicalObjectData();
inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
// Setup the inline
inline.distT = (0);
inline.distR = (0);
inline.distB = (0);
inline.distL = (0);
NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps docPr = inline.AddNewDocPr();
long id = Paragraph.Document.DrawingIdManager.ReserveNew();
docPr.id = (uint)(id);
/* This name is not visible in Word 2010 anywhere. */
docPr.name = ("Drawing " + id);
docPr.descr = (filename);
NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent();
extent.cx = (width);
extent.cy = (height);
// Grab the picture object
NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new OpenXmlFormats.Dml.Picture.CT_Picture();
// Set it up
NPOI.OpenXmlFormats.Dml.Picture.CT_PictureNonVisual nvPicPr = pic.AddNewNvPicPr();
NPOI.OpenXmlFormats.Dml.CT_NonVisualDrawingProps cNvPr = nvPicPr.AddNewCNvPr();
/* use "0" for the id. See ECM-576, 20.2.2.3 */
cNvPr.id = (0);
/* This name is not visible in Word 2010 anywhere */
cNvPr.name = ("Picture " + id);
cNvPr.descr = (filename);
CT_NonVisualPictureProperties cNvPicPr = nvPicPr.AddNewCNvPicPr();
cNvPicPr.AddNewPicLocks().noChangeAspect = true;
CT_BlipFillProperties blipFill = pic.AddNewBlipFill();
CT_Blip blip = blipFill.AddNewBlip();
blip.embed = (picData.GetPackageRelationship().Id);
blipFill.AddNewStretch().AddNewFillRect();
CT_ShapeProperties spPr = pic.AddNewSpPr();
CT_Transform2D xfrm = spPr.AddNewXfrm();
CT_Point2D off = xfrm.AddNewOff();
off.x = (0);
off.y = (0);
NPOI.OpenXmlFormats.Dml.CT_PositiveSize2D ext = xfrm.AddNewExt();
ext.cx = (width);
ext.cy = (height);
CT_PresetGeometry2D prstGeom = spPr.AddNewPrstGeom();
prstGeom.prst = (ST_ShapeType.rect);
prstGeom.AddNewAvLst();
using (var ms = new MemoryStream())
{
StreamWriter sw = new StreamWriter(ms);
pic.Write(sw, "pic:pic");
sw.Flush();
ms.Position = 0;
var sr = new StreamReader(ms);
var picXml = sr.ReadToEnd();
inline.graphic.graphicData.AddPicElement(picXml);
}
// Finish up
XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
pictures.Add(xwpfPicture);
return xwpfPicture;
}
/**
* Returns the embedded pictures of the run. These
* are pictures which reference an external,
* embedded picture image such as a .png or .jpg
*/
public List<XWPFPicture> GetEmbeddedPictures()
{
return pictures;
}
/**
* Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces
*
* @param xs the string to check
*/
static void preserveSpaces(CT_Text xs)
{
String text = xs.Value;
if (text != null && (text.StartsWith(" ") || text.EndsWith(" "))) {
// XmlCursor c = xs.NewCursor();
// c.ToNextToken();
// c.InsertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
// c.Dispose();
xs.space = "preserve";
}
}
/**
* Returns the string version of the text, with tabs and
* carriage returns in place of their xml equivalents.
*/
public override String ToString()
{
StringBuilder text = new StringBuilder();
text.Append(this.Text);
// Any picture text?
if (pictureText != null && pictureText.Length > 0)
{
text.Append("\n").Append(pictureText);
}
return text.ToString();
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// This source file is machine generated. Please do not change the code manually.
using System;
using System.Collections.Generic;
using System.IO.Packaging;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
namespace DocumentFormat.OpenXml.Office.MetaAttributes
{
/// <summary>
/// <para>Defines the Dummy Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is ma:DummyContentTypeElement.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class Dummy : OpenXmlLeafElement
{
private const string tagName = "DummyContentTypeElement";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 41;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12713;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
private static string[] attributeTagNames = { "decimals","default","description","displayName","fieldsID","format","hidden","index","internalName","LCID","list","percentage","readOnly","requiredMultiChoice","root","showField","web" };
private static byte[] attributeNamespaceIds = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
internal override string[] AttributeTagNames {
get{
return attributeTagNames;
}
}
internal override byte[] AttributeNamespaceIds {
get{
return attributeNamespaceIds;
}
}
/// <summary>
/// <para> decimals.</para>
/// <para>Represents the following attribute in the schema: decimals </para>
/// </summary>
[SchemaAttr(0, "decimals")]
public StringValue Decimals
{
get { return (StringValue)Attributes[0]; }
set { Attributes[0] = value; }
}
/// <summary>
/// <para> default.</para>
/// <para>Represents the following attribute in the schema: default </para>
/// </summary>
[SchemaAttr(0, "default")]
public StringValue Default
{
get { return (StringValue)Attributes[1]; }
set { Attributes[1] = value; }
}
/// <summary>
/// <para> description.</para>
/// <para>Represents the following attribute in the schema: description </para>
/// </summary>
[SchemaAttr(0, "description")]
public StringValue Description
{
get { return (StringValue)Attributes[2]; }
set { Attributes[2] = value; }
}
/// <summary>
/// <para> displayName.</para>
/// <para>Represents the following attribute in the schema: displayName </para>
/// </summary>
[SchemaAttr(0, "displayName")]
public StringValue DisplayName
{
get { return (StringValue)Attributes[3]; }
set { Attributes[3] = value; }
}
/// <summary>
/// <para> fieldsID.</para>
/// <para>Represents the following attribute in the schema: fieldsID </para>
/// </summary>
[SchemaAttr(0, "fieldsID")]
public StringValue FieldsID
{
get { return (StringValue)Attributes[4]; }
set { Attributes[4] = value; }
}
/// <summary>
/// <para> format.</para>
/// <para>Represents the following attribute in the schema: format </para>
/// </summary>
[SchemaAttr(0, "format")]
public StringValue Format
{
get { return (StringValue)Attributes[5]; }
set { Attributes[5] = value; }
}
/// <summary>
/// <para> hidden.</para>
/// <para>Represents the following attribute in the schema: hidden </para>
/// </summary>
[SchemaAttr(0, "hidden")]
public StringValue Hidden
{
get { return (StringValue)Attributes[6]; }
set { Attributes[6] = value; }
}
/// <summary>
/// <para> index.</para>
/// <para>Represents the following attribute in the schema: index </para>
/// </summary>
[SchemaAttr(0, "index")]
public Int32Value Index
{
get { return (Int32Value)Attributes[7]; }
set { Attributes[7] = value; }
}
/// <summary>
/// <para> internalName.</para>
/// <para>Represents the following attribute in the schema: internalName </para>
/// </summary>
[SchemaAttr(0, "internalName")]
public StringValue InternalName
{
get { return (StringValue)Attributes[8]; }
set { Attributes[8] = value; }
}
/// <summary>
/// <para> LCID.</para>
/// <para>Represents the following attribute in the schema: LCID </para>
/// </summary>
[SchemaAttr(0, "LCID")]
public Int32Value LCID
{
get { return (Int32Value)Attributes[9]; }
set { Attributes[9] = value; }
}
/// <summary>
/// <para> list.</para>
/// <para>Represents the following attribute in the schema: list </para>
/// </summary>
[SchemaAttr(0, "list")]
public StringValue List
{
get { return (StringValue)Attributes[10]; }
set { Attributes[10] = value; }
}
/// <summary>
/// <para> percentage.</para>
/// <para>Represents the following attribute in the schema: percentage </para>
/// </summary>
[SchemaAttr(0, "percentage")]
public StringValue Percentage
{
get { return (StringValue)Attributes[11]; }
set { Attributes[11] = value; }
}
/// <summary>
/// <para> readOnly.</para>
/// <para>Represents the following attribute in the schema: readOnly </para>
/// </summary>
[SchemaAttr(0, "readOnly")]
public StringValue ReadOnly
{
get { return (StringValue)Attributes[12]; }
set { Attributes[12] = value; }
}
/// <summary>
/// <para> requiredMultiChoice.</para>
/// <para>Represents the following attribute in the schema: requiredMultiChoice </para>
/// </summary>
[SchemaAttr(0, "requiredMultiChoice")]
public StringValue RequiredMultiChoice
{
get { return (StringValue)Attributes[13]; }
set { Attributes[13] = value; }
}
/// <summary>
/// <para> root.</para>
/// <para>Represents the following attribute in the schema: root </para>
/// </summary>
[SchemaAttr(0, "root")]
public EnumValue<DocumentFormat.OpenXml.Office.MetaAttributes.TrueOnlyValues> Root
{
get { return (EnumValue<DocumentFormat.OpenXml.Office.MetaAttributes.TrueOnlyValues>)Attributes[14]; }
set { Attributes[14] = value; }
}
/// <summary>
/// <para> showField.</para>
/// <para>Represents the following attribute in the schema: showField </para>
/// </summary>
[SchemaAttr(0, "showField")]
public StringValue ShowField
{
get { return (StringValue)Attributes[15]; }
set { Attributes[15] = value; }
}
/// <summary>
/// <para> web.</para>
/// <para>Represents the following attribute in the schema: web </para>
/// </summary>
[SchemaAttr(0, "web")]
public StringValue Web
{
get { return (StringValue)Attributes[16]; }
set { Attributes[16] = value; }
}
/// <summary>
/// Initializes a new instance of the Dummy class.
/// </summary>
public Dummy():base(){}
internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name)
{
if( 0 == namespaceId && "decimals" == name)
return new StringValue();
if( 0 == namespaceId && "default" == name)
return new StringValue();
if( 0 == namespaceId && "description" == name)
return new StringValue();
if( 0 == namespaceId && "displayName" == name)
return new StringValue();
if( 0 == namespaceId && "fieldsID" == name)
return new StringValue();
if( 0 == namespaceId && "format" == name)
return new StringValue();
if( 0 == namespaceId && "hidden" == name)
return new StringValue();
if( 0 == namespaceId && "index" == name)
return new Int32Value();
if( 0 == namespaceId && "internalName" == name)
return new StringValue();
if( 0 == namespaceId && "LCID" == name)
return new Int32Value();
if( 0 == namespaceId && "list" == name)
return new StringValue();
if( 0 == namespaceId && "percentage" == name)
return new StringValue();
if( 0 == namespaceId && "readOnly" == name)
return new StringValue();
if( 0 == namespaceId && "requiredMultiChoice" == name)
return new StringValue();
if( 0 == namespaceId && "root" == name)
return new EnumValue<DocumentFormat.OpenXml.Office.MetaAttributes.TrueOnlyValues>();
if( 0 == namespaceId && "showField" == name)
return new StringValue();
if( 0 == namespaceId && "web" == name)
return new StringValue();
return base.AttributeFactory(namespaceId, name);
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<Dummy>(deep);
}
}
/// <summary>
/// Defines the TrueOnlyValues enumeration.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public enum TrueOnlyValues
{
///<summary>
///true.
///<para>When the item is serialized out as xml, its value is "true".</para>
///</summary>
[EnumString("true")]
True,
}
}
| |
/**
* Copyright (c) 2015, GruntTheDivine 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 the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT ,STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
**/
using System;
using System.Collections.Generic;
using Iodine.Util;
using Iodine.Compiler;
namespace Iodine.Runtime
{
/// <summary>
/// Base class for all Iodine objects. Everything in Iodine extends this, as
/// everything in Iodine is an object
/// </summary>
public class IodineObject
{
public static readonly IodineTypeDefinition ObjectTypeDef = new IodineTypeDefinition ("Object");
/*
* This is just a unique value for each Iodine object instance
*/
static long _nextID = 0x00;
public AttributeDictionary Attributes {
get;
internal set;
}
/// <summary>
/// Gets or sets the base class
/// </summary>
/// <value>The base.</value>
public IodineObject Base { set; get; }
/// <summary>
/// Unique identifier
/// </summary>
public readonly long Id;
/// <summary>
/// A list of contracts this object implements
/// </summary>
public readonly List<IodineContract> Interfaces = new List<IodineContract> ();
/// <summary>
/// Object's type
/// </summary>
public IodineTypeDefinition TypeDef {
private set;
get;
}
/// <summary>
/// Object's super object (If it has one)
/// </summary>
/// <value>The super object</value>
public IodineObject Super {
set {
Attributes ["__super__"] = value;
}
get {
return Attributes ["__super__"];
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Iodine.Runtime.IodineObject"/> class.
/// </summary>
/// <param name="typeDef">Type of this object.</param>
public IodineObject (IodineTypeDefinition typeDef)
{
Attributes = new AttributeDictionary ();
SetType (typeDef);
Id = _nextID++;
}
protected IodineObject ()
{
Attributes = new AttributeDictionary ();
}
/// <summary>
/// Modifies the type of this object
/// </summary>
/// <param name="typeDef">The new type.</param>
public void SetType (IodineTypeDefinition typeDef)
{
TypeDef = typeDef;
Attributes ["__type__"] = typeDef;
if (typeDef != null) {
typeDef.BindAttributes (this);
}
}
/// <summary>
/// Determines whether this instance has attribute the specified name.
/// </summary>
/// <returns><c>true</c> if this instance has attribute the specified name; otherwise, <c>false</c>.</returns>
/// <param name="name">Name.</param>
public bool HasAttribute (string name)
{
var res = Attributes.ContainsKey (name);
if (!res && Base != null)
return Base.HasAttribute (name);
return res;
}
public virtual void SetAttribute (VirtualMachine vm, string name, IodineObject value)
{
if (Base != null && !Attributes.ContainsKey (name)) {
if (Base.HasAttribute (name)) {
Base.SetAttribute (vm, name, value);
return;
}
}
SetAttribute (name, value);
}
public void SetAttribute (string name, IodineObject value)
{
if (value is IodineMethod) {
var method = (IodineMethod)value;
Attributes [name] = new IodineBoundMethod (this, method);
} else if (value is BuiltinMethodCallback) {
var callback = (BuiltinMethodCallback)value;
callback.Self = this;
Attributes [name] = value;
} else if (value is IodineBoundMethod) {
var wrapper = (IodineBoundMethod)value;
Attributes [name] = new IodineBoundMethod (this, wrapper.Method);
} else if (value is IodineProperty) {
var property = (IodineProperty)value;
Attributes [name] = new IodineProperty (property.Getter, property.Setter, this);
} else {
Attributes [name] = value;
}
}
public IodineObject GetAttribute (string name)
{
IodineObject ret;
Attributes.TryGetValue (name, out ret);
bool hasAttribute = Attributes.TryGetValue (name, out ret) ||
Base != null &&
Base.Attributes.TryGetValue (name, out ret);
if (hasAttribute) {
return ret;
}
return null;
}
public virtual IodineObject GetAttribute (VirtualMachine vm, string name)
{
if (Attributes.ContainsKey (name)) {
return Attributes [name];
}
if (Base != null && Base.HasAttribute (name)) {
return Base.GetAttribute (name);
}
vm.RaiseException (new IodineAttributeNotFoundException (name));
return null;
}
/// <summary>
/// Determines whether this instance is callable.
/// </summary>
/// <returns><c>true</c> if this instance is callable; otherwise, <c>false</c>.</returns>
public virtual bool IsCallable ()
{
return Attributes.ContainsKey ("__invoke__") && Attributes ["__invoke__"].IsCallable ();
}
/// <summary>
/// Returns a human friendly representation of this object
/// </summary>
/// <returns>The string.</returns>
/// <param name="vm">Vm.</param>
public virtual IodineObject ToString (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__str__")) {
return Attributes ["__str__"].Invoke (vm, new IodineObject[] { });
}
return new IodineString (ToString ());
}
/// <summary>
/// Returns a string represention of this object. This representation *should* be valid
/// Iodine code and pastable into an Iodine REPL.
/// </summary>
/// <param name="vm">Vm.</param>
public virtual IodineObject Represent (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__repr__")) {
return Attributes ["__repr__"].Invoke (vm, new IodineObject[] { });
}
return ToString (vm);
}
/// <summary>
/// Unwraps an enscapulated value, used for pattern matching
/// </summary>
/// <param name="vm">Vm.</param>
public virtual IodineObject Unwrap (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__unwrap__")) {
return Attributes ["__unwrap__"].Invoke (vm, new IodineObject[] { });
}
return this;
}
/// <summary>
/// Compares this instance with another iodine object.
/// </summary>
/// <param name="vm">Virtual Machine.</param>
/// <param name="obj">Object.</param>
public virtual IodineObject Compare (VirtualMachine vm, IodineObject obj)
{
if (HasAttribute ("__cmp__")) {
return GetAttribute ("__cmp__").Invoke (vm, new IodineObject[] { obj });
}
return IodineBool.False;
}
public virtual IodineObject Slice (VirtualMachine vm, IodineSlice slice)
{
if (Attributes.ContainsKey ("__getitem__")) {
return Attributes ["__getitem__"].Invoke (vm, new IodineObject[] { slice });
}
return null;
}
public virtual void SetIndex (VirtualMachine vm, IodineObject key, IodineObject value)
{
if (Attributes.ContainsKey ("__setitem__")) {
Attributes ["__setitem__"].Invoke (vm, new IodineObject[] {
key,
value
});
} else {
vm.RaiseException (new IodineNotSupportedException ("__setitem__ not implemented!"));
}
}
public virtual IodineObject GetIndex (VirtualMachine vm, IodineObject key)
{
if (Attributes.ContainsKey ("__getitem__")) {
return Attributes ["__getitem__"].Invoke (vm, new IodineObject[] { key });
}
return null;
}
public virtual bool Equals (IodineObject obj)
{
return obj == this;
}
/// <summary>
/// Dispatches the proper overload for the specified binary operator
/// </summary>
/// <returns>The result of invoking the overload for Binop.</returns>
/// <param name="vm">Vm.</param>
/// <param name="binop">Binary Operation.</param>
/// <param name="rvalue">Right hand value.</param>
public IodineObject PerformBinaryOperation (
VirtualMachine vm,
BinaryOperation binop,
IodineObject rvalue)
{
switch (binop) {
case BinaryOperation.Add:
return Add (vm, rvalue);
case BinaryOperation.Sub:
return Sub (vm, rvalue);
case BinaryOperation.Pow:
return Pow (vm, rvalue);
case BinaryOperation.Mul:
return Mul (vm, rvalue);
case BinaryOperation.Div:
return Div (vm, rvalue);
case BinaryOperation.And:
return And (vm, rvalue);
case BinaryOperation.Xor:
return Xor (vm, rvalue);
case BinaryOperation.Or:
return Or (vm, rvalue);
case BinaryOperation.Mod:
return Mod (vm, rvalue);
case BinaryOperation.Equals:
return Equals (vm, rvalue);
case BinaryOperation.NotEquals:
return NotEquals (vm, rvalue);
case BinaryOperation.RightShift:
return RightShift (vm, rvalue);
case BinaryOperation.LeftShift:
return LeftShift (vm, rvalue);
case BinaryOperation.LessThan:
return LessThan (vm, rvalue);
case BinaryOperation.GreaterThan:
return GreaterThan (vm, rvalue);
case BinaryOperation.LessThanOrEqu:
return LessThanOrEqual (vm, rvalue);
case BinaryOperation.GreaterThanOrEqu:
return GreaterThanOrEqual (vm, rvalue);
case BinaryOperation.BoolAnd:
return LogicalAnd (vm, rvalue);
case BinaryOperation.BoolOr:
return LogicalOr (vm, rvalue);
case BinaryOperation.HalfRange:
return HalfRange (vm, rvalue);
case BinaryOperation.ClosedRange:
return ClosedRange (vm, rvalue);
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// Dispatches the overload for a specified unary operation
/// </summary>
/// <returns>The unary operation.</returns>
/// <param name="vm">Vm.</param>
/// <param name="op">Operand.</param>
public virtual IodineObject PerformUnaryOperation (VirtualMachine vm, UnaryOperation op)
{
switch (op) {
case UnaryOperation.Negate:
return Negate (vm);
case UnaryOperation.Not:
return Not (vm);
case UnaryOperation.BoolNot:
return LogicalNot (vm);
}
vm.RaiseException (new IodineNotSupportedException (
"The requested unary operator has not been implemented"
));
return null;
}
/// <summary>
/// Calls this object as a method (Overloading the call operator)
/// </summary>
/// <param name="vm">Vm.</param>
/// <param name="arguments">Arguments.</param>
public virtual IodineObject Invoke (VirtualMachine vm, IodineObject[] arguments)
{
if (HasAttribute ("__invoke__")) {
return GetAttribute ("__invoke__").Invoke (vm, arguments);
}
vm.RaiseException (new IodineNotSupportedException (
"Object does not support invocation")
);
return null;
}
/// <summary>
/// Determines whether this instance is evaluates as true.
/// </summary>
/// <returns><c>true</c> if this instance evaluates as true; otherwise, <c>false</c>.</returns>
public virtual bool IsTrue ()
{
return true;
}
/// <summary>
/// Retrieves the length (Size) of this object. By default, this simply
/// attempts to call self.__len__ ();
/// </summary>
/// <param name="vm">Vm.</param>
public virtual IodineObject Len (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__len__")) {
return GetAttribute (vm, "__len__").Invoke (vm, new IodineObject[] { });
}
vm.RaiseException (new IodineAttributeNotFoundException ("__len__"));
return null;
}
/// <summary>
/// Called when entering a with statement
/// </summary>
/// <param name="vm">Vm.</param>
public virtual void Enter (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__enter__")) {
GetAttribute (vm, "__enter__").Invoke (vm, new IodineObject[] { });
}
}
/// <summary>
/// Called when leaving a with statement
/// </summary>
/// <param name="vm">Vm.</param>
public virtual void Exit (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__exit__")) {
GetAttribute (vm, "__exit__").Invoke (vm, new IodineObject[] { });
}
}
#region Unary Operator Stubs
/// <summary>
/// Unary negation operator (-)
/// </summary>
public virtual IodineObject Negate (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__negate__")) {
return GetAttribute (vm, "__negate__").Invoke (vm, new IodineObject[] { });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested unary operator has not been implemented")
);
return null;
}
/// <summary>
/// Unary bitwise inversion operator (~)
/// </summary>
public virtual IodineObject Not (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__invert__")) {
return GetAttribute (vm, "__invert__").Invoke (vm, new IodineObject[] { });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested unary operator has not been implemented")
);
return null;
}
/// <summary>
/// Unary not operator (!)
/// </summary>
public virtual IodineObject LogicalNot (VirtualMachine vm)
{
if (Attributes.ContainsKey ("__not__")) {
return GetAttribute (vm, "__not__").Invoke (vm, new IodineObject[] { });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested unary operator has not been implemented")
);
return null;
}
#endregion
#region Binary Operator Stubs
/// <summary>
/// Addition operator (+)
/// </summary>
public virtual IodineObject Add (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__add__")) {
return GetAttribute (vm, "__add__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// Subtraction operator (-)
/// </summary>
public virtual IodineObject Sub (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__sub__")) {
return GetAttribute (vm, "__sub__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// Division operator (/)
/// </summary>
public virtual IodineObject Div (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__div__")) {
return GetAttribute (vm, "__div__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// Modulo operator (%)
/// </summary>
public virtual IodineObject Mod (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__mod__")) {
return GetAttribute (vm, "__mod__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// Multiplication operator (*)
/// </summary>
public virtual IodineObject Mul (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__mul__")) {
return GetAttribute (vm, "__mul__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// Power operator (**)
/// </summary>
public virtual IodineObject Pow (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__pow__")) {
return GetAttribute (vm, "__pow__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// And operator (&)
/// </summary>
public virtual IodineObject And (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__and__")) {
return GetAttribute (vm, "__and__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
/// <summary>
/// Exclusive or operator (^)
/// </summary>
public virtual IodineObject Xor (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__xor__")) {
return GetAttribute (vm, "__xor__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject Or (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__or__")) {
return GetAttribute (vm, "__or__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject Equals (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__equals__")) {
return GetAttribute (vm, "__equals__").Invoke (vm, new IodineObject[] { right });
}
return IodineBool.Create (this == right);
}
public virtual IodineObject NotEquals (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__notequals__")) {
return GetAttribute (vm, "__notequals__").Invoke (vm, new IodineObject[] { right });
}
return IodineBool.Create (this != right);
}
public virtual IodineObject RightShift (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__rightshift__")) {
return GetAttribute (vm, "__rightshift__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject LeftShift (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__leftshit__")) {
return GetAttribute (vm, "__leftshit__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject LessThan (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__lt__")) {
return GetAttribute (vm, "__lt__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject GreaterThan (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__gt__")) {
return GetAttribute (vm, "__gt__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject LessThanOrEqual (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__lte__")) {
return GetAttribute (vm, "__lte__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject GreaterThanOrEqual (VirtualMachine vm, IodineObject right)
{
if (Attributes.ContainsKey ("__gte__")) {
return GetAttribute (vm, "__gte__").Invoke (vm, new IodineObject[] { right });
}
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject LogicalAnd (VirtualMachine vm, IodineObject right)
{
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject LogicalOr (VirtualMachine vm, IodineObject right)
{
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject ClosedRange (VirtualMachine vm, IodineObject right)
{
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
public virtual IodineObject HalfRange (VirtualMachine vm, IodineObject right)
{
vm.RaiseException (new IodineNotSupportedException (
"The requested binary operator has not been implemented")
);
return null;
}
#endregion
public virtual IodineObject GetIterator (VirtualMachine vm)
{
if (!Attributes.ContainsKey ("__iter__")) {
vm.RaiseException (new IodineNotSupportedException ("__iter__ has not been implemented"));
return null;
}
return GetAttribute ("__iter__").Invoke (vm, new IodineObject[]{ });
}
public virtual IodineObject IterGetCurrent (VirtualMachine vm)
{
if (!Attributes.ContainsKey ("__iterGetCurrent__")) {
vm.RaiseException (new IodineNotSupportedException ("__iterGetCurrent__ has not been implemented"));
return null;
}
return GetAttribute ("__iterGetCurrent__").Invoke (vm, new IodineObject[]{ });
}
public virtual bool IterMoveNext (VirtualMachine vm)
{
if (!Attributes.ContainsKey ("__iterMoveNext__")) {
vm.RaiseException (new IodineNotSupportedException ("__iterMoveNext__ has not been implemented"));
return false;
}
return GetAttribute ("__iterMoveNext__").Invoke (vm, new IodineObject[]{ }).IsTrue ();
}
public virtual void IterReset (VirtualMachine vm)
{
if (!Attributes.ContainsKey ("__iterReset__")) {
Console.WriteLine (this.ToString ());
vm.RaiseException (new IodineNotSupportedException ("__iterReset__ has not been implemented"));
return;
}
GetAttribute ("__iterReset__").Invoke (vm, new IodineObject[]{ });
}
public bool InstanceOf (IodineTypeDefinition def)
{
if (def is IodineTrait) {
var trait = def as IodineTrait;
return trait.HasTrait (this);
}
foreach (IodineContract contract in this.Interfaces) {
if (contract == def) {
return true;
}
}
IodineObject i = this;
while (i != null) {
if (i.TypeDef == def) {
return true;
}
i = i.Base;
}
return false;
}
public override int GetHashCode ()
{
int accum = 17;
unchecked {
foreach (IodineObject obj in Attributes.Values) {
if (obj != null) {
accum += 529 * obj.GetHashCode ();
}
}
}
return accum;
}
public override string ToString ()
{
return string.Format ("<{0}:0x{1:x8}>", TypeDef.Name, 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.Buffers;
using System.IO;
using System.Security.Cryptography.Asn1;
namespace System.Security.Cryptography
{
public abstract partial class ECDsa : AsymmetricAlgorithm
{
private static readonly string[] s_validOids =
{
Oids.EcPublicKey,
// ECDH and ECMQV are not valid in this context.
};
protected ECDsa() { }
public static new ECDsa Create(string algorithm)
{
if (algorithm == null)
{
throw new ArgumentNullException(nameof(algorithm));
}
return CryptoConfig.CreateFromName(algorithm) as ECDsa;
}
/// <summary>
/// When overridden in a derived class, exports the named or explicit ECParameters for an ECCurve.
/// If the curve has a name, the Curve property will contain named curve parameters otherwise it will contain explicit parameters.
/// </summary>
/// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param>
/// <returns></returns>
public virtual ECParameters ExportParameters(bool includePrivateParameters)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
/// <summary>
/// When overridden in a derived class, exports the explicit ECParameters for an ECCurve.
/// </summary>
/// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param>
/// <returns></returns>
public virtual ECParameters ExportExplicitParameters(bool includePrivateParameters)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
/// <summary>
/// When overridden in a derived class, imports the specified ECParameters.
/// </summary>
/// <param name="parameters">The curve parameters.</param>
public virtual void ImportParameters(ECParameters parameters)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
/// <summary>
/// When overridden in a derived class, generates a new public/private keypair for the specified curve.
/// </summary>
/// <param name="curve">The curve to use.</param>
public virtual void GenerateKey(ECCurve curve)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
return SignData(data, 0, data.Length, hashAlgorithm);
}
public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return SignHash(hash);
}
public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
}
if (TryHashData(data, destination, hashAlgorithm, out int hashLength) &&
TrySignHash(destination.Slice(0, hashLength), destination, out bytesWritten))
{
return true;
}
bytesWritten = 0;
return false;
}
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return SignHash(hash);
}
public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
return VerifyData(data, 0, data.Length, signature, hashAlgorithm);
}
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifyHash(hash, signature);
}
public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
}
for (int i = 256; ; i = checked(i * 2))
{
int hashLength = 0;
byte[] hash = ArrayPool<byte>.Shared.Rent(i);
try
{
if (TryHashData(data, hash, hashAlgorithm, out hashLength))
{
return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature);
}
}
finally
{
Array.Clear(hash, 0, hashLength);
ArrayPool<byte>.Shared.Return(hash);
}
}
}
public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return VerifyHash(hash, signature);
}
public abstract byte[] SignHash(byte[] hash);
public abstract bool VerifyHash(byte[] hash, byte[] signature);
public override string KeyExchangeAlgorithm => null;
public override string SignatureAlgorithm => "ECDsa";
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
}
protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
byte[] array = ArrayPool<byte>.Shared.Rent(data.Length);
try
{
data.CopyTo(array);
byte[] hash = HashData(array, 0, data.Length, hashAlgorithm);
if (hash.Length <= destination.Length)
{
new ReadOnlySpan<byte>(hash).CopyTo(destination);
bytesWritten = hash.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
finally
{
Array.Clear(array, 0, data.Length);
ArrayPool<byte>.Shared.Return(array);
}
}
public virtual bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten)
{
byte[] result = SignHash(hash.ToArray());
if (result.Length <= destination.Length)
{
new ReadOnlySpan<byte>(result).CopyTo(destination);
bytesWritten = result.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) =>
VerifyHash(hash.ToArray(), signature.ToArray());
public override unsafe bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
passwordBytes);
ECParameters ecParameters = ExportParameters(true);
fixed (byte* privPtr = ecParameters.D)
{
try
{
using (AsnWriter pkcs8PrivateKey = EccKeyFormatHelper.WritePkcs8PrivateKey(ecParameters))
using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
passwordBytes,
pkcs8PrivateKey,
pbeParameters))
{
return writer.TryEncode(destination, out bytesWritten);
}
}
finally
{
CryptographicOperations.ZeroMemory(ecParameters.D);
}
}
}
public override unsafe bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
ReadOnlySpan<byte>.Empty);
ECParameters ecParameters = ExportParameters(true);
fixed (byte* privPtr = ecParameters.D)
{
try
{
using (AsnWriter pkcs8PrivateKey = EccKeyFormatHelper.WritePkcs8PrivateKey(ecParameters))
using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
password,
pkcs8PrivateKey,
pbeParameters))
{
return writer.TryEncode(destination, out bytesWritten);
}
}
finally
{
CryptographicOperations.ZeroMemory(ecParameters.D);
}
}
}
public override unsafe bool TryExportPkcs8PrivateKey(
Span<byte> destination,
out int bytesWritten)
{
ECParameters ecParameters = ExportParameters(true);
fixed (byte* privPtr = ecParameters.D)
{
try
{
using (AsnWriter writer = EccKeyFormatHelper.WritePkcs8PrivateKey(ecParameters))
{
return writer.TryEncode(destination, out bytesWritten);
}
}
finally
{
CryptographicOperations.ZeroMemory(ecParameters.D);
}
}
}
public override bool TryExportSubjectPublicKeyInfo(
Span<byte> destination,
out int bytesWritten)
{
ECParameters ecParameters = ExportParameters(false);
using (AsnWriter writer = EccKeyFormatHelper.WriteSubjectPublicKeyInfo(ecParameters))
{
return writer.TryEncode(destination, out bytesWritten);
}
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
KeyFormatHelper.ReadEncryptedPkcs8<ECParameters>(
s_validOids,
source,
passwordBytes,
EccKeyFormatHelper.FromECPrivateKey,
out int localRead,
out ECParameters ret);
fixed (byte* privPin = ret.D)
{
try
{
ImportParameters(ret);
bytesRead = localRead;
}
finally
{
CryptographicOperations.ZeroMemory(ret.D);
}
}
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
KeyFormatHelper.ReadEncryptedPkcs8<ECParameters>(
s_validOids,
source,
password,
EccKeyFormatHelper.FromECPrivateKey,
out int localRead,
out ECParameters ret);
fixed (byte* privPin = ret.D)
{
try
{
ImportParameters(ret);
bytesRead = localRead;
}
finally
{
CryptographicOperations.ZeroMemory(ret.D);
}
}
}
public override unsafe void ImportPkcs8PrivateKey(
ReadOnlySpan<byte> source,
out int bytesRead)
{
KeyFormatHelper.ReadPkcs8<ECParameters>(
s_validOids,
source,
EccKeyFormatHelper.FromECPrivateKey,
out int localRead,
out ECParameters key);
fixed (byte* privPin = key.D)
{
try
{
ImportParameters(key);
bytesRead = localRead;
}
finally
{
CryptographicOperations.ZeroMemory(key.D);
}
}
}
public override void ImportSubjectPublicKeyInfo(
ReadOnlySpan<byte> source,
out int bytesRead)
{
KeyFormatHelper.ReadSubjectPublicKeyInfo<ECParameters>(
s_validOids,
source,
EccKeyFormatHelper.FromECPublicKey,
out int localRead,
out ECParameters key);
ImportParameters(key);
bytesRead = localRead;
}
public virtual unsafe void ImportECPrivateKey(ReadOnlySpan<byte> source, out int bytesRead)
{
ECParameters ecParameters = EccKeyFormatHelper.FromECPrivateKey(source, out int localRead);
fixed (byte* privPin = ecParameters.D)
{
try
{
ImportParameters(ecParameters);
bytesRead = localRead;
}
finally
{
CryptographicOperations.ZeroMemory(ecParameters.D);
}
}
}
public virtual unsafe byte[] ExportECPrivateKey()
{
ECParameters ecParameters = ExportParameters(true);
fixed (byte* privPin = ecParameters.D)
{
try
{
using (AsnWriter writer = EccKeyFormatHelper.WriteECPrivateKey(ecParameters))
{
return writer.Encode();
}
}
finally
{
CryptographicOperations.ZeroMemory(ecParameters.D);
}
}
}
public virtual unsafe bool TryExportECPrivateKey(Span<byte> destination, out int bytesWritten)
{
ECParameters ecParameters = ExportParameters(true);
fixed (byte* privPin = ecParameters.D)
{
try
{
using (AsnWriter writer = EccKeyFormatHelper.WriteECPrivateKey(ecParameters))
{
return writer.TryEncode(destination, out bytesWritten);
}
}
finally
{
CryptographicOperations.ZeroMemory(ecParameters.D);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using Microsoft.PowerShell;
// FxCop suppressions for resource strings:
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "Credential.resources", MessageId = "Cred")]
namespace System.Management.Automation
{
/// <summary>
/// Defines the valid types of MSH credentials. Used by PromptForCredential calls.
/// </summary>
[Flags]
public enum PSCredentialTypes
{
/// <summary>
/// Generic credentials.
/// </summary>
Generic = 1,
/// <summary>
/// Credentials valid for a domain.
/// </summary>
Domain = 2,
/// <summary>
/// Default credentials.
/// </summary>
Default = Generic | Domain
}
/// <summary>
/// Defines the options available when prompting for credentials. Used
/// by PromptForCredential calls.
/// </summary>
[Flags]
public enum PSCredentialUIOptions
{
/// <summary>
/// Validates the username, but not its existence
/// or correctness.
/// </summary>
Default = ValidateUserNameSyntax,
/// <summary>
/// Performs no validation.
/// </summary>
None = 0,
/// <summary>
/// Validates the username, but not its existence.
/// or correctness.
/// </summary>
ValidateUserNameSyntax,
/// <summary>
/// Always prompt, even if a persisted credential was available.
/// </summary>
AlwaysPrompt,
/// <summary>
/// Username is read-only, and the user may not modify it.
/// </summary>
ReadOnlyUserName
}
/// <summary>
/// Declare a delegate which returns the encryption key and initialization vector for symmetric encryption algorithm.
/// </summary>
/// <param name="context">The streaming context, which contains the serialization context.</param>
/// <param name="key">Symmetric encryption key.</param>
/// <param name="iv">Symmetric encryption initialization vector.</param>
/// <returns></returns>
public delegate bool GetSymmetricEncryptionKey(StreamingContext context, out byte[] key, out byte[] iv);
/// <summary>
/// Offers a centralized way to manage usernames, passwords, and
/// credentials.
/// </summary>
[Serializable()]
public sealed class PSCredential : ISerializable
{
/// <summary>
/// Gets or sets a delegate which returns the encryption key and initialization vector for symmetric encryption algorithm.
/// </summary>
public static GetSymmetricEncryptionKey GetSymmetricEncryptionKeyDelegate
{
get
{
return s_delegate;
}
set
{
s_delegate = value;
}
}
private static GetSymmetricEncryptionKey s_delegate = null;
/// <summary>
/// GetObjectData.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
return;
// serialize the secure string
string safePassword = string.Empty;
if (_password != null && _password.Length > 0)
{
byte[] key;
byte[] iv;
if (s_delegate != null && s_delegate(context, out key, out iv))
{
safePassword = SecureStringHelper.Encrypt(_password, key, iv).EncryptedData;
}
else
{
try
{
safePassword = SecureStringHelper.Protect(_password);
}
catch (CryptographicException cryptographicException)
{
throw PSTraceSource.NewInvalidOperationException(cryptographicException, Credential.CredentialDisallowed);
}
}
}
info.AddValue("UserName", _userName);
info.AddValue("Password", safePassword);
}
/// <summary>
/// PSCredential.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
private PSCredential(SerializationInfo info, StreamingContext context)
{
if (info == null)
return;
_userName = (string)info.GetValue("UserName", typeof(string));
// deserialize to secure string
string safePassword = (string)info.GetValue("Password", typeof(string));
if (safePassword == string.Empty)
{
_password = new SecureString();
}
else
{
byte[] key;
byte[] iv;
if (s_delegate != null && s_delegate(context, out key, out iv))
{
_password = SecureStringHelper.Decrypt(safePassword, key, iv);
}
else
{
_password = SecureStringHelper.Unprotect(safePassword);
}
}
}
private readonly string _userName;
private readonly SecureString _password;
/// <summary>
/// User's name.
/// </summary>
public string UserName
{
get { return _userName; }
}
/// <summary>
/// User's password.
/// </summary>
public SecureString Password
{
get { return _password; }
}
/// <summary>
/// Initializes a new instance of the PSCredential class with a
/// username and password.
/// </summary>
/// <param name="userName">User's name.</param>
/// <param name="password">User's password.</param>
public PSCredential(string userName, SecureString password)
{
Utils.CheckArgForNullOrEmpty(userName, "userName");
Utils.CheckArgForNull(password, "password");
_userName = userName;
_password = password;
}
/// <summary>
/// Initializes a new instance of the PSCredential class with a
/// username and password from PSObject.
/// </summary>
/// <param name="pso"></param>
public PSCredential(PSObject pso)
{
if (pso == null)
throw PSTraceSource.NewArgumentNullException(nameof(pso));
if (pso.Properties["UserName"] != null)
{
_userName = (string)pso.Properties["UserName"].Value;
if (pso.Properties["Password"] != null)
_password = (SecureString)pso.Properties["Password"].Value;
}
}
/// <summary>
/// Initializes a new instance of the PSCredential class.
/// </summary>
private PSCredential()
{
}
private NetworkCredential _netCred;
/// <summary>
/// Returns an equivalent NetworkCredential object for this
/// PSCredential.
///
/// A null is returned if
/// -- current object has not been initialized
/// -- current creds are not compatible with NetworkCredential
/// (such as smart card creds or cert creds)
/// </summary>
/// <returns>
/// null if the current object has not been initialized.
/// null if the current credentials are incompatible with
/// a NetworkCredential -- such as smart card credentials.
/// the appropriate network credential for this PSCredential otherwise.
/// </returns>
public NetworkCredential GetNetworkCredential()
{
if (_netCred == null)
{
string user = null;
string domain = null;
if (IsValidUserName(_userName, out user, out domain))
{
_netCred = new NetworkCredential(user, _password, domain);
}
}
return _netCred;
}
/// <summary>
/// Provides an explicit cast to get a NetworkCredential
/// from this PSCredential.
/// </summary>
/// <param name="credential">PSCredential to convert.</param>
/// <returns>
/// null if the current object has not been initialized.
/// null if the current credentials are incompatible with
/// a NetworkCredential -- such as smart card credentials.
/// the appropriate network credential for this PSCredential otherwise.
/// </returns>
public static explicit operator NetworkCredential(PSCredential credential)
{
#pragma warning disable 56506
if (credential == null)
{
throw PSTraceSource.NewArgumentNullException("credential");
}
return credential.GetNetworkCredential();
#pragma warning restore 56506
}
/// <summary>
/// Gets an empty PSCredential. This is an PSCredential with both UserName
/// and Password initialized to null.
/// </summary>
public static PSCredential Empty
{
get
{
return s_empty;
}
}
private static readonly PSCredential s_empty = new PSCredential();
/// <summary>
/// Parse a string that represents a fully qualified username
/// to verify that it is syntactically valid. We only support
/// two formats:
/// -- domain\user
/// -- user@domain
///
/// for any other format, we simply treat the entire string
/// as user name and set domain name to "".
/// </summary>
private static bool IsValidUserName(string input,
out string user,
out string domain)
{
if (string.IsNullOrEmpty(input))
{
user = domain = null;
return false;
}
SplitUserDomain(input, out user, out domain);
if ((user == null) ||
(domain == null) ||
(user.Length == 0))
{
// UserName is the public property of Credential object. Use this as
// parameter name in error
// See bug NTRAID#Windows OS Bugs-1106386-2005/03/25-hiteshr
throw PSTraceSource.NewArgumentException("UserName", Credential.InvalidUserNameFormat);
}
return true;
}
/// <summary>
/// Split a given string into its user and domain
/// components. Supported formats are:
/// -- domain\user
/// -- user@domain
///
/// With any other format, the entire input is treated as user
/// name and domain is set to "".
///
/// In any case, the function does not check if the split string
/// are really valid as user or domain names.
/// </summary>
private static void SplitUserDomain(string input,
out string user,
out string domain)
{
int i = 0;
user = null;
domain = null;
if ((i = input.IndexOf('\\')) >= 0)
{
user = input.Substring(i + 1);
domain = input.Substring(0, i);
return;
}
// In V1 and V2, we had a bug where email addresses (i.e. [email protected])
// were being split into Username=Foo, Domain=bar.com.
//
// This was breaking apps (i.e.: Exchange), so we need to make
// Username = [email protected] if the domain has a dot in it (since
// domains can't have dots).
//
// HOWEVER, there was a workaround for this bug in v1 and v2, where the
// cred could be entered as "[email protected]@bar.com" - making:
// Username = [email protected], Domain = bar.com
//
// We need to keep the behaviour in this case.
i = input.LastIndexOf('@');
if (
(i >= 0) &&
(
(input.LastIndexOf('.') < i) ||
(input.IndexOf('@') != i)
)
)
{
domain = input.Substring(i + 1);
user = input.Substring(0, i);
}
else
{
user = input;
domain = string.Empty;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace KERBALISM
{
public enum UnlinkedCtrl
{
none, // disable all controls
limited, // disable all controls except full/zero throttle and staging
full // do not disable controls at all
}
public static class Settings
{
private static string MODS_INCOMPATIBLE = "TacLifeSupport,Snacks,KolonyTools,USILifeSupport";
private static string MODS_WARNING = "RemoteTech,CommNetAntennasInfo";
private static string MODS_SCIENCE = "KEI,[x] Science!";
public static void Parse()
{
var kerbalismConfigNodes = GameDatabase.Instance.GetConfigs("Kerbalism");
if (kerbalismConfigNodes.Length < 1) return;
ConfigNode cfg = kerbalismConfigNodes[0].config;
// profile used
Profile = Lib.ConfigValue(cfg, "Profile", string.Empty);
// user-defined features
Reliability = Lib.ConfigValue(cfg, "Reliability", false);
Deploy = Lib.ConfigValue(cfg, "Deploy", false);
Science = Lib.ConfigValue(cfg, "Science", false);
SpaceWeather = Lib.ConfigValue(cfg, "SpaceWeather", false);
Automation = Lib.ConfigValue(cfg, "Automation", false);
// pressure
PressureFactor = Lib.ConfigValue(cfg, "PressureFactor", 10.0);
PressureThreshold = Lib.ConfigValue(cfg, "PressureThreshold", 0.9);
// poisoning
PoisoningFactor = Lib.ConfigValue(cfg, "PoisoningFactor", 0.0);
PoisoningThreshold = Lib.ConfigValue(cfg, "PoisoningThreshold", 0.02);
// signal
UnlinkedControl = Lib.ConfigEnum(cfg, "UnlinkedControl", UnlinkedCtrl.none);
DataRateMinimumBitsPerSecond = Lib.ConfigValue(cfg, "DataRateMinimumBitsPerSecond", 1.0f);
DataRateDampingExponent = Lib.ConfigValue(cfg, "DataRateDampingExponent", 6.0f);
DataRateDampingExponentRT = Lib.ConfigValue(cfg, "DataRateDampingExponentRT", 6.0f);
DataRateSurfaceExperiment = Lib.ConfigValue(cfg, "DataRateSurfaceExperiment", 0.3f);
TransmitterActiveEcFactor = Lib.ConfigValue(cfg, "TransmitterActiveEcFactor", 1.5);
TransmitterPassiveEcFactor = Lib.ConfigValue(cfg, "TransmitterPassiveEcFactor", 0.04);
// science
ScienceDialog = Lib.ConfigValue(cfg, "ScienceDialog", true);
AsteroidSampleMassPerMB = Lib.ConfigValue(cfg, "AsteroidSampleMassPerMB", 0.00002);
// reliability
QualityScale = Lib.ConfigValue(cfg, "QualityScale", 4.0);
// crew level
LaboratoryCrewLevelBonus = Lib.ConfigValue(cfg, "LaboratoryCrewLevelBonus", 0.2);
MaxLaborartoryBonus = Lib.ConfigValue(cfg, "MaxLaborartoryBonus", 2.0);
HarvesterCrewLevelBonus = Lib.ConfigValue(cfg, "HarvesterCrewLevelBonus", 0.1);
MaxHarvesterBonus = Lib.ConfigValue(cfg, "MaxHarvesterBonus", 2.0);
// misc
EnforceCoherency = Lib.ConfigValue(cfg, "EnforceCoherency", true);
HeadLampsCost = Lib.ConfigValue(cfg, "HeadLampsCost", 0.002);
LowQualityRendering = Lib.ConfigValue(cfg, "LowQualityRendering", false);
UIScale = Lib.ConfigValue(cfg, "UIScale", 1.0f);
UIPanelWidthScale = Lib.ConfigValue(cfg, "UIPanelWidthScale", 1.0f);
KerbalDeathReputationPenalty = Lib.ConfigValue(cfg, "KerbalDeathReputationPenalty", 100.0f);
KerbalBreakdownReputationPenalty = Lib.ConfigValue(cfg, "KerbalBreakdownReputationPenalty", 30f);
// save game settings presets
LifeSupportAtmoLoss = Lib.ConfigValue(cfg, "LifeSupportAtmoLoss", 50);
LifeSupportSurvivalTemperature = Lib.ConfigValue(cfg, "LifeSupportSurvivalTemperature", 295);
LifeSupportSurvivalRange = Lib.ConfigValue(cfg, "LifeSupportSurvivalRange", 5);
ComfortLivingSpace = Lib.ConfigValue(cfg, "ComfortLivingSpace", 20);
ComfortFirmGround = Lib.ConfigValue(cfg, "ComfortFirmGround", 0.1f);
ComfortExercise = Lib.ConfigValue(cfg, "ComfortExercise", 0.2f);
ComfortNotAlone = Lib.ConfigValue(cfg, "ComfortNotAlone", 0.3f);
ComfortCallHome = Lib.ConfigValue(cfg, "ComfortCallHome", 0.2f);
ComfortPanorama = Lib.ConfigValue(cfg, "ComfortPanorama", 0.1f);
ComfortPlants = Lib.ConfigValue(cfg, "ComfortPlants", 0.1f);
StormFrequency = Lib.ConfigValue(cfg, "StormFrequency", 0.4f);
StormDurationHours = Lib.ConfigValue(cfg, "StormDurationHours", 2);
StormEjectionSpeed = Lib.ConfigValue(cfg, "StormEjectionSpeed", 0.33f);
ShieldingEfficiency = Lib.ConfigValue(cfg, "ShieldingEfficiency", 0.9f);
StormRadiation = Lib.ConfigValue(cfg, "StormRadiation", 5.0f);
ExternRadiation = Lib.ConfigValue(cfg, "ExternRadiation", 0.04f);
RadiationInSievert = Lib.ConfigValue(cfg, "RadiationInSievert", false);
ModsIncompatible = Lib.ConfigValue(cfg, "ModsIncompatible", MODS_INCOMPATIBLE);
ModsWarning = Lib.ConfigValue(cfg, "ModsWarning", MODS_WARNING);
ModsScience = Lib.ConfigValue(cfg, "ModsScience", MODS_SCIENCE);
CheckForCRP = Lib.ConfigValue(cfg, "CheckForCRP", true);
UseSamplingSunFactor = Lib.ConfigValue(cfg, "UseSamplingSunFactor", false);
// debug / logging
VolumeAndSurfaceLogging = Lib.ConfigValue(cfg, "VolumeAndSurfaceLogging", false);
loaded = true;
}
// profile used
public static string Profile;
internal static List<string> IncompatibleMods()
{
var result = Lib.Tokenize(ModsIncompatible.ToLower(), ',');
return result;
}
internal static List<string> WarningMods()
{
var result = Lib.Tokenize(ModsWarning.ToLower(), ',');
if (Features.Science) result.AddRange(Lib.Tokenize(ModsScience.ToLower(), ','));
return result;
}
// name of profile to use, if any
// user-defined features
public static bool Reliability; // component malfunctions and critical failures
public static bool Deploy; // add EC cost to keep module working/animation, add EC cost to Extend\Retract
public static bool Science; // science data storage, transmission and analysis
public static bool SpaceWeather; // coronal mass ejections
public static bool Automation; // control vessel components using scripts
// pressure
public static double PressureFactor; // pressurized modifier value for vessels below the threshold
public static double PressureThreshold; // level of atmosphere resource that determine pressurized status
// poisoning
public static double PoisoningFactor; // poisoning modifier value for vessels below threshold
public static double PoisoningThreshold; // level of waste atmosphere resource that determine co2 poisoning status
// signal
public static UnlinkedCtrl UnlinkedControl; // available control for unlinked vessels: 'none', 'limited' or 'full'
public static float DataRateMinimumBitsPerSecond; // as long as there is a control connection, the science data rate will never go below this.
public static float DataRateDampingExponent; // how much to damp data rate. stock is equivalent to 1, 6 gives nice values, RSS would use 4
public static float DataRateDampingExponentRT; // same for RemoteTech
public static float DataRateSurfaceExperiment; // transmission rate for surface experiments (Serenity DLC)
public static double TransmitterActiveEcFactor; // how much of the configured EC rate is used while transmitter is active
public static double TransmitterPassiveEcFactor; // how much of the configured EC rate is used while transmitter is passive
// science
public static bool ScienceDialog; // keep showing the stock science dialog
public static double AsteroidSampleMassPerMB; // When taking an asteroid sample, mass (in t) per MB of sample (baseValue * dataScale). default of 0.00002 => 34 Kg in stock
// reliability
public static double QualityScale; // scale applied to MTBF for high-quality components
// crew level
public static double LaboratoryCrewLevelBonus; // factor for laboratory rate speed gain per crew level above minimum
public static double MaxLaborartoryBonus; // max bonus to be gained by having skilled crew on a laboratory
public static double HarvesterCrewLevelBonus; // factor for harvester speed gain per engineer level above minimum
public static double MaxHarvesterBonus; // max bonus to be gained by having skilled engineers on a mining rig
// misc
public static bool EnforceCoherency; // detect and avoid issues at high timewarp in external modules
public static double HeadLampsCost; // EC/s cost if eva headlamps are on
public static bool LowQualityRendering; // use less particles to render the magnetic fields
public static float UIScale; // scale UI elements by this factor, relative to KSP scaling settings, useful for high PPI screens
public static float UIPanelWidthScale; // scale UI Panel Width by this factor, relative to KSP scaling settings, useful for high PPI screens
public static float KerbalDeathReputationPenalty; // Reputation penalty when Kerbals dies
public static float KerbalBreakdownReputationPenalty; // Reputation removed when Kerbals loose their marbles in space
// presets for save game preferences
public static int LifeSupportAtmoLoss;
public static int LifeSupportSurvivalTemperature;
public static int LifeSupportSurvivalRange;
public static int ComfortLivingSpace;
public static float ComfortFirmGround;
public static float ComfortExercise;
public static float ComfortNotAlone;
public static float ComfortCallHome;
public static float ComfortPanorama;
public static float ComfortPlants;
public static float StormFrequency;
public static int StormDurationHours;
public static float StormEjectionSpeed;
public static float ShieldingEfficiency;
public static float StormRadiation;
public static float ExternRadiation;
public static bool RadiationInSievert; // use Sievert iso. rad
// sanity check settings
public static string ModsIncompatible;
public static string ModsWarning;
public static string ModsScience;
public static bool CheckForCRP;
public static bool UseSamplingSunFactor;
// debug / logging
public static bool VolumeAndSurfaceLogging;
public static bool loaded { get; private set; } = false;
}
} // KERBALISM
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Security.Cert.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 Javax.Security.Cert
{
/// <summary>
/// <para>Abstract class to represent identity certificates. It represents a way to verify the binding of a Principal and its public key. Examples are X.509, PGP, and SDSI. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/Certificate", AccessFlags = 1057)]
public abstract partial class Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Compares the argument to this Certificate. If both have the same bytes they are assumed to be equal.</para><para><para>hashCode </para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if <c> obj </c> is the same as this <c> Certificate </c> , <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns an integer hash code for the receiver. Any two objects which return <code>true</code> when passed to <code>equals</code> must answer the same value for this method.</para><para><para>equals </para></para>
/// </summary>
/// <returns>
/// <para>the receiver's hash </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key. Uses the signature algorithm given by the provider.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key, string sigProvider) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a string containing a concise, human-readable description of the receiver.</para><para></para>
/// </summary>
/// <returns>
/// <para>a printable representation for the receiver. </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1025)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
public abstract global::Java.Security.IPublicKey GetPublicKey() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
public byte[] Encoded
{
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetEncoded(); }
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
public global::Java.Security.IPublicKey PublicKey
{
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
get{ return GetPublicKey(); }
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> has expired. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateExpiredException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateExpiredException", AccessFlags = 33)]
public partial class CertificateExpiredException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateExpiredException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateExpiredException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract base class for X.509 certificates. </para><para>This represents a standard way for accessing the attributes of X.509 v1 certificates. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/X509Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/X509Certificate", AccessFlags = 1057)]
public abstract partial class X509Certificate : global::Javax.Security.Cert.Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public X509Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "(Ljava/io/InputStream;)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(global::Java.Io.InputStream inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(sbyte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25, IgnoreFromJava = true)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(byte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Checks whether the certificate is currently valid. </para><para>The validity defined in ASN.1:</para><para><pre>
/// validity Validity
///
/// Validity ::= SEQUENCE {
/// notBefore CertificateValidityDate,
/// notAfter CertificateValidityDate }
///
/// CertificateValidityDate ::= CHOICE {
/// utcTime UTCTime,
/// generalTime GeneralizedTime }
/// </pre></para><para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "()V", AccessFlags = 1025)]
public abstract void CheckValidity() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether the certificate is valid at the specified date.</para><para><para>checkValidity() </para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "(Ljava/util/Date;)V", AccessFlags = 1025)]
public abstract void CheckValidity(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
public abstract int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
public abstract global::Java.Math.BigInteger GetSerialNumber() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetIssuerDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetSubjectDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotBefore() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotAfter() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgOID() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
public int Version
{
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
get{ return GetVersion(); }
}
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
public global::Java.Math.BigInteger SerialNumber
{
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
get{ return GetSerialNumber(); }
}
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
public global::Java.Security.IPrincipal IssuerDN
{
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetIssuerDN(); }
}
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
public global::Java.Security.IPrincipal SubjectDN
{
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetSubjectDN(); }
}
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
public global::Java.Util.Date NotBefore
{
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotBefore(); }
}
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
public global::Java.Util.Date NotAfter
{
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotAfter(); }
}
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
public string SigAlgName
{
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgName(); }
}
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
public string SigAlgOID
{
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgOID(); }
}
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
public byte[] SigAlgParams
{
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetSigAlgParams(); }
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> can not be parsed. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateParsingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateParsingException", AccessFlags = 33)]
public partial class CertificateParsingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateParsingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateParsingException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The base class for all <c> Certificate </c> related exceptions. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateException", AccessFlags = 33)]
public partial class CertificateException : global::System.Exception
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when an error occurs while a <c> Certificate </c> is being encoded. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateEncodingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateEncodingException", AccessFlags = 33)]
public partial class CertificateEncodingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateEncodingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateEncodingException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> is not yet valid. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateNotYetValidException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateNotYetValidException", AccessFlags = 33)]
public partial class CertificateNotYetValidException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateNotYetValidException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateNotYetValidException() /* MethodBuilder.Create */
{
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using OpenLiveWriter.CoreServices.ResourceDownloading;
using OpenLiveWriter.Localization;
using System.Threading;
namespace OpenLiveWriter.CoreServices.Marketization
{
/// <summary>
/// Summary description for MarketizationOptions.
/// </summary>
public class MarketizationOptions
{
//note: if you add something here, make sure you also add it to the switch statement in this file
//else your feature will not get read in!
public enum Feature
{
Maps,
TeamBlog,
TermsOfUse,
Privacy,
Help,
FTPHelp,
WLGallery,
LiveClipboard,
BlogProviders,
VideoProviders,
TagProviders,
VideoCopyright,
YouTubeVideo,
AllowMultiSelectImage,
Wordpress
}
// TODO: Stop hardcoding feature parameters throughout the code base.
public static class WordpressParameters
{
public const string SignupUrl = "SignupUrl";
public const string LanguageMapping = "LanguageMapping";
}
private static readonly Hashtable _masterOptions = new Hashtable();
private static readonly Hashtable _marketOptions = new Hashtable();
static MarketizationOptions()
{
_masterOptions = CabbedXmlResourceFileDownloader.Instance.ProcessLocalResource(
Assembly.GetExecutingAssembly(),
"Marketization.Master.xml",
ReadMarketizationOptionsMaster
) as Hashtable;
_marketOptions = CabbedXmlResourceFileDownloader.Instance.ProcessLocalResource(
Assembly.GetExecutingAssembly(),
"Marketization.Markets.xml",
ReadMarketizationOptionsMarket
) as Hashtable;
}
public static bool IsFeatureEnabled(Feature name)
{
if (_marketOptions.ContainsKey(name))
return ((FeatureDescription)_marketOptions[name]).Enabled;
if (_masterOptions.ContainsKey(name))
return ((FeatureDescription)_masterOptions[name]).Enabled;
Debug.Assert(false, name + " not found in market or master hashtable");
return false;
}
public static string GetFeatureParameter(Feature name, string parameter)
{
string result;
result = ContainsFeatureParam(_marketOptions, name, parameter);
if (null != result) return result;
result = ContainsFeatureParam(_masterOptions, name, parameter);
if (null != result) return result;
Debug.Assert(false, name + " not found in market or master hashtable");
return null;
}
private static string ContainsFeatureParam(Hashtable table, Feature name, string parameter)
{
if (table.ContainsKey(name))
{
//only return this market's param if it exists
return ((FeatureDescription)table[name]).GetParamValue(parameter);
}
return null;
}
private static object ReadMarketizationOptionsMaster(XmlDocument marketizationXml)
{
return ReadMarketizationOptions(marketizationXml, "default");
}
private static object ReadMarketizationOptionsMarket(XmlDocument marketizationXml)
{
return ReadMarketizationOptions(marketizationXml, CultureInfo.CurrentUICulture.Name.ToLower(CultureInfo.InvariantCulture));
}
private static object ReadMarketizationOptions(XmlDocument providersDocument, string market)
{
//note: this has the effect of wiping out any previous settings, since a new hashtable is created
Hashtable features = new Hashtable();
XmlNode featuresNode = providersDocument.SelectSingleNode("//features");
if (featuresNode == null)
throw new Exception("Invalid marketizationXml.xml file detected");
string selectionXpath = String.Format(CultureInfo.InvariantCulture, "//features/market[@name='{0}']/feature", market);
XmlNodeList featureNodes = providersDocument.SelectNodes(selectionXpath);
foreach (XmlNode featureNode in featureNodes)
ProcessFeatureXml(featureNode, features);
return features;
}
public static void ProcessFeatureXml(XmlNode featureNode, Hashtable features)
{
FeatureDescription description = new FeatureDescription();
string feature = NodeText(featureNode.Attributes["name"]);
Feature thisFeature;
switch (feature)
{
case "Writer Blog": thisFeature = Feature.TeamBlog; break;
case "Insert Maps": thisFeature = Feature.Maps; break;
case "Terms of Use": thisFeature = Feature.TermsOfUse; break;
case "Privacy": thisFeature = Feature.Privacy; break;
case "Help": thisFeature = Feature.Help; break;
case "FTP Help": thisFeature = Feature.FTPHelp; break;
case "Gallery": thisFeature = Feature.WLGallery; break;
case "Live Clipboard": thisFeature = Feature.LiveClipboard; break;
case "Blog Providers": thisFeature = Feature.BlogProviders; break;
case "Insert Video": thisFeature = Feature.VideoProviders; break;
case "Tag Providers": thisFeature = Feature.TagProviders; break;
case "Video Copyright Link": thisFeature = Feature.VideoCopyright; break;
case "YouTube Video": thisFeature = Feature.YouTubeVideo; break;
case "Allow Multiselect Images": thisFeature = Feature.AllowMultiSelectImage; break;
case "Wordpress": thisFeature = Feature.Wordpress; break;
default: return;
}
string enabled = NodeText(featureNode.Attributes["enabled"]);
description.Enabled = (enabled == "true") ? true : false;
//check for parameters
XmlNodeList parameters = featureNode.SelectNodes("parameter");
foreach (XmlNode param in parameters)
{
description.AddParam(param.Attributes["name"].Value, param.Attributes["value"].Value);
}
if (features.ContainsKey(thisFeature))
features[thisFeature] = description;
else
features.Add(thisFeature, description);
}
private static string NodeText(XmlNode node)
{
if (node != null)
return node.InnerText.Trim();
else
return String.Empty;
}
private class FeatureDescription
{
private bool _enabled = false;
private readonly Hashtable _parameters = new Hashtable();
public void AddParam(string paramName, string paramValue)
{
if (_parameters.Contains(paramName))
_parameters[paramName] = paramValue;
else
_parameters.Add(paramName, paramValue);
}
public bool Enabled
{
get
{
return _enabled;
}
set
{
_enabled = value;
}
}
public string GetParamValue(string paramName)
{
if (_parameters.Contains(paramName))
return (string)_parameters[paramName];
return null;
}
}
}
public sealed class WordpressSettings
{
private WordpressSettings()
{
CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;
string map = MarketizationOptions.GetFeatureParameter(MarketizationOptions.Feature.Wordpress, MarketizationOptions.WordpressParameters.LanguageMapping);
string mapTo = null;
if (!string.IsNullOrEmpty(map))
{
string[] mapSplit = map.Split(',');
for (int i = 1; i < mapSplit.Length; i += 2)
{
// in our mapping table (markets.xml), if the "from" entry is longer than two chars, we compare it against
// the current UI culture *name*, not the current UI culture *TwoLetterISOLanguageName*.
string mapFrom = mapSplit[i - 1].Trim();
string currentCultureIdOrLanguage = mapFrom.Length > 2 ? currentCulture.Name : currentCulture.TwoLetterISOLanguageName;
if (string.Compare(mapFrom, currentCultureIdOrLanguage, StringComparison.OrdinalIgnoreCase) == 0)
{
mapTo = mapSplit[i].Trim();
break;
}
}
}
// If no mapping, by default we use the current culture's two-letter-ISO-langauge-name.
if (mapTo == null)
{
mapTo = currentCulture.TwoLetterISOLanguageName;
}
string url = string.Format(CultureInfo.InvariantCulture, MarketizationOptions.GetFeatureParameter(MarketizationOptions.Feature.Wordpress, MarketizationOptions.WordpressParameters.SignupUrl), mapTo);
this.uri = new Uri(url);
}
private Uri uri;
public Uri Uri
{
get { return uri; }
}
private static WordpressSettings value;
public static WordpressSettings Value
{
get
{
if (WordpressSettings.value == null)
{
WordpressSettings.value = new WordpressSettings();
}
return WordpressSettings.value;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BlockBasedBlobReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
internal sealed class BlockBasedBlobReader : TransferReaderWriterBase
{
/// <summary>
/// Instance to represent source location.
/// </summary>
private AzureBlobLocation sourceLocation;
/// <summary>
/// Block/append blob instance to be downloaded from.
/// </summary>
private CloudBlob sourceBlob;
/// <summary>
/// Window to record unfinished chunks to be retransferred again.
/// </summary>
private Queue<long> lastTransferWindow;
private TransferJob transferJob;
/// <summary>
/// Value to indicate whether the transfer is finished.
/// This is to tell the caller that the reader can be disposed,
/// Both error happened or completed will be treated to be finished.
/// </summary>
private volatile bool isFinished = false;
private volatile bool hasWork;
private CountdownEvent downloadCountdownEvent;
public BlockBasedBlobReader(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.transferJob = this.SharedTransferData.TransferJob;
this.sourceLocation = this.transferJob.Source as AzureBlobLocation;
this.sourceBlob = this.sourceLocation.Blob;
Debug.Assert(
(this.sourceBlob is CloudBlockBlob) ||(this.sourceBlob is CloudAppendBlob),
"Initializing BlockBlobReader while source location is not a block blob or an append blob.");
this.hasWork = true;
}
public override bool IsFinished
{
get
{
return this.isFinished;
}
}
public override bool HasWork
{
get
{
return this.hasWork;
}
}
public override async Task DoWorkInternalAsync()
{
try
{
if (!this.PreProcessed)
{
await this.FetchAttributeAsync();
}
else
{
await this.DownloadBlockBlobAsync();
}
}
catch (Exception)
{
this.isFinished = true;
throw;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (null != this.downloadCountdownEvent)
{
this.downloadCountdownEvent.Dispose();
this.downloadCountdownEvent = null;
}
}
}
private async Task FetchAttributeAsync()
{
this.hasWork = false;
this.NotifyStarting();
AccessCondition accessCondition = Utils.GenerateIfMatchConditionWithCustomerCondition(
this.sourceLocation.ETag,
this.sourceLocation.AccessCondition,
this.sourceLocation.CheckedAccessCondition);
try
{
await this.sourceBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.sourceLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception ex) when (ex is StorageException || ex.InnerException is StorageException)
{
var e = ex as StorageException ?? ex.InnerException as StorageException;
#else
catch (StorageException e)
{
#endif
if (null != e.RequestInformation &&
e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
throw new InvalidOperationException(Resources.SourceBlobDoesNotExistException);
}
else
{
throw;
}
}
this.sourceLocation.CheckedAccessCondition = true;
if (this.sourceBlob.Properties.BlobType == BlobType.Unspecified)
{
throw new InvalidOperationException(Resources.FailedToGetBlobTypeException);
}
if (string.IsNullOrEmpty(this.sourceLocation.ETag))
{
if (0 != this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset)
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.sourceLocation.ETag = this.sourceBlob.Properties.ETag;
}
else if ((this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset > this.sourceBlob.Properties.Length)
|| (this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset < 0))
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.SharedTransferData.DisableContentMD5Validation =
null != this.sourceLocation.BlobRequestOptions ?
this.sourceLocation.BlobRequestOptions.DisableContentMD5Validation.HasValue ?
this.sourceLocation.BlobRequestOptions.DisableContentMD5Validation.Value : false : false;
this.SharedTransferData.TotalLength = this.sourceBlob.Properties.Length;
this.SharedTransferData.Attributes = Utils.GenerateAttributes(this.sourceBlob);
if ((0 == this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset)
&& (null != this.SharedTransferData.TransferJob.CheckPoint.TransferWindow)
&& (0 != this.SharedTransferData.TransferJob.CheckPoint.TransferWindow.Count))
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.lastTransferWindow = new Queue<long>(this.SharedTransferData.TransferJob.CheckPoint.TransferWindow);
int downloadCount = this.lastTransferWindow.Count +
(int)Math.Ceiling((double)(this.sourceBlob.Properties.Length - this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset) / this.Scheduler.TransferOptions.BlockSize);
if (0 == downloadCount)
{
this.isFinished = true;
this.PreProcessed = true;
this.hasWork = true;
}
else
{
this.downloadCountdownEvent = new CountdownEvent(downloadCount);
this.PreProcessed = true;
this.hasWork = true;
}
}
private async Task DownloadBlockBlobAsync()
{
this.hasWork = false;
byte[] memoryBuffer = this.Scheduler.MemoryManager.RequireBuffer();
if (null != memoryBuffer)
{
long startOffset = 0;
if (!this.IsTransferWindowEmpty())
{
startOffset = this.lastTransferWindow.Dequeue();
}
else
{
bool canUpload = false;
lock (this.transferJob.CheckPoint.TransferWindowLock)
{
if (this.transferJob.CheckPoint.TransferWindow.Count < Constants.MaxCountInTransferWindow)
{
startOffset = this.transferJob.CheckPoint.EntryTransferOffset;
if (this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength)
{
this.transferJob.CheckPoint.TransferWindow.Add(startOffset);
this.transferJob.CheckPoint.EntryTransferOffset = Math.Min(
this.transferJob.CheckPoint.EntryTransferOffset + this.Scheduler.TransferOptions.BlockSize,
this.SharedTransferData.TotalLength);
canUpload = true;
}
}
}
if (!canUpload)
{
this.hasWork = true;
this.Scheduler.MemoryManager.ReleaseBuffer(memoryBuffer);
return;
}
}
if ((startOffset > this.SharedTransferData.TotalLength)
|| (startOffset < 0))
{
this.Scheduler.MemoryManager.ReleaseBuffer(memoryBuffer);
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.SetBlockDownloadHasWork();
ReadDataState asyncState = new ReadDataState
{
MemoryBuffer = memoryBuffer,
BytesRead = 0,
StartOffset = startOffset,
Length = (int)Math.Min(this.Scheduler.TransferOptions.BlockSize, this.SharedTransferData.TotalLength - startOffset),
MemoryManager = this.Scheduler.MemoryManager,
};
using (asyncState)
{
await this.DownloadChunkAsync(asyncState);
}
return;
}
this.SetBlockDownloadHasWork();
}
private async Task DownloadChunkAsync(ReadDataState asyncState)
{
Debug.Assert(null != asyncState, "asyncState object expected");
// If a parallel operation caused the controller to be placed in
// error state exit early to avoid unnecessary I/O.
if (this.Controller.ErrorOccurred)
{
return;
}
AccessCondition accessCondition = Utils.GenerateIfMatchConditionWithCustomerCondition(
this.sourceBlob.Properties.ETag,
this.sourceLocation.AccessCondition);
// We're to download this block.
asyncState.MemoryStream =
new MemoryStream(
asyncState.MemoryBuffer,
0,
asyncState.Length);
await this.sourceBlob.DownloadRangeToStreamAsync(
asyncState.MemoryStream,
asyncState.StartOffset,
asyncState.Length,
accessCondition,
Utils.GenerateBlobRequestOptions(this.sourceLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
TransferData transferData = new TransferData(this.Scheduler.MemoryManager)
{
StartOffset = asyncState.StartOffset,
Length = asyncState.Length,
MemoryBuffer = asyncState.MemoryBuffer
};
this.SharedTransferData.AvailableData.TryAdd(transferData.StartOffset, transferData);
// Set memory buffer to null. We don't want its dispose method to
// be called once our asyncState is disposed. The memory should
// not be reused yet, we still need to write it to disk.
asyncState.MemoryBuffer = null;
this.SetFinish();
this.SetBlockDownloadHasWork();
}
private void SetFinish()
{
if (this.downloadCountdownEvent.Signal())
{
this.isFinished = true;
}
}
private void SetBlockDownloadHasWork()
{
if (this.HasWork)
{
return;
}
// Check if we have blocks available to download.
if (!this.IsTransferWindowEmpty()
|| this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength)
{
this.hasWork = true;
return;
}
}
private bool IsTransferWindowEmpty()
{
return null == this.lastTransferWindow || this.lastTransferWindow.Count == 0;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xunit;
public static unsafe class DateTimeTests
{
[Fact]
public static void TestConstructors()
{
DateTime dt = new DateTime(2012, 6, 11);
ValidateYearMonthDay(dt, 2012, 6, 11);
dt = new DateTime(2012, 12, 31, 13, 50, 10);
ValidateYearMonthDay(dt, 2012, 12, 31, 13, 50, 10);
dt = new DateTime(1973, 10, 6, 14, 30, 0, 500);
ValidateYearMonthDay(dt, 1973, 10, 6, 14, 30, 0, 500);
dt = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local);
ValidateYearMonthDay(dt, 1986, 8, 15, 10, 20, 5);
}
[Fact]
public static void TestDateTimeLimits()
{
DateTime dt = DateTime.MaxValue;
ValidateYearMonthDay(dt, 9999, 12, 31);
dt = DateTime.MinValue;
ValidateYearMonthDay(dt, 1, 1, 1);
}
[Fact]
public static void TestLeapYears()
{
Assert.Equal(true, DateTime.IsLeapYear(2004));
Assert.Equal(false, DateTime.IsLeapYear(2005));
}
[Fact]
public static void TestAddition()
{
DateTime dt = new DateTime(1986, 8, 15, 10, 20, 5, 70);
Assert.Equal(17, dt.AddDays(2).Day);
Assert.Equal(13, dt.AddDays(-2).Day);
Assert.Equal(10, dt.AddMonths(2).Month);
Assert.Equal(6, dt.AddMonths(-2).Month);
Assert.Equal(1996, dt.AddYears(10).Year);
Assert.Equal(1976, dt.AddYears(-10).Year);
Assert.Equal(13, dt.AddHours(3).Hour);
Assert.Equal(7, dt.AddHours(-3).Hour);
Assert.Equal(25, dt.AddMinutes(5).Minute);
Assert.Equal(15, dt.AddMinutes(-5).Minute);
Assert.Equal(35, dt.AddSeconds(30).Second);
Assert.Equal(2, dt.AddSeconds(-3).Second);
Assert.Equal(80, dt.AddMilliseconds(10).Millisecond);
Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond);
}
[Fact]
public static void TestDayOfWeek()
{
DateTime dt = new DateTime(2012, 6, 18);
Assert.Equal(DayOfWeek.Monday, dt.DayOfWeek);
}
[Fact]
public static void TestTimeSpan()
{
DateTime dt = new DateTime(2012, 6, 18, 10, 5, 1, 0);
TimeSpan ts = dt.TimeOfDay;
DateTime newDate = dt.Subtract(ts);
Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks);
Assert.Equal(dt.Ticks, newDate.Add(ts).Ticks);
}
[Fact]
public static void TestToday()
{
DateTime today = DateTime.Today;
DateTime now = DateTime.Now;
ValidateYearMonthDay(today, now.Year, now.Month, now.Day);
today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc);
Assert.Equal(DateTimeKind.Utc, today.Kind);
Assert.Equal(false, today.IsDaylightSavingTime());
}
[Fact]
public static void TestCoversion()
{
DateTime today = DateTime.Today;
long dateTimeRaw = today.ToBinary();
Assert.Equal(today, DateTime.FromBinary(dateTimeRaw));
dateTimeRaw = today.ToFileTime();
Assert.Equal(today, DateTime.FromFileTime(dateTimeRaw));
dateTimeRaw = today.ToFileTimeUtc();
Assert.Equal(today, DateTime.FromFileTimeUtc(dateTimeRaw).ToLocalTime());
}
[Fact]
public static void TestOperators()
{
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
Assert.Equal(new TimeSpan(185, 14, 47, 0), diff1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date4);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
Assert.Equal(new TimeSpan(55, 4, 20, 0), diff2);
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;
Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date5);
}
[Fact]
public static void TestParsingDateTimeWithTimeDesignator()
{
DateTime result;
Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
public class MyFormater : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (typeof(IFormatProvider) == formatType)
{
return this;
}
else
{
return null;
}
}
}
[Fact]
public static void TestParseWithAdjustToUniversal()
{
var formater = new MyFormater();
var dateBefore = DateTime.Now.ToString();
var dateAfter = DateTime.ParseExact(dateBefore, "G", formater, DateTimeStyles.AdjustToUniversal);
Assert.Equal(dateBefore, dateAfter.ToString());
}
[Fact]
public static void TestFormatParse()
{
DateTime dt = new DateTime(2012, 12, 21, 10, 8, 6);
CultureInfo ci = new CultureInfo("ja-JP");
string s = string.Format(ci, "{0}", dt);
Assert.Equal(dt, DateTime.Parse(s, ci));
}
[Fact]
public static void TestParse1()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString();
DateTime in_1 = DateTime.Parse(s);
string actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse2()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString();
DateTime in_1 = DateTime.Parse(s, null);
string actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse3()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString();
DateTime in_1 = DateTime.Parse(s, null, DateTimeStyles.None);
string actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact3()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString("g");
DateTime in_1 = DateTime.ParseExact(s, "g", null);
string actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString("g");
DateTime in_1 = DateTime.ParseExact(s, "g", null, DateTimeStyles.None);
string actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4a()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString("g");
string[] formats = { "g" };
DateTime in_1 = DateTime.ParseExact(s, formats, null, DateTimeStyles.None);
string actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse2()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParse(s, out in_1);
Assert.True(b);
string actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse4()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParse(s, null, DateTimeStyles.None, out in_1);
Assert.True(b);
string actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExact()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParseExact(s, "g", null, DateTimeStyles.None, out in_1);
Assert.True(b);
string actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExactA()
{
DateTime src = DateTime.MaxValue;
string s = src.ToString("g");
string[] formats = { "g" };
DateTime in_1;
bool b = DateTime.TryParseExact(s, formats, null, DateTimeStyles.None, out in_1);
Assert.True(b);
string actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestGetDateTimeFormats()
{
char[] allStandardFormats =
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15);
List<string> july28Formats = new List<string>();
foreach (char format in allStandardFormats)
{
string[] dates = july28.GetDateTimeFormats(format);
Assert.True(dates.Length > 0);
DateTime parsedDate;
Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate));
july28Formats.AddRange(dates);
}
List<string> actualJuly28Formats = july28.GetDateTimeFormats().ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
actualJuly28Formats = july28.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
}
[Theory]
[InlineData("fi-FI")]
[InlineData("nb-NO")]
[InlineData("nb-SJ")]
[InlineData("sr-Cyrl-XK")]
[InlineData("sr-Latn-ME")]
[InlineData("sr-Latn-RS")]
[InlineData("sr-Latn-XK")]
public static void TestSpecialCulturesParsing(string cultureName)
{
// Test DateTime parsing with cultures which has the date separator and time separator are same
CultureInfo ci;
try
{
ci = new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
// ignore un-supported culture in current platform
return;
}
DateTime date = new DateTime(2015, 11, 20, 11, 49, 50);
string dateString = date.ToString(ci.DateTimeFormat.ShortDatePattern, ci);
DateTime parsedDate;
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
if (ci.DateTimeFormat.ShortDatePattern.Contains("yyyy") || HasDifferentDateTimeSeparators(ci.DateTimeFormat))
{
Assert.Equal(date.Date, parsedDate);
}
else
{
// When the date separator and time separator are the same, DateTime.TryParse cannot
// tell the difference between a short date like dd.MM.yy and a short time
// like HH.mm.ss. So it assumes that if it gets 03.04.11, that must be a time
// and uses the current date to construct the date time.
DateTime now = DateTime.Now;
Assert.Equal(new DateTime(now.Year, now.Month, now.Day, date.Day, date.Month, date.Year % 100), parsedDate);
}
dateString = date.ToString(ci.DateTimeFormat.LongDatePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.Date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.FullDateTimePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.LongTimePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.TimeOfDay, parsedDate.TimeOfDay);
}
/// <summary>
/// Since .NET Core doesn't expose DateTimeFormatInfo DateSeparator and TimeSeparator properties,
/// this method gets the separators using DateTime.ToString by passing in the invariant separators.
/// The invariant separators will then get turned into the culture's separators by ToString,
/// which are then compared.
/// </summary>
private static bool HasDifferentDateTimeSeparators(DateTimeFormatInfo dateTimeFormat)
{
DateTime d = new DateTime(2015, 11, 24, 17, 57, 29);
string separators = d.ToString("/@:", dateTimeFormat);
int delimiterIndex = separators.IndexOf('@');
string dateSeparator = separators.Substring(0, delimiterIndex);
string timeSeparator = separators.Substring(delimiterIndex + 1);
return dateSeparator != timeSeparator;
}
[Fact]
public static void TestGetDateTimeFormats_FormatSpecifier_InvalidFormat()
{
DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15);
Assert.Throws<FormatException>(() => july28.GetDateTimeFormats('x'));
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day)
{
Assert.Equal(dt.Year, year);
Assert.Equal(dt.Month, month);
Assert.Equal(dt.Day, day);
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second)
{
ValidateYearMonthDay(dt, year, month, day);
Assert.Equal(dt.Hour, hour);
Assert.Equal(dt.Minute, minute);
Assert.Equal(dt.Second, second);
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second, int millisecond)
{
ValidateYearMonthDay(dt, year, month, day, hour, minute, second);
Assert.Equal(dt.Millisecond, millisecond);
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DynamoDBv2.Model
{
/// <summary>
/// Container for the parameters to the GetItem operation.
/// The <i>GetItem</i> operation returns a set of attributes for the item with the given
/// primary key. If there is no matching item, <i>GetItem</i> does not return any data.
///
///
/// <para>
/// <i>GetItem</i> provides an eventually consistent read by default. If your application
/// requires a strongly consistent read, set <i>ConsistentRead</i> to <code>true</code>.
/// Although a strongly consistent read might take more time than an eventually consistent
/// read, it always returns the last updated value.
/// </para>
/// </summary>
public partial class GetItemRequest : AmazonDynamoDBRequest
{
private List<string> _attributesToGet = new List<string>();
private bool? _consistentRead;
private Dictionary<string, string> _expressionAttributeNames = new Dictionary<string, string>();
private Dictionary<string, AttributeValue> _key = new Dictionary<string, AttributeValue>();
private string _projectionExpression;
private ReturnConsumedCapacity _returnConsumedCapacity;
private string _tableName;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public GetItemRequest() { }
/// <summary>
/// Instantiates GetItemRequest with the parameterized properties
/// </summary>
/// <param name="tableName">The name of the table containing the requested item.</param>
/// <param name="key">A map of attribute names to <i>AttributeValue</i> objects, representing the primary key of the item to retrieve. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute.</param>
public GetItemRequest(string tableName, Dictionary<string, AttributeValue> key)
{
_tableName = tableName;
_key = key;
}
/// <summary>
/// Instantiates GetItemRequest with the parameterized properties
/// </summary>
/// <param name="tableName">The name of the table containing the requested item.</param>
/// <param name="key">A map of attribute names to <i>AttributeValue</i> objects, representing the primary key of the item to retrieve. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute.</param>
/// <param name="consistentRead">A value that if set to <code>true</code>, then the operation uses strongly consistent reads; otherwise, eventually consistent reads are used.</param>
public GetItemRequest(string tableName, Dictionary<string, AttributeValue> key, bool consistentRead)
{
_tableName = tableName;
_key = key;
_consistentRead = consistentRead;
}
/// <summary>
/// Gets and sets the property AttributesToGet. <important>
/// <para>
/// There is a newer parameter available. Use <i>ProjectionExpression</i> instead. Note
/// that if you use <i>AttributesToGet</i> and <i>ProjectionExpression</i> at the same
/// time, DynamoDB will return a <i>ValidationException</i> exception.
/// </para>
///
/// <para>
/// This parameter allows you to retrieve attributes of type List or Map; however, it
/// cannot retrieve individual elements within a List or a Map.
/// </para>
/// </important>
/// <para>
/// The names of one or more attributes to retrieve. If no attribute names are provided,
/// then all attributes will be returned. If any of the requested attributes are not found,
/// they will not appear in the result.
/// </para>
///
/// <para>
/// Note that <i>AttributesToGet</i> has no effect on provisioned throughput consumption.
/// DynamoDB determines capacity units consumed based on item size, not on the amount
/// of data that is returned to an application.
/// </para>
/// </summary>
public List<string> AttributesToGet
{
get { return this._attributesToGet; }
set { this._attributesToGet = value; }
}
// Check to see if AttributesToGet property is set
internal bool IsSetAttributesToGet()
{
return this._attributesToGet != null && this._attributesToGet.Count > 0;
}
/// <summary>
/// Gets and sets the property ConsistentRead.
/// <para>
/// A value that if set to <code>true</code>, then the operation uses strongly consistent
/// reads; otherwise, eventually consistent reads are used.
/// </para>
/// </summary>
public bool ConsistentRead
{
get { return this._consistentRead.GetValueOrDefault(); }
set { this._consistentRead = value; }
}
// Check to see if ConsistentRead property is set
internal bool IsSetConsistentRead()
{
return this._consistentRead.HasValue;
}
/// <summary>
/// Gets and sets the property ExpressionAttributeNames.
/// <para>
/// One or more substitution tokens for attribute names in an expression. The following
/// are some use cases for using <i>ExpressionAttributeNames</i>:
/// </para>
/// <ul> <li>
/// <para>
/// To access an attribute whose name conflicts with a DynamoDB reserved word.
/// </para>
/// </li> <li>
/// <para>
/// To create a placeholder for repeating occurrences of an attribute name in an expression.
/// </para>
/// </li> <li>
/// <para>
/// To prevent special characters in an attribute name from being misinterpreted in an
/// expression.
/// </para>
/// </li> </ul>
/// <para>
/// Use the <b>#</b> character in an expression to dereference an attribute name. For
/// example, consider the following attribute name:
/// </para>
/// <ul><li>
/// <para>
/// <code>Percentile</code>
/// </para>
/// </li></ul>
/// <para>
/// The name of this attribute conflicts with a reserved word, so it cannot be used directly
/// in an expression. (For the complete list of reserved words, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html">Reserved
/// Words</a> in the <i>Amazon DynamoDB Developer Guide</i>). To work around this, you
/// could specify the following for <i>ExpressionAttributeNames</i>:
/// </para>
/// <ul><li>
/// <para>
/// <code>{"#P":"Percentile"}</code>
/// </para>
/// </li></ul>
/// <para>
/// You could then use this substitution in an expression, as in this example:
/// </para>
/// <ul><li>
/// <para>
/// <code>#P = :val</code>
/// </para>
/// </li></ul> <note>
/// <para>
/// Tokens that begin with the <b>:</b> character are <i>expression attribute values</i>,
/// which are placeholders for the actual value at runtime.
/// </para>
/// </note>
/// <para>
/// For more information on expression attribute names, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing
/// Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
/// </summary>
public Dictionary<string, string> ExpressionAttributeNames
{
get { return this._expressionAttributeNames; }
set { this._expressionAttributeNames = value; }
}
// Check to see if ExpressionAttributeNames property is set
internal bool IsSetExpressionAttributeNames()
{
return this._expressionAttributeNames != null && this._expressionAttributeNames.Count > 0;
}
/// <summary>
/// Gets and sets the property Key.
/// <para>
/// A map of attribute names to <i>AttributeValue</i> objects, representing the primary
/// key of the item to retrieve.
/// </para>
///
/// <para>
/// For the primary key, you must provide all of the attributes. For example, with a hash
/// type primary key, you only need to provide the hash attribute. For a hash-and-range
/// type primary key, you must provide both the hash attribute and the range attribute.
/// </para>
/// </summary>
public Dictionary<string, AttributeValue> Key
{
get { return this._key; }
set { this._key = value; }
}
// Check to see if Key property is set
internal bool IsSetKey()
{
return this._key != null && this._key.Count > 0;
}
/// <summary>
/// Gets and sets the property ProjectionExpression.
/// <para>
/// A string that identifies one or more attributes to retrieve from the table. These
/// attributes can include scalars, sets, or elements of a JSON document. The attributes
/// in the expression must be separated by commas.
/// </para>
///
/// <para>
/// If no attribute names are specified, then all attributes will be returned. If any
/// of the requested attributes are not found, they will not appear in the result.
/// </para>
///
/// <para>
/// For more information, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing
/// Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
/// </summary>
public string ProjectionExpression
{
get { return this._projectionExpression; }
set { this._projectionExpression = value; }
}
// Check to see if ProjectionExpression property is set
internal bool IsSetProjectionExpression()
{
return this._projectionExpression != null;
}
/// <summary>
/// Gets and sets the property ReturnConsumedCapacity.
/// </summary>
public ReturnConsumedCapacity ReturnConsumedCapacity
{
get { return this._returnConsumedCapacity; }
set { this._returnConsumedCapacity = value; }
}
// Check to see if ReturnConsumedCapacity property is set
internal bool IsSetReturnConsumedCapacity()
{
return this._returnConsumedCapacity != null;
}
/// <summary>
/// Gets and sets the property TableName.
/// <para>
/// The name of the table containing the requested item.
/// </para>
/// </summary>
public string TableName
{
get { return this._tableName; }
set { this._tableName = value; }
}
// Check to see if TableName property is set
internal bool IsSetTableName()
{
return this._tableName != null;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.Acceleratedmobilepageurl.v1
{
/// <summary>The Acceleratedmobilepageurl Service.</summary>
public class AcceleratedmobilepageurlService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public AcceleratedmobilepageurlService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public AcceleratedmobilepageurlService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
AmpUrls = new AmpUrlsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "acceleratedmobilepageurl";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://acceleratedmobilepageurl.googleapis.com/";
#else
"https://acceleratedmobilepageurl.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://acceleratedmobilepageurl.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Gets the AmpUrls resource.</summary>
public virtual AmpUrlsResource AmpUrls { get; }
}
/// <summary>A base abstract class for Acceleratedmobilepageurl requests.</summary>
public abstract class AcceleratedmobilepageurlBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new AcceleratedmobilepageurlBaseServiceRequest instance.</summary>
protected AcceleratedmobilepageurlBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Acceleratedmobilepageurl parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "ampUrls" collection of methods.</summary>
public class AmpUrlsResource
{
private const string Resource = "ampUrls";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public AmpUrlsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Returns AMP URL(s) and equivalent [AMP Cache URL(s)](/amp/cache/overview#amp-cache-url-format).
/// </summary>
/// <param name="body">The body of the request.</param>
public virtual BatchGetRequest BatchGet(Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsRequest body)
{
return new BatchGetRequest(service, body);
}
/// <summary>
/// Returns AMP URL(s) and equivalent [AMP Cache URL(s)](/amp/cache/overview#amp-cache-url-format).
/// </summary>
public class BatchGetRequest : AcceleratedmobilepageurlBaseServiceRequest<Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsResponse>
{
/// <summary>Constructs a new BatchGet request.</summary>
public BatchGetRequest(Google.Apis.Services.IClientService service, Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsRequest body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Acceleratedmobilepageurl.v1.Data.BatchGetAmpUrlsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "batchGet";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/ampUrls:batchGet";
/// <summary>Initializes BatchGet parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.Acceleratedmobilepageurl.v1.Data
{
/// <summary>AMP URL response for a requested URL.</summary>
public class AmpUrl : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The AMP URL pointing to the publisher's web server.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ampUrl")]
public virtual string AmpUrlValue { get; set; }
/// <summary>
/// The [AMP Cache URL](/amp/cache/overview#amp-cache-url-format) pointing to the cached document in the Google
/// AMP Cache.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cdnAmpUrl")]
public virtual string CdnAmpUrl { get; set; }
/// <summary>The original non-AMP URL.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("originalUrl")]
public virtual string OriginalUrl { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>AMP URL Error resource for a requested URL that couldn't be found.</summary>
public class AmpUrlError : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The error code of an API call.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorCode")]
public virtual string ErrorCode { get; set; }
/// <summary>An optional descriptive error message.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorMessage")]
public virtual string ErrorMessage { get; set; }
/// <summary>The original non-AMP URL.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("originalUrl")]
public virtual string OriginalUrl { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>AMP URL request for a batch of URLs.</summary>
public class BatchGetAmpUrlsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The lookup_strategy being requested.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lookupStrategy")]
public virtual string LookupStrategy { get; set; }
/// <summary>
/// List of URLs to look up for the paired AMP URLs. The URLs are case-sensitive. Up to 50 URLs per lookup (see
/// [Usage Limits](/amp/cache/reference/limits)).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("urls")]
public virtual System.Collections.Generic.IList<string> Urls { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Batch AMP URL response.</summary>
public class BatchGetAmpUrlsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// For each URL in BatchAmpUrlsRequest, the URL response. The response might not be in the same order as URLs
/// in the batch request. If BatchAmpUrlsRequest contains duplicate URLs, AmpUrl is generated only once.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("ampUrls")]
public virtual System.Collections.Generic.IList<AmpUrl> AmpUrls { get; set; }
/// <summary>The errors for requested URLs that have no AMP URL.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("urlErrors")]
public virtual System.Collections.Generic.IList<AmpUrlError> UrlErrors { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Parameters;
namespace ChainUtils.BouncyCastle.Crypto.Engines
{
/**
* The specification for RC5 came from the <code>RC5 Encryption Algorithm</code>
* publication in RSA CryptoBytes, Spring of 1995.
* <em>http://www.rsasecurity.com/rsalabs/cryptobytes</em>.
* <p>
* This implementation has a word size of 32 bits.</p>
*/
public class RC532Engine
: IBlockCipher
{
/*
* the number of rounds to perform
*/
private int _noRounds;
/*
* the expanded key array of size 2*(rounds + 1)
*/
private int [] _S;
/*
* our "magic constants" for 32 32
*
* Pw = Odd((e-2) * 2^wordsize)
* Qw = Odd((o-2) * 2^wordsize)
*
* where e is the base of natural logarithms (2.718281828...)
* and o is the golden ratio (1.61803398...)
*/
private static readonly int P32 = unchecked((int) 0xb7e15163);
private static readonly int Q32 = unchecked((int) 0x9e3779b9);
private bool forEncryption;
/**
* Create an instance of the RC5 encryption algorithm
* and set some defaults
*/
public RC532Engine()
{
_noRounds = 12; // the default
// _S = null;
}
public string AlgorithmName
{
get { return "RC5-32"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return 2 * 4;
}
/**
* initialise a RC5-32 cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (typeof(RC5Parameters).IsInstanceOfType(parameters))
{
var p = (RC5Parameters)parameters;
_noRounds = p.Rounds;
SetKey(p.GetKey());
}
else if(typeof(KeyParameter).IsInstanceOfType(parameters))
{
var p = (KeyParameter)parameters;
SetKey(p.GetKey());
}
else
{
throw new ArgumentException("invalid parameter passed to RC532 init - " + parameters.GetType().ToString());
}
this.forEncryption = forEncryption;
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (forEncryption)
? EncryptBlock(input, inOff, output, outOff)
: DecryptBlock(input, inOff, output, outOff);
}
public void Reset()
{
}
/**
* Re-key the cipher.
*
* @param key the key to be used
*/
private void SetKey(
byte[] key)
{
//
// KEY EXPANSION:
//
// There are 3 phases to the key expansion.
//
// Phase 1:
// Copy the secret key K[0...b-1] into an array L[0..c-1] of
// c = ceil(b/u), where u = 32/8 in little-endian order.
// In other words, we fill up L using u consecutive key bytes
// of K. Any unfilled byte positions in L are zeroed. In the
// case that b = c = 0, set c = 1 and L[0] = 0.
//
var L = new int[(key.Length + (4 - 1)) / 4];
for (var i = 0; i != key.Length; i++)
{
L[i / 4] += (key[i] & 0xff) << (8 * (i % 4));
}
//
// Phase 2:
// Initialize S to a particular fixed pseudo-random bit pattern
// using an arithmetic progression modulo 2^wordsize determined
// by the magic numbers, Pw & Qw.
//
_S = new int[2*(_noRounds + 1)];
_S[0] = P32;
for (var i=1; i < _S.Length; i++)
{
_S[i] = (_S[i-1] + Q32);
}
//
// Phase 3:
// Mix in the user's secret key in 3 passes over the arrays S & L.
// The max of the arrays sizes is used as the loop control
//
int iter;
if (L.Length > _S.Length)
{
iter = 3 * L.Length;
}
else
{
iter = 3 * _S.Length;
}
int A = 0, B = 0;
int ii = 0, jj = 0;
for (var k = 0; k < iter; k++)
{
A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
ii = (ii+1) % _S.Length;
jj = (jj+1) % L.Length;
}
}
/**
* Encrypt the given block starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param in in byte buffer containing data to encrypt
* @param inOff offset into src buffer
* @param out out buffer where encrypted data is written
* @param outOff offset into out buffer
*/
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
var A = BytesToWord(input, inOff) + _S[0];
var B = BytesToWord(input, inOff + 4) + _S[1];
for (var i = 1; i <= _noRounds; i++)
{
A = RotateLeft(A ^ B, B) + _S[2*i];
B = RotateLeft(B ^ A, A) + _S[2*i+1];
}
WordToBytes(A, outBytes, outOff);
WordToBytes(B, outBytes, outOff + 4);
return 2 * 4;
}
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
var A = BytesToWord(input, inOff);
var B = BytesToWord(input, inOff + 4);
for (var i = _noRounds; i >= 1; i--)
{
B = RotateRight(B - _S[2*i+1], A) ^ A;
A = RotateRight(A - _S[2*i], B) ^ B;
}
WordToBytes(A - _S[0], outBytes, outOff);
WordToBytes(B - _S[1], outBytes, outOff + 4);
return 2 * 4;
}
//////////////////////////////////////////////////////////////
//
// PRIVATE Helper Methods
//
//////////////////////////////////////////////////////////////
/**
* Perform a left "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(32)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % 32
*/
private int RotateLeft(int x, int y) {
return ((int) ( (uint) (x << (y & (32-1))) |
((uint) x >> (32 - (y & (32-1)))) )
);
}
/**
* Perform a right "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(32)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % 32
*/
private int RotateRight(int x, int y) {
return ((int) ( ((uint) x >> (y & (32-1))) |
(uint) (x << (32 - (y & (32-1)))) )
);
}
private int BytesToWord(
byte[] src,
int srcOff)
{
return (src[srcOff] & 0xff) | ((src[srcOff + 1] & 0xff) << 8)
| ((src[srcOff + 2] & 0xff) << 16) | ((src[srcOff + 3] & 0xff) << 24);
}
private void WordToBytes(
int word,
byte[] dst,
int dstOff)
{
dst[dstOff] = (byte)word;
dst[dstOff + 1] = (byte)(word >> 8);
dst[dstOff + 2] = (byte)(word >> 16);
dst[dstOff + 3] = (byte)(word >> 24);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.Common
{
/// <summary>
/// The version of SUT.
/// </summary>
public enum SutVersion
{
/// <summary>
/// The SUT is Exchange Server 2007 SP3
/// </summary>
ExchangeServer2007,
/// <summary>
/// The SUT is Exchange Server 2010 SP3
/// </summary>
ExchangeServer2010,
/// <summary>
/// The SUT is Exchange Server 2013
/// </summary>
ExchangeServer2013,
/// <summary>
/// The SUT is Exchange Server 2016
/// </summary>
ExchangeServer2016,
/// <summary>
/// The SUT is Exchange Server 2019
/// </summary>
ExchangeServer2019
}
/// <summary>
/// Command Name
/// </summary>
public enum CommandName
{
/// <summary>
/// Sync command.
/// </summary>
Sync = 0,
/// <summary>
/// SendMail command.
/// </summary>
SendMail = 1,
/// <summary>
/// SmartForward command.
/// </summary>
SmartForward = 2,
/// <summary>
/// SmartReply command.
/// </summary>
SmartReply = 3,
/// <summary>
/// GetAttachment command.
/// </summary>
GetAttachment = 4,
/// <summary>
/// FolderSync command.
/// </summary>
FolderSync = 9,
/// <summary>
/// FolderCreate command.
/// </summary>
FolderCreate = 10,
/// <summary>
/// FolderDelete command.
/// </summary>
FolderDelete = 11,
/// <summary>
/// FolderUpdate command.
/// </summary>
FolderUpdate = 12,
/// <summary>
/// MoveItems command.
/// </summary>
MoveItems = 13,
/// <summary>
/// GetItemEstimate command.
/// </summary>
GetItemEstimate = 14,
/// <summary>
/// MeetingResponse command.
/// </summary>
MeetingResponse = 15,
/// <summary>
/// Search command.
/// </summary>
Search = 16,
/// <summary>
/// Settings command.
/// </summary>
Settings = 17,
/// <summary>
/// Ping command.
/// </summary>
Ping = 18,
/// <summary>
/// ItemOperations command.
/// </summary>
ItemOperations = 19,
/// <summary>
/// Provision command.
/// </summary>
Provision = 20,
/// <summary>
/// ResolveRecipients command.
/// </summary>
ResolveRecipients = 21,
/// <summary>
/// ValidateCert command.
/// </summary>
ValidateCert = 22,
/// <summary>
/// Autodiscover command.
/// </summary>
Autodiscover = 5,
/// <summary>
/// GetHierarchy command.
/// </summary>
GetHierarchy = 6,
/// <summary>
/// Find command.
/// </summary>
Find = 23,
/// <summary>
/// Not exist command.
/// </summary>
NotExist
}
/// <summary>
/// command parameterName
/// </summary>
public enum CmdParameterName
{
/// <summary>
/// The parameter of AttachmentName.
/// </summary>
AttachmentName = 0,
/// <summary>
/// The parameter of CollectionId.
/// </summary>
CollectionId = 1,
/// <summary>
/// The parameter of CollectionName.
/// </summary>
CollectionName = 2,
/// <summary>
/// The parameter of ItemId.
/// </summary>
ItemId = 3,
/// <summary>
/// The parameter of LongId.
/// </summary>
LongId = 4,
/// <summary>
/// The parameter of ParentId.
/// </summary>
ParentId = 5,
/// <summary>
/// The parameter of Occurrence.
/// </summary>
Occurrence = 6,
/// <summary>
/// The parameter of Options.
/// </summary>
Options = 7,
/// <summary>
/// The parameter of User.
/// </summary>
User = 8,
/// <summary>
/// The parameter of SaveInSent.
/// </summary>
SaveInSent = 9
}
/// <summary>
/// The store to search
/// </summary>
public enum SearchName
{
/// <summary>
/// Search the mailbox
/// </summary>
Mailbox,
/// <summary>
/// Search a Windows SharePoint Services or UNC library
/// </summary>
DocumentLibrary,
/// <summary>
/// Search the Global Address List
/// </summary>
GAL
}
/// <summary>
/// Specifies the type of the folder that was updated (renamed or moved) or added
/// </summary>
public enum FolderType : int
{
/// <summary>
/// User-created folder (generic)
/// </summary>
UserCreatedGeneric = 1,
/// <summary>
/// Default Inbox folder
/// </summary>
Inbox = 2,
/// <summary>
/// Default Drafts folder
/// </summary>
Drafts = 3,
/// <summary>
/// Default Deleted Items folder
/// </summary>
DeletedItems = 4,
/// <summary>
/// Default Sent Items folder
/// </summary>
SentItems = 5,
/// <summary>
/// Default Outbox folder
/// </summary>
Outbox = 6,
/// <summary>
/// Default Tasks folder
/// </summary>
Tasks = 7,
/// <summary>
/// Default Calendar folder
/// </summary>
Calendar = 8,
/// <summary>
/// Default Contacts folder
/// </summary>
Contacts = 9,
/// <summary>
/// Default Notes folder
/// </summary>
Notes = 10,
/// <summary>
/// Default Journal folder
/// </summary>
Journal = 11,
/// <summary>
/// User-created Mail folder
/// </summary>
UserCreatedMail = 12,
/// <summary>
/// User-created Calendar folder
/// </summary>
UserCreatedCalendar = 13,
/// <summary>
/// User-created Contacts folder
/// </summary>
UserCreatedContacts = 14,
/// <summary>
/// User-created Tasks folder
/// </summary>
UserCreatedTasks = 15,
/// <summary>
/// User-created journal folder
/// </summary>
UserCreatedJournal = 16,
/// <summary>
/// User-created Notes folder
/// </summary>
UserCreatedNotes = 17,
/// <summary>
/// Unknown folder type
/// </summary>
Unknown = 18,
/// <summary>
/// Recipient information cache
/// </summary>
RecipientInformationCache = 19
}
/// <summary>
/// Transport Type for HTTP or HTTPS
/// </summary>
public enum ProtocolTransportType
{
/// <summary>
/// HTTP transport.
/// </summary>
HTTP,
/// <summary>
/// HTTPS transport.
/// </summary>
HTTPS
}
/// <summary>
/// Content Type that indicate the body's format
/// </summary>
public enum ContentTypeEnum
{
/// <summary>
/// WBXML format
/// </summary>
Wbxml,
/// <summary>
/// XML format
/// </summary>
Xml,
/// <summary>
/// HTML format
/// </summary>
Html
}
/// <summary>
/// Query value type.
/// </summary>
public enum QueryValueType
{
/// <summary>
/// Plain text.
/// </summary>
PlainText,
/// <summary>
/// Base64 encode.
/// </summary>
Base64,
}
/// <summary>
/// Delivery method for Fetch element in ItemOperations.
/// </summary>
public enum DeliveryMethodForFetch
{
/// <summary>
/// The inline method of delivering binary content is including data encoded with base64 encoding inside the WBXML.
/// </summary>
Inline,
/// <summary>
/// The multipart method of delivering content is a multipart structure with the WBXML being the first part, and the requested data populating the subsequent parts.
/// </summary>
MultiPart
}
}
| |
using System;
using Csla;
using Csla.Data;
using DalEf;
using Csla.Serialization;
using System.ComponentModel.DataAnnotations;
using BusinessObjects.Properties;
using System.Linq;
using BusinessObjects.CoreBusinessClasses;
using BusinessObjects.Security;
namespace BusinessObjects.Projects
{
[Serializable]
public partial class cProjects_Project_Expenses : CoreBusinessClass<cProjects_Project_Expenses>
{
#region Business Methods
public static readonly PropertyInfo<System.Int32> IdProperty = RegisterProperty<System.Int32>(p => p.Id, string.Empty);
#if !SILVERLIGHT
[System.ComponentModel.DataObjectField(true, true)]
#endif
public System.Int32 Id
{
get { return GetProperty(IdProperty); }
internal set { SetProperty(IdProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> projects_ProjectIdProperty = RegisterProperty<System.Int32?>(p => p.Projects_ProjectId, string.Empty, (System.Int32?)null);
public System.Int32? Projects_ProjectId
{
get { return GetProperty(projects_ProjectIdProperty); }
set { SetProperty(projects_ProjectIdProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> mDSubjects_SubjectIdProperty = RegisterProperty<System.Int32?>(p => p.MDSubjects_SubjectId, string.Empty, (System.Int32?)null);
public System.Int32? MDSubjects_SubjectId
{
get { return GetProperty(mDSubjects_SubjectIdProperty); }
set { SetProperty(mDSubjects_SubjectIdProperty, value); }
}
private static readonly PropertyInfo<System.Int32> projects_Enums_ExpensTypeIdProperty = RegisterProperty<System.Int32>(p => p.Projects_Enums_ExpensTypeId, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 Projects_Enums_ExpensTypeId
{
get { return GetProperty(projects_Enums_ExpensTypeIdProperty); }
set { SetProperty(projects_Enums_ExpensTypeIdProperty, value); }
}
private static readonly PropertyInfo<System.DateTime> expenseDateProperty = RegisterProperty<System.DateTime>(p => p.ExpenseDate, string.Empty, System.DateTime.Now);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.DateTime ExpenseDate
{
get { return GetProperty(expenseDateProperty); }
set { SetProperty(expenseDateProperty, value); }
}
private static readonly PropertyInfo<System.Decimal> amountProperty = RegisterProperty<System.Decimal>(p => p.Amount, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Decimal Amount
{
get { return GetProperty(amountProperty); }
set { SetProperty(amountProperty, value); }
}
private static readonly PropertyInfo<bool?> invoicedProperty = RegisterProperty<bool?>(p => p.Invoiced, string.Empty, (bool?)null);
public bool? Invoiced
{
get { return GetProperty(invoicedProperty); }
set { SetProperty(invoicedProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> documents_InvoiceIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_InvoiceId, string.Empty, (System.Int32?)null);
public System.Int32? Documents_InvoiceId
{
get { return GetProperty(documents_InvoiceIdProperty); }
set { SetProperty(documents_InvoiceIdProperty, value); }
}
private static readonly PropertyInfo<System.String> descriptionProperty = RegisterProperty<System.String>(p => p.Description, string.Empty, (System.String)null);
public System.String Description
{
get { return GetProperty(descriptionProperty); }
set { SetProperty(descriptionProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo<System.DateTime> lastActivityDateProperty = RegisterProperty<System.DateTime>(p => p.LastActivityDate, string.Empty, System.DateTime.Now);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.DateTime LastActivityDate
{
get { return GetProperty(lastActivityDateProperty); }
set { SetProperty(lastActivityDateProperty, value); }
}
private static readonly PropertyInfo<System.Int32> mDSubjects_EmployeeWhoChengedIdProperty = RegisterProperty<System.Int32>(p => p.MDSubjects_EmployeeWhoChengedId, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 MDSubjects_EmployeeWhoChengedId
{
get { return GetProperty(mDSubjects_EmployeeWhoChengedIdProperty); }
set { SetProperty(mDSubjects_EmployeeWhoChengedIdProperty, value); }
}
protected static readonly PropertyInfo<System.Int32> companyUsingServiceIdProperty = RegisterProperty<System.Int32>(p => p.CompanyUsingServiceId, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 CompanyUsingServiceId
{
get { return GetProperty(companyUsingServiceIdProperty); }
set { SetProperty(companyUsingServiceIdProperty, value); }
}
private static readonly PropertyInfo<System.Int32?> ordinalProperty = RegisterProperty<System.Int32?>(p => p.Ordinal, string.Empty, (System.Int32?)null);
public System.Int32? Ordinal
{
get { return GetProperty(ordinalProperty); }
set { SetProperty(ordinalProperty, value); }
}
/// <summary>
/// Used for optimistic concurrency.
/// </summary>
[NotUndoable]
internal System.Byte[] LastChanged = new System.Byte[8];
#endregion
#region Factory Methods
public static cProjects_Project_Expenses NewProjects_MaterialTrackingLog()
{
return DataPortal.Create<cProjects_Project_Expenses>();
}
public static cProjects_Project_Expenses GetProjects_MaterialTrackingLog(int uniqueId)
{
return DataPortal.Fetch<cProjects_Project_Expenses>(new SingleCriteria<cProjects_Project_Expenses, int>(uniqueId));
}
public static cProjects_Project_Expenses NewChildProjects_MaterialTrackingLog()
{
return DataPortal.CreateChild<cProjects_Project_Expenses>();
}
internal static cProjects_Project_Expenses GetProjects_MaterialTrackingLog(Projects_Project_Expenses data)
{
return DataPortal.FetchChild<cProjects_Project_Expenses>(data);
}
#endregion
#region Data Access
[RunLocal]
protected override void DataPortal_Create()
{
BusinessRules.CheckRules();
}
private void DataPortal_Fetch(SingleCriteria<cProjects_Project_Expenses, int> criteria)
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
var data = ctx.ObjectContext.Projects_Project_Expenses.First(p => p.Id == criteria.Value);
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<int?>(projects_ProjectIdProperty, data.Projects_ProjectId);
LoadProperty<int?>(mDSubjects_SubjectIdProperty, data.MDSubjects_SubjectId);
LoadProperty<int>(projects_Enums_ExpensTypeIdProperty, data.Projects_Enums_ExpensTypeId);
LoadProperty<DateTime>(expenseDateProperty, data.ExpenseDate);
LoadProperty<decimal>(amountProperty, data.Amount);
LoadProperty<bool?>(invoicedProperty, data.Invoiced);
LoadProperty<int?>(documents_InvoiceIdProperty, data.Documents_InvoiceId);
LoadProperty<string>(descriptionProperty, data.Description);
LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate);
LoadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty, data.MDSubjects_EmployeeWhoChengedId);
LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId);
LoadProperty<int?>(ordinalProperty, data.Ordinal);
LastChanged = data.LastChanged;
BusinessRules.CheckRules();
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
var data = new Projects_Project_Expenses();
data.Projects_ProjectId = ReadProperty<int?>(projects_ProjectIdProperty);
data.MDSubjects_SubjectId = ReadProperty<int?>(mDSubjects_SubjectIdProperty);
data.Projects_Enums_ExpensTypeId = ReadProperty<int>(projects_Enums_ExpensTypeIdProperty);
data.ExpenseDate = ReadProperty<DateTime>(expenseDateProperty);
data.Amount = ReadProperty<decimal>(amountProperty);
data.Invoiced = ReadProperty<bool?>(invoicedProperty);
data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty);
data.Description = ReadProperty<string>(descriptionProperty);
data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty);
data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty);
data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty);
data.Ordinal = ReadProperty<int?>(ordinalProperty);
ctx.ObjectContext.AddToProjects_Project_Expenses(data);
ctx.ObjectContext.SaveChanges();
//Get New id
int newId = data.Id;
//Load New Id into object
LoadProperty(IdProperty, newId);
//Load New EntityKey into Object
LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey));
ctx.ObjectContext.SaveChanges();
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
var data = new Projects_Project_Expenses();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
data.Projects_ProjectId = ReadProperty<int?>(projects_ProjectIdProperty);
data.MDSubjects_SubjectId = ReadProperty<int?>(mDSubjects_SubjectIdProperty);
data.Projects_Enums_ExpensTypeId = ReadProperty<int>(projects_Enums_ExpensTypeIdProperty);
data.ExpenseDate = ReadProperty<DateTime>(expenseDateProperty);
data.Amount = ReadProperty<decimal>(amountProperty);
data.Invoiced = ReadProperty<bool?>(invoicedProperty);
data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty);
data.Description = ReadProperty<string>(descriptionProperty);
data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty);
data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty);
data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty);
data.Ordinal = ReadProperty<int?>(ordinalProperty);
ctx.ObjectContext.SaveChanges();
}
}
#region Child portals
[RunLocal]
protected override void Child_Create()
{
BusinessRules.CheckRules();
}
//private void Child_Fetch(Projects_MaterialTrackingLog data)
private void Child_Fetch(Projects_Project_Expenses data)
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<int?>(projects_ProjectIdProperty, data.Projects_ProjectId);
LoadProperty<int?>(mDSubjects_SubjectIdProperty, data.MDSubjects_SubjectId);
LoadProperty<int>(projects_Enums_ExpensTypeIdProperty, data.Projects_Enums_ExpensTypeId);
LoadProperty<DateTime>(expenseDateProperty, data.ExpenseDate);
LoadProperty<decimal>(amountProperty, data.Amount);
LoadProperty<bool?>(invoicedProperty, data.Invoiced);
LoadProperty<int?>(documents_InvoiceIdProperty, data.Documents_InvoiceId);
LoadProperty<string>(descriptionProperty, data.Description);
LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate);
LoadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty, data.MDSubjects_EmployeeWhoChengedId);
LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId);
LoadProperty<int?>(ordinalProperty, data.Ordinal);
LastChanged = data.LastChanged;
BusinessRules.CheckRules();
}
private void Child_Insert()
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
var data = new Projects_Project_Expenses();
data.Projects_ProjectId = ReadProperty<int?>(projects_ProjectIdProperty);
data.MDSubjects_SubjectId = ReadProperty<int?>(mDSubjects_SubjectIdProperty);
data.Projects_Enums_ExpensTypeId = ReadProperty<int>(projects_Enums_ExpensTypeIdProperty);
data.ExpenseDate = ReadProperty<DateTime>(expenseDateProperty);
data.Amount = ReadProperty<decimal>(amountProperty);
data.Invoiced = ReadProperty<bool?>(invoicedProperty);
data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty);
data.Description = ReadProperty<string>(descriptionProperty);
data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty);
data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty);
data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty);
data.Ordinal = ReadProperty<int?>(ordinalProperty);
ctx.ObjectContext.AddToProjects_Project_Expenses(data);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "Id")
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LastChanged = data.LastChanged;
}
};
}
}
private void Child_Update()
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
var data = new Projects_Project_Expenses();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
data.Projects_ProjectId = ReadProperty<int?>(projects_ProjectIdProperty);
data.MDSubjects_SubjectId = ReadProperty<int?>(mDSubjects_SubjectIdProperty);
data.Projects_Enums_ExpensTypeId = ReadProperty<int>(projects_Enums_ExpensTypeIdProperty);
data.ExpenseDate = ReadProperty<DateTime>(expenseDateProperty);
data.Amount = ReadProperty<decimal>(amountProperty);
data.Invoiced = ReadProperty<bool?>(invoicedProperty);
data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty);
data.Description = ReadProperty<string>(descriptionProperty);
data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty);
data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty);
data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty);
data.Ordinal = ReadProperty<int?>(ordinalProperty);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "LastChanged")
LastChanged = data.LastChanged;
};
}
}
private void Child_DeleteSelf()
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
var data = new Projects_Project_Expenses();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
ctx.ObjectContext.DeleteObject(data);
}
}
#endregion
#endregion
}
[Serializable]
public partial class cProjects_Project_Expenses_List : BusinessListBase<cProjects_Project_Expenses_List, cProjects_Project_Expenses>
{
public static cProjects_Project_Expenses_List NewProjects_MaterialTrackingLog_List()
{
return DataPortal.Create<cProjects_Project_Expenses_List>();
}
public static cProjects_Project_Expenses_List GetcProjects_MaterialTrackingLog_List()
{
return DataPortal.Fetch<cProjects_Project_Expenses_List>();
}
public static cProjects_Project_Expenses_List GetcProjects_MaterialTrackingLog_List_ByLinkDocumentId(int? workorderId = null, int? projectId = null)
{
return DataPortal.Fetch<cProjects_Project_Expenses_List>(new ProjectExpenses_Criteria(workorderId, projectId));
}
private void DataPortal_Fetch()
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
var result = ctx.ObjectContext.Projects_Project_Expenses.Where(p => p.CompanyUsingServiceId == ((PTIdentity)Csla.ApplicationContext.User.Identity).CompanyId);
foreach (var data in result)
{
var obj = cProjects_Project_Expenses.GetProjects_MaterialTrackingLog(data);
this.Add(obj);
}
}
}
private void DataPortal_Fetch(ProjectExpenses_Criteria criteria)
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
IQueryable<DalEf.Projects_Project_Expenses> result = null;
//if (criteria.WorkorderId != null)
//{
// result = ctx.ObjectContext.Projects_Project_Expenses.Where(p => p.Documents_WorkOrderId == criteria.WorkorderId);
//}
if (criteria.ProjectId != null)
{
result = ctx.ObjectContext.Projects_Project_Expenses.Where(p => p.Projects_ProjectId == criteria.ProjectId);
}
foreach (var data in result)
{
var obj = cProjects_Project_Expenses.GetProjects_MaterialTrackingLog(data);
this.Add(obj);
}
}
}
protected override void DataPortal_Update()
{
using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities"))
{
Child_Update();
ctx.ObjectContext.SaveChanges();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
internal class XLRange : XLRangeBase, IXLRange
{
#region Constructor
public XLRange(XLRangeParameters xlRangeParameters)
: base(xlRangeParameters.RangeAddress, (xlRangeParameters.DefaultStyle as XLStyle).Value)
{
}
#endregion Constructor
public override XLRangeType RangeType
{
get { return XLRangeType.Range; }
}
#region IXLRange Members
IXLRangeRow IXLRange.Row(Int32 row)
{
return Row(row);
}
IXLRangeColumn IXLRange.Column(Int32 columnNumber)
{
return Column(columnNumber);
}
IXLRangeColumn IXLRange.Column(String columnLetter)
{
return Column(columnLetter);
}
public virtual IXLRangeColumns Columns(Func<IXLRangeColumn, Boolean> predicate = null)
{
var retVal = new XLRangeColumns();
Int32 columnCount = ColumnCount();
for (Int32 c = 1; c <= columnCount; c++)
{
var column = Column(c);
if (predicate == null || predicate(column))
retVal.Add(column);
}
return retVal;
}
public virtual IXLRangeColumns Columns(Int32 firstColumn, Int32 lastColumn)
{
var retVal = new XLRangeColumns();
for (int co = firstColumn; co <= lastColumn; co++)
retVal.Add(Column(co));
return retVal;
}
public virtual IXLRangeColumns Columns(String firstColumn, String lastColumn)
{
return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn),
XLHelper.GetColumnNumberFromLetter(lastColumn));
}
public virtual IXLRangeColumns Columns(String columns)
{
var retVal = new XLRangeColumns();
var columnPairs = columns.Split(',');
foreach (string tPair in columnPairs.Select(pair => pair.Trim()))
{
String firstColumn;
String lastColumn;
if (tPair.Contains(':') || tPair.Contains('-'))
{
string[] columnRange = XLHelper.SplitRange(tPair);
firstColumn = columnRange[0];
lastColumn = columnRange[1];
}
else
{
firstColumn = tPair;
lastColumn = tPair;
}
if (Int32.TryParse(firstColumn, out Int32 tmp))
{
foreach (IXLRangeColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn)))
retVal.Add(col);
}
else
{
foreach (IXLRangeColumn col in Columns(firstColumn, lastColumn))
retVal.Add(col);
}
}
return retVal;
}
IXLCell IXLRange.Cell(int row, int column)
{
return Cell(row, column);
}
IXLCell IXLRange.Cell(string cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLCell IXLRange.Cell(int row, string column)
{
return Cell(row, column);
}
IXLCell IXLRange.Cell(IXLAddress cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLRange IXLRange.Range(IXLRangeAddress rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLRange.Range(string rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLRange.Range(IXLCell firstCell, IXLCell lastCell)
{
return Range(firstCell, lastCell);
}
IXLRange IXLRange.Range(string firstCellAddress, string lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLRange.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLRange.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn)
{
return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn);
}
public IXLRangeRows Rows(Func<IXLRangeRow, Boolean> predicate = null)
{
var retVal = new XLRangeRows();
Int32 rowCount = RowCount();
for (Int32 r = 1; r <= rowCount; r++)
{
var row = Row(r);
if (predicate == null || predicate(row))
retVal.Add(Row(r));
}
return retVal;
}
public IXLRangeRows Rows(Int32 firstRow, Int32 lastRow)
{
var retVal = new XLRangeRows();
for (int ro = firstRow; ro <= lastRow; ro++)
retVal.Add(Row(ro));
return retVal;
}
public IXLRangeRows Rows(String rows)
{
var retVal = new XLRangeRows();
var rowPairs = rows.Split(',');
foreach (string tPair in rowPairs.Select(pair => pair.Trim()))
{
String firstRow;
String lastRow;
if (tPair.Contains(':') || tPair.Contains('-'))
{
string[] rowRange = XLHelper.SplitRange(tPair);
firstRow = rowRange[0];
lastRow = rowRange[1];
}
else
{
firstRow = tPair;
lastRow = tPair;
}
foreach (IXLRangeRow row in Rows(Int32.Parse(firstRow), Int32.Parse(lastRow)))
retVal.Add(row);
}
return retVal;
}
public void Transpose(XLTransposeOptions transposeOption)
{
int rowCount = RowCount();
int columnCount = ColumnCount();
int squareSide = rowCount > columnCount ? rowCount : columnCount;
var firstCell = FirstCell();
MoveOrClearForTranspose(transposeOption, rowCount, columnCount);
TransposeMerged(squareSide);
TransposeRange(squareSide);
RangeAddress = new XLRangeAddress(
RangeAddress.FirstAddress,
new XLAddress(Worksheet,
firstCell.Address.RowNumber + columnCount - 1,
firstCell.Address.ColumnNumber + rowCount - 1,
RangeAddress.LastAddress.FixedRow,
RangeAddress.LastAddress.FixedColumn));
if (rowCount > columnCount)
{
var rng = Worksheet.Range(
RangeAddress.LastAddress.RowNumber + 1,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber + (rowCount - columnCount),
RangeAddress.LastAddress.ColumnNumber);
rng.Delete(XLShiftDeletedCells.ShiftCellsUp);
}
else if (columnCount > rowCount)
{
var rng = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + 1,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + (columnCount - rowCount));
rng.Delete(XLShiftDeletedCells.ShiftCellsLeft);
}
foreach (IXLCell c in Range(1, 1, columnCount, rowCount).Cells())
{
var border = (c.Style as XLStyle).Value.Border;
c.Style.Border.TopBorder = border.LeftBorder;
c.Style.Border.TopBorderColor = border.LeftBorderColor;
c.Style.Border.LeftBorder = border.TopBorder;
c.Style.Border.LeftBorderColor = border.TopBorderColor;
c.Style.Border.RightBorder = border.BottomBorder;
c.Style.Border.RightBorderColor = border.BottomBorderColor;
c.Style.Border.BottomBorder = border.RightBorder;
c.Style.Border.BottomBorderColor = border.RightBorderColor;
}
}
public IXLTable AsTable()
{
return Worksheet.Table(this, false);
}
public IXLTable AsTable(String name)
{
return Worksheet.Table(this, name, false);
}
IXLTable IXLRange.CreateTable()
{
return CreateTable();
}
public XLTable CreateTable()
{
return (XLTable)Worksheet.Table(this, true, true);
}
IXLTable IXLRange.CreateTable(String name)
{
return CreateTable(name);
}
public XLTable CreateTable(String name)
{
return (XLTable)Worksheet.Table(this, name, true, true);
}
public IXLTable CreateTable(String name, Boolean setAutofilter)
{
return Worksheet.Table(this, name, true, setAutofilter);
}
public new IXLRange CopyTo(IXLCell target)
{
base.CopyTo(target);
Int32 lastRowNumber = target.Address.RowNumber + RowCount() - 1;
if (lastRowNumber > XLHelper.MaxRowNumber)
lastRowNumber = XLHelper.MaxRowNumber;
Int32 lastColumnNumber = target.Address.ColumnNumber + ColumnCount() - 1;
if (lastColumnNumber > XLHelper.MaxColumnNumber)
lastColumnNumber = XLHelper.MaxColumnNumber;
return target.Worksheet.Range(target.Address.RowNumber,
target.Address.ColumnNumber,
lastRowNumber,
lastColumnNumber);
}
public new IXLRange CopyTo(IXLRangeBase target)
{
base.CopyTo(target);
Int32 lastRowNumber = target.RangeAddress.FirstAddress.RowNumber + RowCount() - 1;
if (lastRowNumber > XLHelper.MaxRowNumber)
lastRowNumber = XLHelper.MaxRowNumber;
Int32 lastColumnNumber = target.RangeAddress.FirstAddress.ColumnNumber + ColumnCount() - 1;
if (lastColumnNumber > XLHelper.MaxColumnNumber)
lastColumnNumber = XLHelper.MaxColumnNumber;
return target.Worksheet.Range(target.RangeAddress.FirstAddress.RowNumber,
target.RangeAddress.FirstAddress.ColumnNumber,
lastRowNumber,
lastColumnNumber);
}
public IXLRange SetDataType(XLDataType dataType)
{
DataType = dataType;
return this;
}
public new IXLRange Sort()
{
return base.Sort().AsRange();
}
public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return base.Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks).AsRange();
}
public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return base.Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks).AsRange();
}
public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return base.SortLeftToRight(sortOrder, matchCase, ignoreBlanks).AsRange();
}
#endregion IXLRange Members
internal override void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted)
{
RangeAddress = (XLRangeAddress)ShiftColumns(RangeAddress, range, columnsShifted);
}
internal override void WorksheetRangeShiftedRows(XLRange range, int rowsShifted)
{
RangeAddress = (XLRangeAddress)ShiftRows(RangeAddress, range, rowsShifted);
}
IXLRangeColumn IXLRange.FirstColumn(Func<IXLRangeColumn, Boolean> predicate)
{
return FirstColumn(predicate);
}
public XLRangeColumn FirstColumn(Func<IXLRangeColumn, Boolean> predicate = null)
{
if (predicate == null)
return Column(1);
Int32 columnCount = ColumnCount();
for (Int32 c = 1; c <= columnCount; c++)
{
var column = Column(c);
if (predicate(column)) return column;
}
return null;
}
IXLRangeColumn IXLRange.LastColumn(Func<IXLRangeColumn, Boolean> predicate)
{
return LastColumn(predicate);
}
public XLRangeColumn LastColumn(Func<IXLRangeColumn, Boolean> predicate = null)
{
Int32 columnCount = ColumnCount();
if (predicate == null)
return Column(columnCount);
for (Int32 c = columnCount; c >= 1; c--)
{
var column = Column(c);
if (predicate(column)) return column;
}
return null;
}
IXLRangeColumn IXLRange.FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate)
{
return FirstColumnUsed(false, predicate);
}
public XLRangeColumn FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null)
{
return FirstColumnUsed(false, predicate);
}
IXLRangeColumn IXLRange.FirstColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate)
{
return FirstColumnUsed(includeFormats, predicate);
}
public XLRangeColumn FirstColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 firstColumnUsed = Worksheet.Internals.CellsCollection.FirstColumnUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
return firstColumnUsed == 0 ? null : Column(firstColumnUsed - RangeAddress.FirstAddress.ColumnNumber + 1);
}
Int32 columnCount = ColumnCount();
for (Int32 co = 1; co <= columnCount; co++)
{
var column = Column(co);
if (!column.IsEmpty(includeFormats) && predicate(column))
return column;
}
return null;
}
IXLRangeColumn IXLRange.LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate)
{
return LastColumnUsed(false, predicate);
}
public XLRangeColumn LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null)
{
return LastColumnUsed(false, predicate);
}
IXLRangeColumn IXLRange.LastColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate)
{
return LastColumnUsed(includeFormats, predicate);
}
public XLRangeColumn LastColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 lastColumnUsed = Worksheet.Internals.CellsCollection.LastColumnUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
return lastColumnUsed == 0 ? null : Column(lastColumnUsed - RangeAddress.FirstAddress.ColumnNumber + 1);
}
Int32 columnCount = ColumnCount();
for (Int32 co = columnCount; co >= 1; co--)
{
var column = Column(co);
if (!column.IsEmpty(includeFormats) && predicate(column))
return column;
}
return null;
}
IXLRangeRow IXLRange.FirstRow(Func<IXLRangeRow, Boolean> predicate)
{
return FirstRow(predicate);
}
public XLRangeRow FirstRow(Func<IXLRangeRow, Boolean> predicate = null)
{
if (predicate == null)
return Row(1);
Int32 rowCount = RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = Row(ro);
if (predicate(row)) return row;
}
return null;
}
IXLRangeRow IXLRange.LastRow(Func<IXLRangeRow, Boolean> predicate)
{
return LastRow(predicate);
}
public XLRangeRow LastRow(Func<IXLRangeRow, Boolean> predicate = null)
{
Int32 rowCount = RowCount();
if (predicate == null)
return Row(rowCount);
for (Int32 ro = rowCount; ro >= 1; ro--)
{
var row = Row(ro);
if (predicate(row)) return row;
}
return null;
}
IXLRangeRow IXLRange.FirstRowUsed(Func<IXLRangeRow, Boolean> predicate)
{
return FirstRowUsed(false, predicate);
}
public XLRangeRow FirstRowUsed(Func<IXLRangeRow, Boolean> predicate = null)
{
return FirstRowUsed(false, predicate);
}
IXLRangeRow IXLRange.FirstRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate)
{
return FirstRowUsed(includeFormats, predicate);
}
public XLRangeRow FirstRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 rowFromCells = Worksheet.Internals.CellsCollection.FirstRowUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
//Int32 rowFromRows = Worksheet.Internals.RowsCollection.FirstRowUsed(includeFormats);
return rowFromCells == 0 ? null : Row(rowFromCells - RangeAddress.FirstAddress.RowNumber + 1);
}
Int32 rowCount = RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = Row(ro);
if (!row.IsEmpty(includeFormats) && predicate(row))
return row;
}
return null;
}
IXLRangeRow IXLRange.LastRowUsed(Func<IXLRangeRow, Boolean> predicate)
{
return LastRowUsed(false, predicate);
}
public XLRangeRow LastRowUsed(Func<IXLRangeRow, Boolean> predicate = null)
{
return LastRowUsed(false, predicate);
}
IXLRangeRow IXLRange.LastRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate)
{
return LastRowUsed(includeFormats, predicate);
}
public XLRangeRow LastRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null)
{
if (predicate == null)
{
Int32 lastRowUsed = Worksheet.Internals.CellsCollection.LastRowUsed(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber,
includeFormats);
return lastRowUsed == 0 ? null : Row(lastRowUsed - RangeAddress.FirstAddress.RowNumber + 1);
}
Int32 rowCount = RowCount();
for (Int32 ro = rowCount; ro >= 1; ro--)
{
var row = Row(ro);
if (!row.IsEmpty(includeFormats) && predicate(row))
return row;
}
return null;
}
IXLRangeRows IXLRange.RowsUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate)
{
return RowsUsed(includeFormats, predicate);
}
public XLRangeRows RowsUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null)
{
XLRangeRows rows = new XLRangeRows();
Int32 rowCount = RowCount();
for (Int32 ro = 1; ro <= rowCount; ro++)
{
var row = Row(ro);
if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row)))
rows.Add(row);
}
return rows;
}
IXLRangeRows IXLRange.RowsUsed(Func<IXLRangeRow, Boolean> predicate)
{
return RowsUsed(predicate);
}
public XLRangeRows RowsUsed(Func<IXLRangeRow, Boolean> predicate = null)
{
return RowsUsed(false, predicate);
}
IXLRangeColumns IXLRange.ColumnsUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate)
{
return ColumnsUsed(includeFormats, predicate);
}
public virtual XLRangeColumns ColumnsUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null)
{
XLRangeColumns columns = new XLRangeColumns();
Int32 columnCount = ColumnCount();
for (Int32 co = 1; co <= columnCount; co++)
{
var column = Column(co);
if (!column.IsEmpty(includeFormats) && (predicate == null || predicate(column)))
columns.Add(column);
}
return columns;
}
IXLRangeColumns IXLRange.ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate)
{
return ColumnsUsed(predicate);
}
public virtual XLRangeColumns ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate = null)
{
return ColumnsUsed(false, predicate);
}
public XLRangeRow Row(Int32 row)
{
if (row <= 0 || row > XLHelper.MaxRowNumber)
throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}", XLHelper.MaxRowNumber));
var firstCellAddress = new XLAddress(Worksheet,
RangeAddress.FirstAddress.RowNumber + row - 1,
RangeAddress.FirstAddress.ColumnNumber,
false,
false);
var lastCellAddress = new XLAddress(Worksheet,
RangeAddress.FirstAddress.RowNumber + row - 1,
RangeAddress.LastAddress.ColumnNumber,
false,
false);
return Worksheet.RangeRow(new XLRangeAddress(firstCellAddress, lastCellAddress));
}
public virtual XLRangeColumn Column(Int32 columnNumber)
{
if (columnNumber <= 0 || columnNumber > XLHelper.MaxColumnNumber)
throw new IndexOutOfRangeException(String.Format("Column number must be between 1 and {0}", XLHelper.MaxColumnNumber));
var firstCellAddress = new XLAddress(Worksheet,
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber + columnNumber - 1,
false,
false);
var lastCellAddress = new XLAddress(Worksheet,
RangeAddress.LastAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber + columnNumber - 1,
false,
false);
return Worksheet.RangeColumn(new XLRangeAddress(firstCellAddress, lastCellAddress));
}
public virtual XLRangeColumn Column(String columnLetter)
{
return Column(XLHelper.GetColumnNumberFromLetter(columnLetter));
}
private void TransposeRange(int squareSide)
{
var cellsToInsert = new Dictionary<XLSheetPoint, XLCell>();
var cellsToDelete = new List<XLSheetPoint>();
var rngToTranspose = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.FirstAddress.RowNumber + squareSide - 1,
RangeAddress.FirstAddress.ColumnNumber + squareSide - 1);
Int32 roCount = rngToTranspose.RowCount();
Int32 coCount = rngToTranspose.ColumnCount();
for (Int32 ro = 1; ro <= roCount; ro++)
{
for (Int32 co = 1; co <= coCount; co++)
{
var oldCell = rngToTranspose.Cell(ro, co);
var newKey = rngToTranspose.Cell(co, ro).Address;
// new XLAddress(Worksheet, c.Address.ColumnNumber, c.Address.RowNumber);
var newCell = new XLCell(Worksheet, newKey, oldCell.StyleValue);
newCell.CopyFrom(oldCell, true);
cellsToInsert.Add(new XLSheetPoint(newKey.RowNumber, newKey.ColumnNumber), newCell);
cellsToDelete.Add(new XLSheetPoint(oldCell.Address.RowNumber, oldCell.Address.ColumnNumber));
}
}
cellsToDelete.ForEach(c => Worksheet.Internals.CellsCollection.Remove(c));
cellsToInsert.ForEach(c => Worksheet.Internals.CellsCollection.Add(c.Key, c.Value));
}
private void TransposeMerged(Int32 squareSide)
{
var rngToTranspose = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.FirstAddress.RowNumber + squareSide - 1,
RangeAddress.FirstAddress.ColumnNumber + squareSide - 1);
foreach (var merge in Worksheet.Internals.MergedRanges.Where(Contains).Cast<XLRange>())
{
merge.RangeAddress = new XLRangeAddress(
merge.RangeAddress.FirstAddress,
rngToTranspose.Cell(merge.ColumnCount(), merge.RowCount()).Address);
}
}
private void MoveOrClearForTranspose(XLTransposeOptions transposeOption, int rowCount, int columnCount)
{
if (transposeOption == XLTransposeOptions.MoveCells)
{
if (rowCount > columnCount)
InsertColumnsAfter(false, rowCount - columnCount, false);
else if (columnCount > rowCount)
InsertRowsBelow(false, columnCount - rowCount, false);
}
else
{
if (rowCount > columnCount)
{
int toMove = rowCount - columnCount;
var rngToClear = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + 1,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber + toMove);
rngToClear.Clear();
}
else if (columnCount > rowCount)
{
int toMove = columnCount - rowCount;
var rngToClear = Worksheet.Range(
RangeAddress.LastAddress.RowNumber + 1,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber + toMove,
RangeAddress.LastAddress.ColumnNumber);
rngToClear.Clear();
}
}
}
public override bool Equals(object obj)
{
var other = obj as XLRange;
if (other == null)
return false;
return RangeAddress.Equals(other.RangeAddress)
&& Worksheet.Equals(other.Worksheet);
}
public override int GetHashCode()
{
return RangeAddress.GetHashCode()
^ Worksheet.GetHashCode();
}
public new IXLRange Clear(XLClearOptions clearOptions = XLClearOptions.All)
{
base.Clear(clearOptions);
return this;
}
public IXLRangeColumn FindColumn(Func<IXLRangeColumn, bool> predicate)
{
Int32 columnCount = ColumnCount();
for (Int32 c = 1; c <= columnCount; c++)
{
var column = Column(c);
if (predicate == null || predicate(column))
return column;
}
return null;
}
public IXLRangeRow FindRow(Func<IXLRangeRow, bool> predicate)
{
Int32 rowCount = RowCount();
for (Int32 r = 1; r <= rowCount; r++)
{
var row = Row(r);
if (predicate(row))
return row;
}
return null;
}
}
}
| |
#region license
// Copyright 2004-2012 Castle Project, Henrik Feldt &contributors - https://github.com/castleproject
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace Castle.IO
{
// wow, I am actually using the partial keyword.
// the reason for this is that I think the static
// methods corresponding to System.IO.Path should
// be in their own class declaration, yet
// I'm reluctant to rename this class or
// to rename the static method carrying class
// for that matter!
/// <summary>
/// Immutable value object for dealing with paths. A path as an object,
/// is the idea.
/// </summary>
public partial class Path : IEquatable<Path>
{
private readonly string originalPath;
private readonly PathInfo pathInfo;
private readonly IList<string> segments;
public Path(string path)
{
Contract.Requires(path != null);
Contract.Requires(!string.IsNullOrEmpty(path));
originalPath = path;
pathInfo = PathInfo.Parse(path);
segments = GenerateSegments(path);
}
/// <summary>
/// Gets the drive + directory path. If the given path ends with a slash,
/// the last bit is also included in this property, otherwise, not.
/// </summary>
public string DriveAndDirectory
{
get
{
var sep = DirectorySeparatorChar.ToString();
if (IsDirectoryPath)
return pathInfo.Drive + pathInfo.FolderAndFiles;
if (segments.Count == 1)
return segments[0];
var middle = segments.Skip(1).Take(Math.Max(0, segments.Count - 2));
return string.Join(sep, new[] {pathInfo.Drive}.Concat(middle).ToArray());
}
}
public bool IsRooted
{
get { return pathInfo.IsRooted; }
}
private static IList<string> GenerateSegments(string path)
{
return path
.Split(new[] {DirectorySeparatorChar, AltDirectorySeparatorChar},
StringSplitOptions.RemoveEmptyEntries)
.Except(new[] {"?"})
.ToList();
}
public string FullPath
{
get { return originalPath; }
}
public IEnumerable<string> Segments
{
get { return segments; }
}
/// <summary>
/// Gets whether it's garantueed that the path is a directory (it is of its
/// last character is a directory separator character).
/// </summary>
public bool IsDirectoryPath
{
get
{
return FullPath.EndsWith(DirectorySeparatorChar + "") ||
FullPath.EndsWith(AltDirectorySeparatorChar + "");
}
}
/// <summary>
/// Gets the underlying path info structure. With this you can get a lot
/// more sematic information about the path.
/// </summary>
public PathInfo Info
{
get { return pathInfo; }
}
public Path Combine(params string[] paths)
{
var combinedPath = paths.Aggregate(FullPath, System.IO.Path.Combine);
return new Path(combinedPath);
}
public Path Combine(params Path[] paths)
{
return Combine(paths.Select(p => p.FullPath).ToArray());
}
#region Equality operators
public bool Equals(Path other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.pathInfo.Equals(pathInfo);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (!(obj is Path)) return false;
return Equals((Path) obj);
}
public override int GetHashCode()
{
return pathInfo.GetHashCode();
}
public override string ToString()
{
return originalPath;
}
public static bool operator ==(Path left, Path right)
{
return Equals(left, right);
}
public static bool operator !=(Path left, Path right)
{
return !Equals(left, right);
}
//public static implicit operator string(Path path)
//{
// return path.ToString();
//}
#endregion
/// <summary>
/// Yields a new path instance from the current data object
/// and the object passed as the parameter 'path'.
/// </summary>
/// <param name = "toBasePath">The path to make the invokee relative to.</param>
/// <returns>A new path that is relative to the passed path.</returns>
public Path MakeRelative(Path toBasePath)
{
if (!IsRooted)
return this;
var leftOverSegments = new List<string>();
var relativeSegmentCount = 0;
var thisEnum = Segments.GetEnumerator();
var rootEnum = toBasePath.Segments.GetEnumerator();
bool thisHasValue;
bool rootHasValue;
do
{
thisHasValue = thisEnum.MoveNext();
rootHasValue = rootEnum.MoveNext();
if (thisHasValue && rootHasValue)
{
if (thisEnum.Current.Equals(rootEnum.Current, StringComparison.OrdinalIgnoreCase))
continue;
}
if (thisHasValue)
{
leftOverSegments.Add(thisEnum.Current);
}
if (rootHasValue)
relativeSegmentCount++;
} while (thisHasValue || rootHasValue);
var relativeSegment = Enumerable.Repeat("..", relativeSegmentCount).Aggregate("", System.IO.Path.Combine);
var finalSegment = System.IO.Path.Combine(relativeSegment, leftOverSegments.Aggregate("", System.IO.Path.Combine));
return new Path(finalSegment);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using size_t = System.IntPtr;
using libc = Interop.libc;
using libcurl = Interop.libcurl;
using PollFlags = Interop.libc.PollFlags;
internal static partial class Interop
{
internal static partial class libcurl
{
internal sealed class SafeCurlHandle : SafeHandle
{
public SafeCurlHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return this.handle == IntPtr.Zero; }
}
public static void DisposeAndClearHandle(ref SafeCurlHandle curlHandle)
{
if (curlHandle != null)
{
curlHandle.Dispose();
curlHandle = null;
}
}
protected override bool ReleaseHandle()
{
libcurl.curl_easy_cleanup(this.handle);
return true;
}
}
internal sealed class SafeCurlMultiHandle : SafeHandle
{
private bool _pollCancelled = true;
private readonly int[] _specialFds = new int[2];
private readonly HashSet<int> _fdSet = new HashSet<int>();
private int _requestCount = 0;
private Timer _timer;
internal bool PollCancelled
{
get { return _pollCancelled; }
set { _pollCancelled = value; }
}
internal int RequestCount
{
get { return _requestCount; }
set { _requestCount = value; }
}
internal Timer Timer
{
get { return _timer; }
set { _timer = value; }
}
public SafeCurlMultiHandle()
: base(IntPtr.Zero, true)
{
unsafe
{
fixed(int* fds = _specialFds)
{
while (Interop.CheckIo(Interop.Sys.Pipe(fds)));
}
}
}
public override bool IsInvalid
{
get { return this.handle == IntPtr.Zero; }
}
public static void DisposeAndClearHandle(ref SafeCurlMultiHandle curlHandle)
{
if (curlHandle != null)
{
curlHandle.Dispose();
curlHandle = null;
}
}
internal void PollFds(List<libc.pollfd> readyFds)
{
int count;
libc.pollfd[] pollFds;
readyFds.Clear();
lock (this)
{
// TODO: Avoid the allocation when count is in 100s
count = _fdSet.Count + 1;
pollFds = new libc.pollfd[count];
// Always include special fd in the poll set. This is used to
// return from the poll in case any fds have been added or
// removed to the set of fds being polled. This prevents starvation
// in case current set of fds have no activity but the new fd
// is ready for a read/write. The special fd is the read end of a pipe
// Whenever an fd is added/removed in _fdSet, a write happens to the
// write end of the pipe thus causing the poll to return.
pollFds[0].fd = _specialFds[Interop.Sys.ReadEndOfPipe];
pollFds[0].events = PollFlags.POLLIN;
int i = 1;
foreach (int fd in _fdSet)
{
pollFds[i].fd = fd;
pollFds[i].events = PollFlags.POLLIN | PollFlags.POLLOUT;
i++;
}
}
unsafe
{
fixed (libc.pollfd* fds = pollFds)
{
int numFds = libc.poll(fds, (uint)count, -1);
if (numFds <= 0)
{
Debug.Assert(numFds != 0); // Since timeout is infinite
// TODO: How to handle errors?
throw new InvalidOperationException("Poll failure: " + Marshal.GetLastWin32Error());
}
lock (this)
{
if (0 == _requestCount)
{
return;
}
}
// Check for any fdset changes
if (fds[0].revents != 0)
{
if (ReadSpecialFd(fds[0].revents) < 0)
{
// TODO: How to handle errors?
throw new InvalidOperationException("Cannot read data: " + Marshal.GetLastWin32Error());
}
numFds--;
}
// Now check for events on the remaining fds
for (int i = 1; i < count && numFds > 0; i++)
{
if (fds[i].revents == 0)
{
continue;
}
readyFds.Add(fds[i]);
numFds--;
}
}
}
}
internal void SignalFdSetChange(int fd, bool isRemove)
{
Debug.Assert(Monitor.IsEntered(this));
bool changed = isRemove ? _fdSet.Remove(fd) : _fdSet.Add(fd);
if (!changed)
{
return;
}
unsafe
{
// Write to special fd
byte* dummyBytes = stackalloc byte[1];
if ((int)libc.write(_specialFds[Interop.Sys.WriteEndOfPipe], dummyBytes, (size_t)1) <= 0)
{
// TODO: How to handle errors?
throw new InvalidOperationException("Cannot write data: " + Marshal.GetLastWin32Error());
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (null != _timer)
{
_timer.Dispose();
}
}
base.Dispose(disposing);
}
protected override bool ReleaseHandle()
{
Debug.Assert(0 == _fdSet.Count);
Debug.Assert(0 == _requestCount);
Debug.Assert(_pollCancelled);
Interop.Sys.Close(_specialFds[Interop.Sys.ReadEndOfPipe]);
Interop.Sys.Close(_specialFds[Interop.Sys.WriteEndOfPipe]);
libcurl.curl_multi_cleanup(this.handle);
return true;
}
private int ReadSpecialFd(PollFlags revents)
{
PollFlags badEvents = PollFlags.POLLERR | PollFlags.POLLHUP | PollFlags.POLLNVAL;
if ((revents & badEvents) != 0)
{
return -1;
}
Debug.Assert((revents & PollFlags.POLLIN) != 0);
int pipeReadFd = _specialFds[Interop.Sys.ReadEndOfPipe];
int bytesRead = 0;
unsafe
{
do
{
// Read available data from the pipe
int bufferLength = 1024;
byte* dummyBytes = stackalloc byte[bufferLength];
int numBytes = (int)libc.read(pipeReadFd, dummyBytes, (size_t)bufferLength);
if (numBytes <= 0)
{
return -1;
}
bytesRead += numBytes;
// Check if more data is available
PollFlags outFlags;
int retVal = libc.poll(pipeReadFd, PollFlags.POLLIN, 0, out outFlags);
if (retVal < 0)
{
return -1;
}
else if (0 == retVal)
{
break;
}
}
while (true);
}
return bytesRead;
}
}
internal sealed class SafeCurlSlistHandle : SafeHandle
{
public SafeCurlSlistHandle()
: base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get { return this.handle == IntPtr.Zero; }
}
public new void SetHandle(IntPtr handle)
{
base.SetHandle(handle);
}
public static void DisposeAndClearHandle(ref SafeCurlSlistHandle curlHandle)
{
if (curlHandle != null)
{
curlHandle.Dispose();
curlHandle = null;
}
}
protected override bool ReleaseHandle()
{
libcurl.curl_slist_free_all(this.handle);
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.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
namespace System.Security.Cryptography
{
public class CryptoConfig
{
private const string AssemblyName_Cng = "System.Security.Cryptography.Cng";
private const string AssemblyName_Csp = "System.Security.Cryptography.Csp";
private const string AssemblyName_Pkcs = "System.Security.Cryptography.Pkcs";
private const string AssemblyName_X509Certificates = "System.Security.Cryptography.X509Certificates";
private const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
private const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6";
private const string OID_RSA_MD5 = "1.2.840.113549.2.5";
private const string OID_RSA_RC2CBC = "1.2.840.113549.3.2";
private const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7";
private const string OID_OIWSEC_desCBC = "1.3.14.3.2.7";
private const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26";
private const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1";
private const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2";
private const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3";
private const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1";
private const string ECDsaIdentifier = "ECDsa";
private static volatile Dictionary<string, string> s_defaultOidHT;
private static volatile Dictionary<string, object> s_defaultNameHT;
private static readonly ConcurrentDictionary<string, Type> appNameHT = new ConcurrentDictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
private static readonly ConcurrentDictionary<string, string> appOidHT = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static readonly char[] SepArray = { '.' }; // valid ASN.1 separators
// CoreFx does not support AllowOnlyFipsAlgorithms
public static bool AllowOnlyFipsAlgorithms => false;
private static Dictionary<string, string> DefaultOidHT
{
get
{
if (s_defaultOidHT != null)
{
return s_defaultOidHT;
}
int capacity = 37;
Dictionary<string, string> ht = new Dictionary<string, string>(capacity, StringComparer.OrdinalIgnoreCase);
ht.Add("SHA", OID_OIWSEC_SHA1);
ht.Add("SHA1", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1CryptoServiceProvider", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1Cng", OID_OIWSEC_SHA1);
ht.Add("System.Security.Cryptography.SHA1Managed", OID_OIWSEC_SHA1);
ht.Add("SHA256", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256Cng", OID_OIWSEC_SHA256);
ht.Add("System.Security.Cryptography.SHA256Managed", OID_OIWSEC_SHA256);
ht.Add("SHA384", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384Cng", OID_OIWSEC_SHA384);
ht.Add("System.Security.Cryptography.SHA384Managed", OID_OIWSEC_SHA384);
ht.Add("SHA512", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512Cng", OID_OIWSEC_SHA512);
ht.Add("System.Security.Cryptography.SHA512Managed", OID_OIWSEC_SHA512);
ht.Add("RIPEMD160", OID_OIWSEC_RIPEMD160);
ht.Add("System.Security.Cryptography.RIPEMD160", OID_OIWSEC_RIPEMD160);
ht.Add("System.Security.Cryptography.RIPEMD160Managed", OID_OIWSEC_RIPEMD160);
ht.Add("MD5", OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5", OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5CryptoServiceProvider", OID_RSA_MD5);
ht.Add("System.Security.Cryptography.MD5Managed", OID_RSA_MD5);
ht.Add("TripleDESKeyWrap", OID_RSA_SMIMEalgCMS3DESwrap);
ht.Add("RC2", OID_RSA_RC2CBC);
ht.Add("System.Security.Cryptography.RC2CryptoServiceProvider", OID_RSA_RC2CBC);
ht.Add("DES", OID_OIWSEC_desCBC);
ht.Add("System.Security.Cryptography.DESCryptoServiceProvider", OID_OIWSEC_desCBC);
ht.Add("TripleDES", OID_RSA_DES_EDE3_CBC);
ht.Add("System.Security.Cryptography.TripleDESCryptoServiceProvider", OID_RSA_DES_EDE3_CBC);
Debug.Assert(ht.Count <= capacity); // if more entries are added in the future, increase initial capacity.
s_defaultOidHT = ht;
return s_defaultOidHT;
}
}
private static Dictionary<string, object> DefaultNameHT
{
get
{
if (s_defaultNameHT != null)
{
return s_defaultNameHT;
}
const int capacity = 89;
Dictionary<string, object> ht = new Dictionary<string, object>(capacity: capacity, comparer: StringComparer.OrdinalIgnoreCase);
Type HMACMD5Type = typeof(System.Security.Cryptography.HMACMD5);
Type HMACSHA1Type = typeof(System.Security.Cryptography.HMACSHA1);
Type HMACSHA256Type = typeof(System.Security.Cryptography.HMACSHA256);
Type HMACSHA384Type = typeof(System.Security.Cryptography.HMACSHA384);
Type HMACSHA512Type = typeof(System.Security.Cryptography.HMACSHA512);
Type RijndaelManagedType = typeof(System.Security.Cryptography.RijndaelManaged);
Type AesManagedType = typeof(System.Security.Cryptography.AesManaged);
Type SHA256DefaultType = typeof(System.Security.Cryptography.SHA256Managed);
Type SHA384DefaultType = typeof(System.Security.Cryptography.SHA384Managed);
Type SHA512DefaultType = typeof(System.Security.Cryptography.SHA512Managed);
string SHA1CryptoServiceProviderType = "System.Security.Cryptography.SHA1CryptoServiceProvider, " + AssemblyName_Csp;
string MD5CryptoServiceProviderType = "System.Security.Cryptography.MD5CryptoServiceProvider," + AssemblyName_Csp;
string RSACryptoServiceProviderType = "System.Security.Cryptography.RSACryptoServiceProvider, " + AssemblyName_Csp;
string DSACryptoServiceProviderType = "System.Security.Cryptography.DSACryptoServiceProvider, " + AssemblyName_Csp;
string DESCryptoServiceProviderType = "System.Security.Cryptography.DESCryptoServiceProvider, " + AssemblyName_Csp;
string TripleDESCryptoServiceProviderType = "System.Security.Cryptography.TripleDESCryptoServiceProvider, " + AssemblyName_Csp;
string RC2CryptoServiceProviderType = "System.Security.Cryptography.RC2CryptoServiceProvider, " + AssemblyName_Csp;
string RNGCryptoServiceProviderType = "System.Security.Cryptography.RNGCryptoServiceProvider, " + AssemblyName_Csp;
string AesCryptoServiceProviderType = "System.Security.Cryptography.AesCryptoServiceProvider, " + AssemblyName_Csp;
string ECDsaCngType = "System.Security.Cryptography.ECDsaCng, " + AssemblyName_Cng;
// Random number generator
ht.Add("RandomNumberGenerator", RNGCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RandomNumberGenerator", RNGCryptoServiceProviderType);
// Hash functions
ht.Add("SHA", SHA1CryptoServiceProviderType);
ht.Add("SHA1", SHA1CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.SHA1", SHA1CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.HashAlgorithm", SHA1CryptoServiceProviderType);
ht.Add("MD5", MD5CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.MD5", MD5CryptoServiceProviderType);
ht.Add("SHA256", SHA256DefaultType);
ht.Add("SHA-256", SHA256DefaultType);
ht.Add("System.Security.Cryptography.SHA256", SHA256DefaultType);
ht.Add("SHA384", SHA384DefaultType);
ht.Add("SHA-384", SHA384DefaultType);
ht.Add("System.Security.Cryptography.SHA384", SHA384DefaultType);
ht.Add("SHA512", SHA512DefaultType);
ht.Add("SHA-512", SHA512DefaultType);
ht.Add("System.Security.Cryptography.SHA512", SHA512DefaultType);
// Keyed Hash Algorithms
ht.Add("System.Security.Cryptography.HMAC", HMACSHA1Type);
ht.Add("System.Security.Cryptography.KeyedHashAlgorithm", HMACSHA1Type);
ht.Add("HMACMD5", HMACMD5Type);
ht.Add("System.Security.Cryptography.HMACMD5", HMACMD5Type);
ht.Add("HMACSHA1", HMACSHA1Type);
ht.Add("System.Security.Cryptography.HMACSHA1", HMACSHA1Type);
ht.Add("HMACSHA256", HMACSHA256Type);
ht.Add("System.Security.Cryptography.HMACSHA256", HMACSHA256Type);
ht.Add("HMACSHA384", HMACSHA384Type);
ht.Add("System.Security.Cryptography.HMACSHA384", HMACSHA384Type);
ht.Add("HMACSHA512", HMACSHA512Type);
ht.Add("System.Security.Cryptography.HMACSHA512", HMACSHA512Type);
// Asymmetric algorithms
ht.Add("RSA", RSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RSA", RSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.AsymmetricAlgorithm", RSACryptoServiceProviderType);
ht.Add("DSA", DSACryptoServiceProviderType);
ht.Add("System.Security.Cryptography.DSA", DSACryptoServiceProviderType);
// Windows will register the public ECDsaCng type. Non-Windows gets a special handler.
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
ht.Add(ECDsaIdentifier, ECDsaCngType);
}
ht.Add("ECDsaCng", ECDsaCngType);
ht.Add("System.Security.Cryptography.ECDsaCng", ECDsaCngType);
// Symmetric algorithms
ht.Add("DES", DESCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.DES", DESCryptoServiceProviderType);
ht.Add("3DES", TripleDESCryptoServiceProviderType);
ht.Add("TripleDES", TripleDESCryptoServiceProviderType);
ht.Add("Triple DES", TripleDESCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.TripleDES", TripleDESCryptoServiceProviderType);
ht.Add("RC2", RC2CryptoServiceProviderType);
ht.Add("System.Security.Cryptography.RC2", RC2CryptoServiceProviderType);
ht.Add("Rijndael", RijndaelManagedType);
ht.Add("System.Security.Cryptography.Rijndael", RijndaelManagedType);
// Rijndael is the default symmetric cipher because (a) it's the strongest and (b) we know we have an implementation everywhere
ht.Add("System.Security.Cryptography.SymmetricAlgorithm", RijndaelManagedType);
ht.Add("AES", AesCryptoServiceProviderType);
ht.Add("AesCryptoServiceProvider", AesCryptoServiceProviderType);
ht.Add("System.Security.Cryptography.AesCryptoServiceProvider", AesCryptoServiceProviderType);
ht.Add("AesManaged", AesManagedType);
ht.Add("System.Security.Cryptography.AesManaged", AesManagedType);
// Xml Dsig/ Enc Hash algorithms
ht.Add("http://www.w3.org/2000/09/xmldsig#sha1", SHA1CryptoServiceProviderType);
// Add the other hash algorithms introduced with XML Encryption
ht.Add("http://www.w3.org/2001/04/xmlenc#sha256", SHA256DefaultType);
ht.Add("http://www.w3.org/2001/04/xmlenc#sha512", SHA512DefaultType);
// Xml Encryption symmetric keys
ht.Add("http://www.w3.org/2001/04/xmlenc#des-cbc", DESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", TripleDESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-tripledes", TripleDESCryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes128-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes128", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes192-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes192", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#aes256-cbc", RijndaelManagedType);
ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes256", RijndaelManagedType);
// Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/
ht.Add("http://www.w3.org/2000/09/xmldsig#hmac-sha1", HMACSHA1Type);
// Xml Dsig-more Uri's as defined in http://www.ietf.org/rfc/rfc4051.txt
ht.Add("http://www.w3.org/2001/04/xmldsig-more#md5", MD5CryptoServiceProviderType);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#sha384", SHA384DefaultType);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-md5", HMACMD5Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", HMACSHA256Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", HMACSHA384Type);
ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", HMACSHA512Type);
// X509 Extensions (custom decoders)
// Basic Constraints OID value
ht.Add("2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates);
ht.Add("2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates);
// Subject Key Identifier OID value
ht.Add("2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension, " + AssemblyName_X509Certificates);
// Key Usage OID value
ht.Add("2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension, " + AssemblyName_X509Certificates);
// Enhanced Key Usage OID value
ht.Add("2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension, " + AssemblyName_X509Certificates);
// X509Chain class can be overridden to use a different chain engine.
ht.Add("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain, " + AssemblyName_X509Certificates);
// PKCS9 attributes
ht.Add("1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType, " + AssemblyName_Pkcs);
ht.Add("1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest, " + AssemblyName_Pkcs);
ht.Add("1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime, " + AssemblyName_Pkcs);
ht.Add("1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName, " + AssemblyName_Pkcs);
ht.Add("1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription, " + AssemblyName_Pkcs);
Debug.Assert(ht.Count <= capacity); // // if more entries are added in the future, increase initial capacity.
s_defaultNameHT = ht;
return s_defaultNameHT;
// Types in Desktop but currently unsupported in CoreFx:
// Type HMACRIPEMD160Type = typeof(System.Security.Cryptography.HMACRIPEMD160);
// Type MAC3DESType = typeof(System.Security.Cryptography.MACTripleDES);
// Type DSASignatureDescriptionType = typeof(System.Security.Cryptography.DSASignatureDescription);
// Type RSAPKCS1SHA1SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription);
// Type RSAPKCS1SHA256SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA256SignatureDescription);
// Type RSAPKCS1SHA384SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA384SignatureDescription);
// Type RSAPKCS1SHA512SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA512SignatureDescription);
// string RIPEMD160ManagedType = "System.Security.Cryptography.RIPEMD160Managed" + AssemblyName_Encoding;
// string ECDiffieHellmanCngType = "System.Security.Cryptography.ECDiffieHellmanCng, " + AssemblyName_Cng;
// string MD5CngType = "System.Security.Cryptography.MD5Cng, " + AssemblyName_Cng;
// string SHA1CngType = "System.Security.Cryptography.SHA1Cng, " + AssemblyName_Cng;
// string SHA256CngType = "System.Security.Cryptography.SHA256Cng, " + AssemblyName_Cng;
// string SHA384CngType = "System.Security.Cryptography.SHA384Cng, " + AssemblyName_Cng;
// string SHA512CngType = "System.Security.Cryptography.SHA512Cng, " + AssemblyName_Cng;
// string SHA256CryptoServiceProviderType = "System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyName_Csp;
// string SHA384CryptoSerivceProviderType = "System.Security.Cryptography.SHA384CryptoServiceProvider, " + AssemblyName_Csp;
// string SHA512CryptoServiceProviderType = "System.Security.Cryptography.SHA512CryptoServiceProvider, " + AssemblyName_Csp;
// string DpapiDataProtectorType = "System.Security.Cryptography.DpapiDataProtector, " + AssemblyRef.SystemSecurity;
}
}
public static void AddAlgorithm(Type algorithm, params string[] names)
{
if (algorithm == null)
throw new ArgumentNullException(nameof(algorithm));
if (!algorithm.IsVisible)
throw new ArgumentException(SR.Cryptography_AlgorithmTypesMustBeVisible, nameof(algorithm));
if (names == null)
throw new ArgumentNullException(nameof(names));
string[] algorithmNames = new string[names.Length];
Array.Copy(names, 0, algorithmNames, 0, algorithmNames.Length);
// Pre-check the algorithm names for validity so that we don't add a few of the names and then
// throw an exception if we find an invalid name partway through the list.
foreach (string name in algorithmNames)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName);
}
}
// Everything looks valid, so we're safe to add the name mappings.
foreach (string name in algorithmNames)
{
appNameHT[name] = algorithm;
}
}
public static object CreateFromName(string name, params object[] args)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
// Check to see if we have an application defined mapping
appNameHT.TryGetValue(name, out Type retvalType);
// We allow the default table to Types and Strings
// Types get used for types in .Algorithms assembly.
// strings get used for delay-loaded stuff in other assemblies such as .Csp.
if (retvalType == null && DefaultNameHT.TryGetValue(name, out object retvalObj))
{
retvalType = retvalObj as Type;
if (retvalType == null)
{
if (retvalObj is string retvalString)
{
retvalType = Type.GetType(retvalString, false, false);
if (retvalType != null && !retvalType.IsVisible)
{
retvalType = null;
}
if (retvalType != null)
{
// Add entry to the appNameHT, which makes subsequent calls much faster.
appNameHT[name] = retvalType;
}
}
else
{
Debug.Fail("Unsupported Dictionary value:" + retvalObj.ToString());
}
}
}
// Special case asking for "ECDsa" since the default map from .NET Framework uses
// a Windows-only type.
if (retvalType == null &&
(args == null || args.Length == 1) &&
name == ECDsaIdentifier)
{
return ECDsa.Create();
}
// Maybe they gave us a classname.
if (retvalType == null)
{
retvalType = Type.GetType(name, false, false);
if (retvalType != null && !retvalType.IsVisible)
{
retvalType = null;
}
}
// Still null? Then we didn't find it.
if (retvalType == null)
{
return null;
}
// Locate all constructors.
MethodBase[] cons = retvalType.GetConstructors(ConstructorDefault);
if (cons == null)
{
return null;
}
if (args == null)
{
args = Array.Empty<object>();
}
List<MethodBase> candidates = new List<MethodBase>();
for (int i = 0; i < cons.Length; i++)
{
MethodBase con = cons[i];
if (con.GetParameters().Length == args.Length)
{
candidates.Add(con);
}
}
if (candidates.Count == 0)
{
return null;
}
cons = candidates.ToArray();
// Bind to matching ctor.
ConstructorInfo rci = Type.DefaultBinder.BindToMethod(
ConstructorDefault,
cons,
ref args,
null,
null,
null,
out object state) as ConstructorInfo;
// Check for ctor we don't like (non-existent, delegate or decorated with declarative linktime demand).
if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType))
{
return null;
}
// Ctor invoke and allocation.
object retval = rci.Invoke(ConstructorDefault, Type.DefaultBinder, args, null);
// Reset any parameter re-ordering performed by the binder.
if (state != null)
{
Type.DefaultBinder.ReorderArgumentArray(ref args, state);
}
return retval;
}
public static object CreateFromName(string name)
{
return CreateFromName(name, null);
}
public static void AddOID(string oid, params string[] names)
{
if (oid == null)
throw new ArgumentNullException(nameof(oid));
if (names == null)
throw new ArgumentNullException(nameof(names));
string[] oidNames = new string[names.Length];
Array.Copy(names, 0, oidNames, 0, oidNames.Length);
// Pre-check the input names for validity, so that we don't add a few of the names and throw an
// exception if an invalid name is found further down the array.
foreach (string name in oidNames)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName);
}
}
// Everything is valid, so we're good to lock the hash table and add the application mappings
foreach (string name in oidNames)
{
appOidHT[name] = oid;
}
}
public static string MapNameToOID(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
appOidHT.TryGetValue(name, out string oidName);
if (string.IsNullOrEmpty(oidName) && !DefaultOidHT.TryGetValue(name, out oidName))
{
try
{
Oid oid = Oid.FromFriendlyName(name, OidGroup.All);
oidName = oid.Value;
}
catch (CryptographicException) { }
}
return oidName;
}
public static byte[] EncodeOID(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
string[] oidString = str.Split(SepArray);
uint[] oidNums = new uint[oidString.Length];
for (int i = 0; i < oidString.Length; i++)
{
oidNums[i] = unchecked((uint)int.Parse(oidString[i], CultureInfo.InvariantCulture));
}
// Handle the first two oidNums special
if (oidNums.Length < 2)
throw new CryptographicUnexpectedOperationException(SR.Cryptography_InvalidOID);
uint firstTwoOidNums = unchecked((oidNums[0] * 40) + oidNums[1]);
// Determine length of output array
int encodedOidNumsLength = 2; // Reserve first two bytes for later
EncodeSingleOidNum(firstTwoOidNums, null, ref encodedOidNumsLength);
for (int i = 2; i < oidNums.Length; i++)
{
EncodeSingleOidNum(oidNums[i], null, ref encodedOidNumsLength);
}
// Allocate the array to receive encoded oidNums
byte[] encodedOidNums = new byte[encodedOidNumsLength];
int encodedOidNumsIndex = 2;
// Encode each segment
EncodeSingleOidNum(firstTwoOidNums, encodedOidNums, ref encodedOidNumsIndex);
for (int i = 2; i < oidNums.Length; i++)
{
EncodeSingleOidNum(oidNums[i], encodedOidNums, ref encodedOidNumsIndex);
}
Debug.Assert(encodedOidNumsIndex == encodedOidNumsLength);
// Final return value is 06 <length> encodedOidNums[]
if (encodedOidNumsIndex - 2 > 0x7f)
throw new CryptographicUnexpectedOperationException(SR.Cryptography_Config_EncodedOIDError);
encodedOidNums[0] = (byte)0x06;
encodedOidNums[1] = (byte)(encodedOidNumsIndex - 2);
return encodedOidNums;
}
private static void EncodeSingleOidNum(uint value, byte[] destination, ref int index)
{
// Write directly to destination starting at index, and update index based on how many bytes written.
// If destination is null, just return updated index.
if (unchecked((int)value) < 0x80)
{
if (destination != null)
{
destination[index++] = unchecked((byte)value);
}
else
{
index += 1;
}
}
else if (value < 0x4000)
{
if (destination != null)
{
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
else
{
index += 2;
}
}
else if (value < 0x200000)
{
if (destination != null)
{
unchecked
{
destination[index++] = (byte)((value >> 14) | 0x80);
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
}
else
{
index += 3;
}
}
else if (value < 0x10000000)
{
if (destination != null)
{
unchecked
{
destination[index++] = (byte)((value >> 21) | 0x80);
destination[index++] = (byte)((value >> 14) | 0x80);
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
}
else
{
index += 4;
}
}
else
{
if (destination != null)
{
unchecked
{
destination[index++] = (byte)((value >> 28) | 0x80);
destination[index++] = (byte)((value >> 21) | 0x80);
destination[index++] = (byte)((value >> 14) | 0x80);
destination[index++] = (byte)((value >> 7) | 0x80);
destination[index++] = (byte)(value & 0x7f);
}
}
else
{
index += 5;
}
}
}
}
}
| |
// 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.Reflection;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Part of ComEventHelpers APIs which allow binding
/// managed delegates to COM's connection point based events.
/// </summary>
internal class ComEventsMethod
{
/// <summary>
/// This delegate wrapper class handles dynamic invocation of delegates. The reason for the wrapper's
/// existence is that under certain circumstances we need to coerce arguments to types expected by the
/// delegates signature. Normally, reflection (Delegate.DynamicInvoke) handles type coercion
/// correctly but one known case is when the expected signature is 'ref Enum' - in this case
/// reflection by design does not do the coercion. Since we need to be compatible with COM interop
/// handling of this scenario - we are pre-processing delegate's signature by looking for 'ref enums'
/// and cache the types required for such coercion.
/// </summary>
public class DelegateWrapper
{
private bool _once = false;
private int _expectedParamsCount;
private Type?[]? _cachedTargetTypes;
public DelegateWrapper(Delegate d)
{
Delegate = d;
}
public Delegate Delegate { get; set; }
public object? Invoke(object[] args)
{
if (Delegate == null)
{
return null;
}
if (!_once)
{
PreProcessSignature();
_once = true;
}
if (_cachedTargetTypes != null && _expectedParamsCount == args.Length)
{
for (int i = 0; i < _expectedParamsCount; i++)
{
if (_cachedTargetTypes[i] != null)
{
args[i] = Enum.ToObject(_cachedTargetTypes[i]!, args[i]); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644)
}
}
}
return Delegate.DynamicInvoke(args);
}
private void PreProcessSignature()
{
ParameterInfo[] parameters = Delegate.Method.GetParameters();
_expectedParamsCount = parameters.Length;
bool needToHandleCoercion = false;
var targetTypes = new List<Type?>();
foreach (ParameterInfo pi in parameters)
{
Type? targetType = null;
// recognize only 'ref Enum' signatures and cache
// both enum type and the underlying type.
if (pi.ParameterType.IsByRef
&& pi.ParameterType.HasElementType
&& pi.ParameterType.GetElementType()!.IsEnum)
{
needToHandleCoercion = true;
targetType = pi.ParameterType.GetElementType();
}
targetTypes.Add(targetType);
}
if (needToHandleCoercion)
{
_cachedTargetTypes = targetTypes.ToArray();
}
}
}
/// <summary>
/// Invoking ComEventsMethod means invoking a multi-cast delegate attached to it.
/// Since multicast delegate's built-in chaining supports only chaining instances of the same type,
/// we need to complement this design by using an explicit linked list data structure.
/// </summary>
private readonly List<DelegateWrapper> _delegateWrappers = new List<DelegateWrapper>();
private readonly int _dispid;
private ComEventsMethod? _next;
public ComEventsMethod(int dispid)
{
_dispid = dispid;
}
public static ComEventsMethod? Find(ComEventsMethod? methods, int dispid)
{
while (methods != null && methods._dispid != dispid)
{
methods = methods._next;
}
return methods;
}
public static ComEventsMethod Add(ComEventsMethod? methods, ComEventsMethod method)
{
method._next = methods;
return method;
}
public static ComEventsMethod? Remove(ComEventsMethod methods, ComEventsMethod method)
{
Debug.Assert(methods != null, "removing method from empty methods collection");
Debug.Assert(method != null, "specify method is null");
if (methods == method)
{
return methods._next;
}
else
{
ComEventsMethod? current = methods;
while (current != null && current._next != method)
{
current = current._next;
}
if (current != null)
{
current._next = method._next;
}
return methods;
}
}
public bool Empty
{
get
{
lock (_delegateWrappers)
{
return _delegateWrappers.Count == 0;
}
}
}
public void AddDelegate(Delegate d)
{
lock (_delegateWrappers)
{
// Update an existing delegate wrapper
foreach (DelegateWrapper wrapper in _delegateWrappers)
{
if (wrapper.Delegate.GetType() == d.GetType())
{
wrapper.Delegate = Delegate.Combine(wrapper.Delegate, d);
return;
}
}
var newWrapper = new DelegateWrapper(d);
_delegateWrappers.Add(newWrapper);
}
}
public void RemoveDelegate(Delegate d)
{
lock (_delegateWrappers)
{
// Find delegate wrapper index
int removeIdx = -1;
DelegateWrapper? wrapper = null;
for (int i = 0; i < _delegateWrappers.Count; i++)
{
DelegateWrapper wrapperMaybe = _delegateWrappers[i];
if (wrapperMaybe.Delegate.GetType() == d.GetType())
{
removeIdx = i;
wrapper = wrapperMaybe;
break;
}
}
if (removeIdx < 0)
{
// Not present in collection
return;
}
// Update wrapper or remove from collection
Delegate? newDelegate = Delegate.Remove(wrapper!.Delegate, d);
if (newDelegate != null)
{
wrapper.Delegate = newDelegate;
}
else
{
_delegateWrappers.RemoveAt(removeIdx);
}
}
}
public object? Invoke(object[] args)
{
Debug.Assert(!Empty);
object? result = null;
lock (_delegateWrappers)
{
foreach (DelegateWrapper wrapper in _delegateWrappers)
{
result = wrapper.Invoke(args);
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MRTutorial.Identity.Client.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace StreamAnalytics.Tests
{
public class FunctionTests : TestBase
{
[Fact(Skip = "ReRecord due to CR change")]
public async Task FunctionOperationsTest_Scalar_AzureMLWebService()
{
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string functionName = TestUtilities.GenerateName("function");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedFunctionType = TestHelper.GetFullRestOnlyResourceType(TestHelper.FunctionsResourceType);
string expectedFunctionResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.FunctionsResourceType, functionName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
var expectedFunction = new Function()
{
Properties = new ScalarFunctionProperties()
{
Inputs = new List<FunctionInput>()
{
new FunctionInput()
{
DataType = @"nvarchar(max)",
IsConfigurationParameter = null
}
},
Output = new FunctionOutput()
{
DataType = @"nvarchar(max)"
},
Binding = new AzureMachineLearningWebServiceFunctionBinding()
{
Endpoint = TestHelper.ExecuteEndpoint,
ApiKey = null,
Inputs = new AzureMachineLearningWebServiceInputs()
{
Name = "input1",
ColumnNames = new AzureMachineLearningWebServiceInputColumn[]
{
new AzureMachineLearningWebServiceInputColumn()
{
Name = "tweet",
DataType = "string",
MapTo = 0
}
}
},
Outputs = new List<AzureMachineLearningWebServiceOutputColumn>()
{
new AzureMachineLearningWebServiceOutputColumn()
{
Name = "Sentiment",
DataType = "string"
}
},
BatchSize = 1000
}
}
};
// PUT job
streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName);
// Retrieve default definition
AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters retrieveDefaultDefinitionParameters = new AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters()
{
UdfType = UdfType.Scalar,
ExecuteEndpoint = TestHelper.ExecuteEndpoint
};
var function = streamAnalyticsManagementClient.Functions.RetrieveDefaultDefinition(resourceGroupName, jobName, functionName, retrieveDefaultDefinitionParameters);
Assert.Equal(functionName, function.Name);
Assert.Null(function.Id);
Assert.Null(function.Type);
ValidationHelper.ValidateFunctionProperties(expectedFunction.Properties, function.Properties, false);
// PUT function
((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)function.Properties).Binding).ApiKey = TestHelper.ApiKey;
var putResponse = await streamAnalyticsManagementClient.Functions.CreateOrReplaceWithHttpMessagesAsync(function, resourceGroupName, jobName, functionName);
((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)function.Properties).Binding).ApiKey = null; // Null out because secrets are not returned in responses
ValidationHelper.ValidateFunction(function, putResponse.Body, false);
Assert.Equal(expectedFunctionResourceId, putResponse.Body.Id);
Assert.Equal(functionName, putResponse.Body.Name);
Assert.Equal(expectedFunctionType, putResponse.Body.Type);
// Verify GET request returns expected function
var getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName);
ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// Test Function
var testResult = streamAnalyticsManagementClient.Functions.Test(resourceGroupName, jobName, functionName);
Assert.Equal("TestSucceeded", testResult.Status);
Assert.Null(testResult.Error);
// PATCH function
var functionPatch = new Function()
{
Properties = new ScalarFunctionProperties()
{
Binding = new AzureMachineLearningWebServiceFunctionBinding()
{
BatchSize = 5000
}
}
};
((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)putResponse.Body.Properties).Binding).BatchSize = ((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)functionPatch.Properties).Binding).BatchSize;
var patchResponse = await streamAnalyticsManagementClient.Functions.UpdateWithHttpMessagesAsync(functionPatch, resourceGroupName, jobName, functionName);
ValidationHelper.ValidateFunction(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
// Run another GET function to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName);
ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List function and verify that the function shows up in the list
var listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName);
Assert.Single(listResult);
ValidationHelper.ValidateFunction(putResponse.Body, listResult.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag);
// Get job with function expanded and verify that the function shows up
var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions");
Assert.Single(getJobResponse.Functions);
ValidationHelper.ValidateFunction(putResponse.Body, getJobResponse.Functions.Single(), true);
Assert.Equal(getResponse.Headers.ETag, getJobResponse.Functions.Single().Properties.Etag);
// Delete function
streamAnalyticsManagementClient.Functions.Delete(resourceGroupName, jobName, functionName);
// Verify that list operation returns an empty list after deleting the function
listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName);
Assert.Empty(listResult);
// Get job with function expanded and verify that there are no functions after deleting the function
getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions");
Assert.Empty(getJobResponse.Functions);
}
}
[Fact]
public async Task FunctionOperationsTest_Scalar_JavaScript()
{
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string functionName = TestUtilities.GenerateName("function");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedFunctionType = TestHelper.GetFullRestOnlyResourceType(TestHelper.FunctionsResourceType);
string expectedFunctionResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.FunctionsResourceType, functionName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
string javaScriptFunctionCode = @"function (x, y) { return x + y; }";
var function = new Function()
{
Properties = new ScalarFunctionProperties()
{
Inputs = new List<FunctionInput>()
{
new FunctionInput()
{
DataType = @"Any",
IsConfigurationParameter = null
}
},
Output = new FunctionOutput()
{
DataType = @"Any"
},
Binding = new JavaScriptFunctionBinding()
{
Script = javaScriptFunctionCode
}
}
};
// PUT job
streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName);
// Retrieve default definition
JavaScriptFunctionRetrieveDefaultDefinitionParameters retrieveDefaultDefinitionParameters = new JavaScriptFunctionRetrieveDefaultDefinitionParameters()
{
UdfType = UdfType.Scalar,
Script = javaScriptFunctionCode
};
CloudException cloudException = Assert.Throws<CloudException>(
() => streamAnalyticsManagementClient.Functions.RetrieveDefaultDefinition(resourceGroupName, jobName, functionName, retrieveDefaultDefinitionParameters));
Assert.Equal(HttpStatusCode.InternalServerError, cloudException.Response.StatusCode);
Assert.Contains(@"Retrieve default definition is not supported for function type: Microsoft.StreamAnalytics/JavascriptUdf", cloudException.Response.Content);
// PUT function
var putResponse = await streamAnalyticsManagementClient.Functions.CreateOrReplaceWithHttpMessagesAsync(function, resourceGroupName, jobName, functionName);
ValidationHelper.ValidateFunction(function, putResponse.Body, false);
Assert.Equal(expectedFunctionResourceId, putResponse.Body.Id);
Assert.Equal(functionName, putResponse.Body.Name);
Assert.Equal(expectedFunctionType, putResponse.Body.Type);
// Verify GET request returns expected function
var getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName);
ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// Test Function
var testResult = streamAnalyticsManagementClient.Functions.Test(resourceGroupName, jobName, functionName);
Assert.Equal("TestFailed", testResult.Status);
Assert.NotNull(testResult.Error);
Assert.Equal("BadRequest", testResult.Error.Code);
Assert.Equal(@"Test operation is not supported for function type: Microsoft.StreamAnalytics/JavascriptUdf", testResult.Error.Message);
// PATCH function
var functionPatch = new Function()
{
Properties = new ScalarFunctionProperties()
{
Binding = new JavaScriptFunctionBinding()
{
Script = @"function (a, b) { return a * b; }"
}
}
};
((JavaScriptFunctionBinding)((ScalarFunctionProperties)putResponse.Body.Properties).Binding).Script = ((JavaScriptFunctionBinding)((ScalarFunctionProperties)functionPatch.Properties).Binding).Script;
var patchResponse = await streamAnalyticsManagementClient.Functions.UpdateWithHttpMessagesAsync(functionPatch, resourceGroupName, jobName, functionName);
ValidationHelper.ValidateFunction(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
// Run another GET function to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName);
ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List function and verify that the function shows up in the list
var listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName);
Assert.Single(listResult);
ValidationHelper.ValidateFunction(putResponse.Body, listResult.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag);
// Get job with function expanded and verify that the function shows up
var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions");
Assert.Single(getJobResponse.Functions);
ValidationHelper.ValidateFunction(putResponse.Body, getJobResponse.Functions.Single(), true);
Assert.Equal(getResponse.Headers.ETag, getJobResponse.Functions.Single().Properties.Etag);
// Delete function
streamAnalyticsManagementClient.Functions.Delete(resourceGroupName, jobName, functionName);
// Verify that list operation returns an empty list after deleting the function
listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName);
Assert.Empty(listResult);
// Get job with function expanded and verify that there are no functions after deleting the function
getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions");
Assert.Empty(getJobResponse.Functions);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System.Diagnostics;
using System.Security.Principal;
using Xunit;
namespace System.ServiceProcess.Tests
{
internal sealed class ServiceProvider
{
public readonly string TestMachineName;
public readonly TimeSpan ControlTimeout;
public readonly string TestServiceName;
public readonly string TestServiceDisplayName;
public readonly string DependentTestServiceNamePrefix;
public readonly string DependentTestServiceDisplayNamePrefix;
public readonly string TestServiceRegistryKey;
public ServiceProvider()
{
TestMachineName = ".";
ControlTimeout = TimeSpan.FromSeconds(10);
TestServiceName = Guid.NewGuid().ToString();
TestServiceDisplayName = "Test Service " + TestServiceName;
DependentTestServiceNamePrefix = TestServiceName + ".Dependent";
DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent";
TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName;
// Create the service
CreateTestServices();
}
private void CreateTestServices()
{
// Create the test service and its dependent services. Then, start the test service.
// All control tests assume that the test service is running when they are executed.
// So all tests should make sure to restart the service if they stop, pause, or shut
// it down.
RunServiceExecutable("create");
}
public void DeleteTestServices()
{
RunServiceExecutable("delete");
RegistryKey users = Registry.Users;
if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null)
users.DeleteSubKeyTree(".DEFAULT\\dotnetTests");
}
private void RunServiceExecutable(string action)
{
const string serviceExecutable = "System.ServiceProcess.ServiceController.TestNativeService.exe";
var process = new Process();
process.StartInfo.FileName = serviceExecutable;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action);
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("error: " + serviceExecutable + " failed with exit code " + process.ExitCode.ToString());
}
}
}
[OuterLoop(/* Modifies machine state */)]
public class ServiceControllerTests : IDisposable
{
private const int ExpectedDependentServiceCount = 3;
private static readonly Lazy<bool> s_runningWithElevatedPrivileges = new Lazy<bool>(
() => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator));
private readonly ServiceProvider _testService;
public ServiceControllerTests()
{
_testService = new ServiceProvider();
}
private static bool RunningWithElevatedPrivileges
{
get { return s_runningWithElevatedPrivileges.Value; }
}
private void AssertExpectedProperties(ServiceController testServiceController)
{
Assert.Equal(_testService.TestServiceName, testServiceController.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, testServiceController.DisplayName);
Assert.Equal(_testService.TestMachineName, testServiceController.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithServiceName()
{
var controller = new ServiceController(_testService.TestServiceName);
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithServiceName_ToUpper()
{
var controller = new ServiceController(_testService.TestServiceName.ToUpperInvariant());
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithDisplayName()
{
var controller = new ServiceController(_testService.TestServiceDisplayName);
AssertExpectedProperties(controller);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithMachineName()
{
var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName);
AssertExpectedProperties(controller);
Assert.Throws<ArgumentException>(() => { var c = new ServiceController(_testService.TestServiceName, ""); });
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ControlCapabilities()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.True(controller.CanStop);
Assert.True(controller.CanPauseAndContinue);
Assert.False(controller.CanShutdown);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StartWithArguments()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
var args = new[] { "a", "b", "c", "d", "e" };
controller.Start(args);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
// The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey.
// Read this key to verify that the arguments were properly passed to the service.
string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string;
Assert.Equal(string.Join(",", args), argsString);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StopAndStart()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void PauseAndContinue()
{
var controller = new ServiceController(_testService.TestServiceName);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Pause();
controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Paused, controller.Status);
controller.Continue();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void GetServices_FindSelf()
{
bool foundTestService = false;
foreach (var service in ServiceController.GetServices())
{
if (service.ServiceName == _testService.TestServiceName)
{
foundTestService = true;
AssertExpectedProperties(service);
}
}
Assert.True(foundTestService, "Test service was not enumerated with all services");
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void Dependencies()
{
// The test service creates a number of dependent services, each of which is depended on
// by all the services created after it.
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ExpectedDependentServiceCount, controller.DependentServices.Length);
for (int i = 0; i < controller.DependentServices.Length; i++)
{
var dependent = AssertHasDependent(controller, _testService.DependentTestServiceNamePrefix + i, _testService.DependentTestServiceDisplayNamePrefix + i);
Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType);
// Assert that this dependent service is depended on by all the test services created after it
Assert.Equal(ExpectedDependentServiceCount - i - 1, dependent.DependentServices.Length);
for (int j = i + 1; j < ExpectedDependentServiceCount; j++)
{
AssertHasDependent(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
// Assert that the dependent service depends on the main test service
AssertDependsOn(dependent, _testService.TestServiceName, _testService.TestServiceDisplayName);
// Assert that this dependent service depends on all the test services created before it
Assert.Equal(i + 1, dependent.ServicesDependedOn.Length);
for (int j = i - 1; j >= 0; j--)
{
AssertDependsOn(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ServicesStartMode()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceStartMode.Manual, controller.StartType);
// Check for the startType of the dependent services.
for (int i = 0; i < controller.DependentServices.Length; i++)
{
Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType);
}
}
public void Dispose()
{
_testService.DeleteTestServices();
}
private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName)
{
var dependent = FindService(controller.DependentServices, serviceName, displayName);
Assert.NotNull(dependent);
return dependent;
}
private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName)
{
var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName);
Assert.NotNull(dependency);
return dependency;
}
private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName)
{
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName && service.DisplayName == displayName)
{
return service;
}
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.Transactions;
namespace System.Data.SqlClient
{
internal static class AsyncHelper
{
internal static Task CreateContinuationTask(Task task, Action onSuccess, Action<Exception> onFailure = null)
{
if (task == null)
{
onSuccess();
return null;
}
else
{
TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
ContinueTaskWithState(task, completion,
state: Tuple.Create(onSuccess, onFailure,completion),
onSuccess: (state) => {
var parameters = (Tuple<Action, Action<Exception>, TaskCompletionSource<object>>)state;
Action success = parameters.Item1;
TaskCompletionSource<object> taskCompletionSource = parameters.Item3;
success();
taskCompletionSource.SetResult(null);
},
onFailure: (exception,state) =>
{
var parameters = (Tuple<Action, Action<Exception>, TaskCompletionSource<object>>)state;
Action<Exception> failure = parameters.Item2;
failure?.Invoke(exception);
}
);
return completion.Task;
}
}
internal static Task CreateContinuationTaskWithState(Task task, object state, Action<object> onSuccess, Action<Exception,object> onFailure = null)
{
if (task == null)
{
onSuccess(state);
return null;
}
else
{
var completion = new TaskCompletionSource<object>();
ContinueTaskWithState(task, completion, state,
onSuccess: (continueState) => {
onSuccess(continueState);
completion.SetResult(null);
},
onFailure: onFailure
);
return completion.Task;
}
}
internal static Task CreateContinuationTask<T1, T2>(Task task, Action<T1, T2> onSuccess, T1 arg1, T2 arg2, Action<Exception> onFailure = null)
{
return CreateContinuationTask(task, () => onSuccess(arg1, arg2), onFailure);
}
internal static void ContinueTask(Task task,
TaskCompletionSource<object> completion,
Action onSuccess,
Action<Exception> onFailure = null,
Action onCancellation = null,
Func<Exception, Exception> exceptionConverter = null
)
{
task.ContinueWith(
tsk =>
{
if (tsk.Exception != null)
{
Exception exc = tsk.Exception.InnerException;
if (exceptionConverter != null)
{
exc = exceptionConverter(exc);
}
try
{
onFailure?.Invoke(exc);
}
finally
{
completion.TrySetException(exc);
}
}
else if (tsk.IsCanceled)
{
try
{
onCancellation?.Invoke();
}
finally
{
completion.TrySetCanceled();
}
}
else
{
try
{
onSuccess();
}
catch (Exception e)
{
completion.SetException(e);
}
}
}, TaskScheduler.Default
);
}
// the same logic as ContinueTask but with an added state parameter to allow the caller to avoid the use of a closure
// the parameter allocation cannot be avoided here and using closure names is clearer than Tuple numbered properties
internal static void ContinueTaskWithState(Task task,
TaskCompletionSource<object> completion,
object state,
Action<object> onSuccess,
Action<Exception, object> onFailure = null,
Action<object> onCancellation = null,
Func<Exception, Exception> exceptionConverter = null
)
{
task.ContinueWith(
tsk =>
{
if (tsk.Exception != null)
{
Exception exc = tsk.Exception.InnerException;
if (exceptionConverter != null)
{
exc = exceptionConverter(exc);
}
try
{
onFailure?.Invoke(exc, state);
}
finally
{
completion.TrySetException(exc);
}
}
else if (tsk.IsCanceled)
{
try
{
onCancellation?.Invoke(state);
}
finally
{
completion.TrySetCanceled();
}
}
else
{
try
{
onSuccess(state);
}
catch (Exception e)
{
completion.SetException(e);
}
}
}, TaskScheduler.Default
);
}
internal static void WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions = true)
{
try
{
task.Wait(timeout > 0 ? (1000 * timeout) : Timeout.Infinite);
}
catch (AggregateException ae)
{
if (rethrowExceptions)
{
Debug.Assert(ae.InnerExceptions.Count == 1, "There is more than one exception in AggregateException");
ExceptionDispatchInfo.Capture(ae.InnerException).Throw();
}
}
if (!task.IsCompleted)
{
if (onTimeout != null)
{
onTimeout();
}
}
}
internal static void SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken)
{
if (timeout > 0)
{
Task.Delay(timeout * 1000, ctoken).ContinueWith((tsk) =>
{
if (!tsk.IsCanceled && !completion.Task.IsCompleted)
{
completion.TrySetException(exc());
}
});
}
}
}
internal static class SQL
{
// The class SQL defines the exceptions that are specific to the SQL Adapter.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource Framework.txt.
// The exception is then returned to the caller, so that the caller may then throw from its
// location so that the catcher of the exception will have the appropriate call stack.
// This class is used so that there will be compile time checking of error
// messages. The resource Framework.txt will ensure proper string text based on the appropriate
// locale.
//
// SQL specific exceptions
//
//
// SQL.Connection
//
internal static Exception CannotGetDTCAddress()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_CannotGetDTCAddress));
}
internal static Exception InvalidInternalPacketSize(string str)
{
return ADP.ArgumentOutOfRange(str);
}
internal static Exception InvalidPacketSize()
{
return ADP.ArgumentOutOfRange(SR.GetString(SR.SQL_InvalidTDSPacketSize));
}
internal static Exception InvalidPacketSizeValue()
{
return ADP.Argument(SR.GetString(SR.SQL_InvalidPacketSizeValue));
}
internal static Exception InvalidSSPIPacketSize()
{
return ADP.Argument(SR.GetString(SR.SQL_InvalidSSPIPacketSize));
}
internal static Exception NullEmptyTransactionName()
{
return ADP.Argument(SR.GetString(SR.SQL_NullEmptyTransactionName));
}
internal static Exception UserInstanceFailoverNotCompatible()
{
return ADP.Argument(SR.GetString(SR.SQL_UserInstanceFailoverNotCompatible));
}
internal static Exception ParsingErrorLibraryType(ParsingErrorState state, int libraryType)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorAuthLibraryType, ((int)state).ToString(CultureInfo.InvariantCulture), libraryType));
}
internal static Exception InvalidSQLServerVersionUnknown()
{
return ADP.DataAdapter(SR.GetString(SR.SQL_InvalidSQLServerVersionUnknown));
}
internal static Exception SynchronousCallMayNotPend()
{
return new Exception(SR.GetString(SR.Sql_InternalError));
}
internal static Exception ConnectionLockedForBcpEvent()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ConnectionLockedForBcpEvent));
}
internal static Exception InstanceFailure()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_InstanceFailure));
}
internal static Exception ChangePasswordArgumentMissing(string argumentName)
{
return ADP.ArgumentNull(SR.GetString(SR.SQL_ChangePasswordArgumentMissing, argumentName));
}
internal static Exception ChangePasswordConflictsWithSSPI()
{
return ADP.Argument(SR.GetString(SR.SQL_ChangePasswordConflictsWithSSPI));
}
internal static Exception ChangePasswordRequiresYukon()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ChangePasswordRequiresYukon));
}
static internal Exception ChangePasswordUseOfUnallowedKey(string key)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ChangePasswordUseOfUnallowedKey, key));
}
//
// Global Transactions.
//
internal static Exception GlobalTransactionsNotEnabled()
{
return ADP.InvalidOperation(SR.GetString(SR.GT_Disabled));
}
internal static Exception UnknownSysTxIsolationLevel(Transactions.IsolationLevel isolationLevel)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString()));
}
internal static Exception InvalidPartnerConfiguration(string server, string database)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidPartnerConfiguration, server, database));
}
internal static Exception MARSUnspportedOnConnection()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_MarsUnsupportedOnConnection));
}
internal static Exception CannotModifyPropertyAsyncOperationInProgress([CallerMemberName] string property = "")
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_CannotModifyPropertyAsyncOperationInProgress, property));
}
internal static Exception NonLocalSSEInstance()
{
return ADP.NotSupported(SR.GetString(SR.SQL_NonLocalSSEInstance));
}
//
// SQL.DataCommand
//
internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value)
{
return ADP.ArgumentOutOfRange(SR.GetString(SR.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
}
internal static ArgumentOutOfRangeException NotSupportedCommandType(CommandType value)
{
#if DEBUG
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
Debug.Fail("valid CommandType " + value.ToString());
break;
case CommandType.TableDirect:
break;
default:
Debug.Fail("invalid CommandType " + value.ToString());
break;
}
#endif
return NotSupportedEnumerationValue(typeof(CommandType), (int)value);
}
internal static ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value)
{
#if DEBUG
switch (value)
{
case IsolationLevel.Unspecified:
case IsolationLevel.ReadCommitted:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Fail("valid IsolationLevel " + value.ToString());
break;
case IsolationLevel.Chaos:
break;
default:
Debug.Fail("invalid IsolationLevel " + value.ToString());
break;
}
#endif
return NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value);
}
internal static Exception OperationCancelled()
{
Exception exception = ADP.InvalidOperation(SR.GetString(SR.SQL_OperationCancelled));
return exception;
}
internal static Exception PendingBeginXXXExists()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_PendingBeginXXXExists));
}
internal static ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param)
{
return ADP.ArgumentOutOfRange(SR.GetString(SR.SqlDependency_InvalidTimeout), param);
}
internal static Exception NonXmlResult()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_NonXmlResult));
}
//
// SQL.DataParameter
//
internal static Exception InvalidUdt3PartNameFormat()
{
return ADP.Argument(SR.GetString(SR.SQL_InvalidUdt3PartNameFormat));
}
internal static Exception InvalidParameterTypeNameFormat()
{
return ADP.Argument(SR.GetString(SR.SQL_InvalidParameterTypeNameFormat));
}
internal static Exception InvalidParameterNameLength(string value)
{
return ADP.Argument(SR.GetString(SR.SQL_InvalidParameterNameLength, value));
}
internal static Exception PrecisionValueOutOfRange(byte precision)
{
return ADP.Argument(SR.GetString(SR.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception ScaleValueOutOfRange(byte scale)
{
return ADP.Argument(SR.GetString(SR.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception TimeScaleValueOutOfRange(byte scale)
{
return ADP.Argument(SR.GetString(SR.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception InvalidSqlDbType(SqlDbType value)
{
return ADP.InvalidEnumerationValue(typeof(SqlDbType), (int)value);
}
internal static Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName)
{
return ADP.NotSupported(SR.GetString(SR.SqlParameter_UnsupportedTVPOutputParameter,
direction.ToString(), paramName));
}
internal static Exception DBNullNotSupportedForTVPValues(string paramName)
{
return ADP.NotSupported(SR.GetString(SR.SqlParameter_DBNullNotSupportedForTVP, paramName));
}
internal static Exception UnexpectedTypeNameForNonStructParams(string paramName)
{
return ADP.NotSupported(SR.GetString(SR.SqlParameter_UnexpectedTypeNameForNonStruct, paramName));
}
internal static Exception ParameterInvalidVariant(string paramName)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ParameterInvalidVariant, paramName));
}
internal static Exception MustSetTypeNameForParam(string paramType, string paramName)
{
return ADP.Argument(SR.GetString(SR.SQL_ParameterTypeNameRequired, paramType, paramName));
}
internal static Exception NullSchemaTableDataTypeNotSupported(string columnName)
{
return ADP.Argument(SR.GetString(SR.NullSchemaTableDataTypeNotSupported, columnName));
}
internal static Exception InvalidSchemaTableOrdinals()
{
return ADP.Argument(SR.GetString(SR.InvalidSchemaTableOrdinals));
}
internal static Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber)
{
return ADP.Argument(SR.GetString(SR.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber));
}
internal static Exception EnumeratedRecordFieldCountChanged(int recordNumber)
{
return ADP.Argument(SR.GetString(SR.SQL_EnumeratedRecordFieldCountChanged, recordNumber));
}
//
// SQL.SqlDataAdapter
//
//
// SQL.TDSParser
//
internal static Exception InvalidTDSVersion()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidTDSVersion));
}
internal static Exception ParsingError()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingError));
}
static internal Exception ParsingError(ParsingErrorState state)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)));
}
static internal Exception ParsingErrorValue(ParsingErrorState state, int value)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorValue, ((int)state).ToString(CultureInfo.InvariantCulture), value));
}
static internal Exception ParsingErrorFeatureId(ParsingErrorState state, int featureId)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorFeatureId, ((int)state).ToString(CultureInfo.InvariantCulture), featureId));
}
internal static Exception MoneyOverflow(string moneyValue)
{
return ADP.Overflow(SR.GetString(SR.SQL_MoneyOverflow, moneyValue));
}
internal static Exception SmallDateTimeOverflow(string datetime)
{
return ADP.Overflow(SR.GetString(SR.SQL_SmallDateTimeOverflow, datetime));
}
internal static Exception SNIPacketAllocationFailure()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_SNIPacketAllocationFailure));
}
internal static Exception TimeOverflow(string time)
{
return ADP.Overflow(SR.GetString(SR.SQL_TimeOverflow, time));
}
//
// SQL.SqlDataReader
//
internal static Exception InvalidRead()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidRead));
}
internal static Exception NonBlobColumn(string columnName)
{
return ADP.InvalidCast(SR.GetString(SR.SQL_NonBlobColumn, columnName));
}
internal static Exception NonCharColumn(string columnName)
{
return ADP.InvalidCast(SR.GetString(SR.SQL_NonCharColumn, columnName));
}
internal static Exception StreamNotSupportOnColumnType(string columnName)
{
return ADP.InvalidCast(SR.GetString(SR.SQL_StreamNotSupportOnColumnType, columnName));
}
internal static Exception TextReaderNotSupportOnColumnType(string columnName)
{
return ADP.InvalidCast(SR.GetString(SR.SQL_TextReaderNotSupportOnColumnType, columnName));
}
internal static Exception XmlReaderNotSupportOnColumnType(string columnName)
{
return ADP.InvalidCast(SR.GetString(SR.SQL_XmlReaderNotSupportOnColumnType, columnName));
}
internal static Exception UDTUnexpectedResult(string exceptionText)
{
return ADP.TypeLoad(SR.GetString(SR.SQLUDT_Unexpected, exceptionText));
}
//
// SQL.SqlDependency
//
internal static Exception SqlCommandHasExistingSqlNotificationRequest()
{
return ADP.InvalidOperation(SR.GetString(SR.SQLNotify_AlreadyHasCommand));
}
internal static Exception SqlDepDefaultOptionsButNoStart()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DefaultOptionsButNoStart));
}
internal static Exception SqlDependencyDatabaseBrokerDisabled()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DatabaseBrokerDisabled));
}
internal static Exception SqlDependencyEventNoDuplicate()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_EventNoDuplicate));
}
internal static Exception SqlDependencyDuplicateStart()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DuplicateStart));
}
internal static Exception SqlDependencyIdMismatch()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_IdMismatch));
}
internal static Exception SqlDependencyNoMatchingServerStart()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_NoMatchingServerStart));
}
internal static Exception SqlDependencyNoMatchingServerDatabaseStart()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_NoMatchingServerDatabaseStart));
}
//
// SQL.SqlDelegatedTransaction
//
internal static TransactionPromotionException PromotionFailed(Exception inner)
{
TransactionPromotionException e = new TransactionPromotionException(SR.GetString(SR.SqlDelegatedTransaction_PromotionFailed), inner);
ADP.TraceExceptionAsReturnValue(e);
return e;
}
//Failure while attempting to promote transaction.
//
// SQL.SqlMetaData
//
internal static Exception UnexpectedUdtTypeNameForNonUdtParams()
{
return ADP.Argument(SR.GetString(SR.SQLUDT_UnexpectedUdtTypeName));
}
internal static Exception MustSetUdtTypeNameForUdtParams()
{
return ADP.Argument(SR.GetString(SR.SQLUDT_InvalidUdtTypeName));
}
internal static Exception UDTInvalidSqlType(string typeName)
{
return ADP.Argument(SR.GetString(SR.SQLUDT_InvalidSqlType, typeName));
}
internal static Exception InvalidSqlDbTypeForConstructor(SqlDbType type)
{
return ADP.Argument(SR.GetString(SR.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString()));
}
internal static Exception NameTooLong(string parameterName)
{
return ADP.Argument(SR.GetString(SR.SqlMetaData_NameTooLong), parameterName);
}
internal static Exception InvalidSortOrder(SortOrder order)
{
return ADP.InvalidEnumerationValue(typeof(SortOrder), (int)order);
}
internal static Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal)
{
return ADP.InvalidOperation(SR.GetString(SR.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal));
}
internal static Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName)
{
return ADP.Argument(SR.GetString(SR.SqlProvider_InvalidDataColumnType, columnName, typeName));
}
internal static Exception InvalidColumnMaxLength(string columnName, long maxLength)
{
return ADP.Argument(SR.GetString(SR.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength));
}
internal static Exception InvalidColumnPrecScale()
{
return ADP.Argument(SR.GetString(SR.SqlMisc_InvalidPrecScaleMessage));
}
internal static Exception NotEnoughColumnsInStructuredType()
{
return ADP.Argument(SR.GetString(SR.SqlProvider_NotEnoughColumnsInStructuredType));
}
internal static Exception DuplicateSortOrdinal(int sortOrdinal)
{
return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_DuplicateSortOrdinal, sortOrdinal));
}
internal static Exception MissingSortOrdinal(int sortOrdinal)
{
return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_MissingSortOrdinal, sortOrdinal));
}
internal static Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal)
{
return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal));
}
internal static Exception IEnumerableOfSqlDataRecordHasNoRows()
{
return ADP.Argument(SR.GetString(SR.IEnumerableOfSqlDataRecordHasNoRows));
}
//
// SQL.BulkLoad
//
internal static Exception BulkLoadMappingInaccessible()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMappingInaccessible));
}
internal static Exception BulkLoadMappingsNamesOrOrdinalsOnly()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMappingsNamesOrOrdinalsOnly));
}
internal static Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, Exception e)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadCannotConvertValue, sourcetype.Name, metatype.TypeName), e);
}
internal static Exception BulkLoadNonMatchingColumnMapping()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNonMatchingColumnMapping));
}
internal static Exception BulkLoadNonMatchingColumnName(string columnName)
{
return BulkLoadNonMatchingColumnName(columnName, null);
}
internal static Exception BulkLoadNonMatchingColumnName(string columnName, Exception e)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNonMatchingColumnName, columnName), e);
}
internal static Exception BulkLoadStringTooLong()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadStringTooLong));
}
internal static Exception BulkLoadInvalidVariantValue()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidVariantValue));
}
internal static Exception BulkLoadInvalidTimeout(int timeout)
{
return ADP.Argument(SR.GetString(SR.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception BulkLoadExistingTransaction()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadExistingTransaction));
}
internal static Exception BulkLoadNoCollation()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNoCollation));
}
internal static Exception BulkLoadConflictingTransactionOption()
{
return ADP.Argument(SR.GetString(SR.SQL_BulkLoadConflictingTransactionOption));
}
internal static Exception BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName)
{
return ADP.InvalidOperation(SR.GetString(SR.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName));
}
internal static Exception InvalidOperationInsideEvent()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidOperationInsideEvent));
}
internal static Exception BulkLoadMissingDestinationTable()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMissingDestinationTable));
}
internal static Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidDestinationTable, tableName), inner);
}
internal static Exception BulkLoadBulkLoadNotAllowDBNull(string columnName)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNotAllowDBNull, columnName));
}
internal static Exception BulkLoadPendingOperation()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadPendingOperation));
}
internal static Exception InvalidTableDerivedPrecisionForTvp(string columnName, byte precision)
{
return ADP.InvalidOperation(SR.GetString(SR.SqlParameter_InvalidTableDerivedPrecisionForTvp, precision, columnName, System.Data.SqlTypes.SqlDecimal.MaxPrecision));
}
//
// transactions.
//
internal static Exception ConnectionDoomed()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_ConnectionDoomed));
}
internal static Exception OpenResultCountExceeded()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_OpenResultCountExceeded));
}
internal static Exception UnsupportedSysTxForGlobalTransactions()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_UnsupportedSysTxVersion));
}
internal static readonly byte[] AttentionHeader = new byte[] {
TdsEnums.MT_ATTN, // Message Type
TdsEnums.ST_EOM, // Status
TdsEnums.HEADER_LEN >> 8, // length - upper byte
TdsEnums.HEADER_LEN & 0xff, // length - lower byte
0, // spid
0, // spid
0, // packet (out of band)
0 // window
};
//
// MultiSubnetFailover
//
/// <summary>
/// used to block two scenarios if MultiSubnetFailover is true:
/// * server-provided failover partner - raising SqlException in this case
/// * connection string with failover partner and MultiSubnetFailover=true - raising argument one in this case with the same message
/// </summary>
internal static Exception MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection)
{
string msg = SR.GetString(SR.SQLMSF_FailoverPartnerNotSupported);
if (serverProvidedFailoverPartner)
{
// Replacing InvalidOperation with SQL exception
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, msg, "", 0));
SqlException exc = SqlException.CreateException(errors, null, internalConnection);
exc._doNotReconnect = true; // disable open retry logic on this error
return exc;
}
else
{
return ADP.Argument(msg);
}
}
internal static Exception MultiSubnetFailoverWithMoreThan64IPs()
{
string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs);
return ADP.InvalidOperation(msg);
}
internal static Exception MultiSubnetFailoverWithInstanceSpecified()
{
string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified);
return ADP.Argument(msg);
}
internal static Exception MultiSubnetFailoverWithNonTcpProtocol()
{
string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol);
return ADP.Argument(msg);
}
//
// Read-only routing
//
internal static Exception ROR_FailoverNotSupportedConnString()
{
return ADP.Argument(SR.GetString(SR.SQLROR_FailoverNotSupported));
}
internal static Exception ROR_FailoverNotSupportedServer(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_FailoverNotSupported)), "", 0));
SqlException exc = SqlException.CreateException(errors, null, internalConnection);
exc._doNotReconnect = true;
return exc;
}
internal static Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_RecursiveRoutingNotSupported)), "", 0));
SqlException exc = SqlException.CreateException(errors, null, internalConnection);
exc._doNotReconnect = true;
return exc;
}
internal static Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_UnexpectedRoutingInfo)), "", 0));
SqlException exc = SqlException.CreateException(errors, null, internalConnection);
exc._doNotReconnect = true;
return exc;
}
internal static Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_InvalidRoutingInfo)), "", 0));
SqlException exc = SqlException.CreateException(errors, null, internalConnection);
exc._doNotReconnect = true;
return exc;
}
internal static Exception ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_TimeoutAfterRoutingInfo)), "", 0));
SqlException exc = SqlException.CreateException(errors, null, internalConnection);
exc._doNotReconnect = true;
return exc;
}
//
// Connection resiliency
//
internal static SqlException CR_ReconnectTimeout()
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.Timeout(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
SqlException exc = SqlException.CreateException(errors, "");
return exc;
}
internal static SqlException CR_ReconnectionCancelled()
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.OperationCancelled(), "", 0));
SqlException exc = SqlException.CreateException(errors, "");
return exc;
}
internal static Exception CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SR.GetString(SR.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0));
SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
return exc;
}
internal static Exception CR_EncryptionChanged(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_EncryptionChanged), "", 0));
SqlException exc = SqlException.CreateException(errors, "", internalConnection);
return exc;
}
internal static SqlException CR_AllAttemptsFailed(SqlException innerException, Guid connectionId)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SR.GetString(SR.SQLCR_AllAttemptsFailed), "", 0));
SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
return exc;
}
internal static SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_NoCRAckAtReconnection), "", 0));
SqlException exc = SqlException.CreateException(errors, "", internalConnection);
return exc;
}
internal static SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internalConnection)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_TDSVestionNotPreserved), "", 0));
SqlException exc = SqlException.CreateException(errors, "", internalConnection);
return exc;
}
internal static SqlException CR_UnrecoverableServer(Guid connectionId)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_UnrecoverableServer), "", 0));
SqlException exc = SqlException.CreateException(errors, "", connectionId);
return exc;
}
internal static SqlException CR_UnrecoverableClient(Guid connectionId)
{
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_UnrecoverableClient), "", 0));
SqlException exc = SqlException.CreateException(errors, "", connectionId);
return exc;
}
internal static Exception StreamWriteNotSupported()
{
return ADP.NotSupported(SR.GetString(SR.SQL_StreamWriteNotSupported));
}
internal static Exception StreamReadNotSupported()
{
return ADP.NotSupported(SR.GetString(SR.SQL_StreamReadNotSupported));
}
internal static Exception StreamSeekNotSupported()
{
return ADP.NotSupported(SR.GetString(SR.SQL_StreamSeekNotSupported));
}
internal static System.Data.SqlTypes.SqlNullValueException SqlNullValue()
{
System.Data.SqlTypes.SqlNullValueException e = new System.Data.SqlTypes.SqlNullValueException();
return e;
}
internal static Exception SubclassMustOverride()
{
return ADP.InvalidOperation(SR.GetString(SR.SqlMisc_SubclassMustOverride));
}
// ProjectK\CoreCLR specific errors
internal static Exception UnsupportedKeyword(string keyword)
{
return ADP.NotSupported(SR.GetString(SR.SQL_UnsupportedKeyword, keyword));
}
internal static Exception NetworkLibraryKeywordNotSupported()
{
return ADP.NotSupported(SR.GetString(SR.SQL_NetworkLibraryNotSupported));
}
internal static Exception UnsupportedFeatureAndToken(SqlInternalConnectionTds internalConnection, string token)
{
var innerException = ADP.NotSupported(SR.GetString(SR.SQL_UnsupportedToken, token));
SqlErrorCollection errors = new SqlErrorCollection();
errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQL_UnsupportedFeature), "", 0));
SqlException exc = SqlException.CreateException(errors, "", internalConnection, innerException);
return exc;
}
internal static Exception BatchedUpdatesNotAvailableOnContextConnection()
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_BatchedUpdatesNotAvailableOnContextConnection));
}
/// <summary>
/// gets a message for SNI error (sniError must be valid, non-zero error code)
/// </summary>
internal static string GetSNIErrorMessage(int sniError)
{
Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range");
string errorMessageId = string.Format("SNI_ERROR_{0}", sniError);
return SR.GetResourceString(errorMessageId, errorMessageId);
}
// Default values for SqlDependency and SqlNotificationRequest
internal const int SqlDependencyTimeoutDefault = 0;
internal const int SqlDependencyServerTimeout = 5 * 24 * 3600; // 5 days - used to compute default TTL of the dependency
internal const string SqlNotificationServiceDefault = "SqlQueryNotificationService";
internal const string SqlNotificationStoredProcedureDefault = "SqlQueryNotificationStoredProcedure";
}
sealed internal class SQLMessage
{
private SQLMessage() { /* prevent utility class from being instantiated*/ }
// The class SQLMessage defines the error messages that are specific to the SqlDataAdapter
// that are caused by a netlib error. The functions will be called and then return the
// appropriate error message from the resource Framework.txt. The SqlDataAdapter will then
// take the error message and then create a SqlError for the message and then place
// that into a SqlException that is either thrown to the user or cached for throwing at
// a later time. This class is used so that there will be compile time checking of error
// messages. The resource Framework.txt will ensure proper string text based on the appropriate
// locale.
internal static string CultureIdError()
{
return SR.GetString(SR.SQL_CultureIdError);
}
internal static string EncryptionNotSupportedByClient()
{
return SR.GetString(SR.SQL_EncryptionNotSupportedByClient);
}
internal static string EncryptionNotSupportedByServer()
{
return SR.GetString(SR.SQL_EncryptionNotSupportedByServer);
}
internal static string OperationCancelled()
{
return SR.GetString(SR.SQL_OperationCancelled);
}
internal static string SevereError()
{
return SR.GetString(SR.SQL_SevereError);
}
internal static string SSPIInitializeError()
{
return SR.GetString(SR.SQL_SSPIInitializeError);
}
internal static string SSPIGenerateError()
{
return SR.GetString(SR.SQL_SSPIGenerateError);
}
internal static string SqlServerBrowserNotAccessible()
{
return SR.GetString(SR.SQL_SqlServerBrowserNotAccessible);
}
internal static string KerberosTicketMissingError()
{
return SR.GetString(SR.SQL_KerberosTicketMissingError);
}
internal static string Timeout()
{
return SR.GetString(SR.SQL_Timeout);
}
internal static string Timeout_PreLogin_Begin()
{
return SR.GetString(SR.SQL_Timeout_PreLogin_Begin);
}
internal static string Timeout_PreLogin_InitializeConnection()
{
return SR.GetString(SR.SQL_Timeout_PreLogin_InitializeConnection);
}
internal static string Timeout_PreLogin_SendHandshake()
{
return SR.GetString(SR.SQL_Timeout_PreLogin_SendHandshake);
}
internal static string Timeout_PreLogin_ConsumeHandshake()
{
return SR.GetString(SR.SQL_Timeout_PreLogin_ConsumeHandshake);
}
internal static string Timeout_Login_Begin()
{
return SR.GetString(SR.SQL_Timeout_Login_Begin);
}
internal static string Timeout_Login_ProcessConnectionAuth()
{
return SR.GetString(SR.SQL_Timeout_Login_ProcessConnectionAuth);
}
internal static string Timeout_PostLogin()
{
return SR.GetString(SR.SQL_Timeout_PostLogin);
}
internal static string Timeout_FailoverInfo()
{
return SR.GetString(SR.SQL_Timeout_FailoverInfo);
}
internal static string Timeout_RoutingDestination()
{
return SR.GetString(SR.SQL_Timeout_RoutingDestinationInfo);
}
internal static string Duration_PreLogin_Begin(long PreLoginBeginDuration)
{
return SR.GetString(SR.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration);
}
internal static string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration)
{
return SR.GetString(SR.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration);
}
internal static string Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration)
{
return SR.GetString(SR.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration);
}
internal static string Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration)
{
return SR.GetString(SR.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration);
}
internal static string Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration)
{
return SR.GetString(SR.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration);
}
internal static string UserInstanceFailure()
{
return SR.GetString(SR.SQL_UserInstanceFailure);
}
internal static string PreloginError()
{
return SR.GetString(SR.Snix_PreLogin);
}
internal static string ExClientConnectionId()
{
return SR.GetString(SR.SQL_ExClientConnectionId);
}
internal static string ExErrorNumberStateClass()
{
return SR.GetString(SR.SQL_ExErrorNumberStateClass);
}
internal static string ExOriginalClientConnectionId()
{
return SR.GetString(SR.SQL_ExOriginalClientConnectionId);
}
internal static string ExRoutingDestination()
{
return SR.GetString(SR.SQL_ExRoutingDestination);
}
}
/// <summary>
/// This class holds helper methods to escape Microsoft SQL Server identifiers, such as table, schema, database or other names
/// </summary>
internal static class SqlServerEscapeHelper
{
/// <summary>
/// Escapes the identifier with square brackets. The input has to be in unescaped form, like the parts received from MultipartIdentifier.ParseMultipartIdentifier.
/// </summary>
/// <param name="name">name of the identifier, in unescaped form</param>
/// <returns>escapes the name with [], also escapes the last close bracket with double-bracket</returns>
internal static string EscapeIdentifier(string name)
{
Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed");
return "[" + name.Replace("]", "]]") + "]";
}
/// <summary>
/// Same as above EscapeIdentifier, except that output is written into StringBuilder
/// </summary>
internal static void EscapeIdentifier(StringBuilder builder, string name)
{
Debug.Assert(builder != null, "builder cannot be null");
Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed");
builder.Append("[");
builder.Append(name.Replace("]", "]]"));
builder.Append("]");
}
/// <summary>
/// Escape a string to be used inside TSQL literal, such as N'somename' or 'somename'
/// </summary>
internal static string EscapeStringAsLiteral(string input)
{
Debug.Assert(input != null, "input string cannot be null");
return input.Replace("'", "''");
}
/// <summary>
/// Escape a string as a TSQL literal, wrapping it around with single quotes.
/// Use this method to escape input strings to prevent SQL injection
/// and to get correct behavior for embedded quotes.
/// </summary>
/// <param name="input">unescaped string</param>
/// <returns>escaped and quoted literal string</returns>
internal static string MakeStringLiteral(string input)
{
if (string.IsNullOrEmpty(input))
{
return "''";
}
else
{
return "'" + EscapeStringAsLiteral(input) + "'";
}
}
}
/// <summary>
/// This class holds methods invoked on System.Transactions through reflection for Global Transactions
/// </summary>
static internal class SysTxForGlobalTransactions
{
private static readonly Lazy<MethodInfo> _enlistPromotableSinglePhase = new Lazy<MethodInfo>(() =>
typeof(Transaction).GetMethod("EnlistPromotableSinglePhase", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) }));
private static readonly Lazy<MethodInfo> _setDistributedTransactionIdentifier = new Lazy<MethodInfo>(() =>
typeof(Transaction).GetMethod("SetDistributedTransactionIdentifier", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) }));
private static readonly Lazy<MethodInfo> _getPromotedToken = new Lazy<MethodInfo>(() =>
typeof(Transaction).GetMethod("GetPromotedToken"));
/// <summary>
/// Enlists the given IPromotableSinglePhaseNotification and Non-MSDTC Promoter type into a transaction
/// </summary>
/// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
public static MethodInfo EnlistPromotableSinglePhase
{
get
{
return _enlistPromotableSinglePhase.Value;
}
}
/// <summary>
/// Sets the given DistributedTransactionIdentifier for a Transaction instance.
/// Needs to be invoked when using a Non-MSDTC Promoter type
/// </summary>
/// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
public static MethodInfo SetDistributedTransactionIdentifier
{
get
{
return _setDistributedTransactionIdentifier.Value;
}
}
/// <summary>
/// Gets the Promoted Token for a Transaction
/// </summary>
/// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
public static MethodInfo GetPromotedToken
{
get
{
return _getPromotedToken.Value;
}
}
}
}//namespace
| |
//=============================================================================
// System : Sandcastle Help File Builder Components
// File : ShowMissingComponent.cs
// Author : Eric Woodruff ([email protected])
// Updated : 11/19/2009
// Note : Copyright 2007-2009, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a build component that is used to add "missing" notes
// for missing summary, parameter, returns, value, and remarks tags. It can
// also add default summary documentation for constructors.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.4.0.0 02/16/2007 EFW Created the code
// 1.6.0.5 02/25/2008 EFW Fixed the auto-doc constructor class link
// 1.6.0.6 03/20/2008 EFW Added auto-doc of constructors on list pages
// 1.6.0.7 03/23/2008 EFW Added support for ShowMissingTypeParams and
// localized the messages.
// 1.8.0.1 01/16/2009 EFW Added support for missing <include> target docs
// 1.8.0.3 11/19/2009 EFW Added support for auto-documenting Dispose methods
//=============================================================================
using System;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Ddue.Tools;
namespace SandcastleBuilder.Components
{
/// <summary>
/// This build component is used to add "missing" notes for missing
/// summary, parameter, returns, value, and remarks tags. It can also
/// add default summary documentation for constructors.
/// </summary>
/// <example>
/// <code lang="xml" title="Example configuration">
/// <!-- Show missing documentation component configuration. This must
/// appear before the TransformComponent. -->
/// <component type="SandcastleBuilder.Components.ShowMissingComponent"
/// assembly="C:\SandcastleBuilder\SandcastleBuilder.Components.dll">
/// <!-- All elements are optional. -->
///
/// <!-- Auto-document constructors (true by default) -->
/// <AutoDocumentConstructors value="true" />
///
/// <!-- Auto-document dispose methods (true by default) -->
/// <AutoDocumentDisposeMethods value="true" />
///
/// <!-- Show missing param tags (true by default) -->
/// <ShowMissingParams value="true" />
///
/// <!-- Show missing typeparam tags (true by default) -->
/// <ShowMissingTypeParams value="true" />
///
/// <!-- Show missing remarks tags (false by default) -->
/// <ShowMissingRemarks value="false" />
///
/// <!-- Show missing returns tags (true by default) -->
/// <ShowMissingReturns value="true" />
///
/// <!-- Show missing summary tags (true by default) -->
/// <ShowMissingSummaries value="true" />
///
/// <!-- Show missing value tags (false by default) -->
/// <ShowMissingValues value="false" />
///
/// <!-- Show missing namespace comments (true by default) -->
/// <ShowMissingNamespaces value="true" />
///
/// <!-- Show missing include target docs (false by default) -->
/// <ShowMissingIncludeTargets value="false" />
///
/// <!-- Shared content file containing the localized
/// messages (optional) -->
/// <contentFile filename="C:\Working\SharedContent.xml" />
/// </component>
/// </code>
/// </example>
public class ShowMissingComponent : BuildComponent
{
#region Private data members
//=====================================================================
private static Regex reStripWhitespace = new Regex(@"\s");
private bool autoDocConstructors, autoDocDispose, showMissingParams,
showMissingTypeParams, showMissingRemarks, showMissingReturns,
showMissingSummaries, showMissingValues, showMissingNamespaces,
showMissingIncludeTargets, isEnabled;
// Auto-documented constructor and "missing" messages
private string autoDocCtorMsg, autoDocStaticCtorMsg, autoDocDisposeMsg,
autoDocDisposeBoolMsg, autoDocDisposeParamMsg, missingTagMsg,
missingParamTagMsg, missingIncludeTargetMsg;
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="assembler">A reference to the build assembler.</param>
/// <param name="configuration">The configuration information</param>
/// <remarks>See the <see cref="ShowMissingComponent"/> class topic
/// for an example of the configuration</remarks>
/// <exception cref="ConfigurationErrorsException">This is thrown if
/// an error is detected in the configuration.</exception>
public ShowMissingComponent(BuildAssembler assembler,
XPathNavigator configuration) : base(assembler, configuration)
{
XPathDocument content;
XPathNavigator nav, contentNav;
string value = null;
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
base.WriteMessage(MessageLevel.Info, String.Format(
CultureInfo.InvariantCulture,
"\r\n [{0}, version {1}]\r\n Show Missing " +
"Documentation Component. {2}\r\n http://SHFB.CodePlex.com",
fvi.ProductName, fvi.ProductVersion, fvi.LegalCopyright));
// All elements are optional. If omitted, all properties are
// true except for showMissingRemarks and showMissingValues;
autoDocConstructors = autoDocDispose = showMissingParams =
showMissingTypeParams = showMissingReturns = showMissingSummaries =
showMissingNamespaces = true;
nav = configuration.SelectSingleNode("AutoDocumentConstructors");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out autoDocConstructors))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <AutoDocumentConstructors> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("AutoDocumentDisposeMethods");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out autoDocDispose))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <AutoDocumentDisposeMethods> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingParams");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingParams))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingParams> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingTypeParams");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingTypeParams))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingTypeParams> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingRemarks");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingRemarks))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingRemarks> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingReturns");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingReturns))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingReturns> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingSummaries");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingSummaries))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingSummaries> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingValues");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingValues))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingValues> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingNamespaces");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingNamespaces))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingNamespaces> " +
"'value' attribute.");
}
nav = configuration.SelectSingleNode("ShowMissingIncludeTargets");
if(nav != null)
{
value = nav.GetAttribute("value", String.Empty);
if(!String.IsNullOrEmpty(value) && !Boolean.TryParse(value,
out showMissingIncludeTargets))
throw new ConfigurationErrorsException("You must specify " +
"a Boolean value for the <ShowMissingIncludeTargets> " +
"'value' attribute.");
}
autoDocCtorMsg = "Initializes a new instance of the <see " +
"cref=\"T:{0}\"/> class";
autoDocStaticCtorMsg = "Initializes the static fields of the " +
"<see cref=\"T:{0}\"/> class";
autoDocDisposeMsg = "Releases all resources used by the <see " +
"cref=\"T:{0}\"/>";
autoDocDisposeBoolMsg = "Releases the unmanaged resources used by " +
"the <see cref=\"T:{0}\"/> and optionally releases the " +
"managed resources";
autoDocDisposeParamMsg = "True to release both managed and " +
"unmanaged resources; false to release only unmanaged resources";
missingTagMsg = "<p style=\"color: #dc143c; font-size: 8.5pt; " +
"font-weight: bold;\">[Missing <{0}> " +
"documentation for {1}]</p>";
missingParamTagMsg = "<p style=\"color: #dc143c; font-size: 8.5pt; " +
"font-weight: bold;\">[Missing <{0} name=\"{1}\"/> " +
"documentation for \"{2}\"]</p>";
missingIncludeTargetMsg = "<p style=\"color: #dc143c; font-size: 8.5pt; " +
"font-weight: bold;\">[Missing <include> target " +
"documentation in '{0}'. File: '{1}' Path: '{2}']</p>";
nav = configuration.SelectSingleNode("contentFile");
if(nav != null)
{
value = nav.GetAttribute("filename", String.Empty);
if(String.IsNullOrEmpty(value) || !File.Exists(value))
throw new ConfigurationErrorsException("You must specify " +
"a filename value for the <contentFile> 'filename' " +
"attribute and it must exist.");
content = new XPathDocument(value);
contentNav = content.CreateNavigator();
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbAutoDocConstructor']");
if(nav != null)
autoDocCtorMsg = nav.Value;
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbAutoDocStaticConstructor']");
if(nav != null)
autoDocStaticCtorMsg = nav.Value;
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbAutoDocDispose']");
if(nav != null)
autoDocDisposeMsg = nav.Value;
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbAutoDocDisposeBool']");
if(nav != null)
autoDocDisposeBoolMsg = nav.Value;
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbAutoDocDisposeParam']");
if(nav != null)
autoDocDisposeParamMsg = nav.Value;
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbMissingTag']");
if(nav != null)
missingTagMsg = nav.Value;
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbMissingParamTag']");
if(nav != null)
missingParamTagMsg = nav.Value;
nav = contentNav.SelectSingleNode(
"content/item[@id='shfbMissingIncludeTarget']");
if(nav != null)
missingIncludeTargetMsg = nav.Value;
}
isEnabled = (autoDocConstructors || autoDocDispose ||
showMissingParams || showMissingTypeParams ||
showMissingRemarks || showMissingReturns ||
showMissingSummaries || showMissingValues ||
showMissingNamespaces || showMissingIncludeTargets);
if(!isEnabled)
base.WriteMessage(MessageLevel.Info, " All Show Missing " +
"options are disabled. The component will do nothing.");
}
#endregion
#region Apply the component
//=====================================================================
/// <summary>
/// This is implemented to add the missing documentation tags
/// </summary>
/// <param name="document">The XML document with which to work.</param>
/// <param name="key">The key (member name) of the item being
/// documented.</param>
public override void Apply(XmlDocument document, string key)
{
XmlNodeList items;
XmlNode comments, returnsNode;
string apiKey;
// Auto-document the constructor(s) on the type's list pages if
// necessary.
if(isEnabled && autoDocConstructors && (key[0] == 'T' ||
key.StartsWith("AllMembers", StringComparison.Ordinal) ||
(key.StartsWith("Overload", StringComparison.Ordinal) &&
(key.IndexOf(".ctor", StringComparison.Ordinal) != -1 ||
key.IndexOf(".#ctor", StringComparison.Ordinal) != -1))))
{
apiKey = "M:" + key.Substring(key.IndexOf(':') + 1);
if(key.IndexOf(".ctor", StringComparison.Ordinal) == -1 &&
key.IndexOf(".#ctor", StringComparison.Ordinal) == -1)
apiKey += ".#ctor";
else
apiKey = apiKey.Replace("..ctor", ".#ctor");
foreach(XmlNode element in document.SelectNodes(
"document/reference/elements/element[starts-with(@api, '" +
apiKey + "')]"))
this.CheckForMissingText(element, apiKey, "summary");
}
// Auto-document the Dispose method(s) on the type's list pages if
// necessary.
if(isEnabled && autoDocDispose && (key[0] == 'T' ||
key.StartsWith("AllMembers", StringComparison.Ordinal) ||
(key.StartsWith("Overload", StringComparison.Ordinal) &&
key.EndsWith(".Dispose", StringComparison.Ordinal))))
{
apiKey = "M:" + key.Substring(key.IndexOf(':') + 1);
if(!key.EndsWith(".Dispose", StringComparison.Ordinal))
apiKey += ".Dispose";
// Handle IDisposable.Dispose()
foreach(XmlNode element in document.SelectNodes(
"document/reference/elements/element[@api = '" + apiKey + "']"))
this.CheckForMissingText(element, apiKey, "summary");
// Handle the Boolean overload if present
apiKey += "(System.Boolean)";
foreach(XmlNode element in document.SelectNodes(
"document/reference/elements/element[@api = '" + apiKey + "']"))
this.CheckForMissingText(element, apiKey, "summary");
}
// Don't bother if there is nothing to add
if(!isEnabled || key[0] == 'R' || key[1] != ':' ||
(key[0] == 'N' && !showMissingNamespaces))
return;
try
{
// Add missing tags based on the type of item it represents
comments = document.SelectSingleNode("document/comments");
// All elements can have a summary
if(showMissingSummaries || (autoDocConstructors &&
(key.Contains("#ctor") || key.Contains("#cctor"))) ||
(autoDocDispose && (key.EndsWith(".Dispose", StringComparison.Ordinal) ||
key.EndsWith(".Dispose(System.Boolean)", StringComparison.Ordinal))))
this.CheckForMissingText(comments, key, "summary");
// All elements can have an include. We check for this after
// summary since the "missing" message is appended to the
// summary and we don't want it to count as the summary.
if(showMissingIncludeTargets)
this.CheckForMissingIncludeTarget(comments, key);
// All elements can have remarks except namespaces
if(showMissingRemarks && key[0] != 'N')
this.CheckForMissingText(comments, key, "remarks");
// If it's a property, check for a missing <value> tag
if(key[0] == 'P' && showMissingValues)
this.CheckForMissingText(comments, key, "value");
else
{
if(showMissingTypeParams && (key[0] == 'T' ||
key[0] == 'M'))
{
items = document.SelectNodes(
"document/reference/templates/template");
foreach(XmlNode p in items)
this.CheckForMissingParameter(comments, key,
p.Attributes["name"].Value, "typeparam");
}
if(key[0] == 'M')
{
// If it's a member, check for missing <returns>
// and <param> tags.
if(showMissingReturns)
{
returnsNode = document.SelectSingleNode(
"document/reference/returns");
if(returnsNode != null)
this.CheckForMissingText(comments, key,
"returns");
}
if(showMissingParams || (autoDocDispose &&
key.EndsWith(".Dispose(System.Boolean)", StringComparison.Ordinal)))
{
items = document.SelectNodes(
"document/reference/parameters/parameter");
foreach(XmlNode p in items)
this.CheckForMissingParameter(comments, key,
p.Attributes["name"].Value, "param");
}
}
}
}
catch(Exception ex)
{
base.WriteMessage(MessageLevel.Error, "Error adding " +
"missing documentation tags: " + ex.Message);
}
}
#endregion
#region Helper methods
//=====================================================================
/// <summary>
/// Check for missing text in the specified documentation tag and, if
/// it doesn't exist or the text is blank, add a "missing" message as
/// the documentation tag's text.
/// </summary>
/// <param name="comments">The comments node to check.</param>
/// <param name="key">The key (name) for the current item</param>
/// <param name="tagName">The tag type for which to check.</param>
private void CheckForMissingText(XmlNode comments, string key,
string tagName)
{
string text;
XmlNode tag = comments.SelectSingleNode(tagName);
if(tag == null)
{
tag = comments.OwnerDocument.CreateNode(XmlNodeType.Element,
tagName, null);
comments.AppendChild(tag);
text = String.Empty;
}
else
text = reStripWhitespace.Replace(tag.InnerText, String.Empty);
if(text.Length == 0)
{
// Auto document constructor?
if(tagName == "summary" && autoDocConstructors &&
(key.Contains("#ctor") || key.Contains("#cctor")))
{
this.WriteMessage(MessageLevel.Info, "Auto-documenting " +
"constructor " + key);
if(key.Contains("#cctor"))
tag.InnerXml = String.Format(
CultureInfo.InvariantCulture, autoDocStaticCtorMsg,
HttpUtility.HtmlEncode(key.Substring(2,
key.IndexOf(".#cctor", StringComparison.Ordinal) - 2)));
else
tag.InnerXml = String.Format(
CultureInfo.InvariantCulture, autoDocCtorMsg,
HttpUtility.HtmlEncode(key.Substring(2,
key.IndexOf(".#ctor", StringComparison.Ordinal) - 2)));
return;
}
// Auto document Dispose method?
if(tagName == "summary" && (autoDocDispose &&
key.EndsWith(".Dispose", StringComparison.Ordinal) ||
key.EndsWith(".Dispose(System.Boolean)", StringComparison.Ordinal)))
{
this.WriteMessage(MessageLevel.Info, "Auto-documenting " +
"dispose method " + key);
if(key.EndsWith(".Dispose", StringComparison.Ordinal))
tag.InnerXml = String.Format(
CultureInfo.InvariantCulture, autoDocDisposeMsg,
HttpUtility.HtmlEncode(key.Substring(2, key.Length - 10)));
else
tag.InnerXml = String.Format(
CultureInfo.InvariantCulture, autoDocDisposeBoolMsg,
HttpUtility.HtmlEncode(key.Substring(2, key.Length - 26)));
return;
}
this.WriteMessage(MessageLevel.Warn, String.Format(
CultureInfo.InvariantCulture,
"Missing <{0}> documentation for {1}", tagName, key));
tag.InnerXml = String.Format(CultureInfo.InvariantCulture,
missingTagMsg, tagName, HttpUtility.HtmlEncode(key));
}
}
/// <summary>
/// Check for missing text in the specified <param> or
/// <typeparam> tag and, if it doesn't exist or the text is
/// blank, add a "missing" message as the tag's text.
/// </summary>
/// <param name="comments">The comments node to check.</param>
/// <param name="key">The key (name) for the current item</param>
/// <param name="paramName">The parameter name for which to check.</param>
/// <param name="tagName">The tag type for which to check.</param>
private void CheckForMissingParameter(XmlNode comments, string key,
string paramName, string tagName)
{
string text;
XmlAttribute name;
XmlNode tag = comments.SelectSingleNode(tagName + "[@name='" +
paramName + "']");
if(tag == null)
{
tag = comments.OwnerDocument.CreateNode(XmlNodeType.Element,
tagName, null);
name = comments.OwnerDocument.CreateAttribute("name");
name.Value = paramName;
tag.Attributes.Append(name);
comments.AppendChild(tag);
text = String.Empty;
}
else
text = reStripWhitespace.Replace(tag.InnerText, String.Empty);
if(text.Length == 0)
{
// Auto document Dispose(Bool) parameter?
if(autoDocDispose && key.EndsWith(".Dispose(System.Boolean)", StringComparison.Ordinal))
{
this.WriteMessage(MessageLevel.Info, "Auto-documenting " +
"dispose method parameter for " + key);
tag.InnerXml = String.Format(CultureInfo.InvariantCulture,
autoDocDisposeParamMsg, HttpUtility.HtmlEncode(
key.Substring(2, key.Length - 26)));
return;
}
this.WriteMessage(MessageLevel.Warn, String.Format(
CultureInfo.InvariantCulture,
"Missing <{0} name=\"{1}\"/> documentation for {2}",
tagName, paramName, key));
tag.InnerXml = String.Format(CultureInfo.InvariantCulture,
missingParamTagMsg, tagName,
HttpUtility.HtmlEncode(paramName),
HttpUtility.HtmlEncode(key));
}
}
/// <summary>
/// Check for bad <c>include</c> elements and, if any are found, add a
/// "missing" message to the summary tag's text.
/// </summary>
/// <param name="comments">The comments node to check.</param>
/// <param name="key">The key (name) for the current item</param>
private void CheckForMissingIncludeTarget(XmlNode comments, string key)
{
XmlNodeList includes = comments.SelectNodes("include");
XmlNode tag;
if(includes.Count != 0)
{
tag = comments.SelectSingleNode("summary");
if(tag == null)
{
tag = comments.OwnerDocument.CreateNode(XmlNodeType.Element,
"summary", null);
comments.AppendChild(tag);
tag.InnerXml = String.Empty;
}
foreach(XmlNode include in includes)
{
this.WriteMessage(MessageLevel.Warn, String.Format(
CultureInfo.InvariantCulture, missingIncludeTargetMsg,
key, include.Attributes["file"].Value,
include.Attributes["path"].Value));
tag.InnerXml += String.Format(CultureInfo.InvariantCulture,
missingIncludeTargetMsg, HttpUtility.HtmlEncode(key),
HttpUtility.HtmlEncode(include.Attributes["file"].Value),
HttpUtility.HtmlEncode(include.Attributes["path"].Value));
}
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.