context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//-----------------------------------------------------------------------
// <copyright file="CloudBlockBlob.cs" company="Microsoft">
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <summary>
// Contains code for the CloudBlockBlob class.
// </summary>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.StorageClient
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Protocol;
using Tasks;
using TaskSequence = System.Collections.Generic.IEnumerable<Tasks.ITask>;
/// <summary>
/// Represents a blob that is uploaded as a set of blocks.
/// </summary>
public class CloudBlockBlob : CloudBlob
{
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using an absolute URI to the blob.
/// </summary>
/// <param name="blobAbsoluteUri">The absolute URI to the blob.</param>
/// <param name="credentials">The account credentials.</param>
public CloudBlockBlob(string blobAbsoluteUri, StorageCredentials credentials)
: base(blobAbsoluteUri, credentials)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using a relative URI to the blob.
/// </summary>
/// <param name="blobUri">The relative URI to the blob, beginning with the container name.</param>
/// <param name="client">A client object that specifies the endpoint for the Blob service.</param>
public CloudBlockBlob(string blobUri, CloudBlobClient client)
: this(blobUri, null, client)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using a relative URI to the blob.
/// </summary>
/// <param name="blobUri">The relative URI to the blob, beginning with the container name.</param>
/// <param name="snapshotTime">The snapshot timestamp, if the blob is a snapshot.</param>
/// <param name="client">A client object that specifies the endpoint for the Blob service.</param>
public CloudBlockBlob(string blobUri, DateTime? snapshotTime, CloudBlobClient client)
: base(blobUri, snapshotTime, client)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using an absolute URI to the blob.
/// </summary>
/// <param name="blobAbsoluteUri">The absolute URI to the blob.</param>
public CloudBlockBlob(string blobAbsoluteUri)
: base(blobAbsoluteUri)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using an absolute URI to the blob.
/// </summary>
/// <param name="blobAbsoluteUri">The absolute URI to the blob.</param>
/// <param name="credentials">The account credentials.</param>
/// <param name="usePathStyleUris"><c>True</c> to use path-style URIs; otherwise, <c>false</c>.</param>
public CloudBlockBlob(string blobAbsoluteUri, StorageCredentials credentials, bool usePathStyleUris)
: base(blobAbsoluteUri, credentials, usePathStyleUris)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using an absolute URI to the blob.
/// </summary>
/// <param name="blobAbsoluteUri">The absolute URI to the blob.</param>
/// <param name="usePathStyleUris"><c>True</c> to use path-style URIs; otherwise, <c>false</c>.</param>
public CloudBlockBlob(string blobAbsoluteUri, bool usePathStyleUris)
: base(blobAbsoluteUri, usePathStyleUris)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class based on an existing blob.
/// </summary>
/// <param name="cloudBlob">The blob to clone.</param>
internal CloudBlockBlob(CloudBlob cloudBlob) : base(cloudBlob)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class.
/// </summary>
/// <param name="attributes">The attributes.</param>
/// <param name="serviceClient">The service client.</param>
/// <param name="snapshotTime">The snapshot time.</param>
internal CloudBlockBlob(BlobAttributes attributes, CloudBlobClient serviceClient, string snapshotTime)
: base(attributes, serviceClient, snapshotTime)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using the specified blob Uri.
/// Note that this is just a reference to a blob instance and no requests are issued to the service
/// yet to update the blob properties, attribute or metaddata. FetchAttributes is the API that
/// issues such request to the service.
/// </summary>
/// <param name="blobUri">Relative Uri to the blob.</param>
/// <param name="client">Existing Blob service client which provides the base address.</param>
/// <param name="containerReference">The reference to the parent container.</param>
internal CloudBlockBlob(string blobUri, CloudBlobClient client, CloudBlobContainer containerReference)
: this(blobUri, null, client, containerReference)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CloudBlockBlob"/> class using the specified blob Uri.
/// If snapshotTime is not null, the blob instance represents a Snapshot.
/// Note that this is just a reference to a blob instance and no requests are issued to the service
/// yet to update the blob properties, attribute or metaddata. FetchAttributes is the API that
/// issues such request to the service.
/// </summary>
/// <param name="blobUri">Relative Uri to the blob.</param>
/// <param name="snapshotTime">Snapshot time in case the blob is a snapshot.</param>
/// <param name="client">Existing Blob service client which provides the base address.</param>
/// <param name="containerReference">The reference to the parent container.</param>
internal CloudBlockBlob(string blobUri, DateTime? snapshotTime, CloudBlobClient client, CloudBlobContainer containerReference)
: base(blobUri, snapshotTime, client, containerReference)
{
this.Properties.BlobType = BlobType.BlockBlob;
}
/// <summary>
/// Returns an enumerable collection of the committed blocks comprising the blob.
/// </summary>
/// <returns>An enumerable collection of objects implementing <see cref="ListBlockItem"/>.</returns>
public IEnumerable<ListBlockItem> DownloadBlockList()
{
return this.DownloadBlockList(null);
}
/// <summary>
/// Returns an enumerable collection of the committed blocks comprising the blob.
/// </summary>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>An enumerable collection of objects implementing <see cref="ListBlockItem"/>.</returns>
public IEnumerable<ListBlockItem> DownloadBlockList(BlobRequestOptions options)
{
return this.DownloadBlockList(BlockListingFilter.Committed, options);
}
/// <summary>
/// Returns an enumerable collection of the blob's blocks, using the specified block list filter.
/// </summary>
/// <param name="blockListingFilter">One of the enumeration values that indicates whether to return
/// committed blocks, uncommitted blocks, or both.</param>
/// <returns>An enumerable collection of objects implementing <see cref="ListBlockItem"/>.</returns>
public IEnumerable<ListBlockItem> DownloadBlockList(BlockListingFilter blockListingFilter)
{
return this.DownloadBlockList(blockListingFilter, null);
}
/// <summary>
/// Returns an enumerable collection of the blob's blocks, using the specified block list filter.
/// </summary>
/// <param name="blockListingFilter">One of the enumeration values that indicates whether to return
/// committed blocks, uncommitted blocks, or both.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>An enumerable collection of objects implementing <see cref="ListBlockItem"/>.</returns>
public IEnumerable<ListBlockItem> DownloadBlockList(BlockListingFilter blockListingFilter, BlobRequestOptions options)
{
var fullModifier = BlobRequestOptions.CreateFullModifier(this.ServiceClient, options);
return TaskImplHelper.ExecuteImplWithRetry<IEnumerable<ListBlockItem>>(
(result) =>
{
return this.GetDownloadBlockList(blockListingFilter, fullModifier, result);
},
fullModifier.RetryPolicy);
}
/// <summary>
/// Begins an asynchronous operation to return an enumerable collection of the blob's blocks,
/// using the specified block list filter.
/// </summary>
/// <param name="blockListingFilter">One of the enumeration values that indicates whether to return
/// committed blocks, uncommitted blocks, or both.</param>
/// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param>
/// <param name="state">A user-defined object that will be passed to the callback delegate.</param>
/// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
public IAsyncResult BeginDownloadBlockList(BlockListingFilter blockListingFilter, AsyncCallback callback, object state)
{
return this.BeginDownloadBlockList(blockListingFilter, null, callback, state);
}
/// <summary>
/// Begins an asynchronous operation to return an enumerable collection of the blob's blocks,
/// using the specified block list filter.
/// </summary>
/// <param name="blockListingFilter">One of the enumeration values that indicates whether to return
/// committed blocks, uncommitted blocks, or both.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param>
/// <param name="state">A user-defined object that will be passed to the callback delegate.</param>
/// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
public IAsyncResult BeginDownloadBlockList(BlockListingFilter blockListingFilter, BlobRequestOptions options, AsyncCallback callback, object state)
{
var fullModifier = BlobRequestOptions.CreateFullModifier(this.ServiceClient, options);
return TaskImplHelper.BeginImplWithRetry<IEnumerable<ListBlockItem>>(
(result) =>
{
return this.GetDownloadBlockList(blockListingFilter, fullModifier, result);
},
fullModifier.RetryPolicy,
callback,
state);
}
/// <summary>
/// Ends an asynchronous operation to return an enumerable collection of the blob's blocks,
/// using the specified block list filter.
/// </summary>
/// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the pending asynchronous operation.</param>
/// <returns>An enumerable collection of objects implementing <see cref="ListBlockItem"/>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is a member-operation")]
public IEnumerable<ListBlockItem> EndDownloadBlockList(IAsyncResult asyncResult)
{
return TaskImplHelper.EndImplWithRetry<IEnumerable<ListBlockItem>>(asyncResult);
}
/// <summary>
/// Uploads a single block.
/// </summary>
/// <param name="blockId">A base64-encoded block ID that identifies the block.</param>
/// <param name="blockData">A stream that provides the data for the block.</param>
/// <param name="contentMD5">An optional hash value that will be used to set the <see cref="BlobProperties.ContentMD5"/> property
/// on the blob. May be <c>null</c> or an empty string.</param>
public void PutBlock(string blockId, Stream blockData, string contentMD5)
{
this.PutBlock(blockId, blockData, contentMD5, null);
}
/// <summary>
/// Uploads a single block.
/// </summary>
/// <param name="blockId">A base64-encoded block ID that identifies the block.</param>
/// <param name="blockData">A stream that provides the data for the block.</param>
/// <param name="contentMD5">An optional hash value that will be used to set the <see cref="BlobProperties.ContentMD5"/> property
/// on the blob. May be <c>null</c> or an empty string.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public void PutBlock(string blockId, Stream blockData, string contentMD5, BlobRequestOptions options)
{
var fullModifier = BlobRequestOptions.CreateFullModifier(this.ServiceClient, options);
var position = blockData.Position;
var retryPolicy = blockData.CanSeek ? fullModifier.RetryPolicy : RetryPolicies.NoRetry();
TaskImplHelper.ExecuteImplWithRetry(
() =>
{
if (blockData.CanSeek)
{
blockData.Position = position;
}
return this.UploadBlock(blockData, blockId, contentMD5, fullModifier);
},
retryPolicy);
}
/// <summary>
/// Begins an asynchronous operation to upload a single block.
/// </summary>
/// <param name="blockId">A base64-encoded block ID that identifies the block.</param>
/// <param name="blockData">A stream that provides the data for the block.</param>
/// <param name="contentMD5">An optional hash value that will be used to set the <see cref="BlobProperties.ContentMD5"/> property
/// on the blob. May be <c>null</c> or an empty string.</param>
/// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param>
/// <param name="state">A user-defined object that will be passed to the callback delegate.</param>
/// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
public IAsyncResult BeginPutBlock(string blockId, Stream blockData, string contentMD5, AsyncCallback callback, object state)
{
return this.BeginPutBlock(blockId, blockData, contentMD5, null, callback, state);
}
/// <summary>
/// Begins an asynchronous operation to upload a single block.
/// </summary>
/// <param name="blockId">A base64-encoded block ID that identifies the block.</param>
/// <param name="blockData">A stream that provides the data for the block.</param>
/// <param name="contentMD5">An optional hash value that will be used to set the <see cref="BlobProperties.ContentMD5"/> property
/// on the blob. May be <c>null</c> or an empty string.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param>
/// <param name="state">A user-defined object that will be passed to the callback delegate.</param>
/// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
public IAsyncResult BeginPutBlock(string blockId, Stream blockData, string contentMD5, BlobRequestOptions options, AsyncCallback callback, object state)
{
var fullModifier = BlobRequestOptions.CreateFullModifier(this.ServiceClient, options);
var position = blockData.Position;
var retryPolicy = blockData.CanSeek ? fullModifier.RetryPolicy : RetryPolicies.NoRetry();
return TaskImplHelper.BeginImplWithRetry(
() =>
{
if (blockData.CanSeek)
{
blockData.Position = position;
}
return this.UploadBlock(blockData, blockId, contentMD5, fullModifier);
},
retryPolicy,
callback,
state);
}
/// <summary>
/// Ends an asynchronous operation to upload a single block.
/// </summary>
/// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the pending asynchronous operation.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is a member-operation")]
public void EndPutBlock(IAsyncResult asyncResult)
{
TaskImplHelper.EndImplWithRetry(asyncResult);
}
/// <summary>
/// Uploads a list of blocks to a new or existing blob.
/// </summary>
/// <param name="blockList">An enumerable collection of block IDs, as base64-encoded strings.</param>
public void PutBlockList(IEnumerable<string> blockList)
{
this.PutBlockList(blockList, null);
}
/// <summary>
/// Uploads a list of blocks to a new or existing blob.
/// </summary>
/// <param name="blockList">An enumerable collection of block IDs, as base64-encoded strings.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public void PutBlockList(IEnumerable<string> blockList, BlobRequestOptions options)
{
var fullModifier = BlobRequestOptions.CreateFullModifier(this.ServiceClient, options);
List<PutBlockListItem> items = blockList.Select(i => { return new PutBlockListItem(i, BlockSearchMode.Latest); }).ToList();
TaskImplHelper.ExecuteImplWithRetry(() => { return this.UploadBlockList(items, fullModifier); }, fullModifier.RetryPolicy);
}
/// <summary>
/// Begins an asynchronous operation to upload a list of blocks to a new or existing blob.
/// </summary>
/// <param name="blockList">An enumerable collection of block IDs, as base64-encoded strings.</param>
/// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param>
/// <param name="state">A user-defined object that will be passed to the callback delegate.</param>
/// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
public IAsyncResult BeginPutBlockList(IEnumerable<string> blockList, AsyncCallback callback, object state)
{
return this.BeginPutBlockList(blockList, null, callback, state);
}
/// <summary>
/// Begins an asynchronous operation to upload a list of blocks to a new or existing blob.
/// </summary>
/// <param name="blockList">An enumerable collection of block IDs, as base64-encoded strings.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <param name="callback">The callback delegate that will receive notification when the asynchronous operation completes.</param>
/// <param name="state">A user-defined object that will be passed to the callback delegate.</param>
/// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
public IAsyncResult BeginPutBlockList(IEnumerable<string> blockList, BlobRequestOptions options, AsyncCallback callback, object state)
{
var fullModifier = BlobRequestOptions.CreateFullModifier(this.ServiceClient, options);
List<PutBlockListItem> items = blockList.Select(i => { return new PutBlockListItem(i, BlockSearchMode.Latest); }).ToList();
return TaskImplHelper.BeginImplWithRetry(() => { return this.UploadBlockList(items, fullModifier); }, fullModifier.RetryPolicy, callback, state);
}
/// <summary>
/// Ends an asynchronous operation to upload a list of blocks to a new or existing blob.
/// </summary>
/// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the pending asynchronous operation.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is a member-operation")]
public void EndPutBlockList(IAsyncResult asyncResult)
{
TaskImplHelper.EndImplWithRetry(asyncResult);
}
/// <summary>
/// Uploads the block list.
/// </summary>
/// <param name="blocks">The blocks to upload.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>A <see cref="TaskSequence"/> that uploads the block list.</returns>
internal TaskSequence UploadBlockList(List<PutBlockListItem> blocks, BlobRequestOptions options)
{
if (options == null)
{
throw new ArgumentNullException("modifers");
}
var request = ProtocolHelper.GetWebRequest(this.ServiceClient, options, (timeout) => BlobRequest.PutBlockList(this.TransformedAddress, timeout, this.Properties, null));
options.AccessCondition.ApplyCondition(request);
BlobRequest.AddMetadata(request, this.Metadata);
using (var memoryStream = new SmallBlockMemoryStream(Constants.DefaultBufferSize))
{
BlobRequest.WriteBlockListBody(blocks, memoryStream);
CommonUtils.ApplyRequestOptimizations(request, memoryStream.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
// Compute the MD5
var md5 = System.Security.Cryptography.MD5.Create();
request.Headers[HttpRequestHeader.ContentMd5] = Convert.ToBase64String(md5.ComputeHash(memoryStream));
this.ServiceClient.Credentials.SignRequest(request);
memoryStream.Seek(0, SeekOrigin.Begin);
// Retrieve the stream
var requestStreamTask = request.GetRequestStreamAsync();
yield return requestStreamTask;
using (Stream requestStream = requestStreamTask.Result)
{
// Copy the data
var copyTask = new InvokeTaskSequenceTask(() => { return memoryStream.WriteTo(requestStream); });
yield return copyTask;
// Materialize any exceptions
var scratch = copyTask.Result;
Console.WriteLine(scratch);
}
}
// Get the response
var responseTask = request.GetResponseAsyncWithTimeout(this.ServiceClient, options.Timeout);
yield return responseTask;
using (var response = responseTask.Result as HttpWebResponse)
{
ParseSizeAndLastModified(response);
this.Properties.Length = 0;
}
}
/// <summary>
/// Gets the download block list.
/// </summary>
/// <param name="typesOfBlocks">The types of blocks.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <param name="setResult">The result report delegate.</param>
/// <returns>A <see cref="TaskSequence"/> that gets the download block list.</returns>
internal TaskSequence GetDownloadBlockList(BlockListingFilter typesOfBlocks, BlobRequestOptions options, Action<IEnumerable<ListBlockItem>> setResult)
{
var request = ProtocolHelper.GetWebRequest(this.ServiceClient, options, (timeout) => BlobRequest.GetBlockList(this.TransformedAddress, timeout, this.SnapshotTime, typesOfBlocks, null));
this.ServiceClient.Credentials.SignRequest(request);
// Retrieve the stream
var requestStreamTask = request.GetResponseAsyncWithTimeout(this.ServiceClient, options.Timeout);
yield return requestStreamTask;
// Copy the data
using (var response = requestStreamTask.Result as HttpWebResponse)
{
using (var responseStream = response.GetResponseStream())
{
var blockListResponse = new GetBlockListResponse(responseStream);
setResult(ParseResponse(blockListResponse));
}
this.ParseSizeAndLastModified(response);
}
}
/// <summary>
/// Parses the response.
/// </summary>
/// <param name="blockListResponse">The block list response.</param>
/// <returns>An enumerable list of <see cref="ListBlockItem"/> objects.</returns>
private static IEnumerable<ListBlockItem> ParseResponse(GetBlockListResponse blockListResponse)
{
List<ListBlockItem> result = new List<ListBlockItem>();
result.AddRange(blockListResponse.Blocks);
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ReadTimeout_Property : PortsTest
{
//The default number of chars to write with when testing timeout with Read(char[], int, int)
private const int DEFAULT_READ_CHAR_ARRAY_SIZE = 8;
//The default number of bytes to write with when testing timeout with Read(byte[], int, int)
private const int DEFAULT_READ_BYTE_ARRAY_SIZE = 8;
//The ammount of time to wait when expecting an infinite timeout
private const int DEFAULT_WAIT_INFINITE_TIMEOUT = 250;
//The maximum acceptable time allowed when a read method should timeout immediately
private const int MAX_ACCEPTABLE_ZERO_TIMEOUT = 100;
//The maximum acceptable time allowed when a read method should timeout immediately when it is called for the first time
private const int MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT = 1000;
private const int NUM_TRYS = 5;
private enum ThrowAt { Set, Open };
#region Test Cases
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Default_Read_byte_int_int()
{
Debug.WriteLine("Verifying default ReadTimeout with Read(byte[] buffer, int offset, int count)");
VerifyInfiniteTimeout(Read_byte_int_int, false);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Default_Read_char_int_int()
{
Debug.WriteLine("Verifying default ReadTimeout with Read(char[] buffer, int offset, int count)");
VerifyInfiniteTimeout(Read_char_int_int, false);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Default_ReadByte()
{
Debug.WriteLine("Verifying default ReadTimeout with ReadByte()");
VerifyInfiniteTimeout(ReadByte, false);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Default_ReadLine()
{
Debug.WriteLine("Verifying default ReadTimeout with ReadLine()");
VerifyInfiniteTimeout(ReadLine, false);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Default_ReadTo()
{
Debug.WriteLine("Verifying default ReadTimeout with ReadTo()");
VerifyInfiniteTimeout(ReadTo, false);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Infinite_Read_byte_int_int()
{
Debug.WriteLine("Verifying infinite ReadTimeout with Read(byte[] buffer, int offset, int count)");
VerifyInfiniteTimeout(Read_byte_int_int, true);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Infinite_Read_char_int_int()
{
Debug.WriteLine("Verifying infinite ReadTimeout with Read(char[] buffer, int offset, int count)");
VerifyInfiniteTimeout(Read_char_int_int, true);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Infinite_ReadByte()
{
Debug.WriteLine("Verifying infinite ReadTimeout with ReadByte()");
VerifyInfiniteTimeout(ReadByte, true);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Infinite_ReadLine()
{
Debug.WriteLine("Verifying infinite ReadTimeout with ReadLine()");
VerifyInfiniteTimeout(ReadLine, true);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Infinite_ReadTo()
{
Debug.WriteLine("Verifying infinite ReadTimeout with ReadTo()");
VerifyInfiniteTimeout(ReadTo, true);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_Read_byte_int_int_BeforeOpen()
{
Debug.WriteLine("Verifying setting ReadTimeout=0 before Open() with Read(byte[] buffer, int offset, int count)");
VerifyZeroTimeoutBeforeOpen(Read_byte_int_int);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_Read_char_int_int_BeforeOpen()
{
Debug.WriteLine("Verifying setting ReadTimeout=0 before Open() with Read(char[] buffer, int offset, int count)");
VerifyZeroTimeoutBeforeOpen(Read_char_int_int);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_ReadByte_BeforeOpen()
{
Debug.WriteLine("Verifying zero ReadTimeout before Open with ReadByte()");
VerifyZeroTimeoutBeforeOpen(ReadByte);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_ReadLine_BeforeOpen()
{
Debug.WriteLine("Verifying zero ReadTimeout before Open with ReadLine()");
VerifyZeroTimeoutBeforeOpen(ReadLine);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_ReadTo_BeforeOpen()
{
Debug.WriteLine("Verifying zero ReadTimeout before Open with ReadTo()");
VerifyZeroTimeoutBeforeOpen(ReadTo);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_Read_byte_int_int_AfterOpen()
{
Debug.WriteLine("Verifying setting ReadTimeout=0 after Open() with Read(byte[] buffer, int offset, int count)");
VerifyZeroTimeoutAfterOpen(Read_byte_int_int);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_Read_char_int_int_AfterOpen()
{
Debug.WriteLine("Verifying setting ReadTimeout=0 after Open() with Read(char[] buffer, int offset, int count)");
VerifyZeroTimeoutAfterOpen(Read_char_int_int);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_ReadByte_AfterOpen()
{
Debug.WriteLine("Verifying zero ReadTimeout after Open with ReadByte()");
VerifyZeroTimeoutAfterOpen(ReadByte);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_ReadLine_AfterOpen()
{
Debug.WriteLine("Verifying zero ReadTimeout after Open with ReadLine()");
VerifyZeroTimeoutAfterOpen(ReadLine);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_0_ReadTo_AfterOpen()
{
Debug.WriteLine("Verifying zero ReadTimeout after Open with ReadTo()");
VerifyZeroTimeoutAfterOpen(ReadTo);
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_Int32MinValue()
{
Debug.WriteLine("Verifying Int32.MinValue ReadTimeout");
VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ActiveIssue(15961)]
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadTimeout_NEG2()
{
Debug.WriteLine("Verifying -2 ReadTimeout");
VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
#endregion
#region Verification for Test Cases
private static void VerifyInfiniteTimeout(Action<SerialPort> readMethod, bool setInfiniteTimeout)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.SetProperty("WriteTimeout", 10);
com1.WriteTimeout = 10;
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
if (!com2.IsOpen)
com2.Open();
if (setInfiniteTimeout)
{
com1.ReadTimeout = 500;
com1.ReadTimeout = SerialPort.InfiniteTimeout;
}
Task task = Task.Run(() => readMethod(com1));
Thread.Sleep(DEFAULT_WAIT_INFINITE_TIMEOUT);
Assert.True(!task.IsCompleted);
serPortProp.VerifyPropertiesAndPrint(com1);
com2.WriteLine(string.Empty);
TCSupport.WaitForTaskCompletion(task);
}
}
private void VerifyZeroTimeoutBeforeOpen(Action<SerialPort> readMethod)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
com.ReadTimeout = 0;
com.Open();
VerifyZeroTimeout(com, readMethod);
}
}
private void VerifyZeroTimeoutAfterOpen(Action<SerialPort> readMethod)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
com.Open();
com.ReadTimeout = 0;
VerifyZeroTimeout(com, readMethod);
}
}
private void VerifyZeroTimeout(SerialPort com, Action<SerialPort> readMethod)
{
SerialPortProperties serPortProp = new SerialPortProperties();
Stopwatch sw = new Stopwatch();
int actualTime = 0;
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp.SetProperty("ReadTimeout", 0);
serPortProp.SetProperty("WriteTimeout", 1000);
com.WriteTimeout = 1000;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
sw.Start();
readMethod(com);
sw.Stop();
if (MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT < sw.ElapsedMilliseconds)
{
Fail("Err_2570ajdlkj!!! Read Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, sw.ElapsedMilliseconds, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT);
}
sw.Reset();
for (int i = 0; i < NUM_TRYS; i++)
{
sw.Start();
readMethod(com);
sw.Stop();
actualTime += (int)sw.ElapsedMilliseconds;
sw.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
if (MAX_ACCEPTABLE_ZERO_TIMEOUT < actualTime)
{
Fail("ERROR!!! Read Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, actualTime, MAX_ACCEPTABLE_ZERO_TIMEOUT);
}
serPortProp.VerifyPropertiesAndPrint(com);
com.ReadTimeout = 0;
}
private void VerifyException(int readTimeout, ThrowAt throwAt, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
VerifyExceptionAtOpen(com, readTimeout, throwAt, expectedException);
if (com.IsOpen)
com.Close();
VerifyExceptionAfterOpen(com, readTimeout, expectedException);
}
}
private void VerifyExceptionAtOpen(SerialPort com, int readTimeout, ThrowAt throwAt, Type expectedException)
{
int origReadTimeout = com.ReadTimeout;
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
if (ThrowAt.Open == throwAt)
serPortProp.SetProperty("ReadTimeout", readTimeout);
try
{
com.ReadTimeout = readTimeout;
if (ThrowAt.Open == throwAt)
com.Open();
if (null != expectedException)
{
Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
com.ReadTimeout = origReadTimeout;
}
private void VerifyExceptionAfterOpen(SerialPort com, int readTimeout, Type expectedException)
{
SerialPortProperties serPortProp = new SerialPortProperties();
com.Open();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
try
{
com.ReadTimeout = readTimeout;
if (null != expectedException)
{
Fail("ERROR!!! Expected setting the ReadTimeout after Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected setting the ReadTimeout after Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected setting the ReadTimeout after Open() throw {0} and {1} was thrown",
expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
}
private void Read_byte_int_int(SerialPort com)
{
try
{
com.Read(new byte[DEFAULT_READ_BYTE_ARRAY_SIZE], 0, DEFAULT_READ_BYTE_ARRAY_SIZE);
}
catch (TimeoutException) { }
}
private void Read_char_int_int(SerialPort com)
{
try
{
com.Read(new char[DEFAULT_READ_CHAR_ARRAY_SIZE], 0, DEFAULT_READ_CHAR_ARRAY_SIZE);
}
catch (TimeoutException) { }
}
private void ReadByte(SerialPort com)
{
try
{
com.ReadByte();
}
catch (TimeoutException) { }
}
private void ReadChar(SerialPort com)
{
try
{
com.ReadChar();
}
catch (TimeoutException) { }
}
private void ReadLine(SerialPort com)
{
try
{
com.ReadLine();
}
catch (TimeoutException) { }
}
private void ReadTo(SerialPort com)
{
try
{
com.ReadTo(com.NewLine);
}
catch (TimeoutException) { }
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json.Linq;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// Extension rule to verify Json ve.0 feed:
/// If the JSON array represents a partial collection of entities, a nextLinkNVP name value pair MUST be included
/// in the JSON array to indicate it represents a partial collection.
/// </summary>
[Export(typeof(ExtensionRule))]
public class FeedCore2001 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Feed.Core.2001";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "If the JSON array represents a partial collection of entities, a nextLinkNVP name value pair MUST be included in the JSON array to indicate it represents a partial collection.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "2.2.6.3.2";
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets descriptive summary of the rule
/// </summary>
public override string Aspect
{
get
{
return "semantic";
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Feed;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Json;
}
}
/// <summary>
/// Gets the OData version of the response to which the rule applies.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V2;
}
}
/// <summary>
/// Verifies the semantic rule
/// </summary>
/// <param name="context">The Interop service context</param>
/// <param name="info">out parameter to return violation information when rule does not pass</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
info = null;
bool? passed = null;
if (FeedCore2001.IsNextLinkPresent(context))
{
passed = true;
}
else
{
passed = !FeedCore2001.IsPartialColleclection(context);
if (!passed.Value)
{
info = new ExtensionRuleViolationInfo(Resource.PayloadExpectingNextLink, context.Destination, context.ResponsePayload);
}
}
return passed;
}
/// <summary>
/// Checks whether the context payload is a partial collection of entrities
/// </summary>
/// <param name="context">The service context</param>
/// <returns>True if it is partial collection; false otherwise</returns>
private static bool IsPartialColleclection(ServiceContext context)
{
bool anyNewEntry = false;
JObject contextResponse = JsonParserHelper.GetResponseObject(context);
if (contextResponse != null)
{
JArray contextEntries = JsonParserHelper.GetEntries(contextResponse);
if (contextEntries.Count > 0)
{
// if any more entries return, the context response payload was a partial collection
Uri prober = FeedCore2001.ConstructProbeUri(context);
var resp = WebHelper.Get(prober, Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
if (resp == null || string.IsNullOrEmpty(resp.ResponsePayload) || !JsonHelper.IsJsonVerboseFeed(resp.ResponsePayload))
{
return false;
}
JObject response = JsonParserHelper.GetResponseObject(resp.ResponsePayload);
if (response != null)
{
JArray entries = JsonParserHelper.GetEntries(response);
if (entries.Count > 0)
{
// some producers do not respect $skipton;
// need to look at each entry to see whether there is any new entry.
HashSet<string> contextEntryKeys = new HashSet<string>(EqualityComparer<string>.Default);
foreach (var e in contextEntries)
{
if (e.Type == JTokenType.Object)
{
var i = JsonParserHelper.GetTokenOfEntry((JObject)e);
contextEntryKeys.Add(i);
}
}
foreach (var e in entries)
{
if (e.Type == JTokenType.Object)
{
var i = JsonParserHelper.GetTokenOfEntry((JObject)e);
if (!contextEntryKeys.Contains(i))
{
anyNewEntry = true;
break;
}
}
}
}
}
}
}
return anyNewEntry;
}
/// <summary>
/// Builds the uri for purpose of probing any remaining entries satisfying the request of service context
/// use the last entry's token in the feed as the marker of skiptoken;
/// and reduce the $top count if top was in context request URI.
/// </summary>
/// <param name="context">The service context object</param>
/// <returns>Uri object if a meaningful prober can be constructed; null otherwise </returns>
private static Uri ConstructProbeUri(ServiceContext context)
{
Uri result = null;
JObject response = JsonParserHelper.GetResponseObject(context);
if (response != null)
{
JArray entries = JsonParserHelper.GetEntries(response);
if (entries != null)
{
JObject lastEntry = JsonParserHelper.GetLastEntry(entries);
if (lastEntry != null)
{
string lastToken = JsonParserHelper.GetTokenOfEntry(lastEntry);
string lastTokenOfValues = ResourcePathHelper.GetValuesOfKey(lastToken);
var uri = context.Destination;
ResourcePathHelper pathHelper = new ResourcePathHelper(uri);
// replace top value with the reduced value, if $top was in context request
string topValue = pathHelper.GetQueryValue("$top");
if (!string.IsNullOrEmpty(topValue))
{
pathHelper.RemoveQueryOption("$top");
int entriesGot = entries.Count;
int entriesToGet;
if (Int32.TryParse(topValue, out entriesToGet) && entriesToGet > entriesGot)
{
int entriesLeft = entriesToGet - entriesGot;
pathHelper.AddQueryOption("$top", entriesLeft.ToString(CultureInfo.InvariantCulture));
}
}
// set up new skiptoken query
pathHelper.RemoveQueryOption("$skiptoken");
pathHelper.AddQueryOption("$skiptoken", lastTokenOfValues);
result = new Uri(pathHelper.Product);
}
}
}
return result;
}
/// <summary>
/// Checks whether __next name-value pair is included in the (json) response payload
/// </summary>
/// <param name="context">The service context object</param>
/// <returns>True if it is found in the response; false otherwise</returns>
private static bool IsNextLinkPresent(ServiceContext context)
{
bool hasNextLink = false;
JObject feedV2 = JsonParserHelper.GetResponseObject(context);
if (feedV2 != null && feedV2.Count == 1)
{
var d = (JProperty)feedV2.First;
if (d.Name.Equals("d", StringComparison.Ordinal))
{
var sub = d.Value;
if (sub.Type == JTokenType.Object)
{
// looking for property of name-value pair of "__next:..."
JObject resultObject = (JObject)sub;
var nextLinks = from p in resultObject.Children<JProperty>()
where p.Name.Equals("__next", StringComparison.Ordinal)
select p;
hasNextLink = nextLinks.Any();
}
}
}
return hasNextLink;
}
}
}
| |
//
// OracleParameterCollection.cs
//
// Part of the Mono class libraries at
// mcs/class/System.Data.OracleClient/System.Data.OracleClient
//
// Assembly: System.Data.OracleClient.dll
// Namespace: System.Data.OracleClient
//
// Authors:
// Tim Coleman <tim@timcoleman.com>
//
// Copyright (C) Tim Coleman , 2003
//
// Licensed under the MIT/X11 License.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient.Oci;
using System.Drawing.Design;
using System.Reflection;
namespace System.Data.OracleClient {
[ListBindable (false)]
[Editor ("Microsoft.VSDesigner.Data.Oracle.Design.DBParametersEditor, " + Consts.AssemblyMicrosoft_VSDesigner, typeof(UITypeEditor))]
public sealed class OracleParameterCollection : MarshalByRefObject, IDataParameterCollection, IList, ICollection, IEnumerable
{
#region Fields
OracleCommand command;
ArrayList list;
#endregion // Fields
#region Constructors
internal OracleParameterCollection (OracleCommand command)
: this ()
{
this.command = command;
}
public OracleParameterCollection ()
{
list = new ArrayList ();
}
#endregion // Constructors
#region Properties
public int Count {
get { return list.Count; }
}
public bool IsFixedSize {
get { return false; }
}
public bool IsReadOnly {
get { return false; }
}
public bool IsSynchronized {
get { return false; }
}
public OracleParameter this [string parameterName] {
get {
foreach (OracleParameter p in list)
if (p.ParameterName.Equals (parameterName))
return p;
throw new IndexOutOfRangeException ("The specified name does not exist: " + parameterName);
}
set {
if (!Contains (parameterName))
throw new IndexOutOfRangeException ("The specified name does not exist: " + parameterName);
this [IndexOf (parameterName)] = value;
}
}
object IList.this [int index] {
get { return (OracleParameter) this [index]; }
set { this [index] = (OracleParameter) value; }
}
bool IList.IsFixedSize {
get { return IsFixedSize; }
}
bool IList.IsReadOnly {
get { return IsReadOnly; }
}
bool ICollection.IsSynchronized {
get { return IsSynchronized; }
}
object ICollection.SyncRoot {
get { return SyncRoot; }
}
public OracleParameter this [int index] {
get { return (OracleParameter) list [index]; }
set { list [index] = value; }
}
object IDataParameterCollection.this [string parameterName] {
get { return this [parameterName]; }
set {
if (!(value is OracleParameter))
throw new InvalidCastException ("The parameter was not an OracleParameter.");
this [parameterName] = (OracleParameter) value;
}
}
public object SyncRoot {
get { return this; }
}
#endregion // Properties
#region Methods
public int Add (object value)
{
if (!(value is OracleParameter))
throw new InvalidCastException ("The parameter was not an OracleParameter.");
Add ((OracleParameter) value);
return IndexOf (value);
}
public OracleParameter Add (OracleParameter value)
{
if (value.Container != null)
throw new ArgumentException ("The OracleParameter specified in the value parameter is already added to this or another OracleParameterCollection.");
value.Container = this;
list.Add (value);
return value;
}
public OracleParameter Add (string parameterName, object value)
{
return Add (new OracleParameter (parameterName, value));
}
public OracleParameter Add (string parameterName, OracleType dataType)
{
return Add (new OracleParameter (parameterName, dataType));
}
public OracleParameter Add (string parameterName, OracleType dataType, int size)
{
return Add (new OracleParameter (parameterName, dataType, size));
}
public OracleParameter Add (string parameterName, OracleType dataType, int size, string srcColumn)
{
return Add (new OracleParameter (parameterName, dataType, size, srcColumn));
}
public void Clear ()
{
list.Clear ();
}
public bool Contains (object value)
{
if (!(value is OracleParameter))
throw new InvalidCastException ("The parameter was not an OracleParameter.");
return Contains (((OracleParameter) value).ParameterName);
}
public bool Contains (string parameterName)
{
foreach (OracleParameter p in list)
if (p.ParameterName.Equals (parameterName))
return true;
return false;
}
public void CopyTo (Array array, int index)
{
list.CopyTo (array, index);
}
public IEnumerator GetEnumerator ()
{
return list.GetEnumerator ();
}
public int IndexOf (object value)
{
if (!(value is OracleParameter))
throw new InvalidCastException ("The parameter was not an OracleParameter.");
return IndexOf (((OracleParameter) value).ParameterName);
}
public int IndexOf (string parameterName)
{
for (int i = 0; i < Count; i += 1)
if (this [i].ParameterName.Equals (parameterName))
return i;
return -1;
}
public void Insert (int index, object value)
{
if (!(value is OracleParameter))
throw new InvalidCastException ("The parameter was not an OracleParameter.");
list.Insert (index, value);
}
public void Remove (object value)
{
if (!(value is OracleParameter))
throw new InvalidCastException ("The parameter was not an OracleParameter.");
list.Remove (value);
}
public void RemoveAt (int index)
{
list.RemoveAt (index);
}
public void RemoveAt (string parameterName)
{
list.RemoveAt (IndexOf (parameterName));
}
#endregion // 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.Linq;
using System.Reactive.Disposables;
using System.Runtime.Remoting.Messaging;
using Microsoft.Its.Recipes;
namespace Microsoft.Its.Domain
{
/// <summary>
/// Used to scope a unit of work and share state (the unit of work's subject) across a number of participants.
/// </summary>
/// <typeparam name="T">The type of the subject of the unit of work.</typeparam>
public sealed class UnitOfWork<T> : IDisposable where T : class
{
private static readonly string callContextPrefix = typeof (UnitOfWork<>).Assembly.GetName().Name + ".UnitOfWork:" + typeof (T);
private readonly bool isOutermost;
private bool canCommit;
private readonly UnitOfWork<T> outer;
private bool rejected;
private bool disposed;
private readonly Dictionary<Type, object> resources;
private readonly CompositeDisposable disposables;
private Exception exception;
private readonly RejectUnitOfWork reject = Reject;
private readonly CommitUnitOfWork commit = Commit;
/// <summary>
/// Occurs when a unit of work is committed.
/// </summary>
public static event EventHandler<T> Committed;
/// <summary>
/// Occurs when a unit of work is rejected.
/// </summary>
public static event EventHandler<T> Rejected;
/// <summary>
/// Initializes the <see cref="UnitOfWork{T}"/> class.
/// </summary>
static UnitOfWork()
{
if (Create == null)
{
ConfigureDefault();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork{T}" /> class.
/// </summary>
public UnitOfWork(params object[] resources)
{
outer = GetFromContext();
Action mergeResources = () =>
{
if (resources != null && resources.Length > 0)
{
resources.ForEach(r => AddResource(r));
}
};
if (outer == null)
{
isOutermost = true;
outer = this;
this.resources = new Dictionary<Type, object>();
disposables = new CompositeDisposable();
mergeResources();
Create(this, subject => subject.IfNotNull()
.ThenDo(s => AddResource(subject)));
SetInContext(this);
}
else
{
this.resources = outer.resources;
disposables = outer.disposables;
mergeResources();
}
}
public UnitOfWork(Func<T> create,
Action<T> reject = null,
Action<T> commit = null) : this()
{
if (isOutermost)
{
AddResource(create());
if (commit != null)
{
this.commit = work => commit(work.Resource<T>());
}
if (reject != null)
{
this.reject = work => reject(work.Resource<T>());
}
}
}
/// <summary>
/// Gets the subject of the current unit of work.
/// </summary>
public T Subject
{
get
{
return Resource<T>();
}
}
/// <summary>
/// Reports an exception due to which the unit of work must be rejected.
/// </summary>
/// <param name="exception">The exception.</param>
public void RejectDueTo(Exception exception)
{
if (exception == null)
{
throw new ArgumentNullException("exception");
}
rejected = true;
Exception = exception;
}
/// <summary>
/// Adds a resource to the unit of work which will be accessible to nested units of work and will be disposed when the unit of work is disposed.
/// </summary>
/// <typeparam name="TResource">The type of the resource.</typeparam>
/// <param name="resource">The resource.</param>
/// <param name="dispose">if set to <c>true</c> dipose the resource when the unit of work is completed; otherwise, don't dispose it.</param>
/// <returns>
/// The same unit of work.
/// </returns>
/// <exception cref="System.ArgumentNullException">resource</exception>
/// <exception cref="System.InvalidOperationException">Resources cannot be added to a disposed UnitOfWork.</exception>
public UnitOfWork<T> AddResource<TResource>(TResource resource, bool dispose = true)
{
return AddResource(typeof(TResource), resource, dispose);
}
internal UnitOfWork<T> AddResource(Type resourceType, object resource, bool dispose)
{
if (resource == null)
{
throw new ArgumentNullException("resource");
}
if (disposed)
{
throw new InvalidOperationException("Resources cannot be added to a disposed UnitOfWork.");
}
resources.Add(resourceType, resource);
if (dispose)
{
resource.IfTypeIs<IDisposable>()
.ThenDo(d => disposables.Add(d));
}
return this;
}
/// <summary>
/// Gets the exception, if any, that caused the unit of work to be rejected.
/// </summary>
public Exception Exception
{
get
{
return outer.exception;
}
private set
{
outer.exception = value;
}
}
/// <summary>
/// Gets a resource of the specified type, if availble, or null.
/// </summary>
/// <typeparam name="TResource">The type of the resource.</typeparam>
/// <returns></returns>
public TResource Resource<TResource>() where TResource : class
{
object resource;
if (resources.TryGetValue(typeof (TResource), out resource))
{
return (TResource) resource;
}
return null;
}
/// <summary>
/// Gets or sets a delegate used to instantate the subject and add resources when a new unit of work is started.
/// </summary>
public static CreateUnitOfWork Create { get; set; }
/// <summary>
/// Gets or sets a delegate used to commit a unit of work.
/// </summary>
public static CommitUnitOfWork Commit { get; set; }
/// <summary>
/// Gets or sets a delegate used to reject a unit of work.
/// </summary>
public static RejectUnitOfWork Reject { get; set; }
/// <summary>
/// Gets the ambient unit of work in progress, if any, in the current context.
/// </summary>
public static UnitOfWork<T> Current
{
get
{
return CallContext.LogicalGetData(callContextPrefix) as UnitOfWork<T>;
}
}
/// <summary>
/// Completes the unit of work.
/// </summary>
/// <remarks>
/// By default, if the subject of the unit of work implements <see cref="IDisposable" />, then it will disposed when the root unit of work is disposed.
/// </remarks>
public void Dispose()
{
var subject = Subject;
if (!canCommit && subject != null)
{
RejectAll();
}
if (isOutermost)
{
if (!rejected && subject != null)
{
try
{
commit(this);
// check again that Commit did not fail in a way that requires rejection
if (!rejected)
{
var handler = Committed;
if (handler != null)
{
handler(this, subject);
}
}
else
{
RejectAll();
}
}
catch (Exception ex)
{
RejectDueTo(ex);
RejectAll();
}
}
SetInContext(null);
disposables.Dispose();
resources.Clear();
}
disposed = true;
}
private void RejectAll()
{
if (isOutermost)
{
rejected = true;
reject(this);
var handler = Rejected;
if (handler != null)
{
handler(this, Subject);
}
}
else
{
outer.RejectAll();
}
}
private UnitOfWork<T> GetFromContext()
{
return CallContext.LogicalGetData(callContextPrefix) as UnitOfWork<T>;
}
private void SetInContext(UnitOfWork<T> context)
{
CallContext.LogicalSetData(callContextPrefix, context);
}
/// <summary>
/// Votes that the unit of work should be committed.
/// </summary>
/// <remarks>
/// All participants in the unit of work must vote commit for it to actually be committed.
/// </remarks>
public void VoteCommit()
{
canCommit = true;
}
/// <summary>
/// Sets the unit of work for type <typeparamref name="T" /> to its default behavior.
/// </summary>
public static void ConfigureDefault()
{
Create = (_, __) => { };
Action<UnitOfWork<T>> dispose = work => work.disposables.Dispose();
Commit = work => dispose(work);
Reject = work => dispose(work);
}
public delegate void CreateUnitOfWork(UnitOfWork<T> unitOfWork, Action<T> setSubject);
public delegate void CommitUnitOfWork(UnitOfWork<T> unitOfWork);
public delegate void RejectUnitOfWork(UnitOfWork<T> unitOfWork);
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.Time;
namespace NLog.Config
{
/// <summary>
/// Loads NLog configuration from <see cref="ILoggingConfigurationElement"/>
/// </summary>
public abstract class LoggingConfigurationParser : LoggingConfiguration
{
private ConfigurationItemFactory _configurationItemFactory;
/// <summary>
/// Constructor
/// </summary>
/// <param name="logFactory"></param>
protected LoggingConfigurationParser(LogFactory logFactory)
: base(logFactory)
{
}
/// <summary>
/// Loads NLog configuration from provided config section
/// </summary>
/// <param name="nlogConfig"></param>
/// <param name="basePath"></param>
protected void LoadConfig(ILoggingConfigurationElement nlogConfig, string basePath)
{
InternalLogger.Trace("ParseNLogConfig");
nlogConfig.AssertName("nlog");
SetNLogElementSettings(nlogConfig);
var children = nlogConfig.Children.ToList();
//first load the extensions, as the can be used in other elements (targets etc)
var extensionsChilds = children.Where(child => child.MatchesName("extensions")).ToList();
foreach (var extensionsChild in extensionsChilds)
{
ParseExtensionsElement(extensionsChild, basePath);
}
var rulesList = new List<ILoggingConfigurationElement>();
//parse all other direct elements
foreach (var child in children)
{
if (child.MatchesName("rules"))
{
//postpone parsing <rules> to the end
rulesList.Add(child);
}
else if (child.MatchesName("extensions"))
{
//already parsed
}
else if (!ParseNLogSection(child))
{
InternalLogger.Warn("Skipping unknown 'NLog' child node: {0}", child.Name);
}
}
foreach (var ruleChild in rulesList)
{
ParseRulesElement(ruleChild, LoggingRules);
}
}
private void SetNLogElementSettings(ILoggingConfigurationElement nlogConfig)
{
var sortedList = CreateUniqueSortedListFromConfig(nlogConfig);
bool? parseMessageTemplates = null;
bool internalLoggerEnabled = false;
foreach (var configItem in sortedList)
{
switch (configItem.Key.ToUpperInvariant())
{
case "THROWEXCEPTIONS":
LogFactory.ThrowExceptions = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.ThrowExceptions);
break;
case "THROWCONFIGEXCEPTIONS":
LogFactory.ThrowConfigExceptions = ParseNullableBooleanValue(configItem.Key, configItem.Value, false);
break;
case "INTERNALLOGLEVEL":
InternalLogger.LogLevel = ParseLogLevelSafe(configItem.Key, configItem.Value, InternalLogger.LogLevel);
internalLoggerEnabled = InternalLogger.LogLevel != LogLevel.Off;
break;
case "USEINVARIANTCULTURE":
if (ParseBooleanValue(configItem.Key, configItem.Value, false))
DefaultCultureInfo = CultureInfo.InvariantCulture;
break;
#pragma warning disable 618
case "EXCEPTIONLOGGINGOLDSTYLE":
ExceptionLoggingOldStyle = ParseBooleanValue(configItem.Key, configItem.Value, ExceptionLoggingOldStyle);
break;
#pragma warning restore 618
case "KEEPVARIABLESONRELOAD":
LogFactory.KeepVariablesOnReload = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.KeepVariablesOnReload);
break;
case "INTERNALLOGTOCONSOLE":
InternalLogger.LogToConsole = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsole);
break;
case "INTERNALLOGTOCONSOLEERROR":
InternalLogger.LogToConsoleError = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsoleError);
break;
case "INTERNALLOGFILE":
var internalLogFile = configItem.Value?.Trim();
if (!string.IsNullOrEmpty(internalLogFile))
{
internalLogFile = ExpandFilePathVariables(internalLogFile);
InternalLogger.LogFile = internalLogFile;
}
break;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
case "INTERNALLOGTOTRACE":
InternalLogger.LogToTrace = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToTrace);
break;
#endif
case "INTERNALLOGINCLUDETIMESTAMP":
InternalLogger.IncludeTimestamp = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.IncludeTimestamp);
break;
case "GLOBALTHRESHOLD":
LogFactory.GlobalThreshold = ParseLogLevelSafe(configItem.Key, configItem.Value, LogFactory.GlobalThreshold);
break; // expanding variables not possible here, they are created later
case "PARSEMESSAGETEMPLATES":
parseMessageTemplates = ParseNullableBooleanValue(configItem.Key, configItem.Value, true);
break;
case "AUTOSHUTDOWN":
LogFactory.AutoShutdown = ParseBooleanValue(configItem.Key, configItem.Value, true);
break;
case "AUTORELOAD":
break; // Ignore here, used by other logic
default:
InternalLogger.Debug("Skipping unknown 'NLog' property {0}={1}", configItem.Key, configItem.Value);
break;
}
}
if (!internalLoggerEnabled && !InternalLogger.HasActiveLoggers())
{
InternalLogger.LogLevel = LogLevel.Off; // Reduce overhead of the InternalLogger when not configured
}
_configurationItemFactory = ConfigurationItemFactory.Default;
_configurationItemFactory.ParseMessageTemplates = parseMessageTemplates;
}
/// <summary>
/// Builds list with unique keys, using last value of duplicates. High priority keys placed first.
/// </summary>
/// <param name="nlogConfig"></param>
/// <returns></returns>
private static IList<KeyValuePair<string, string>> CreateUniqueSortedListFromConfig(ILoggingConfigurationElement nlogConfig)
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var configItem in nlogConfig.Values)
{
if (!string.IsNullOrEmpty(configItem.Key))
{
string key = configItem.Key.Trim();
if (dict.ContainsKey(key))
{
InternalLogger.Debug("Skipping duplicate value for 'NLog' property {0}. Value={1}", configItem.Key, dict[key]);
}
dict[key] = configItem.Value;
}
}
var sortedList = new List<KeyValuePair<string, string>>(dict.Count);
AddHighPrioritySetting("ThrowExceptions");
AddHighPrioritySetting("ThrowConfigExceptions");
AddHighPrioritySetting("InternalLogLevel");
AddHighPrioritySetting("InternalLogFile");
AddHighPrioritySetting("InternalLogToConsole");
foreach (var configItem in dict)
{
sortedList.Add(configItem);
}
return sortedList;
void AddHighPrioritySetting(string settingName)
{
if (dict.ContainsKey(settingName))
{
sortedList.Add(new KeyValuePair<string, string>(settingName, dict[settingName]));
dict.Remove(settingName);
}
}
}
private string ExpandFilePathVariables(string internalLogFile)
{
try
{
#if !SILVERLIGHT
if (ContainsSubStringIgnoreCase(internalLogFile, "${currentdir}", out string currentDirToken))
internalLogFile = internalLogFile.Replace(currentDirToken, System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar.ToString());
if (ContainsSubStringIgnoreCase(internalLogFile, "${basedir}", out string baseDirToken))
internalLogFile = internalLogFile.Replace(baseDirToken, LogFactory.CurrentAppEnvironment.AppDomainBaseDirectory + System.IO.Path.DirectorySeparatorChar.ToString());
if (ContainsSubStringIgnoreCase(internalLogFile, "${tempdir}", out string tempDirToken))
internalLogFile = internalLogFile.Replace(tempDirToken, LogFactory.CurrentAppEnvironment.UserTempFilePath + System.IO.Path.DirectorySeparatorChar.ToString());
#if !NETSTANDARD1_3
if (ContainsSubStringIgnoreCase(internalLogFile, "${processdir}", out string processDirToken))
internalLogFile = internalLogFile.Replace(processDirToken, System.IO.Path.GetDirectoryName(LogFactory.CurrentAppEnvironment.CurrentProcessFilePath) + System.IO.Path.DirectorySeparatorChar.ToString());
#endif
if (internalLogFile.IndexOf('%') >= 0)
internalLogFile = Environment.ExpandEnvironmentVariables(internalLogFile);
#endif
return internalLogFile;
}
catch
{
return internalLogFile;
}
}
private static bool ContainsSubStringIgnoreCase(string haystack, string needle, out string result)
{
int needlePos = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
result = needlePos >= 0 ? haystack.Substring(needlePos, needle.Length) : null;
return result != null;
}
/// <summary>
/// Parse loglevel, but don't throw if exception throwing is disabled
/// </summary>
/// <param name="attributeName">Name of attribute for logging.</param>
/// <param name="attributeValue">Value of parse.</param>
/// <param name="default">Used if there is an exception</param>
/// <returns></returns>
private LogLevel ParseLogLevelSafe(string attributeName, string attributeValue, LogLevel @default)
{
try
{
var internalLogLevel = LogLevel.FromString(attributeValue?.Trim());
return internalLogLevel;
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
const string message = "attribute '{0}': '{1}' isn't valid LogLevel. {2} will be used.";
var configException =
new NLogConfigurationException(exception, message, attributeName, attributeValue, @default);
if (MustThrowConfigException(configException))
throw configException;
return @default;
}
}
/// <summary>
/// Parses a single config section within the NLog-config
/// </summary>
/// <param name="configSection"></param>
/// <returns>Section was recognized</returns>
protected virtual bool ParseNLogSection(ILoggingConfigurationElement configSection)
{
switch (configSection.Name?.Trim().ToUpperInvariant())
{
case "TIME":
ParseTimeElement(configSection);
return true;
case "VARIABLE":
ParseVariableElement(configSection);
return true;
case "VARIABLES":
ParseVariablesElement(configSection);
return true;
case "APPENDERS":
case "TARGETS":
ParseTargetsElement(configSection);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom",
Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(ILoggingConfigurationElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
foreach (var childItem in extensionsElement.Children)
{
string prefix = null;
string type = null;
string assemblyFile = null;
string assemblyName = null;
foreach (var childProperty in childItem.Values)
{
if (MatchesName(childProperty.Key, "prefix"))
{
prefix = childProperty.Value + ".";
}
else if (MatchesName(childProperty.Key, "type"))
{
type = childProperty.Value;
}
else if (MatchesName(childProperty.Key, "assemblyFile"))
{
assemblyFile = childProperty.Value;
}
else if (MatchesName(childProperty.Key, "assembly"))
{
assemblyName = childProperty.Value;
}
else
{
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, childItem.Name, extensionsElement.Name);
}
}
if (!StringHelpers.IsNullOrWhiteSpace(type))
{
RegisterExtension(type, prefix);
}
#if !NETSTANDARD1_3
if (!StringHelpers.IsNullOrWhiteSpace(assemblyFile))
{
ParseExtensionWithAssemblyFile(baseDirectory, assemblyFile, prefix);
continue;
}
#endif
if (!StringHelpers.IsNullOrWhiteSpace(assemblyName))
{
ParseExtensionWithAssembly(assemblyName, prefix);
}
}
}
private void RegisterExtension(string type, string itemNamePrefix)
{
try
{
_configurationItemFactory.RegisterType(Type.GetType(type, true), itemNamePrefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + type, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
#if !NETSTANDARD1_3
private void ParseExtensionWithAssemblyFile(string baseDirectory, string assemblyFile, string prefix)
{
try
{
Assembly asm = AssemblyHelpers.LoadFromPath(assemblyFile, baseDirectory);
_configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
#endif
private void ParseExtensionWithAssembly(string assemblyName, string prefix)
{
try
{
Assembly asm = AssemblyHelpers.LoadFromName(assemblyName);
_configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
private void ParseVariableElement(ILoggingConfigurationElement variableElement)
{
string variableName = null;
string variableValue = null;
foreach (var childProperty in variableElement.Values)
{
if (MatchesName(childProperty.Key, "name"))
variableName = childProperty.Value;
else if (MatchesName(childProperty.Key, "value"))
variableValue = childProperty.Value;
else
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, variableElement.Name, "variables");
}
if (!AssertNonEmptyValue(variableName, "name", variableElement.Name, "variables"))
return;
if (!AssertNotNullValue(variableValue, "value", variableElement.Name, "variables"))
return;
string value = ExpandSimpleVariables(variableValue);
Variables[variableName] = value;
}
private void ParseVariablesElement(ILoggingConfigurationElement variableElement)
{
variableElement.AssertName("variables");
foreach (var childItem in variableElement.Children)
{
ParseVariableElement(childItem);
}
}
private void ParseTimeElement(ILoggingConfigurationElement timeElement)
{
timeElement.AssertName("time");
string timeSourceType = null;
foreach (var childProperty in timeElement.Values)
{
if (MatchesName(childProperty.Key, "type"))
timeSourceType = childProperty.Value;
else
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, timeElement.Name, timeElement.Name);
}
if (!AssertNonEmptyValue(timeSourceType, "type", timeElement.Name, string.Empty))
return;
TimeSource newTimeSource = _configurationItemFactory.TimeSources.CreateInstance(timeSourceType);
ConfigureObjectFromAttributes(newTimeSource, timeElement, true);
InternalLogger.Info("Selecting time source {0}", newTimeSource);
TimeSource.Current = newTimeSource;
}
[ContractAnnotation("value:notnull => true")]
private static bool AssertNotNullValue(string value, string propertyName, string elementName, string sectionName)
{
if (value != null)
return true;
return AssertNonEmptyValue(string.Empty, propertyName, elementName, sectionName);
}
[ContractAnnotation("value:null => false")]
private static bool AssertNonEmptyValue(string value, string propertyName, string elementName, string sectionName)
{
if (!StringHelpers.IsNullOrWhiteSpace(value))
return true;
if (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions)
throw new NLogConfigurationException(
$"Expected property {propertyName} on element name: {elementName} in section: {sectionName}");
InternalLogger.Warn("Skipping element name: {0} in section: {1} because property {2} is blank", elementName,
sectionName, propertyName);
return false;
}
/// <summary>
/// Parse {Rules} xml element
/// </summary>
/// <param name="rulesElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseRulesElement(ILoggingConfigurationElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
foreach (var childItem in rulesElement.Children)
{
LoggingRule loggingRule = ParseRuleElement(childItem);
if (loggingRule != null)
{
lock (rulesCollection)
{
rulesCollection.Add(loggingRule);
}
}
}
}
private LogLevel LogLevelFromString(string text)
{
return LogLevel.FromString(ExpandSimpleVariables(text).Trim());
}
/// <summary>
/// Parse {Logger} xml element
/// </summary>
/// <param name="loggerElement"></param>
private LoggingRule ParseRuleElement(ILoggingConfigurationElement loggerElement)
{
string minLevel = null;
string maxLevel = null;
string enableLevels = null;
string ruleName = null;
string namePattern = null;
bool enabled = true;
bool final = false;
string writeTargets = null;
string filterDefaultAction = null;
foreach (var childProperty in loggerElement.Values)
{
switch (childProperty.Key?.Trim().ToUpperInvariant())
{
case "NAME":
if (loggerElement.MatchesName("logger"))
namePattern = childProperty.Value; // Legacy Style
else
ruleName = childProperty.Value;
break;
case "RULENAME":
ruleName = childProperty.Value; // Legacy Style
break;
case "LOGGER":
namePattern = childProperty.Value;
break;
case "ENABLED":
enabled = ParseBooleanValue(childProperty.Key, childProperty.Value, true);
break;
case "APPENDTO":
writeTargets = childProperty.Value;
break;
case "WRITETO":
writeTargets = childProperty.Value;
break;
case "FINAL":
final = ParseBooleanValue(childProperty.Key, childProperty.Value, false);
break;
case "LEVEL":
enableLevels = childProperty.Value;
break;
case "LEVELS":
enableLevels = StringHelpers.IsNullOrWhiteSpace(childProperty.Value) ? "," : childProperty.Value;
break;
case "MINLEVEL":
minLevel = childProperty.Value;
break;
case "MAXLEVEL":
maxLevel = childProperty.Value;
break;
case "FILTERDEFAULTACTION":
filterDefaultAction = childProperty.Value;
break;
default:
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, loggerElement.Name, "rules");
break;
}
}
if (string.IsNullOrEmpty(ruleName) && string.IsNullOrEmpty(namePattern) &&
string.IsNullOrEmpty(writeTargets) && !final)
{
InternalLogger.Debug("Logging rule without name or filter or targets is ignored");
return null;
}
namePattern = namePattern ?? "*";
if (!enabled)
{
InternalLogger.Debug("Logging rule {0} with filter `{1}` is disabled", ruleName, namePattern);
return null;
}
var rule = new LoggingRule(ruleName)
{
LoggerNamePattern = namePattern,
Final = final,
};
EnableLevelsForRule(rule, enableLevels, minLevel, maxLevel);
ParseLoggingRuleTargets(writeTargets, rule);
ParseLoggingRuleChildren(loggerElement, rule, filterDefaultAction);
return rule;
}
private void EnableLevelsForRule(LoggingRule rule, string enableLevels, string minLevel, string maxLevel)
{
if (enableLevels != null)
{
enableLevels = ExpandSimpleVariables(enableLevels);
if (enableLevels.IndexOf('{') >= 0)
{
SimpleLayout simpleLayout = ParseLevelLayout(enableLevels);
rule.EnableLoggingForLevels(simpleLayout);
}
else
{
if (enableLevels.IndexOf(',') >= 0)
{
IEnumerable<LogLevel> logLevels = ParseLevels(enableLevels);
foreach (var logLevel in logLevels)
rule.EnableLoggingForLevel(logLevel);
}
else
{
rule.EnableLoggingForLevel(LogLevelFromString(enableLevels));
}
}
}
else
{
minLevel = minLevel != null ? ExpandSimpleVariables(minLevel) : minLevel;
maxLevel = maxLevel != null ? ExpandSimpleVariables(maxLevel) : maxLevel;
if (minLevel?.IndexOf('{') >= 0 || maxLevel?.IndexOf('{') >= 0)
{
SimpleLayout minLevelLayout = ParseLevelLayout(minLevel);
SimpleLayout maxLevelLayout = ParseLevelLayout(maxLevel);
rule.EnableLoggingForRange(minLevelLayout, maxLevelLayout);
}
else
{
LogLevel minLogLevel = minLevel != null ? LogLevelFromString(minLevel) : LogLevel.MinLevel;
LogLevel maxLogLevel = maxLevel != null ? LogLevelFromString(maxLevel) : LogLevel.MaxLevel;
rule.SetLoggingLevels(minLogLevel, maxLogLevel);
}
}
}
private SimpleLayout ParseLevelLayout(string levelLayout)
{
SimpleLayout simpleLayout = !StringHelpers.IsNullOrWhiteSpace(levelLayout) ? new SimpleLayout(levelLayout, _configurationItemFactory) : null;
simpleLayout?.Initialize(this);
return simpleLayout;
}
private IEnumerable<LogLevel> ParseLevels(string enableLevels)
{
string[] tokens = enableLevels.SplitAndTrimTokens(',');
var logLevels = tokens.Select(LogLevelFromString);
return logLevels;
}
private void ParseLoggingRuleTargets(string writeTargets, LoggingRule rule)
{
if (string.IsNullOrEmpty(writeTargets))
return;
foreach (string targetName in writeTargets.SplitAndTrimTokens(','))
{
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
var configException =
new NLogConfigurationException($"Target '{targetName}' not found for logging rule: {(string.IsNullOrEmpty(rule.RuleName) ? rule.LoggerNamePattern : rule.RuleName)}.");
if (MustThrowConfigException(configException))
throw configException;
}
}
}
private void ParseLoggingRuleChildren(ILoggingConfigurationElement loggerElement, LoggingRule rule, string filterDefaultAction = null)
{
foreach (var child in loggerElement.Children)
{
LoggingRule childRule = null;
if (child.MatchesName("filters"))
{
ParseFilters(rule, child, filterDefaultAction);
}
else if (child.MatchesName("logger") && loggerElement.MatchesName("logger"))
{
childRule = ParseRuleElement(child);
}
else if (child.MatchesName("rule") && loggerElement.MatchesName("rule"))
{
childRule = ParseRuleElement(child);
}
else
{
InternalLogger.Debug("Skipping unknown child {0} for element {1} in section {2}", child.Name,
loggerElement.Name, "rules");
}
if (childRule != null)
{
lock (rule.ChildRules)
{
rule.ChildRules.Add(childRule);
}
}
}
}
private void ParseFilters(LoggingRule rule, ILoggingConfigurationElement filtersElement, string filterDefaultAction = null)
{
filtersElement.AssertName("filters");
filterDefaultAction = filtersElement.GetOptionalValue("defaultAction", null) ?? filtersElement.GetOptionalValue("filterDefaultAction", null) ?? filterDefaultAction;
if (filterDefaultAction != null)
{
PropertyHelper.SetPropertyFromString(rule, nameof(rule.DefaultFilterResult), filterDefaultAction,
_configurationItemFactory);
}
foreach (var filterElement in filtersElement.Children)
{
var filterType = filterElement.GetOptionalValue("type", null) ?? filterElement.Name;
Filter filter = _configurationItemFactory.Filters.CreateInstance(filterType);
ConfigureObjectFromAttributes(filter, filterElement, true);
rule.Filters.Add(filter);
}
}
private void ParseTargetsElement(ILoggingConfigurationElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
var asyncItem = targetsElement.Values.FirstOrDefault(configItem => MatchesName(configItem.Key, "async"));
bool asyncWrap = !string.IsNullOrEmpty(asyncItem.Value) &&
ParseBooleanValue(asyncItem.Key, asyncItem.Value, false);
ILoggingConfigurationElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters =
new Dictionary<string, ILoggingConfigurationElement>(StringComparer.OrdinalIgnoreCase);
foreach (var targetElement in targetsElement.Children)
{
string targetTypeName = targetElement.GetConfigItemTypeAttribute();
string targetValueName = targetElement.GetOptionalValue("name", null);
Target newTarget = null;
if (!string.IsNullOrEmpty(targetValueName))
targetValueName = $"{targetElement.Name}(Name={targetValueName})";
else
targetValueName = targetElement.Name;
switch (targetElement.Name?.Trim().ToUpperInvariant())
{
case "DEFAULT-WRAPPER":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
defaultWrapperElement = targetElement;
}
break;
case "DEFAULT-TARGET-PARAMETERS":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
ParseDefaultTargetParameters(targetElement, targetTypeName, typeNameToDefaultTargetParameters);
}
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
ParseTargetElement(newTarget, targetElement, typeNameToDefaultTargetParameters);
}
}
break;
default:
InternalLogger.Debug("Skipping unknown element {0} in section {1}", targetValueName,
targetsElement.Name);
break;
}
if (newTarget != null)
{
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}(Name={1})", newTarget.GetType().Name, newTarget.Name);
AddTarget(newTarget.Name, newTarget);
}
}
}
private Target CreateTargetType(string targetTypeName)
{
Target newTarget = null;
try
{
newTarget = _configurationItemFactory.Targets.CreateInstance(targetTypeName);
if (newTarget == null)
throw new NLogConfigurationException($"Factory returned null for target type: {targetTypeName}");
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
var configException = new NLogConfigurationException($"Failed to create target type: {targetTypeName}", ex);
if (MustThrowConfigException(configException))
throw configException;
}
return newTarget;
}
void ParseDefaultTargetParameters(ILoggingConfigurationElement defaultTargetElement, string targetType,
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters)
{
typeNameToDefaultTargetParameters[targetType.Trim()] = defaultTargetElement;
}
private void ParseTargetElement(Target target, ILoggingConfigurationElement targetElement,
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters = null)
{
string targetTypeName = targetElement.GetConfigItemTypeAttribute("targets");
ILoggingConfigurationElement defaults;
if (typeNameToDefaultTargetParameters != null &&
typeNameToDefaultTargetParameters.TryGetValue(targetTypeName, out defaults))
{
ParseTargetElement(target, defaults, null);
}
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
ConfigureObjectFromAttributes(target, targetElement, true);
foreach (var childElement in targetElement.Children)
{
string name = childElement.Name;
if (compound != null &&
ParseCompoundTarget(typeNameToDefaultTargetParameters, name, childElement, compound, null))
{
continue;
}
if (wrapper != null &&
ParseTargetWrapper(typeNameToDefaultTargetParameters, name, childElement, wrapper))
{
continue;
}
SetPropertyFromElement(target, childElement, targetElement);
}
}
private bool ParseTargetWrapper(
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters, string name,
ILoggingConfigurationElement childElement,
WrapperTargetBase wrapper)
{
if (IsTargetRefElement(name))
{
var targetName = childElement.GetRequiredValue("name", GetName(wrapper));
Target newTarget = FindTargetByName(targetName);
if (newTarget == null)
{
var configException = new NLogConfigurationException($"Referenced target '{targetName}' not found.");
if (MustThrowConfigException(configException))
throw configException;
}
wrapper.WrappedTarget = newTarget;
return true;
}
if (IsTargetElement(name))
{
string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(wrapper));
Target newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
var configException = new NLogConfigurationException($"Failed to assign wrapped target {targetTypeName}, because target {wrapper.Name} already has one.");
if (MustThrowConfigException(configException))
throw configException;
}
}
wrapper.WrappedTarget = newTarget;
return true;
}
return false;
}
private bool ParseCompoundTarget(
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters, string name,
ILoggingConfigurationElement childElement,
CompoundTargetBase compound, string targetName)
{
if (MatchesName(name, "targets") || MatchesName(name, "appenders"))
{
foreach (var child in childElement.Children)
{
ParseCompoundTarget(typeNameToDefaultTargetParameters, child.Name, child, compound, null);
}
return true;
}
if (IsTargetRefElement(name))
{
targetName = childElement.GetRequiredValue("name", GetName(compound));
Target newTarget = FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
return true;
}
if (IsTargetElement(name))
{
string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(compound));
Target newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
if (targetName != null)
newTarget.Name = targetName;
ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, ILoggingConfigurationElement element, bool ignoreType)
{
foreach (var kvp in element.Values)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && MatchesName(childName, "type"))
{
continue;
}
try
{
PropertyHelper.SetPropertyFromString(targetObject, childName, ExpandSimpleVariables(childValue),
_configurationItemFactory);
}
catch (NLogConfigurationException ex)
{
if (MustThrowConfigException(ex))
throw;
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
var configException = new NLogConfigurationException(ex, $"Error when setting value '{childValue}' for property '{childName}' on element '{element}'");
if (MustThrowConfigException(configException))
throw;
}
}
}
private void SetPropertyFromElement(object o, ILoggingConfigurationElement childElement, ILoggingConfigurationElement parentElement)
{
if (!PropertyHelper.TryGetPropertyInfo(o, childElement.Name, out var propInfo))
{
InternalLogger.Debug("Skipping unknown element {0} in section {1}. Not matching any property on {2} - {3}", childElement.Name, parentElement.Name, o, o?.GetType());
return;
}
if (AddArrayItemFromElement(o, propInfo, childElement))
{
return;
}
if (SetLayoutFromElement(o, propInfo, childElement))
{
return;
}
if (SetFilterFromElement(o, propInfo, childElement))
{
return;
}
SetItemFromElement(o, propInfo, childElement);
}
private bool AddArrayItemFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
if (string.Equals(propInfo.Name, element.Name, StringComparison.OrdinalIgnoreCase))
{
var children = element.Children.ToList();
if (children.Count > 0)
{
foreach (var child in children)
{
propertyValue.Add(ParseArrayItemFromElement(elementType, child));
}
return true;
}
}
object arrayItem = ParseArrayItemFromElement(elementType, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private object ParseArrayItemFromElement(Type elementType, ILoggingConfigurationElement element)
{
object arrayItem = TryCreateLayoutInstance(element, elementType);
// arrayItem is not a layout
if (arrayItem == null)
arrayItem = FactoryHelper.CreateInstance(elementType);
ConfigureObjectFromAttributes(arrayItem, element, true);
ConfigureObjectFromElement(arrayItem, element);
return arrayItem;
}
private bool SetLayoutFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
var layout = TryCreateLayoutInstance(element, propInfo.PropertyType);
// and is a Layout and 'type' attribute has been specified
if (layout != null)
{
SetItemOnProperty(o, propInfo, element, layout);
return true;
}
return false;
}
private bool SetFilterFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
var type = propInfo.PropertyType;
Filter filter = TryCreateFilterInstance(element, type);
// and is a Filter and 'type' attribute has been specified
if (filter != null)
{
SetItemOnProperty(o, propInfo, element, filter);
return true;
}
return false;
}
private Layout TryCreateLayoutInstance(ILoggingConfigurationElement element, Type type)
{
return TryCreateInstance(element, type, _configurationItemFactory.Layouts);
}
private Filter TryCreateFilterInstance(ILoggingConfigurationElement element, Type type)
{
return TryCreateInstance(element, type, _configurationItemFactory.Filters);
}
private T TryCreateInstance<T>(ILoggingConfigurationElement element, Type type, INamedItemFactory<T, Type> factory)
where T : class
{
// Check if correct type
if (!IsAssignableFrom<T>(type))
return null;
// Check if the 'type' attribute has been specified
string layoutTypeName = element.GetConfigItemTypeAttribute();
if (layoutTypeName == null)
return null;
return factory.CreateInstance(ExpandSimpleVariables(layoutTypeName));
}
private static bool IsAssignableFrom<T>(Type type)
{
return typeof(T).IsAssignableFrom(type);
}
private void SetItemOnProperty(object o, PropertyInfo propInfo, ILoggingConfigurationElement element, object properyValue)
{
ConfigureObjectFromAttributes(properyValue, element, true);
ConfigureObjectFromElement(properyValue, element);
propInfo.SetValue(o, properyValue, null);
}
private void SetItemFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
object item = propInfo.GetValue(o, null);
ConfigureObjectFromAttributes(item, element, true);
ConfigureObjectFromElement(item, element);
}
private void ConfigureObjectFromElement(object targetObject, ILoggingConfigurationElement element)
{
foreach (var child in element.Children)
{
SetPropertyFromElement(targetObject, child, element);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
#if !NET3_5 && !SILVERLIGHT4
if (target is AsyncTaskTarget)
{
InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name);
return target;
}
#endif
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}",
asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
private Target WrapWithDefaultWrapper(Target target, ILoggingConfigurationElement defaultParameters)
{
string wrapperTypeName = defaultParameters.GetConfigItemTypeAttribute("targets");
Target wrapperTargetInstance = CreateTargetType(wrapperTypeName);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
ParseTargetElement(wrapperTargetInstance, defaultParameters);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException(
"Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
#if !NET3_5 && !SILVERLIGHT4
if (target is AsyncTaskTarget && wrapperTargetInstance is AsyncTargetWrapper && ReferenceEquals(wrapperTargetInstance, wtb))
{
InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name);
return target;
}
#endif
wtb.WrappedTarget = target;
wrapperTargetInstance.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name,
wrapperTargetInstance.GetType().Name, target.Name);
return wrapperTargetInstance;
}
/// <summary>
/// Parse boolean
/// </summary>
/// <param name="propertyName">Name of the property for logging.</param>
/// <param name="value">value to parse</param>
/// <param name="defaultValue">Default value to return if the parse failed</param>
/// <returns>Boolean attribute value or default.</returns>
private bool ParseBooleanValue(string propertyName, string value, bool defaultValue)
{
try
{
return Convert.ToBoolean(value?.Trim(), CultureInfo.InvariantCulture);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException = new NLogConfigurationException(exception, $"'{propertyName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used");
if (MustThrowConfigException(configException))
throw configException;
return defaultValue;
}
}
private bool? ParseNullableBooleanValue(string propertyName, string value, bool defaultValue)
{
return StringHelpers.IsNullOrWhiteSpace(value)
? (bool?)null
: ParseBooleanValue(propertyName, value, defaultValue);
}
private bool MustThrowConfigException(NLogConfigurationException configException)
{
if (configException.MustBeRethrown())
return true; // Global LogManager says throw
if (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions)
return true; // Local LogFactory says throw
return false;
}
private static bool MatchesName(string key, string expectedKey)
{
return string.Equals(key?.Trim(), expectedKey, StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
private static string GetName(Target target)
{
return string.IsNullOrEmpty(target.Name) ? target.GetType().Name : target.Name;
}
}
}
| |
#region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Gigya.Common.Contracts.Exceptions;
using Gigya.Microdot.Interfaces.Logging;
using Gigya.Microdot.ServiceDiscovery.Config;
using Gigya.Microdot.SharedLogic.Events;
using Gigya.Microdot.SharedLogic.HttpService;
using Gigya.Microdot.SharedLogic.Monitor;
using Metrics;
namespace Gigya.Microdot.ServiceDiscovery.HostManagement
{
/// <summary>
/// A pool of remote hosts that provides round-robin load balancing and failure management.
/// </summary>
public sealed class RemoteHostPool : IDisposable
{
public ISourceBlock<ServiceReachabilityStatus> ReachabilitySource => ReachabilityBroadcaster;
public bool IsServiceDeploymentDefined => DiscoverySource.IsServiceDeploymentDefined;
private readonly BroadcastBlock<EndPointsResult> _endPointsChanged = new BroadcastBlock<EndPointsResult>(null);
public ISourceBlock<EndPointsResult> EndPointsChanged => _endPointsChanged;
/// <summary>
/// Time of the last attempt to reach the service.
/// </summary>
private DateTime LastEndpointRequest { get; set; }
internal ServiceDiscoveryConfig GetConfig() => GetDiscoveryConfig().Services[DeploymentIdentifier.ServiceName];
internal ReachabilityChecker ReachabilityChecker { get; }
private Func<DiscoveryConfig> GetDiscoveryConfig { get; }
internal ILog Log { get; }
internal DeploymentIdentifier DeploymentIdentifier { get; }
private ulong Counter { get; set; }
private ComponentHealthMonitor Health { get; }
private List<RemoteHost> ReachableHosts { get; set; }
private List<RemoteHost> UnreachableHosts { get; set; }
private EndPointsResult EndPointsResult { get; set; }
private EndPoint[] EndPoints => EndPointsResult?.EndPoints;
private readonly object _lock = new object();
private readonly Random _random = new Random();
private TaskCompletionSource<RemoteHost> FirstAvailableHostCompletionSource { get; set; }
private MetricsContext Metrics { get; }
private IDisposable EndPointsChangedBlockLink { get; }
private BroadcastBlock<ServiceReachabilityStatus> ReachabilityBroadcaster { get; }
private IServiceDiscoverySource DiscoverySource { get; }
/// <summary>
/// Creates a new RemoteHostPool using the specified system name and liveliness checker.
/// </summary>
/// <param name="reachabilityChecker">A delegate that checks if a given host is reachable or not. Used for background checks of unreachable hosts.
/// Should return true if the host is reachable, or false if it is unreachable. It should not throw an exception.</param>
/// <param name="log">An implementation of <see cref="ILog"/> used for logging.</param>
public RemoteHostPool(
DeploymentIdentifier deploymentIdentifier
, IServiceDiscoverySource discovery
, ReachabilityChecker reachabilityChecker
, Func<DiscoveryConfig> getDiscoveryConfig
, ILog log
, HealthMonitor healthMonitor
, MetricsContext metrics
)
{
DiscoverySource = discovery;
DeploymentIdentifier = deploymentIdentifier;
ReachabilityChecker = reachabilityChecker;
GetDiscoveryConfig = getDiscoveryConfig;
Log = log;
ReachabilityBroadcaster = new BroadcastBlock<ServiceReachabilityStatus>(null);
Health = healthMonitor.Get(discovery.Deployment);
Health.SetHealthData(HealthData);
ReachableHosts = new List<RemoteHost>();
UnreachableHosts = new List<RemoteHost>();
EndPointsChangedBlockLink = discovery.EndPointsChanged.LinkTo(new ActionBlock<EndPointsResult>(_ => ReloadEndpoints(_)));
ReloadEndpoints(discovery.Result);
Metrics = metrics;
var metricsContext = Metrics.Context(DiscoverySource.Deployment);
metricsContext.Gauge("ReachableHosts", () => ReachableHosts.Count, Unit.Custom("EndPoints"));
metricsContext.Gauge("UnreachableHosts", () => UnreachableHosts.Count, Unit.Custom("EndPoints"));
}
/// <summary>
/// Loads the specified settings, overwriting existing settings.
/// </summary>
/// <param name="updatedEndPointsResult"></param>
/// this <see cref="RemoteHostPool"/>.
/// <exception cref="ArgumentNullException">Thrown when </exception>
/// <exception cref="EnvironmentException"></exception>
private void ReloadEndpoints(EndPointsResult updatedEndPointsResult)
{
lock (_lock)
{
try
{
var updatedEndPoints = updatedEndPointsResult.EndPoints;
if (updatedEndPoints.Any() == false)
{
Health.SetHealthFunction(() =>
{
var config = GetConfig();
if (IsHealthCheckSuppressed(config))
return HealthCheckResult.Healthy(
$"No endpoints were discovered from source '{config.Source}' but the remote service was not in use for more than {config.SuppressHealthCheckAfterServiceUnused.TotalSeconds} seconds.");
else
return HealthCheckResult.Unhealthy(
$"No endpoints were discovered from source '{config.Source}'.");
});
EndPointsResult = updatedEndPointsResult;
ReachableHosts = new List<RemoteHost>();
UnreachableHosts = new List<RemoteHost>();
}
else
{
if (EndPoints != null)
{
foreach (var removedEndPoint in EndPoints.Except(updatedEndPoints))
{
ReachableHosts.SingleOrDefault(h => h.Equals(removedEndPoint))?.StopMonitoring();
ReachableHosts.RemoveAll(h => h.Equals(removedEndPoint));
UnreachableHosts.RemoveAll(h => h.Equals(removedEndPoint));
}
}
var newHosts = updatedEndPoints
.Except(EndPoints ?? Enumerable.Empty<EndPoint>())
.Select(ep => new RemoteHost(ep.HostName, this, _lock, ep.Port));
ReachableHosts.AddRange(newHosts);
EndPointsResult = updatedEndPointsResult;
Counter = (ulong)_random.Next(0, ReachableHosts.Count);
Health.SetHealthFunction(CheckHealth);
}
_endPointsChanged.Post(EndPointsResult);
}
catch (Exception ex)
{
Log.Warn("Failed to process newly discovered endpoints", exception: ex);
Health.SetHealthFunction(() =>
HealthCheckResult.Unhealthy("Failed to process newly discovered endpoints: " +
HealthMonitor.GetMessages(ex)));
}
}
}
private Dictionary<string, string> HealthData()
{
lock (_lock)
{
return new Dictionary<string, string>
{
{"ReachableHosts", string.Join(",", ReachableHosts.Select(_ => _.HostName))},
{"UnreachableHosts", string.Join(",", UnreachableHosts.Select(_ => _.HostName))}
};
}
}
private bool IsHealthCheckSuppressed(ServiceDiscoveryConfig config)
{
var serviceUnuseTime = DateTime.UtcNow.Subtract(LastEndpointRequest);
//If a service was unused for pre-defined time period, always treat it as healthy.
if (serviceUnuseTime > config.SuppressHealthCheckAfterServiceUnused)
return true;
return false;
}
private HealthCheckResult CheckHealth()
{
var config = GetConfig();
if (IsHealthCheckSuppressed(config))
return HealthCheckResult.Healthy($"Health check suppressed because service was not in use for more than {config.SuppressHealthCheckAfterServiceUnused.TotalSeconds} seconds.");
int reachableCount;
int unreachableCount;
Exception exception;
string[] unreachableHosts;
lock (_lock)
{
reachableCount = ReachableHosts.Count;
unreachableHosts = UnreachableHosts.Select(x => $"{x.HostName}:{x.Port}").ToArray();
unreachableCount = unreachableHosts.Length;
exception = UnreachableHosts.FirstOrDefault()?.LastException;
}
if (reachableCount == 0)
{
return HealthCheckResult.Unhealthy($"All of the {unreachableCount} hosts are unreachable: " +
$"{string.Join(",", unreachableHosts)}. Last exception: {HealthMonitor.GetMessages(exception)}");
}
else
{
if (unreachableCount > 0)
{
return HealthCheckResult.Unhealthy($"The following {unreachableCount} hosts " +
$"(out of {unreachableCount + reachableCount}) are unreachable: {string.Join(",", unreachableHosts)}. " +
$"Last exception: {HealthMonitor.GetMessages(exception)}");
}
else
{
return HealthCheckResult.Healthy($"All {reachableCount} hosts are reachable.");
}
}
}
/// <summary>
/// Retrieves the next reachable <see cref="RemoteHost"/>.
/// </summary>
/// <param name="affinityToken">
/// A string to generate a consistent affinity to a specific host within the set of available hosts.
/// Identical strings will return the same host for a given pool of reachable hosts. A request ID is usually provided.
/// </param>
/// <returns>A reachable <see cref="RemoteHost"/>.</returns>
/// <exception cref="EnvironmentException">Thrown when there is no reachable <see cref="RemoteHost"/> available.</exception>
public IEndPointHandle GetNextHost(string affinityToken = null)
{
LastEndpointRequest = DateTime.UtcNow;
var hostOverride = TracingContext.GetHostOverride(DeploymentIdentifier.ServiceName);
if (hostOverride != null)
return new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Host, hostOverride.Port?? GetConfig().DefaultPort);
lock (_lock)
{
Health.Activate();
if (ReachableHosts.Count == 0)
{
var lastExceptionEndPoint = UnreachableHosts.FirstOrDefault();
// TODO: Exception throwing code should be in this class, not in another.
throw DiscoverySource.AllEndpointsUnreachable(EndPointsResult, lastExceptionEndPoint?.LastException, lastExceptionEndPoint == null ? null : $"{lastExceptionEndPoint.HostName}:{lastExceptionEndPoint.Port}", string.Join(", ", UnreachableHosts));
}
Counter++;
ulong hostId = affinityToken == null ? Counter : (ulong)affinityToken.GetHashCode();
return ReachableHosts[(int)(hostId % (ulong)ReachableHosts.Count)];
}
}
public async Task<IEndPointHandle> GetOrWaitForNextHost(CancellationToken cancellationToken)
{
var hostOverride = TracingContext.GetHostOverride(DeploymentIdentifier.ServiceName);
if (hostOverride != null)
return new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Host, hostOverride.Port ?? GetConfig().DefaultPort);
if (ReachableHosts.Count > 0)
return GetNextHost();
lock (_lock)
{
if (FirstAvailableHostCompletionSource == null)
FirstAvailableHostCompletionSource = new TaskCompletionSource<RemoteHost>();
cancellationToken.Register(() => FirstAvailableHostCompletionSource?.SetCanceled());
}
return await FirstAvailableHostCompletionSource.Task.ConfigureAwait(false);
}
/// <summary>
/// Resets the state of all hosts as reachable.
/// </summary>
public void MarkAllAsReachable()
{
lock (_lock)
{
foreach (var unreachableHost in UnreachableHosts.ToArray())
{
unreachableHost.ReportSuccess();
MarkReachable(unreachableHost);
}
}
}
internal bool MarkUnreachable(RemoteHost remoteHost)
{
lock (_lock)
{
if (ReachableHosts.Remove(remoteHost))
{
if (ReachableHosts.Count == 0)
ReachabilityBroadcaster.Post(new ServiceReachabilityStatus { IsReachable = false });
UnreachableHosts.Add(remoteHost);
return true;
}
return false;
}
}
internal bool MarkReachable(RemoteHost remoteHost)
{
lock (_lock)
{
if (UnreachableHosts.Remove(remoteHost))
{
ReachableHosts.Add(remoteHost);
if (ReachableHosts.Count == 1)
ReachabilityBroadcaster.Post(new ServiceReachabilityStatus { IsReachable = true });
FirstAvailableHostCompletionSource?.SetResult(remoteHost);
FirstAvailableHostCompletionSource = null;
return true;
}
return false;
}
}
internal string GetAllHosts()
{
lock (_lock)
{
return string.Join(", ", ReachableHosts.Concat(UnreachableHosts).Select(h => h.HostName));
}
}
public void Dispose()
{
lock (_lock)
{
EndPointsChangedBlockLink.Dispose();
foreach (var host in ReachableHosts.Concat(UnreachableHosts).ToArray())
host.StopMonitoring();
ReachabilityBroadcaster.Complete();
DiscoverySource.Dispose();
Health.Dispose();
}
}
public void DeactivateMetrics()
{
Health.Deactivate();
}
public EndPoint[] GetAllEndPoints() { return EndPointsResult.EndPoints; }
}
public interface IRemoteHostPoolFactory
{
RemoteHostPool Create(DeploymentIdentifier deploymentIdentifier, IServiceDiscoverySource discovery,
ReachabilityChecker reachabilityChecker);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualMachineScaleSetVMsOperations operations.
/// </summary>
public partial interface IVirtualMachineScaleSetVMsOperations
{
/// <summary>
/// Reimages (upgrade the operating system) a specific virtual machine
/// in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> ReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to re-image all the disks ( including data disks ) in
/// the a virtual machine scale set instance. This operation is only
/// supported for managed disks.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> ReimageAllWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deallocates a specific virtual machine in a VM scale set. Shuts
/// down the virtual machine and releases the compute resources it
/// uses. You are not billed for the compute resources of this virtual
/// machine once it is deallocated.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualMachineScaleSetVM>> GetWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the status of a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualMachineScaleSetVMInstanceView>> GetInstanceViewWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of all virtual machines in a VM scale sets.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// The list parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, ODataQuery<VirtualMachineScaleSetVM> odataQuery = default(ODataQuery<VirtualMachineScaleSetVM>), string select = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Power off (stop) a virtual machine in a VM scale set. Note that
/// resources are still attached and you are getting charged for the
/// resources. Instead, use deallocate to release resources and avoid
/// charges.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Restarts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> RestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Starts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> StartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Reimages (upgrade the operating system) a specific virtual machine
/// in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Allows you to re-image all the disks ( including data disks ) in
/// the a virtual machine scale set instance. This operation is only
/// supported for managed disks.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginReimageAllWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deallocates a specific virtual machine in a VM scale set. Shuts
/// down the virtual machine and releases the compute resources it
/// uses. You are not billed for the compute resources of this virtual
/// machine once it is deallocated.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a virtual machine from a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Power off (stop) a virtual machine in a VM scale set. Note that
/// resources are still attached and you are getting charged for the
/// resources. Instead, use deallocate to release resources and avoid
/// charges.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Restarts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Starts a virtual machine in a VM scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmScaleSetName'>
/// The name of the VM scale set.
/// </param>
/// <param name='instanceId'>
/// The instance ID of the virtual machine.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatusResponse>> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, string instanceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of all virtual machines in a VM scale sets.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualMachineScaleSetVM>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System.Xml
{
// Summary:
// Encodes and decodes XML names and provides methods for converting between
// common language runtime types and XML Schema definition language (XSD) types.
// When converting data types the values returned are locale independent.
public class XmlConvert
{
// Summary:
// Initializes a new instance of the System.Xml.XmlConvert class.
//public XmlConvert();
// Summary:
// Decodes a name. This method does the reverse of the System.Xml.XmlConvert.EncodeName(System.String)
// and System.Xml.XmlConvert.EncodeLocalName(System.String) methods.
//
// Parameters:
// name:
// The name to be transformed.
//
// Returns:
// The decoded name.
//extern public static string DecodeName(string name);
//
// Summary:
// Converts the name to a valid XML local name.
//
// Parameters:
// name:
// The name to be encoded.
//
// Returns:
// The encoded name.
//public static string EncodeLocalName(string name);
//
// Summary:
// Converts the name to a valid XML name.
//
// Parameters:
// name:
// A name to be translated.
//
// Returns:
// Returns the name with any invalid characters replaced by an escape string.
//extern public static string EncodeName(string name);
//
// Summary:
// Verifies the name is valid according to the XML specification.
//
// Parameters:
// name:
// The name to be encoded.
//
// Returns:
// The encoded name.
//extern public static string EncodeNmToken(string name);
//
// Summary:
// Converts the System.String to a System.Boolean equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A Boolean value, that is, true or false.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s does not represent a Boolean value.
public static bool ToBoolean(string s)
{
Contract.Requires(s != null);
return default(bool);
}
//
// Summary:
// Converts the System.String to a System.Byte equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A Byte equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.Byte.MinValue or greater than System.Byte.MaxValue.
public static byte ToByte(string s)
{
Contract.Requires(s != null);
return default(byte);
}
//
// Summary:
// Converts the System.String to a System.Char equivalent.
//
// Parameters:
// s:
// The string containing a single character to convert.
//
// Returns:
// A Char representing the single character.
//
// Exceptions:
// System.ArgumentNullException:
// The value of the s parameter is null.
//
// System.FormatException:
// The s parameter contains more than one character.
public static char ToChar(string s)
{
Contract.Requires(s != null);
Contract.Requires(s.Length == 1);
return default(char);
}
//
// Summary:
// Converts the System.String to a System.DateTime equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A DateTime equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is an empty string or is not in the correct format.
//[Obsolete("Use XmlConvert.ToDateTime() that takes in XmlDateTimeSerializationMode")]
#if !SILVERLIGHT
public static DateTime ToDateTime(string s)
{
Contract.Requires(s != null);
return default(DateTime);
}
#endif
//
// Summary:
// Converts the System.String to a System.DateTime equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// format:
// The format structure to apply to the converted DateTime. Valid formats include
// "yyyy-MM-ddTHH:mm:sszzzzzz" and its subsets. The string is validated against
// this format.
//
// Returns:
// A DateTime equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s or format is String.Empty -or- s does not contain a date and time that
// corresponds to format.
public static DateTime ToDateTime(string s, string format)
{
Contract.Requires(s != null);
Contract.Requires(s.Length != 0);
Contract.Requires(format.Length != 0);
return default(DateTime);
}
//
// Summary:
// Converts the System.String to a System.DateTime equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// formats:
// An array containing the format structures to apply to the converted DateTime.
// Valid formats include "yyyy-MM-ddTHH:mm:sszzzzzz" and its subsets.
//
// Returns:
// A DateTime equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s or an element of formats is String.Empty -or- s does not contain a date
// and time that corresponds to any of the elements of formats.
public static DateTime ToDateTime(string s, string[] formats)
{
Contract.Requires(s != null);
Contract.Requires(s.Length != 0);
Contract.Requires(Contract.ForAll(formats, str => str != String.Empty));
return default(DateTime);
}
//
// Summary:
// Converts the System.String to a System.DateTime using the System.Xml.XmlDateTimeSerializationMode
// specified
//
// Parameters:
// s:
// The System.String value to convert.
//
// dateTimeOption:
// One of the System.Xml.XmlDateTimeSerializationMode values that specify whether
// the date should be converted to local time or preserved as Coordinated Universal
// Time (UTC), if it is a UTC date.
//
// Returns:
// A System.DateTime equivalent of the System.String.
//
// Exceptions:
// System.NullReferenceException:
// s is null.
//
// System.ArgumentNullException:
// The dateTimeOption value is null.
//
// System.FormatException:
// s is an empty string or is not in a valid format.
//public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption);
//
// Summary:
// Converts the supplied System.String to a System.DateTimeOffset equivalent.
//
// Parameters:
// s:
// The string to convert. Note: The string must conform to a subset of the
// W3C Recommendation for the XML dateTime type. For more information see http://www.w3.org/TR/xmlschema-2/#dateTime.
//
// Returns:
// The System.DateTimeOffset equivalent of the supplied string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.ArgumentOutOfRangeException:
// The argument passed to this method is outside the range of allowable values.
// For information about allowable values, see System.DateTimeOffset.
//
// System.FormatException:
// The argument passed to this method does not conform to a subset of the W3C
// Recommendations for the XML dateTime type. For more information see http://www.w3.org/TR/xmlschema-2/#dateTime.
public static DateTimeOffset ToDateTimeOffset(string s)
{
Contract.Requires(s != null);
return default(DateTimeOffset);
}
//
// Summary:
// Converts the supplied System.String to a System.DateTimeOffset equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// format:
// The format from which s is converted. The format parameter can be any subset
// of the W3C Recommendation for the XML dateTime type. (For more information
// see http://www.w3.org/TR/xmlschema-2/#dateTime.) The string s is validated
// against this format.
//
// Returns:
// The System.DateTimeOffset equivalent of the supplied string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s or format is an empty string or is not in the specified format.
public static DateTimeOffset ToDateTimeOffset(string s, string format)
{
Contract.Requires(s != null);
Contract.Requires(s != String.Empty);
Contract.Requires(format != String.Empty);
return default(DateTimeOffset);
}
//
// Summary:
// Converts the supplied System.String to a System.DateTimeOffset equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// formats:
// An array of formats from which s can be converted. Each format in formats
// can be any subset of the W3C Recommendation for the XML dateTime type. (For
// more information see http://www.w3.org/TR/xmlschema-2/#dateTime.) The string
// s is validated against one of these formats.
//
// Returns:
// The System.DateTimeOffset equivalent of the supplied string.
public static DateTimeOffset ToDateTimeOffset(string s, string[] formats)
{
Contract.Requires(s != null);
return default(DateTimeOffset);
}
//
// Summary:
// Converts the System.String to a System.Decimal equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A Decimal equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.Decimal.MinValue or greater than System.Decimal.MaxValue.
public static decimal ToDecimal(string s)
{
Contract.Requires(s != null);
return default(decimal);
}
//
// Summary:
// Converts the System.String to a System.Double equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A Double equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.Double.MinValue or greater than System.Double.MaxValue.
public static double ToDouble(string s)
{
Contract.Requires(s != null);
return default(double);
}
//
// Summary:
// Converts the System.String to a System.Guid equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A Guid equivalent of the string.
public static Guid ToGuid(string s)
{
Contract.Requires(s != null);
return default(Guid);
}
//
// Summary:
// Converts the System.String to a System.Int16 equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// An Int16 equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.Int16.MinValue or greater than System.Int16.MaxValue.
public static short ToInt16(string s)
{
Contract.Requires(s != null);
return default(short);
}
//
// Summary:
// Converts the System.String to a System.Int32 equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// An Int32 equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.Int32.MinValue or greater than System.Int32.MaxValue.
public static int ToInt32(string s)
{
Contract.Requires(s != null);
return default(int);
}
//
// Summary:
// Converts the System.String to a System.Int64 equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// An Int64 equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.Int64.MinValue or greater than System.Int64.MaxValue.
public static long ToInt64(string s)
{
Contract.Requires(s != null);
return default(long);
}
//
// Summary:
// Converts the System.String to a System.SByte equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// An SByte equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.SByte.MinValue or greater than System.SByte.MaxValue.
//[CLSCompliant(false)]
public static sbyte ToSByte(string s)
{
Contract.Requires(s != null);
return default(sbyte);
}
//
// Summary:
// Converts the System.String to a System.Single equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A Single equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.Single.MinValue or greater than System.Single.MaxValue.
public static float ToSingle(string s)
{
Contract.Requires(s != null);
return default(float);
}
//
// Summary:
// Converts the System.Boolean to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Boolean, that is, "true" or "false".
public static string ToString(bool value)
{
Contract.Ensures(!value || Contract.Result<string>() == "true");
Contract.Ensures(value || Contract.Result<string>() == "false");
return default(string);
}
//
// Summary:
// Converts the System.Byte to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Byte.
#if !SILVERLIGHT
public static string ToString(byte value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
#endif
//
// Summary:
// Converts the System.Char to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Char.
public static string ToString(char value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.DateTime to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the DateTime in the format yyyy-MM-ddTHH:mm:ss
// where 'T' is a constant literal.
#if !SILVERLIGHT
[Obsolete("Use XmlConvert.ToString() that takes in XmlDateTimeSerializationMode")]
public static string ToString(DateTime value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
#endif
//
// Summary:
// Converts the supplied System.DateTimeOffset to a System.String.
//
// Parameters:
// value:
// The System.DateTimeOffset to be converted.
//
// Returns:
// A System.String representation of the supplied System.DateTimeOffset.
public static string ToString(DateTimeOffset value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.Decimal to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Decimal.
public static string ToString(decimal value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.Double to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Double.
public static string ToString(double value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.Single to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Single.
public static string ToString(float value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.Guid to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Guid.
public static string ToString(Guid value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.Int32 to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Int32.
public static string ToString(int value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.Int64 to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Int64.
public static string ToString(long value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.SByte to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the SByte.
//[CLSCompliant(false)]
public static string ToString(sbyte value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.Int16 to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the Int16.
public static string ToString(short value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.TimeSpan to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the TimeSpan.
public static string ToString(TimeSpan value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.UInt32 to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the UInt32.
//[CLSCompliant(false)]
#if !SILVERLIGHT
public static string ToString(uint value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
#endif
//
// Summary:
// Converts the System.UInt64 to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the UInt64.
//[CLSCompliant(false)]
public static string ToString(ulong value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.UInt16 to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// Returns:
// A string representation of the UInt16.
//[CLSCompliant(false)]
#if !SILVERLIGHT
public static string ToString(ushort value)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
#endif
//
// Summary:
// Converts the System.DateTime to a System.String.
//
// Parameters:
// value:
// The value to convert.
//
// format:
// The format structure that defines how to display the converted string. Valid
// formats include "yyyy-MM-ddTHH:mm:sszzzzzz" and its subsets.
//
// Returns:
// A string representation of the DateTime in the specified format.
#if !SILVERLIGHT
public static string ToString(DateTime value, string format)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
#endif
//
// Summary:
// Converts the System.DateTime to a System.String using the System.Xml.XmlDateTimeSerializationMode
// specified.
//
// Parameters:
// value:
// The System.DateTime value to convert.
//
// dateTimeOption:
// One of the System.Xml.XmlDateTimeSerializationMode values that specify how
// to treat the System.DateTime value.
//
// Returns:
// A System.String equivalent of the System.DateTime.
//
// Exceptions:
// System.ArgumentException:
// The dateTimeOption value is not valid.
//
// System.ArgumentNullException:
// The value or dateTimeOption value is null.
//public static string ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption);
//
// Summary:
// Converts the supplied System.DateTimeOffset to a System.String in the specified
// format.
//
// Parameters:
// value:
// The System.DateTimeOffset to be converted.
//
// format:
// The format to which s is converted. The format parameter can be any subset
// of the W3C Recommendation for the XML dateTime type. (For more information
// see http://www.w3.org/TR/xmlschema-2/#dateTime.)
//
// Returns:
// A System.String representation in the specified format of the supplied System.DateTimeOffset.
public static string ToString(DateTimeOffset value, string format)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>().Length > 0);
return default(string);
}
//
// Summary:
// Converts the System.String to a System.TimeSpan equivalent.
//
// Parameters:
// s:
// The string to convert. The string format must conform to the W3C XML Schema
// Part 2: Datatypes recommendation for duration.
//
// Returns:
// A TimeSpan equivalent of the string.
//
// Exceptions:
// System.FormatException:
// s is not in correct format to represent a TimeSpan value.
//extern public static TimeSpan ToTimeSpan(string s);
//
// Summary:
// Converts the System.String to a System.UInt16 equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A UInt16 equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.UInt16.MinValue or greater than System.UInt16.MaxValue.
public static ushort ToUInt16(string s)
{
Contract.Requires(s != null);
return default(ushort);
}
//
// Summary:
// Converts the System.String to a System.UInt32 equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A UInt32 equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.UInt32.MinValue or greater than System.UInt32.MaxValue.
//// [CLSCompliant(false)]
public static uint ToUInt32(string s)
{
Contract.Requires(s != null);
return default(ushort);
}
//
// Summary:
// Converts the System.String to a System.UInt64 equivalent.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// A UInt64 equivalent of the string.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s is not in the correct format.
//
// System.OverflowException:
// s represents a number less than System.UInt64.MinValue or greater than System.UInt64.MaxValue.
//// [CLSCompliant(false)]
public static ulong ToUInt64(string s)
{
Contract.Requires(s != null);
return default(ulong);
}
//
// Summary:
// Verifies that the name is a valid name according to the W3C Extended Markup
// Language recommendation.
//
// Parameters:
// name:
// The name to verify.
//
// Returns:
// The name, if it is a valid XML name.
//
// Exceptions:
// System.Xml.XmlException:
// name is not a valid XML name.
//
// System.ArgumentNullException:
// name is null or String.Empty.
public static string VerifyName(string name)
{
Contract.Requires(!string.IsNullOrEmpty(name));
Contract.Ensures(Contract.Result<string>() == name);
return default(string);
}
//
// Summary:
// Verifies that the name is a valid NCName according to the W3C Extended Markup
// Language recommendation.
//
// Parameters:
// name:
// The name to verify.
//
// Returns:
// The name, if it is a valid NCName.
//
// Exceptions:
// System.ArgumentNullException:
// name is null or String.Empty.
//
// System.Xml.XmlException:
// name is not a valid NCName.
public static string VerifyNCName(string name)
{
Contract.Requires(!string.IsNullOrEmpty(name));
Contract.Ensures(Contract.Result<string>() == name);
return default(string);
}
//
// Summary:
// Verifies that the string is a valid NMTOKEN according to the W3C XML Schema
// Part2: Datatypes recommendation
//
// Parameters:
// name:
// The string you wish to verify.
//
// Returns:
// The name token, if it is a valid NMTOKEN.
//
// Exceptions:
// System.Xml.XmlException:
// The string is not a valid name token.
//
// System.ArgumentNullException:
// name is null.
public static string VerifyNMTOKEN(string name)
{
Contract.Requires(name != null);
return default(string);
}
//
// Summary:
// Verifies that the string is a valid token according to the W3C XML Schema
// Part2: Datatypes recommendation.
//
// Parameters:
// token:
// The string value you wish to verify.
//
// Returns:
// The token, if it is a valid token.
//
// Exceptions:
// System.Xml.XmlException:
// The string value is not a valid token.
//extern public static string VerifyTOKEN(string token);
}
}
| |
/*Copyright 2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.?*/
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.JTX;
using ESRI.ArcGIS.JTX.Utilities;
namespace JTXSamples
{
[Guid("9d4a3611-7455-485d-a583-3bfe5b66789b")]
public class CreateJob : IJTXCustomStep
{
#region Registration Code
[ComRegisterFunction()]
static void Reg(String regKey)
{
ESRI.ArcGIS.JTX.Utilities.JTXUtilities.RegisterJTXCustomStep(regKey);
}
[ComUnregisterFunction()]
static void Unreg(String regKey)
{
ESRI.ArcGIS.JTX.Utilities.JTXUtilities.UnregisterJTXCustomStep(regKey);
}
#endregion
////////////////////////////////////////////////////////////////////////
// DECLARE: Data Members
private readonly string[] m_expectedArgs = { "jobtypeid", "assigngroup", "assignuser" };
private IJTXDatabase m_ipDatabase = null;
#region IJTXCustomStep Members
/// <summary>
/// A description of the expected arguments for the step type. This should
/// include the syntax of the argument, whether or not it is required/optional,
/// and any return codes coming from the step type.
/// </summary>
public string ArgumentDescriptions
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(@"Job Type ID:");
sb.AppendFormat("\t/{0}:<job type id> (required)\r\n\r\n", m_expectedArgs[0]);
sb.AppendLine(@"Assign To Group:");
sb.AppendFormat("\t/{0}:<group to assign to> (optional)\r\n", m_expectedArgs[1]);
sb.AppendLine(@"Assign To User:");
sb.AppendFormat("\t/{0}:<username to assign to> (optional)\r\n", m_expectedArgs[2]);
return sb.ToString();
}
}
/// <summary>
/// Called when a step of this type is executed in the workflow.
/// </summary>
/// <param name="JobID">ID of the job being executed</param>
/// <param name="StepID">ID of the step being executed</param>
/// <param name="argv">Array of arguments passed into the step's execution</param>
/// <param name="ipFeedback">Feedback object to return status messages and files</param>
/// <returns>Return code of execution for workflow path traversal</returns>
public int Execute(int JobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback)
{
System.Diagnostics.Debug.Assert(m_ipDatabase != null);
string strValue = "";
int jobTypeID = 0;
if (!StepUtilities.GetArgument(ref argv, m_expectedArgs[0], true, out strValue))
{
throw new ArgumentNullException(m_expectedArgs[0], string.Format("\nMissing the {0} parameter!", m_expectedArgs[0]));
}
if (!Int32.TryParse(strValue, out jobTypeID))
{
throw new ArgumentNullException(m_expectedArgs[0], "Argument must be an integrer!");
}
IJTXJobType pJobType = m_ipDatabase.ConfigurationManager.GetJobTypeByID(jobTypeID);
IJTXJobManager pJobMan = m_ipDatabase.JobManager;
IJTXJob pNewJob = pJobMan.CreateJob(pJobType, 0, true);
IJTXActivityType pActType = m_ipDatabase.ConfigurationManager.GetActivityType(Constants.ACTTYPE_CREATE_JOB);
if (pActType != null)
{
pNewJob.LogJobAction(pActType, null, "");
}
JTXUtilities.SendNotification(Constants.NOTIF_JOB_CREATED, m_ipDatabase, pNewJob, null);
// Assign a status to the job if the Auto Assign Job Status setting is enabled
IJTXConfigurationProperties pConfigProps = (IJTXConfigurationProperties)m_ipDatabase.ConfigurationManager;
if (pConfigProps.PropertyExists(Constants.JTX_PROPERTY_AUTO_STATUS_ASSIGN))
{
string strAutoAssign = pConfigProps.GetProperty(Constants.JTX_PROPERTY_AUTO_STATUS_ASSIGN);
if (strAutoAssign == "TRUE")
{
pNewJob.Status = m_ipDatabase.ConfigurationManager.GetStatus("Created");
}
}
// Associate the current job with the new job with a parent-child relationship
pNewJob.ParentJob = JobID;
// Assign the job as specified in the arguments
string strAssignTo = "";
if (StepUtilities.GetArgument(ref argv, m_expectedArgs[1], true, out strAssignTo))
{
pNewJob.AssignedType = jtxAssignmentType.jtxAssignmentTypeGroup;
pNewJob.AssignedTo = strAssignTo;
}
else if (StepUtilities.GetArgument(ref argv, m_expectedArgs[2], true, out strAssignTo))
{
pNewJob.AssignedType = jtxAssignmentType.jtxAssignmentTypeUser;
pNewJob.AssignedTo = strAssignTo;
}
pNewJob.Store();
// Copy the workflow to the new job
WorkflowUtilities.CopyWorkflowXML(m_ipDatabase, pNewJob);
// Create 1-1 extended property entries
IJTXAuxProperties pAuxProps = (IJTXAuxProperties)pNewJob;
System.Array contNames = pAuxProps.ContainerNames;
IEnumerator contNamesEnum = contNames.GetEnumerator();
contNamesEnum.Reset();
while (contNamesEnum.MoveNext())
{
string strContainerName = (string)contNamesEnum.Current;
IJTXAuxRecordContainer pAuxContainer = pAuxProps.GetRecordContainer(strContainerName);
if (pAuxContainer.RelationshipType == esriRelCardinality.esriRelCardinalityOneToOne)
{
pAuxContainer.CreateRecord();
}
}
m_ipDatabase.LogMessage(5, 1000, System.Diagnostics.Process.GetCurrentProcess().MainWindowTitle);
// Update Application message about the new job
if (System.Diagnostics.Process.GetCurrentProcess().MainWindowTitle.Length > 0) //if its not running in server
{
MessageBox.Show("Created " + pJobType.Name + " Job " + pNewJob.ID, "Job Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return 0;
}
/// <summary>
/// Invoke an editor tool for managing custom step arguments. This is
/// an optional feature of the custom step and may not be implemented.
/// </summary>
/// <param name="hWndParent">Handle to the parent application window</param>
/// <param name="argsIn">Array of arguments already configured for this custom step</param>
/// <returns>Returns a list of newely configured arguments as specified via the editor tool</returns>
public object[] InvokeEditor(int hWndParent, object[] argsIn)
{
JTXSamples.ArgEditor editorForm = new JTXSamples.ArgEditor(m_ipDatabase, m_expectedArgs);
object[] newArgs = null;
return (editorForm.ShowDialog(argsIn, out newArgs) == DialogResult.OK) ? newArgs : argsIn;
}
/// <summary>
/// Called when the step is instantiated in the workflow.
/// </summary>
/// <param name="ipDatabase">Database connection to the JTX repository.</param>
public void OnCreate(IJTXDatabase ipDatabase)
{
m_ipDatabase = ipDatabase;
}
/// <summary>
/// Method to validate the configured arguments for the step type. The
/// logic of this method depends on the implementation of the custom step
/// but typically checks for proper argument names and syntax.
/// </summary>
/// <param name="argv">Array of arguments configured for the step type</param>
/// <returns>Returns 'true' if arguments are valid, 'false' if otherwise</returns>
public bool ValidateArguments(ref object[] argv)
{
string strValue = "";
if (!StepUtilities.GetArgument(ref argv, m_expectedArgs[0], true, out strValue)) { return false; }
return StepUtilities.AreArgumentNamesValid(ref argv, m_expectedArgs);
}
#endregion
} // End Class
} // End Namespace
| |
using sly.buildresult;
using sly.lexer;
using Xunit;
namespace ParserTests.comments
{
public enum CommentsTokenError1
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[Comment("//", "/*", "*/")] [SingleLineComment("//")] COMMENT
}
public enum CommentsTokenError2
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[Comment("//", "/*", "*/")] [MultiLineComment("/*", "*/")] COMMENT
}
public enum CommentsTokenError3
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[Comment("//", "/*", "*/")] [SingleLineComment("//")] [MultiLineComment("/*", "*/")] COMMENT
}
public enum CommentsTokenError4
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[SingleLineComment("//")] [SingleLineComment("//")] COMMENT
}
public enum CommentsTokenError5
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[MultiLineComment("/*", "*/")] [MultiLineComment("/*", "*/")] COMMENT
}
public enum CommentsTokenError6
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[Comment("//", "/*", "*/")] [Comment("//", "/*", "*/")] COMMENT
}
public enum CommentsTokenError7
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[Comment("//", "/*", "*/")] [SingleLineComment("//")] [SingleLineComment("//")] COMMENT
}
public enum CommentsTokenError8
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[Comment("//", "/*", "*/")] [MultiLineComment("/*", "*/")] [MultiLineComment("/*", "*/")] COMMENT
}
public enum CommentsTokenError9
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[MultiLineComment("/*", "*/")] [MultiLineComment("/*", "*/")] [SingleLineComment("//")] [SingleLineComment("//")] COMMENT
}
public enum CommentsTokenError10
{
[Lexeme(GenericToken.Int)] INT,
[Lexeme(GenericToken.Double)] DOUBLE,
[Lexeme(GenericToken.Identifier)] ID,
[Comment("//", "/*", "*/")] [Comment("//", "/*", "*/")] [MultiLineComment("/*", "*/")] [MultiLineComment("/*", "*/")] [SingleLineComment("//")] [SingleLineComment("//")] COMMENT
}
public class CommentsErrorTest
{
[Fact]
public void MultipleAttributes()
{
var lexerRes6 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError6>>());
Assert.True(lexerRes6.IsError);
Assert.Single(lexerRes6.Errors);
var expectedErrors = new[]
{
"too many comment lexem"
};
foreach (var expectedError in expectedErrors)
{
Assert.True(lexerRes6.Errors.Exists(x => x.Level == ErrorLevel.FATAL && x.Message == expectedError));
}
var lexerRes5 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError5>>());
Assert.True(lexerRes5.IsError);
Assert.Single(lexerRes5.Errors);
expectedErrors = new[]
{
"too many multi-line comment lexem"
};
foreach (var expectedError in expectedErrors)
{
Assert.True(lexerRes5.Errors.Exists(x => x.Level == ErrorLevel.FATAL && x.Message == expectedError));
}
var lexerRes4 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError4>>());
Assert.True(lexerRes4.IsError);
Assert.Single(lexerRes4.Errors);
expectedErrors = new[]
{
"too many single-line comment lexem"
};
foreach (var expectedError in expectedErrors)
{
Assert.True(lexerRes4.Errors.Exists(x => x.Level == ErrorLevel.FATAL && x.Message == expectedError));
}
}
[Fact]
public void RedundantAttributes()
{
var lexerRes3 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError3>>());
Assert.True(lexerRes3.IsError);
Assert.Single(lexerRes3.Errors);
Assert.Equal(ErrorLevel.FATAL, lexerRes3.Errors[0].Level);
Assert.Equal("comment lexem can't be used together with single-line or multi-line comment lexems", lexerRes3.Errors[0].Message);
var lexerRes2 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError2>>());
Assert.True(lexerRes2.IsError);
Assert.Single(lexerRes2.Errors);
Assert.Equal(ErrorLevel.FATAL, lexerRes2.Errors[0].Level);
Assert.Equal("comment lexem can't be used together with single-line or multi-line comment lexems", lexerRes2.Errors[0].Message);
var lexerRes1 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError1>>());
Assert.True(lexerRes1.IsError);
Assert.Single(lexerRes1.Errors);
Assert.Equal(ErrorLevel.FATAL, lexerRes1.Errors[0].Level);
Assert.Equal("comment lexem can't be used together with single-line or multi-line comment lexems", lexerRes1.Errors[0].Message);
}
[Fact]
public void MixedErrors()
{
var lexerRes10 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError10>>(),lang: "en");
Assert.True(lexerRes10.IsError);
Assert.Equal(4, lexerRes10.Errors.Count);
var expectedErrors = new[]
{
"too many comment lexem", "too many multi-line comment lexem", "too many single-line comment lexem",
"comment lexem can't be used together with single-line or multi-line comment lexems"
};
foreach (var expectedError in expectedErrors)
{
Assert.True(lexerRes10.Errors.Exists(x => x.Level == ErrorLevel.FATAL && x.Message == expectedError));
}
expectedErrors = new[] {"too many multi-line comment lexem", "too many single-line comment lexem"};
var lexerRes9 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError9>>(),lang: "en");
Assert.True(lexerRes9.IsError);
Assert.Equal(2, lexerRes9.Errors.Count);
foreach (var expectedError in expectedErrors)
{
Assert.True(lexerRes9.Errors.Exists(x => x.Level == ErrorLevel.FATAL && x.Message == expectedError));
}
expectedErrors = new[] {"too many multi-line comment lexem","comment lexem can't be used together with single-line or multi-line comment lexems"};
var lexerRes8 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError8>>(),lang: "en");
Assert.True(lexerRes8.IsError);
Assert.Equal(2, lexerRes8.Errors.Count);
foreach (var expectedError in expectedErrors)
{
Assert.True(lexerRes8.Errors.Exists(x => x.Level == ErrorLevel.FATAL && x.Message == expectedError));
}
expectedErrors = new[] {"too many single-line comment lexem" , "comment lexem can't be used together with single-line or multi-line comment lexems"};
var lexerRes7 = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsTokenError7>>());
Assert.True(lexerRes7.IsError);
Assert.Equal(2, lexerRes7.Errors.Count);
foreach (var expectedError in expectedErrors)
{
Assert.True(lexerRes7.Errors.Exists(x => x.Level == ErrorLevel.FATAL && x.Message == expectedError));
}
}
}
}
| |
// 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.
// Uncomment to turn on logging of non-dictionary strings written to binary writers.
// This can help identify element/attribute name/ns that could be written as XmlDictionaryStrings to get better compactness and performance.
// #define LOG_NON_DICTIONARY_WRITES
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Globalization;
using System.Collections.Generic;
using System.Security;
namespace System.Xml
{
internal class XmlBinaryNodeWriter : XmlStreamNodeWriter
{
private IXmlDictionary _dictionary;
private XmlBinaryWriterSession _session;
private bool _inAttribute;
private bool _inList;
private bool _wroteAttributeValue;
private AttributeValue _attributeValue;
private const int maxBytesPerChar = 3;
private int _textNodeOffset;
public XmlBinaryNodeWriter()
{
// Sanity check on node values
DiagnosticUtility.DebugAssert(XmlBinaryNodeType.MaxAttribute < XmlBinaryNodeType.MinElement &&
XmlBinaryNodeType.MaxElement < XmlBinaryNodeType.MinText &&
(int)XmlBinaryNodeType.MaxText < 256, "NodeTypes enumeration messed up");
}
public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream)
{
_dictionary = dictionary;
_session = session;
_inAttribute = false;
_inList = false;
_attributeValue.Clear();
_textNodeOffset = -1;
SetOutput(stream, ownsStream, null);
}
private void WriteNode(XmlBinaryNodeType nodeType)
{
WriteByte((byte)nodeType);
_textNodeOffset = -1;
}
private void WroteAttributeValue()
{
if (_wroteAttributeValue && !_inList)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlySingleValue)));
_wroteAttributeValue = true;
}
private void WriteTextNode(XmlBinaryNodeType nodeType)
{
if (_inAttribute)
WroteAttributeValue();
DiagnosticUtility.DebugAssert(nodeType >= XmlBinaryNodeType.MinText && nodeType <= XmlBinaryNodeType.MaxText && ((byte)nodeType & 1) == 0, "Invalid nodeType");
WriteByte((byte)nodeType);
_textNodeOffset = this.BufferOffset - 1;
}
private byte[] GetTextNodeBuffer(int size, out int offset)
{
if (_inAttribute)
WroteAttributeValue();
byte[] buffer = GetBuffer(size, out offset);
_textNodeOffset = offset;
return buffer;
}
private void WriteTextNodeWithLength(XmlBinaryNodeType nodeType, int length)
{
DiagnosticUtility.DebugAssert(nodeType == XmlBinaryNodeType.Chars8Text || nodeType == XmlBinaryNodeType.Bytes8Text || nodeType == XmlBinaryNodeType.UnicodeChars8Text, "");
int offset;
byte[] buffer = GetTextNodeBuffer(5, out offset);
if (length < 256)
{
buffer[offset + 0] = (byte)nodeType;
buffer[offset + 1] = (byte)length;
Advance(2);
}
else if (length < 65536)
{
buffer[offset + 0] = (byte)(nodeType + 1 * 2); // WithEndElements interleave
buffer[offset + 1] = (byte)length;
length >>= 8;
buffer[offset + 2] = (byte)length;
Advance(3);
}
else
{
buffer[offset + 0] = (byte)(nodeType + 2 * 2); // WithEndElements interleave
buffer[offset + 1] = (byte)length;
length >>= 8;
buffer[offset + 2] = (byte)length;
length >>= 8;
buffer[offset + 3] = (byte)length;
length >>= 8;
buffer[offset + 4] = (byte)length;
Advance(5);
}
}
private void WriteTextNodeWithInt64(XmlBinaryNodeType nodeType, Int64 value)
{
int offset;
byte[] buffer = GetTextNodeBuffer(9, out offset);
buffer[offset + 0] = (byte)nodeType;
buffer[offset + 1] = (byte)value;
value >>= 8;
buffer[offset + 2] = (byte)value;
value >>= 8;
buffer[offset + 3] = (byte)value;
value >>= 8;
buffer[offset + 4] = (byte)value;
value >>= 8;
buffer[offset + 5] = (byte)value;
value >>= 8;
buffer[offset + 6] = (byte)value;
value >>= 8;
buffer[offset + 7] = (byte)value;
value >>= 8;
buffer[offset + 8] = (byte)value;
Advance(9);
}
public override void WriteDeclaration()
{
}
public override void WriteStartElement(string prefix, string localName)
{
if (prefix.Length == 0)
{
WriteNode(XmlBinaryNodeType.ShortElement);
WriteName(localName);
}
else
{
char ch = prefix[0];
if (prefix.Length == 1 && ch >= 'a' && ch <= 'z')
{
WritePrefixNode(XmlBinaryNodeType.PrefixElementA, ch - 'a');
WriteName(localName);
}
else
{
WriteNode(XmlBinaryNodeType.Element);
WriteName(prefix);
WriteName(localName);
}
}
}
private void WritePrefixNode(XmlBinaryNodeType nodeType, int ch)
{
WriteNode((XmlBinaryNodeType)((int)nodeType + ch));
}
public override void WriteStartElement(string prefix, XmlDictionaryString localName)
{
int key;
if (!TryGetKey(localName, out key))
{
WriteStartElement(prefix, localName.Value);
}
else
{
if (prefix.Length == 0)
{
WriteNode(XmlBinaryNodeType.ShortDictionaryElement);
WriteDictionaryString(localName, key);
}
else
{
char ch = prefix[0];
if (prefix.Length == 1 && ch >= 'a' && ch <= 'z')
{
WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryElementA, ch - 'a');
WriteDictionaryString(localName, key);
}
else
{
WriteNode(XmlBinaryNodeType.DictionaryElement);
WriteName(prefix);
WriteDictionaryString(localName, key);
}
}
}
}
public override void WriteEndStartElement(bool isEmpty)
{
if (isEmpty)
{
WriteEndElement();
}
}
public override void WriteEndElement(string prefix, string localName)
{
WriteEndElement();
}
private void WriteEndElement()
{
if (_textNodeOffset != -1)
{
byte[] buffer = this.StreamBuffer;
XmlBinaryNodeType nodeType = (XmlBinaryNodeType)buffer[_textNodeOffset];
DiagnosticUtility.DebugAssert(nodeType >= XmlBinaryNodeType.MinText && nodeType <= XmlBinaryNodeType.MaxText && ((byte)nodeType & 1) == 0, "");
buffer[_textNodeOffset] = (byte)(nodeType + 1);
_textNodeOffset = -1;
}
else
{
WriteNode(XmlBinaryNodeType.EndElement);
}
}
public override void WriteStartAttribute(string prefix, string localName)
{
if (prefix.Length == 0)
{
WriteNode(XmlBinaryNodeType.ShortAttribute);
WriteName(localName);
}
else
{
char ch = prefix[0];
if (prefix.Length == 1 && ch >= 'a' && ch <= 'z')
{
WritePrefixNode(XmlBinaryNodeType.PrefixAttributeA, ch - 'a');
WriteName(localName);
}
else
{
WriteNode(XmlBinaryNodeType.Attribute);
WriteName(prefix);
WriteName(localName);
}
}
_inAttribute = true;
_wroteAttributeValue = false;
}
public override void WriteStartAttribute(string prefix, XmlDictionaryString localName)
{
int key;
if (!TryGetKey(localName, out key))
{
WriteStartAttribute(prefix, localName.Value);
}
else
{
if (prefix.Length == 0)
{
WriteNode(XmlBinaryNodeType.ShortDictionaryAttribute);
WriteDictionaryString(localName, key);
}
else
{
char ch = prefix[0];
if (prefix.Length == 1 && ch >= 'a' && ch <= 'z')
{
WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryAttributeA, ch - 'a');
WriteDictionaryString(localName, key);
}
else
{
WriteNode(XmlBinaryNodeType.DictionaryAttribute);
WriteName(prefix);
WriteDictionaryString(localName, key);
}
}
_inAttribute = true;
_wroteAttributeValue = false;
}
}
public override void WriteEndAttribute()
{
_inAttribute = false;
if (!_wroteAttributeValue)
{
_attributeValue.WriteTo(this);
}
_textNodeOffset = -1;
}
public override void WriteXmlnsAttribute(string prefix, string ns)
{
if (prefix.Length == 0)
{
WriteNode(XmlBinaryNodeType.ShortXmlnsAttribute);
WriteName(ns);
}
else
{
WriteNode(XmlBinaryNodeType.XmlnsAttribute);
WriteName(prefix);
WriteName(ns);
}
}
public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
int key;
if (!TryGetKey(ns, out key))
{
WriteXmlnsAttribute(prefix, ns.Value);
}
else
{
if (prefix.Length == 0)
{
WriteNode(XmlBinaryNodeType.ShortDictionaryXmlnsAttribute);
WriteDictionaryString(ns, key);
}
else
{
WriteNode(XmlBinaryNodeType.DictionaryXmlnsAttribute);
WriteName(prefix);
WriteDictionaryString(ns, key);
}
}
}
private bool TryGetKey(XmlDictionaryString s, out int key)
{
key = -1;
if (s.Dictionary == _dictionary)
{
key = s.Key * 2;
return true;
}
XmlDictionaryString t;
if (_dictionary != null && _dictionary.TryLookup(s, out t))
{
DiagnosticUtility.DebugAssert(t.Dictionary == _dictionary, "");
key = t.Key * 2;
return true;
}
if (_session == null)
return false;
int sessionKey;
if (!_session.TryLookup(s, out sessionKey))
{
if (!_session.TryAdd(s, out sessionKey))
return false;
}
key = sessionKey * 2 + 1;
return true;
}
private void WriteDictionaryString(XmlDictionaryString s, int key)
{
WriteMultiByteInt32(key);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
private unsafe void WriteName(string s)
{
int length = s.Length;
if (length == 0)
{
WriteByte(0);
}
else
{
fixed (char* pch = s)
{
UnsafeWriteName(pch, length);
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
private unsafe void UnsafeWriteName(char* chars, int charCount)
{
if (charCount < 128 / maxBytesPerChar)
{
// Optimize if we know we can fit the converted string in the buffer
// so we don't have to make a pass to count the bytes
// 1 byte for the length
int offset;
byte[] buffer = GetBuffer(1 + charCount * maxBytesPerChar, out offset);
int length = UnsafeGetUTF8Chars(chars, charCount, buffer, offset + 1);
DiagnosticUtility.DebugAssert(length < 128, "");
buffer[offset] = (byte)length;
Advance(1 + length);
}
else
{
int byteCount = UnsafeGetUTF8Length(chars, charCount);
WriteMultiByteInt32(byteCount);
UnsafeWriteUTF8Chars(chars, charCount);
}
}
private void WriteMultiByteInt32(int i)
{
int offset;
byte[] buffer = GetBuffer(5, out offset);
int startOffset = offset;
while ((i & 0xFFFFFF80) != 0)
{
buffer[offset++] = (byte)((i & 0x7F) | 0x80);
i >>= 7;
}
buffer[offset++] = (byte)i;
Advance(offset - startOffset);
}
public override void WriteComment(string value)
{
WriteNode(XmlBinaryNodeType.Comment);
WriteName(value);
}
public override void WriteCData(string value)
{
WriteText(value);
}
private void WriteEmptyText()
{
WriteTextNode(XmlBinaryNodeType.EmptyText);
}
public override void WriteBoolText(bool value)
{
if (value)
{
WriteTextNode(XmlBinaryNodeType.TrueText);
}
else
{
WriteTextNode(XmlBinaryNodeType.FalseText);
}
}
public override void WriteInt32Text(int value)
{
if (value >= -128 && value < 128)
{
if (value == 0)
{
WriteTextNode(XmlBinaryNodeType.ZeroText);
}
else if (value == 1)
{
WriteTextNode(XmlBinaryNodeType.OneText);
}
else
{
int offset;
byte[] buffer = GetTextNodeBuffer(2, out offset);
buffer[offset + 0] = (byte)XmlBinaryNodeType.Int8Text;
buffer[offset + 1] = (byte)value;
Advance(2);
}
}
else if (value >= -32768 && value < 32768)
{
int offset;
byte[] buffer = GetTextNodeBuffer(3, out offset);
buffer[offset + 0] = (byte)XmlBinaryNodeType.Int16Text;
buffer[offset + 1] = (byte)value;
value >>= 8;
buffer[offset + 2] = (byte)value;
Advance(3);
}
else
{
int offset;
byte[] buffer = GetTextNodeBuffer(5, out offset);
buffer[offset + 0] = (byte)XmlBinaryNodeType.Int32Text;
buffer[offset + 1] = (byte)value;
value >>= 8;
buffer[offset + 2] = (byte)value;
value >>= 8;
buffer[offset + 3] = (byte)value;
value >>= 8;
buffer[offset + 4] = (byte)value;
Advance(5);
}
}
public override void WriteInt64Text(Int64 value)
{
if (value >= int.MinValue && value <= int.MaxValue)
{
WriteInt32Text((int)value);
}
else
{
WriteTextNodeWithInt64(XmlBinaryNodeType.Int64Text, value);
}
}
public override void WriteUInt64Text(UInt64 value)
{
if (value <= Int64.MaxValue)
{
WriteInt64Text((Int64)value);
}
else
{
WriteTextNodeWithInt64(XmlBinaryNodeType.UInt64Text, (Int64)value);
}
}
private void WriteInt64(Int64 value)
{
int offset;
byte[] buffer = GetBuffer(8, out offset);
buffer[offset + 0] = (byte)value;
value >>= 8;
buffer[offset + 1] = (byte)value;
value >>= 8;
buffer[offset + 2] = (byte)value;
value >>= 8;
buffer[offset + 3] = (byte)value;
value >>= 8;
buffer[offset + 4] = (byte)value;
value >>= 8;
buffer[offset + 5] = (byte)value;
value >>= 8;
buffer[offset + 6] = (byte)value;
value >>= 8;
buffer[offset + 7] = (byte)value;
Advance(8);
}
public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] base64Buffer, int base64Offset, int base64Count)
{
if (_inAttribute)
{
_attributeValue.WriteBase64Text(trailBytes, trailByteCount, base64Buffer, base64Offset, base64Count);
}
else
{
int length = trailByteCount + base64Count;
if (length > 0)
{
WriteTextNodeWithLength(XmlBinaryNodeType.Bytes8Text, length);
if (trailByteCount > 0)
{
int offset;
byte[] buffer = GetBuffer(trailByteCount, out offset);
for (int i = 0; i < trailByteCount; i++)
buffer[offset + i] = trailBytes[i];
Advance(trailByteCount);
}
if (base64Count > 0)
{
WriteBytes(base64Buffer, base64Offset, base64Count);
}
}
else
{
WriteEmptyText();
}
}
}
public override void WriteText(XmlDictionaryString value)
{
if (_inAttribute)
{
_attributeValue.WriteText(value);
}
else
{
int key;
if (!TryGetKey(value, out key))
{
WriteText(value.Value);
}
else
{
WriteTextNode(XmlBinaryNodeType.DictionaryText);
WriteDictionaryString(value, key);
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteText(string value)
{
if (_inAttribute)
{
_attributeValue.WriteText(value);
}
else
{
if (value.Length > 0)
{
fixed (char* pch = value)
{
UnsafeWriteText(pch, value.Length);
}
}
else
{
WriteEmptyText();
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteText(char[] chars, int offset, int count)
{
if (_inAttribute)
{
_attributeValue.WriteText(new string(chars, offset, count));
}
else
{
if (count > 0)
{
fixed (char* pch = &chars[offset])
{
UnsafeWriteText(pch, count);
}
}
else
{
WriteEmptyText();
}
}
}
public override void WriteText(byte[] chars, int charOffset, int charCount)
{
WriteTextNodeWithLength(XmlBinaryNodeType.Chars8Text, charCount);
WriteBytes(chars, charOffset, charCount);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
private unsafe void UnsafeWriteText(char* chars, int charCount)
{
// Callers should handle zero
DiagnosticUtility.DebugAssert(charCount > 0, "");
if (charCount == 1)
{
char ch = chars[0];
if (ch == '0')
{
WriteTextNode(XmlBinaryNodeType.ZeroText);
return;
}
if (ch == '1')
{
WriteTextNode(XmlBinaryNodeType.OneText);
return;
}
}
if (charCount <= byte.MaxValue / maxBytesPerChar)
{
// Optimize if we know we can fit the converted string in the buffer
// so we don't have to make a pass to count the bytes
int offset;
byte[] buffer = GetBuffer(1 + 1 + charCount * maxBytesPerChar, out offset);
int length = UnsafeGetUTF8Chars(chars, charCount, buffer, offset + 2);
if (length / 2 <= charCount)
{
buffer[offset] = (byte)XmlBinaryNodeType.Chars8Text;
}
else
{
buffer[offset] = (byte)XmlBinaryNodeType.UnicodeChars8Text;
length = UnsafeGetUnicodeChars(chars, charCount, buffer, offset + 2);
}
_textNodeOffset = offset;
DiagnosticUtility.DebugAssert(length <= byte.MaxValue, "");
buffer[offset + 1] = (byte)length;
Advance(2 + length);
}
else
{
int byteCount = UnsafeGetUTF8Length(chars, charCount);
if (byteCount / 2 > charCount)
{
WriteTextNodeWithLength(XmlBinaryNodeType.UnicodeChars8Text, charCount * 2);
UnsafeWriteUnicodeChars(chars, charCount);
}
else
{
WriteTextNodeWithLength(XmlBinaryNodeType.Chars8Text, byteCount);
UnsafeWriteUTF8Chars(chars, charCount);
}
}
}
public override void WriteEscapedText(string value)
{
WriteText(value);
}
public override void WriteEscapedText(XmlDictionaryString value)
{
WriteText(value);
}
public override void WriteEscapedText(char[] chars, int offset, int count)
{
WriteText(chars, offset, count);
}
public override void WriteEscapedText(byte[] chars, int offset, int count)
{
WriteText(chars, offset, count);
}
public override void WriteCharEntity(int ch)
{
if (ch > char.MaxValue)
{
SurrogateChar sch = new SurrogateChar(ch);
char[] chars = new char[2] { sch.HighChar, sch.LowChar, };
WriteText(chars, 0, 2);
}
else
{
char[] chars = new char[1] { (char)ch };
WriteText(chars, 0, 1);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteFloatText(float f)
{
long l;
if (f >= long.MinValue && f <= long.MaxValue && (l = (long)f) == f)
{
WriteInt64Text(l);
}
else
{
int offset;
byte[] buffer = GetTextNodeBuffer(1 + sizeof(float), out offset);
byte* bytes = (byte*)&f;
buffer[offset + 0] = (byte)XmlBinaryNodeType.FloatText;
buffer[offset + 1] = bytes[0];
buffer[offset + 2] = bytes[1];
buffer[offset + 3] = bytes[2];
buffer[offset + 4] = bytes[3];
Advance(1 + sizeof(float));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteDoubleText(double d)
{
float f;
if (d >= float.MinValue && d <= float.MaxValue && (f = (float)d) == d)
{
WriteFloatText(f);
}
else
{
int offset;
byte[] buffer = GetTextNodeBuffer(1 + sizeof(double), out offset);
byte* bytes = (byte*)&d;
buffer[offset + 0] = (byte)XmlBinaryNodeType.DoubleText;
buffer[offset + 1] = bytes[0];
buffer[offset + 2] = bytes[1];
buffer[offset + 3] = bytes[2];
buffer[offset + 4] = bytes[3];
buffer[offset + 5] = bytes[4];
buffer[offset + 6] = bytes[5];
buffer[offset + 7] = bytes[6];
buffer[offset + 8] = bytes[7];
Advance(1 + sizeof(double));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteDecimalText(decimal d)
{
int offset;
byte[] buffer = GetTextNodeBuffer(1 + sizeof(decimal), out offset);
byte* bytes = (byte*)&d;
buffer[offset++] = (byte)XmlBinaryNodeType.DecimalText;
for (int i = 0; i < sizeof(decimal); i++)
{
buffer[offset++] = bytes[i];
}
Advance(1 + sizeof(decimal));
}
public override void WriteDateTimeText(DateTime dt)
{
WriteTextNodeWithInt64(XmlBinaryNodeType.DateTimeText, ToBinary(dt));
}
private static long ToBinary(DateTime dt)
{
long temp = 0;
switch (dt.Kind)
{
case DateTimeKind.Local:
temp = temp | -9223372036854775808L; // 0x8000000000000000
temp = temp | dt.ToUniversalTime().Ticks;
break;
case DateTimeKind.Utc:
temp = temp | 0x4000000000000000L;
temp = temp | dt.Ticks;
break;
case DateTimeKind.Unspecified:
temp = dt.Ticks;
break;
}
return temp;
}
public override void WriteUniqueIdText(UniqueId value)
{
if (value.IsGuid)
{
int offset;
byte[] buffer = GetTextNodeBuffer(17, out offset);
buffer[offset] = (byte)XmlBinaryNodeType.UniqueIdText;
value.TryGetGuid(buffer, offset + 1);
Advance(17);
}
else
{
WriteText(value.ToString());
}
}
public override void WriteGuidText(Guid guid)
{
int offset;
byte[] buffer = GetTextNodeBuffer(17, out offset);
buffer[offset] = (byte)XmlBinaryNodeType.GuidText;
Buffer.BlockCopy(guid.ToByteArray(), 0, buffer, offset + 1, 16);
Advance(17);
}
public override void WriteTimeSpanText(TimeSpan value)
{
WriteTextNodeWithInt64(XmlBinaryNodeType.TimeSpanText, value.Ticks);
}
public override void WriteStartListText()
{
DiagnosticUtility.DebugAssert(!_inList, "");
_inList = true;
WriteNode(XmlBinaryNodeType.StartListText);
}
public override void WriteListSeparator()
{
}
public override void WriteEndListText()
{
DiagnosticUtility.DebugAssert(_inList, "");
_inList = false;
_wroteAttributeValue = true;
WriteNode(XmlBinaryNodeType.EndListText);
}
public void WriteArrayNode()
{
WriteNode(XmlBinaryNodeType.Array);
}
private void WriteArrayInfo(XmlBinaryNodeType nodeType, int count)
{
WriteNode(nodeType);
WriteMultiByteInt32(count);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe public void UnsafeWriteArray(XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax)
{
WriteArrayInfo(nodeType, count);
UnsafeWriteArray(array, (int)(arrayMax - array));
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
private unsafe void UnsafeWriteArray(byte* array, int byteCount)
{
base.UnsafeWriteBytes(array, byteCount);
}
public void WriteDateTimeArray(DateTime[] array, int offset, int count)
{
WriteArrayInfo(XmlBinaryNodeType.DateTimeTextWithEndElement, count);
for (int i = 0; i < count; i++)
{
WriteInt64(ToBinary(array[offset + i]));
}
}
public void WriteGuidArray(Guid[] array, int offset, int count)
{
WriteArrayInfo(XmlBinaryNodeType.GuidTextWithEndElement, count);
for (int i = 0; i < count; i++)
{
byte[] buffer = array[offset + i].ToByteArray();
WriteBytes(buffer, 0, 16);
}
}
public void WriteTimeSpanArray(TimeSpan[] array, int offset, int count)
{
WriteArrayInfo(XmlBinaryNodeType.TimeSpanTextWithEndElement, count);
for (int i = 0; i < count; i++)
{
WriteInt64(array[offset + i].Ticks);
}
}
public override void WriteQualifiedName(string prefix, XmlDictionaryString localName)
{
if (prefix.Length == 0)
{
WriteText(localName);
}
else
{
char ch = prefix[0];
int key;
if (prefix.Length == 1 && (ch >= 'a' && ch <= 'z') && TryGetKey(localName, out key))
{
WriteTextNode(XmlBinaryNodeType.QNameDictionaryText);
WriteByte((byte)(ch - 'a'));
WriteDictionaryString(localName, key);
}
else
{
WriteText(prefix);
WriteText(":");
WriteText(localName);
}
}
}
protected override void FlushBuffer()
{
base.FlushBuffer();
_textNodeOffset = -1;
}
public override void Close()
{
base.Close();
_attributeValue.Clear();
}
private struct AttributeValue
{
private string _captureText;
private XmlDictionaryString _captureXText;
private MemoryStream _captureStream;
public void Clear()
{
_captureText = null;
_captureXText = null;
_captureStream = null;
}
public void WriteText(string s)
{
if (_captureStream != null)
{
ArraySegment<byte> arraySegment;
bool result = _captureStream.TryGetBuffer(out arraySegment);
DiagnosticUtility.DebugAssert(result, "");
_captureText = XmlConverter.Base64Encoding.GetString(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
_captureStream = null;
}
if (_captureXText != null)
{
_captureText = _captureXText.Value;
_captureXText = null;
}
if (_captureText == null || _captureText.Length == 0)
{
_captureText = s;
}
else
{
_captureText += s;
}
}
public void WriteText(XmlDictionaryString s)
{
if (_captureText != null || _captureStream != null)
{
WriteText(s.Value);
}
else
{
_captureXText = s;
}
}
public void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count)
{
if (_captureText != null || _captureXText != null)
{
if (trailByteCount > 0)
{
WriteText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount));
}
WriteText(XmlConverter.Base64Encoding.GetString(buffer, offset, count));
}
else
{
if (_captureStream == null)
_captureStream = new MemoryStream();
if (trailByteCount > 0)
_captureStream.Write(trailBytes, 0, trailByteCount);
_captureStream.Write(buffer, offset, count);
}
}
public void WriteTo(XmlBinaryNodeWriter writer)
{
if (_captureText != null)
{
writer.WriteText(_captureText);
_captureText = null;
}
else if (_captureXText != null)
{
writer.WriteText(_captureXText);
_captureXText = null;
}
else if (_captureStream != null)
{
ArraySegment<byte> arraySegment;
bool result = _captureStream.TryGetBuffer(out arraySegment);
DiagnosticUtility.DebugAssert(result, "");
writer.WriteBase64Text(null, 0, arraySegment.Array, arraySegment.Offset, arraySegment.Count);
_captureStream = null;
}
else
{
writer.WriteEmptyText();
}
}
}
}
internal class XmlBinaryWriter : XmlBaseWriter
{
private XmlBinaryNodeWriter _writer;
private char[] _chars;
private byte[] _bytes;
public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
if (_writer == null)
_writer = new XmlBinaryNodeWriter();
_writer.SetOutput(stream, dictionary, session, ownsStream);
SetOutput(_writer);
}
protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute)
{
Type type = reader.ValueType;
if (type == typeof(string))
{
XmlDictionaryString value;
if (reader.TryGetValueAsDictionaryString(out value))
{
WriteString(value);
}
else
{
if (reader.CanReadValueChunk)
{
if (_chars == null)
{
_chars = new char[256];
}
int count;
while ((count = reader.ReadValueChunk(_chars, 0, _chars.Length)) > 0)
{
this.WriteChars(_chars, 0, count);
}
}
else
{
WriteString(reader.Value);
}
}
if (!attribute)
{
reader.Read();
}
}
else if (type == typeof(byte[]))
{
if (reader.CanReadBinaryContent)
{
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
if (_bytes == null)
{
_bytes = new byte[384];
}
int count;
while ((count = reader.ReadValueAsBase64(_bytes, 0, _bytes.Length)) > 0)
{
this.WriteBase64(_bytes, 0, count);
}
}
else
{
WriteString(reader.Value);
}
if (!attribute)
{
reader.Read();
}
}
else if (type == typeof(int))
WriteValue(reader.ReadContentAsInt());
else if (type == typeof(long))
WriteValue(reader.ReadContentAsLong());
else if (type == typeof(bool))
WriteValue(reader.ReadContentAsBoolean());
else if (type == typeof(double))
WriteValue(reader.ReadContentAsDouble());
else if (type == typeof(DateTime))
WriteValue(reader.ReadContentAsDateTimeOffset().DateTime);
else if (type == typeof(float))
WriteValue(reader.ReadContentAsFloat());
else if (type == typeof(decimal))
WriteValue(reader.ReadContentAsDecimal());
else if (type == typeof(UniqueId))
WriteValue(reader.ReadContentAsUniqueId());
else if (type == typeof(Guid))
WriteValue(reader.ReadContentAsGuid());
else if (type == typeof(TimeSpan))
WriteValue(reader.ReadContentAsTimeSpan());
else
WriteValue(reader.ReadContentAsObject());
}
private void WriteStartArray(string prefix, string localName, string namespaceUri, int count)
{
StartArray(count);
_writer.WriteArrayNode();
WriteStartElement(prefix, localName, namespaceUri);
WriteEndElement();
}
private void WriteStartArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int count)
{
StartArray(count);
_writer.WriteArrayNode();
WriteStartElement(prefix, localName, namespaceUri);
WriteEndElement();
}
private void WriteEndArray()
{
EndArray();
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
private unsafe void UnsafeWriteArray(string prefix, string localName, string namespaceUri,
XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.UnsafeWriteArray(nodeType, count, array, arrayMax);
WriteEndArray();
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
private unsafe void UnsafeWriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri,
XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.UnsafeWriteArray(nodeType, count, array, arrayMax);
WriteEndArray();
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
// bool
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (bool* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (bool* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
// Int16
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, Int16[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (Int16* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (Int16* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
// Int32
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, Int32[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (Int32* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (Int32* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
// Int64
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, Int64[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (Int64* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (Int64* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
// float
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (float* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (float* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
// double
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (double* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (double* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
// decimal
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (decimal* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
fixed (decimal* items = &array[offset])
{
UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement, count, (byte*)items, (byte*)&items[count]);
}
}
}
}
// DateTime
public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.WriteDateTimeArray(array, offset, count);
WriteEndArray();
}
}
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.WriteDateTimeArray(array, offset, count);
WriteEndArray();
}
}
}
// Guid
public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.WriteGuidArray(array, offset, count);
WriteEndArray();
}
}
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.WriteGuidArray(array, offset, count);
WriteEndArray();
}
}
}
// TimeSpan
public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.WriteTimeSpanArray(array, offset, count);
WriteEndArray();
}
}
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
{
CheckArray(array, offset, count);
if (count > 0)
{
WriteStartArray(prefix, localName, namespaceUri, count);
_writer.WriteTimeSpanArray(array, offset, count);
WriteEndArray();
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (C) LogicKing.com
//-----------------------------------------------------------------------------
//
// Templates are used for describing certain type of game object
//
//List of available types of template's variables. Type of variable will
//define
//
// string - simple editbox
// bool - will be shown as a checkBox
// list - drop window
//
// file - a filepath, can be specified with an edit box or calling 'openFileDialog'
// vector - a sting with three numeric values. Empty vector string will be treat as "0 0 0"
// code - a stirng with TorqueScript code. Code edit window allow made reference to other object with "pick mode"
//
// action - describes an action that can be select for drop list of code edit window
//
// group - describes array of one type params that contains one main string (can be "code" or "file" type) and one additional (optional)
// sound - variant of "file"-type includes button for playing selected sound file
// command - add button that evaluates chunk stored in field value
// objectLink -
//-----------------------------------------------------------------------------
function assertBis( %value, %message )
{
if(%value $= "")
{
error(%message);
}
}
package TemplateFunctions
{
//set template field values
function setTemplateField(%templateName, %fieldName, %value, %type, %group, %hint, %additional, %skipSaving)
{
assertBis(%templateName, "Wrong templateName while set field " @ %fieldName @ " with value = " @ %value @ "!!!!!");
assertBis(%fieldName, "Wrong fieldName in template " @ %templateName @ "!!!!!");
%index = checkField(%templateName, %fieldName);
$Templates[%templateName, %index, fieldName] = %fieldName;
//defult type is string
%type = %type $= "" ? "string" : %type;
$Templates[%templateName, %index, type] = %type;
// list represented as an array of elements
if(%type $= "list")
{
%count = getWordCount(%value);
for(%i = 0; %i < %count; %i++)
{
$Templates[%templateName, %index, values, %i] = getWord(%value, %i);
}
$Templates[%templateName, %index, valuesCount] = %count;
}
else
$Templates[%templateName, %index, value] = %value;
// an object without specified group will be place in "default" group
%group = %group $= "" ? getFieldGroup(%templateName, %index) : %group;
%group = %group $= "" ? "Default" : %group;
$Templates[%templateName, %index, group] = %group;
$Templates[%templateName, %index, hint] = getFieldHint(%templateName, %index) $= "" ? %hint : getFieldHint(%templateName, %index);
$Templates[%templateName, %index, additional] = %additional;
$Templates[%templateName, %index, skipSaving] = %skipSaving;
}
// helper functions
// define event field for a template
function setTemplateEvent(%templateName, %fieldName, %value, %hint, %additional)
{
setTemplateField(%templateName, %fieldName, %value, "code", "Events", %hint, %additional);
}
// define action field for a template
function setTemplateAction(%templateName, %actionName, %hint, %additional)
{
setTemplateField(%templateName, %actionName, %actionName, "action", "Actions", %hint, %additional, true);
}
// Define params group for a template.
// This function adds to prototype a parameters' list - similirar to list of dynamic fields .
// Params are represented as a sting, wich has following format: main_field_type|main_field_caption|secondary_01_field_caption|secondary_02_field_caption...
// '|' symbol used as separator. Only main field can have type, secondary fields treated as text field.
function setTemplateParamsGroup(%templateName, %groupName, %mainParamType, %hint, %additional)
{
setTemplateField(%templateName, %groupName, %mainParamType, "group", "", %hint, %additional, true);
}
// define command field for a template
// Adds a button wich executes code %command for selected object
function setTemplateCommand(%templateName, %buttonText, %hint, %command)
{
setTemplateField(%templateName, %buttonText, %command, "command", "", %hint, %command, true);
}
// define sound file field for a template
// adding a path to sound file
function setTemplateSoundField(%templateName, %fieldName, %value, %group, %hint)
{
setTemplateField(%templateName, %fieldName, %value, "sound", %group, %hint, $soundFilesMask);
}
// Add template for adding 'internal' objects, like markets in paths
function setTemplateInternalObjects(%templateName, %fieldName, %value, %hint, %namesMask)
{
setTemplateField(%templateName, %fieldName, %value, "internalObjectsList", "", %hint, %namesMask, true);
}
// Checks whether field with a certain name exist in a template.
// Returns an index of the field.
// If the field is abscent it will increase field counter and
// returns the last available index.
function checkField(%templateName, %fieldName)
{
%index = getFieldIndex(%templateName, %fieldName);
if(%index == -1)
{
%index = getFieldsCounter(%templateName);
increaseFieldsCounter(%templateName);
}
return %index;
}
// return an index of the template field by field name.
// if there's no such field returns -1
function getFieldIndex(%templateName, %fieldName)
{
assertBis(%templateName, "Wrong templateName while get field " @ %fieldName @ " index!!!!!");
assertBis(%fieldName, "Wrong fieldName to get it's index in template " @ %templateName @ "!!!!!");
%index = -1;
%counter = getFieldsCounter(%templateName);
for(%i = 0; %i < %counter; %i++)
{
if($Templates[%templateName, %i, fieldName] $= %fieldName)
{
%index = %i;
break;
}
}
return %index;
}
// returns a name by index
function getFieldName(%templateName, %index)
{
assertBis(%templateName, "Wrong templateName while get field " @ %index @ "!!!!!");
assertBis(%index, "Wrong index in template " @ %templateName @ "!!!!!");
return $Templates[%templateName, %index, fieldName];
}
// increments count of the fields
function increaseFieldsCounter(%templateName)
{
$Templates[%templateName, fieldsCounter]++;
}
// field counter
function getFieldsCounter(%templateName)
{
return $Templates[%templateName, fieldsCounter] ? $Templates[%templateName, fieldsCounter] : 0;
}
// Returns a field value by index.
// If there's a complex field , than usign second %valueIndex to get value
function getFieldValue(%templateName, %index, %valueIndex)
{
assertBis(%templateName, "Wrong templateName while get field " @ %index @ "!!!!!");
assertBis(%index, "Wrong index in template " @ %templateName @ "!!!!!");
if($Templates[%templateName, %index, valuesCount] > 0)
{
return $Templates[%templateName, %index, values, %valueIndex];
}
else
return $Templates[%templateName, %index, value];
}
// returns a category of given field
function getFieldGroup(%templateName, %index)
{
assertBis(%templateName, "Wrong templateName while get field " @ %index @ "!!!!!");
assertBis(%index, "Wrong index in template " @ %templateName @ "!!!!!");
return $Templates[%templateName, %index, group];
}
// returns a hint for a field
function getFieldHint(%templateName, %index)
{
assertBis(%templateName, "Wrong templateName while get field " @ %index @ "!!!!!");
assertBis(%index, "Wrong index in template " @ %templateName @ "!!!!!");
return $Templates[%templateName, %index, hint];
}
// returns a type of a field
function getFieldType(%templateName, %index)
{
assertBis(%templateName, "Wrong templateName while get field " @ %index @ "!!!!!");
assertBis(%index, "Wrong index in template " @ %templateName @ "!!!!!");
return $Templates[%templateName, %index, type];
}
// returns a field's additional param
function getFieldAdditional(%templateName, %index)
{
assertBis(%templateName, "Wrong templateName while get field " @ %index @ "!!!!!");
assertBis(%index, "Wrong index in template " @ %templateName @ "!!!!!");
return $Templates[%templateName, %index, additional];
}
// returns a field's additional param
function skipFieldSaving(%templateName, %index)
{
assertBis(%templateName, "Wrong templateName while get field " @ %index @ "!!!!!");
assertBis(%index, "Wrong index in template " @ %templateName @ "!!!!!");
return $Templates[%templateName, %index, skipSaving];
}
// returns a field's values count
function getFieldValuesCount(%templateName, %index)
{
return $Templates[%templateName, %index, valuesCount];
}
// register a new template with(%templateName) within a specified categor(%categoryName).
// %creationChunk is piece of TorqueScript code that returns a newly created object by the template
function registerTemplate(%templateName, %categoryName, %creationChunk)
{
assertBis(%templateName, "Wrong templateName for register!!!!!");
assertBis(%categoryName, "Wrong category name in template " @ %templateName @ "!!!!!");
%index = getTemplateIndex(%templateName);
if(%index == -1)
{
%index = getTemplatesAmount();
$Templates[templatesCounter]++;
}
$Templates[%index, templateName] = %templateName;
$Templates[%index, creationChunk] = %creationChunk;
$Templates[%index, categoryName] = %categoryName;
}
// Inherits one template from another. Actualy copies fields of %templateParent to %templateName.
function inheritTemplate(%templateName, %templateParent)
{
%count = getFieldsCounter(%templateParent);
%parentIndex = getTemplateIndex(%templateParent);
registerTemplate(%templateName, getTemplateCategory(%parentIndex), getTemplateCreationChunk(%parentIndex));
for(%i = 0; %i < %count; %i++)
{
%fieldName = getFieldName(%templateParent, %i);
%count2 = getFieldValuesCount(%templateParent, %i);
%type = getFieldType(%templateParent, %i);
%group = getFieldGroup(%templateParent, %i);
%hint = getFieldHint(%templateParent, %i);
%additional = getFieldAdditional(%templateParent, %i);
%skipSaving = skipFieldSaving(%templateParent, %i);
%value = "";
if(%type $= "list")
{
for(%j = 0; %j < %count2; %j++)
{
%value = %value @ getFieldValue(%templateParent, %i, %j) @ " ";
}
}
else
%value = getFieldValue(%templateParent, %i);
setTemplateField(%templateName, %fieldName, %value, %type, %group, %hint, %additional, %skipSaving);
}
}
// returns amount of registered prototypes.
function getTemplatesAmount()
{
return $Templates[templatesCounter] ? $Templates[templatesCounter] : 0;
}
// returns a template index from its name
function getTemplateIndex(%templateName)
{
assertBis(%templateName, "Wrong templateName to get it's index!!!!!");
%index = -1;
%counter = getTemplatesAmount();
for(%i = 0; %i < %counter; %i++)
{
if($Templates[%i, templateName] $= %templateName)
{
%index = %i;
break;
}
}
return %index;
}
// returns a template name from its index
function getTemplateName(%index)
{
return $Templates[%index, templateName];
}
// returns a template creation code
function getTemplateCreationChunk(%index)
{
return $Templates[%index, creationChunk];
}
// returns a template category by its index
function getTemplateCategory(%index)
{
return $Templates[%index, categoryName];
}
// a function creates and returns an object from template.
function createObject(%templateName, %objectName)
{
if(%templateName $= "")
{
error("Wrong templateName to create new object!!!!");
return -1;
}
%index = getTemplateIndex(%templateName);
if(%index == -1)
{
error("Error!!! No such template - " @ %templateName);
return;
}
%chunk = getTemplateCreationChunk(%index);
%object = eval(%chunk);
assertBis(%object, "Error!!! Can't create object " @ %objectName @ " by template " @ %templateName);
MissionGroup.add(%object);
%object.templateName = %templateName;
%templateIndex = getTemplateIndex(%templateName);
%object.category = getTemplateCategory(%templateIndex);
%categoryIndex = getCategoryIndex(%object.category);
%object.editorIcon = getCategoryIcon(%categoryIndex);
%object.setName(%objectName);
%fieldsCount = getFieldsCounter(%templateName);
for(%i = 0; %i < %fieldsCount; %i++)
{
if(getFieldValuesCount(%object.templateName, %i) $= "")
{
%skipSaving = skipFieldSaving(%object.templateName, %i);
if(%skipSaving) continue;
%fieldName = getFieldName(%object.templateName, %i);
%value = getFieldValue(%object.templateName, %i);
%object.setFieldValue(%fieldName, %value);
}
}
return %object;
}
function addCategory(%categoryName, %icon)
{
assertBis(%categoryName, "Wrong category name to add. Icon is " @ %icon @"!!!!");
assertBis(%icon, "Wrong icon to add for category - " @ %categoryName @ "!!!!!");
%index = getCategoryIndex(%categoryName);
// add new category only when category with same name doesn't exists
if(%index == -1)
{
%index = getCategoriesAmount();
$Categories[counter]++;
}
$Categories[%index, name] = %categoryName;
$Categories[%index, icon] = %icon;
}
function getCategoriesAmount()
{
$Categories[counter] = $Categories[counter] ? $Categories[counter] : 0;
return $Categories[counter];
}
function getCategoryIndex(%categoryName)
{
assertBis(%categoryName, "Wrong categoryName to get it's index!!!!!");
%index = -1;
%counter = getCategoriesAmount();
for(%i = 0; %i < %counter; %i++)
{
if($Categories[%i, name] $= %categoryName)
{
%index = %i;
break;
}
}
return %index;
}
function getCategoryName(%index)
{
assertBis(%index, "Wrong index to get category name!!!!!");
%categoryName = $Categories[%index, name];
assertBis(%categoryName, "Wrong index to get category name!!!!!");
return %categoryName;
}
function getCategoryIcon(%index)
{
assertBis(%index, "Wrong index to get category icon!!!!!");
%icon = $Categories[%index, icon];
assertBis(%icon, "Wrong index to get category icon!!!!!");
return %icon;
}
function getCategoryIconByName(%name)
{
assertBis(%name, "Wrong name to get category icon!!!!!");
%index = getCategoryIndex(%name);
%icon = $Categories[%index, icon];
assertBis(%icon, "Wrong index to get category icon!!!!!");
return %icon;
}
};
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 Outercurve Foundation 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 System.Diagnostics;
using System.Text;
using System.Threading;
using Microsoft.Web.PlatformInstaller;
using WebsitePanel.Server.Code;
namespace WebsitePanel.Server.WPIService
{
// Define a service contract.
//[ServiceContract(Namespace = "http://Helicon.Zoo.WPIService")]
//public interface IWPIService
//{
// // [OperationContract]
// void Initialize(string[] feeds);
// //[OperationContract]
// void BeginInstallation(string[] productsToInstall);
// //[OperationContract]
// string GetStatus();
// string GetLogs();
//}
enum EWPIServiceStatus
{
Initialised,
Installation,
InstallationComplete,
InstallationError
}
// Service class which implements the service contract.
//[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class WPIService : WPIServiceContract
{
private WpiHelper _wpiHelper;
private string[] _productsToInstall;
private EWPIServiceStatus _installationStatus;
private string _statusMessage = "preparing...";
private Thread _installerThread;
private object _lock = new object();
public bool IsFinished { get; private set; }
#region IWPIService contract
public override string Ping()
{
return "OK";
}
public override void Initialize(string[] feeds)
{
lock (_lock)
{
if (_installationStatus == EWPIServiceStatus.Installation)
{
throw new Exception("Invalid state, already in Installation process");
}
_installationStatus = EWPIServiceStatus.Initialised;
if (_wpiHelper == null)
{
_wpiHelper = new WpiHelper(feeds);
Console.WriteLine("_wpiHelper initialized");
}
}
}
public override void BeginInstallation(string[] productsToInstall)
{
lock (_lock)
{
if (_installationStatus != EWPIServiceStatus.Initialised)
{
throw new Exception("Invalid state, expected EWPIServiceStatus.Initialised. now: " + _installationStatus);
}
_installationStatus = EWPIServiceStatus.Installation;
_statusMessage = "Preparing for install";
_productsToInstall = new string[productsToInstall.Length];
productsToInstall.CopyTo(_productsToInstall,0);
_installerThread = new Thread(new ThreadStart(InternalBeginInstallation));
_installerThread.Start();
}
}
public override string GetStatus()
{
lock(_lock)
{
string result = this._statusMessage;
//Allow exit from app, if finished
IsInstallationProceed();
return result;
}
}
public override string GetLogFileDirectory()
{
lock (_lock)
{
return null != _wpiHelper ? _wpiHelper.GetLogFileDirectory() : null;
}
}
#endregion
#region private implementaion
private bool IsInstallationProceed()
{
if (_installationStatus == EWPIServiceStatus.InstallationComplete)
{
IsFinished = true;
return false;
}
else if (_installationStatus == EWPIServiceStatus.InstallationError)
{
IsFinished = true;
return false;
}
return true;
}
private void InternalBeginInstallation()
{
_wpiHelper.InstallProducts(
_productsToInstall,
true, //search and install dependencies
WpiHelper.DeafultLanguage,
InstallStatusUpdatedHandler,
InstallCompleteHandler
);
lock (_lock)
{
_installationStatus = EWPIServiceStatus.InstallationComplete;
}
}
private void InstallCompleteHandler(object sender, EventArgs eventArgs)
{
lock(_lock)
{
_installationStatus = EWPIServiceStatus.InstallationComplete;
}
CheckIISAlive();
}
private void InstallStatusUpdatedHandler(object sender, InstallStatusEventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}: ", e.InstallerContext.ProductName);
switch (e.InstallerContext.InstallationState)
{
case InstallationState.Waiting:
sb.Append("please wait...").AppendLine();
break;
case InstallationState.Downloading:
sb.Append("downloading").AppendLine();
if (e.ProgressValue > 0)
{
sb.AppendFormat("{0} of {1} Kb downloaded", e.ProgressValue,
e.InstallerContext.Installer.InstallerFile.FileSize);
sb.AppendLine();
}
break;
case InstallationState.Downloaded:
sb.Append("downloaded").AppendLine();
break;
case InstallationState.DownloadFailed:
sb.AppendFormat("download failed").AppendLine();
sb.AppendLine(e.InstallerContext.InstallStateDetails);
break;
case InstallationState.DependencyFailed:
sb.AppendFormat("dependency failed").AppendLine();
sb.AppendLine(e.InstallerContext.InstallStateDetails);
sb.AppendFormat("{0}: {1}", e.InstallerContext.ReturnCode.Status, e.InstallerContext.ReturnCode.DetailedInformation).AppendLine();
break;
case InstallationState.Installing:
sb.Append("installing").AppendLine();
break;
case InstallationState.InstallCompleted:
sb.Append("install completed").AppendLine();
break;
case InstallationState.Canceled:
sb.AppendFormat("canceled").AppendLine();
sb.AppendLine(e.InstallerContext.InstallStateDetails);
sb.AppendFormat("{0}: {1}", e.InstallerContext.ReturnCode.Status, e.InstallerContext.ReturnCode.DetailedInformation).AppendLine();
break;
default:
throw new ArgumentOutOfRangeException();
}
lock (_lock)
{
_statusMessage = sb.ToString();
}
}
private void CheckIISAlive()
{
// run iisreset /start
ProcessStartInfo processStartInfo = new ProcessStartInfo(@"C:\Windows\System32\iisreset.exe", "/start");
processStartInfo.UseShellExecute = false;
try
{
using (Process exeProcess = Process.Start(processStartInfo))
{
exeProcess.WaitForExit();
Debug.Write("WPIService: iisreset /start returns "+exeProcess.ExitCode);
}
}
catch (Exception ex)
{
Debug.Write("WPIService: iisreset /start exception: "+ex.ToString());
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
public static partial class ManagedPlanOperationsExtensions
{
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='parameters'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedPlanCreateOrUpdateResult CreateOrUpdate(this IManagedPlanOperations operations, string resourceGroupName, ManagedPlanCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='parameters'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedPlanCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedPlanOperations operations, string resourceGroupName, ManagedPlanCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).DeleteAsync(resourceGroupName, planId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return operations.DeleteAsync(resourceGroupName, planId, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedPlanGetResult Get(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).GetAsync(resourceGroupName, planId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedPlanGetResult> GetAsync(this IManagedPlanOperations operations, string resourceGroupName, string planId)
{
return operations.GetAsync(resourceGroupName, planId, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <param name='metricDefinitionId'>
/// Required. Your documentation here.
/// </param>
/// <param name='filter'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedPlanGetMetricDefinitionsResult GetMetricDefinitions(this IManagedPlanOperations operations, string resourceGroupName, string planId, string metricDefinitionId, string filter)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).GetMetricDefinitionsAsync(resourceGroupName, planId, metricDefinitionId, filter);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <param name='metricDefinitionId'>
/// Required. Your documentation here.
/// </param>
/// <param name='filter'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedPlanGetMetricDefinitionsResult> GetMetricDefinitionsAsync(this IManagedPlanOperations operations, string resourceGroupName, string planId, string metricDefinitionId, string filter)
{
return operations.GetMetricDefinitionsAsync(resourceGroupName, planId, metricDefinitionId, filter, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <param name='metricId'>
/// Required. Your documentation here.
/// </param>
/// <param name='filter'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedPlanGetMetricsResult GetMetrics(this IManagedPlanOperations operations, string resourceGroupName, string planId, string metricId, string filter)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).GetMetricsAsync(resourceGroupName, planId, metricId, filter);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='planId'>
/// Required. Your documentation here.
/// </param>
/// <param name='metricId'>
/// Required. Your documentation here.
/// </param>
/// <param name='filter'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedPlanGetMetricsResult> GetMetricsAsync(this IManagedPlanOperations operations, string resourceGroupName, string planId, string metricId, string filter)
{
return operations.GetMetricsAsync(resourceGroupName, planId, metricId, filter, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='includeDetails'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedPlanListResult List(this IManagedPlanOperations operations, string resourceGroupName, bool includeDetails)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).ListAsync(resourceGroupName, includeDetails);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Your documentation here.
/// </param>
/// <param name='includeDetails'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedPlanListResult> ListAsync(this IManagedPlanOperations operations, string resourceGroupName, bool includeDetails)
{
return operations.ListAsync(resourceGroupName, includeDetails, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedPlanListResult ListNext(this IManagedPlanOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='nextLink'>
/// Required. Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedPlanListResult> ListNextAsync(this IManagedPlanOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='includeDetails'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static ManagedPlanListResult ListWithoutResourceGroup(this IManagedPlanOperations operations, bool includeDetails)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedPlanOperations)s).ListWithoutResourceGroupAsync(includeDetails);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Your documentation here. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedPlanOperations.
/// </param>
/// <param name='includeDetails'>
/// Required. Your documentation here.
/// </param>
/// <returns>
/// Your documentation here.
/// </returns>
public static Task<ManagedPlanListResult> ListWithoutResourceGroupAsync(this IManagedPlanOperations operations, bool includeDetails)
{
return operations.ListWithoutResourceGroupAsync(includeDetails, CancellationToken.None);
}
}
}
| |
using System.Collections.Generic;
namespace Plugin.Iconize.Fonts
{
/// <summary>
/// Defines the <see cref="FontAwesomeCollection" /> icon collection.
/// </summary>
public static class FontAwesomeCollection
{
/// <summary>
/// Gets the icons.
/// </summary>
/// <value>
/// The icons.
/// </value>
public static IList<IIcon> Icons { get; } = new List<IIcon>();
/// <summary>
/// Initializes the <see cref="FontAwesomeCollection" /> class.
/// </summary>
static FontAwesomeCollection()
{
Icons.Add("fa-500px", '\uf26e');
Icons.Add("fa-address-book", '\uf2b9');
Icons.Add("fa-address-book-o", '\uf2ba');
Icons.Add("fa-address-card", '\uf2bb');
Icons.Add("fa-address-card-o", '\uf2bc');
Icons.Add("fa-adjust", '\uf042');
Icons.Add("fa-adn", '\uf170');
Icons.Add("fa-align-center", '\uf037');
Icons.Add("fa-align-justify", '\uf039');
Icons.Add("fa-align-left", '\uf036');
Icons.Add("fa-align-right", '\uf038');
Icons.Add("fa-amazon", '\uf270');
Icons.Add("fa-ambulance", '\uf0f9');
Icons.Add("fa-american-sign-language-interpreting", '\uf2a3');
Icons.Add("fa-anchor", '\uf13d');
Icons.Add("fa-android", '\uf17b');
Icons.Add("fa-angellist", '\uf209');
Icons.Add("fa-angle-double-down", '\uf103');
Icons.Add("fa-angle-double-left", '\uf100');
Icons.Add("fa-angle-double-right", '\uf101');
Icons.Add("fa-angle-double-up", '\uf102');
Icons.Add("fa-angle-down", '\uf107');
Icons.Add("fa-angle-left", '\uf104');
Icons.Add("fa-angle-right", '\uf105');
Icons.Add("fa-angle-up", '\uf106');
Icons.Add("fa-apple", '\uf179');
Icons.Add("fa-archive", '\uf187');
Icons.Add("fa-area-chart", '\uf1fe');
Icons.Add("fa-arrow-circle-down", '\uf0ab');
Icons.Add("fa-arrow-circle-left", '\uf0a8');
Icons.Add("fa-arrow-circle-o-down", '\uf01a');
Icons.Add("fa-arrow-circle-o-left", '\uf190');
Icons.Add("fa-arrow-circle-o-right", '\uf18e');
Icons.Add("fa-arrow-circle-o-up", '\uf01b');
Icons.Add("fa-arrow-circle-right", '\uf0a9');
Icons.Add("fa-arrow-circle-up", '\uf0aa');
Icons.Add("fa-arrow-down", '\uf063');
Icons.Add("fa-arrow-left", '\uf060');
Icons.Add("fa-arrow-right", '\uf061');
Icons.Add("fa-arrow-up", '\uf062');
Icons.Add("fa-arrows", '\uf047');
Icons.Add("fa-arrows-alt", '\uf0b2');
Icons.Add("fa-arrows-h", '\uf07e');
Icons.Add("fa-arrows-v", '\uf07d');
Icons.Add("fa-asl-interpreting", '\uf2a3');
Icons.Add("fa-assistive-listening-systems", '\uf2a2');
Icons.Add("fa-asterisk", '\uf069');
Icons.Add("fa-at", '\uf1fa');
Icons.Add("fa-audio-description", '\uf29e');
Icons.Add("fa-automobile", '\uf1b9');
Icons.Add("fa-backward", '\uf04a');
Icons.Add("fa-balance-scale", '\uf24e');
Icons.Add("fa-ban", '\uf05e');
Icons.Add("fa-bandcamp", '\uf2d5');
Icons.Add("fa-bank", '\uf19c');
Icons.Add("fa-bar-chart", '\uf080');
Icons.Add("fa-bar-chart-o", '\uf080');
Icons.Add("fa-barcode", '\uf02a');
Icons.Add("fa-bars", '\uf0c9');
Icons.Add("fa-bath", '\uf2cd');
Icons.Add("fa-bathtub", '\uf2cd');
Icons.Add("fa-battery", '\uf240');
Icons.Add("fa-battery-0", '\uf244');
Icons.Add("fa-battery-1", '\uf243');
Icons.Add("fa-battery-2", '\uf242');
Icons.Add("fa-battery-3", '\uf241');
Icons.Add("fa-battery-4", '\uf240');
Icons.Add("fa-battery-empty", '\uf244');
Icons.Add("fa-battery-full", '\uf240');
Icons.Add("fa-battery-half", '\uf242');
Icons.Add("fa-battery-quarter", '\uf243');
Icons.Add("fa-battery-three-quarters", '\uf241');
Icons.Add("fa-bed", '\uf236');
Icons.Add("fa-beer", '\uf0fc');
Icons.Add("fa-behance", '\uf1b4');
Icons.Add("fa-behance-square", '\uf1b5');
Icons.Add("fa-bell", '\uf0f3');
Icons.Add("fa-bell-o", '\uf0a2');
Icons.Add("fa-bell-slash", '\uf1f6');
Icons.Add("fa-bell-slash-o", '\uf1f7');
Icons.Add("fa-bicycle", '\uf206');
Icons.Add("fa-binoculars", '\uf1e5');
Icons.Add("fa-birthday-cake", '\uf1fd');
Icons.Add("fa-bitbucket", '\uf171');
Icons.Add("fa-bitbucket-square", '\uf172');
Icons.Add("fa-bitcoin", '\uf15a');
Icons.Add("fa-black-tie", '\uf27e');
Icons.Add("fa-blind", '\uf29d');
Icons.Add("fa-bluetooth", '\uf293');
Icons.Add("fa-bluetooth-b", '\uf294');
Icons.Add("fa-bold", '\uf032');
Icons.Add("fa-bolt", '\uf0e7');
Icons.Add("fa-bomb", '\uf1e2');
Icons.Add("fa-book", '\uf02d');
Icons.Add("fa-bookmark", '\uf02e');
Icons.Add("fa-bookmark-o", '\uf097');
Icons.Add("fa-braille", '\uf2a1');
Icons.Add("fa-briefcase", '\uf0b1');
Icons.Add("fa-btc", '\uf15a');
Icons.Add("fa-bug", '\uf188');
Icons.Add("fa-building", '\uf1ad');
Icons.Add("fa-building-o", '\uf0f7');
Icons.Add("fa-bullhorn", '\uf0a1');
Icons.Add("fa-bullseye", '\uf140');
Icons.Add("fa-bus", '\uf207');
Icons.Add("fa-buysellads", '\uf20d');
Icons.Add("fa-cab", '\uf1ba');
Icons.Add("fa-calculator", '\uf1ec');
Icons.Add("fa-calendar", '\uf073');
Icons.Add("fa-calendar-check-o", '\uf274');
Icons.Add("fa-calendar-minus-o", '\uf272');
Icons.Add("fa-calendar-o", '\uf133');
Icons.Add("fa-calendar-plus-o", '\uf271');
Icons.Add("fa-calendar-times-o", '\uf273');
Icons.Add("fa-camera", '\uf030');
Icons.Add("fa-camera-retro", '\uf083');
Icons.Add("fa-car", '\uf1b9');
Icons.Add("fa-caret-down", '\uf0d7');
Icons.Add("fa-caret-left", '\uf0d9');
Icons.Add("fa-caret-right", '\uf0da');
Icons.Add("fa-caret-square-o-down", '\uf150');
Icons.Add("fa-caret-square-o-left", '\uf191');
Icons.Add("fa-caret-square-o-right", '\uf152');
Icons.Add("fa-caret-square-o-up", '\uf151');
Icons.Add("fa-caret-up", '\uf0d8');
Icons.Add("fa-cart-arrow-down", '\uf218');
Icons.Add("fa-cart-plus", '\uf217');
Icons.Add("fa-cc", '\uf20a');
Icons.Add("fa-cc-amex", '\uf1f3');
Icons.Add("fa-cc-diners-club", '\uf24c');
Icons.Add("fa-cc-discover", '\uf1f2');
Icons.Add("fa-cc-jcb", '\uf24b');
Icons.Add("fa-cc-mastercard", '\uf1f1');
Icons.Add("fa-cc-paypal", '\uf1f4');
Icons.Add("fa-cc-stripe", '\uf1f5');
Icons.Add("fa-cc-visa", '\uf1f0');
Icons.Add("fa-certificate", '\uf0a3');
Icons.Add("fa-chain", '\uf0c1');
Icons.Add("fa-chain-broken", '\uf127');
Icons.Add("fa-check", '\uf00c');
Icons.Add("fa-check-circle", '\uf058');
Icons.Add("fa-check-circle-o", '\uf05d');
Icons.Add("fa-check-square", '\uf14a');
Icons.Add("fa-check-square-o", '\uf046');
Icons.Add("fa-chevron-circle-down", '\uf13a');
Icons.Add("fa-chevron-circle-left", '\uf137');
Icons.Add("fa-chevron-circle-right", '\uf138');
Icons.Add("fa-chevron-circle-up", '\uf139');
Icons.Add("fa-chevron-down", '\uf078');
Icons.Add("fa-chevron-left", '\uf053');
Icons.Add("fa-chevron-right", '\uf054');
Icons.Add("fa-chevron-up", '\uf077');
Icons.Add("fa-child", '\uf1ae');
Icons.Add("fa-chrome", '\uf268');
Icons.Add("fa-circle", '\uf111');
Icons.Add("fa-circle-o", '\uf10c');
Icons.Add("fa-circle-o-notch", '\uf1ce');
Icons.Add("fa-circle-thin", '\uf1db');
Icons.Add("fa-clipboard", '\uf0ea');
Icons.Add("fa-clock-o", '\uf017');
Icons.Add("fa-clone", '\uf24d');
Icons.Add("fa-close", '\uf00d');
Icons.Add("fa-cloud", '\uf0c2');
Icons.Add("fa-cloud-download", '\uf0ed');
Icons.Add("fa-cloud-upload", '\uf0ee');
Icons.Add("fa-cny", '\uf157');
Icons.Add("fa-code", '\uf121');
Icons.Add("fa-code-fork", '\uf126');
Icons.Add("fa-codepen", '\uf1cb');
Icons.Add("fa-codiepie", '\uf284');
Icons.Add("fa-coffee", '\uf0f4');
Icons.Add("fa-cog", '\uf013');
Icons.Add("fa-cogs", '\uf085');
Icons.Add("fa-columns", '\uf0db');
Icons.Add("fa-comment", '\uf075');
Icons.Add("fa-comment-o", '\uf0e5');
Icons.Add("fa-commenting", '\uf27a');
Icons.Add("fa-commenting-o", '\uf27b');
Icons.Add("fa-comments", '\uf086');
Icons.Add("fa-comments-o", '\uf0e6');
Icons.Add("fa-compass", '\uf14e');
Icons.Add("fa-compress", '\uf066');
Icons.Add("fa-connectdevelop", '\uf20e');
Icons.Add("fa-contao", '\uf26d');
Icons.Add("fa-copy", '\uf0c5');
Icons.Add("fa-copyright", '\uf1f9');
Icons.Add("fa-creative-commons", '\uf25e');
Icons.Add("fa-credit-card", '\uf09d');
Icons.Add("fa-credit-card-alt", '\uf283');
Icons.Add("fa-crop", '\uf125');
Icons.Add("fa-crosshairs", '\uf05b');
Icons.Add("fa-css3", '\uf13c');
Icons.Add("fa-cube", '\uf1b2');
Icons.Add("fa-cubes", '\uf1b3');
Icons.Add("fa-cut", '\uf0c4');
Icons.Add("fa-cutlery", '\uf0f5');
Icons.Add("fa-dashboard", '\uf0e4');
Icons.Add("fa-dashcube", '\uf210');
Icons.Add("fa-database", '\uf1c0');
Icons.Add("fa-deaf", '\uf2a4');
Icons.Add("fa-deafness", '\uf2a4');
Icons.Add("fa-dedent", '\uf03b');
Icons.Add("fa-delicious", '\uf1a5');
Icons.Add("fa-desktop", '\uf108');
Icons.Add("fa-deviantart", '\uf1bd');
Icons.Add("fa-diamond", '\uf219');
Icons.Add("fa-digg", '\uf1a6');
Icons.Add("fa-dollar", '\uf155');
Icons.Add("fa-dot-circle-o", '\uf192');
Icons.Add("fa-download", '\uf019');
Icons.Add("fa-dribbble", '\uf17d');
Icons.Add("fa-drivers-license", '\uf2c2');
Icons.Add("fa-drivers-license-o", '\uf2c3');
Icons.Add("fa-dropbox", '\uf16b');
Icons.Add("fa-drupal", '\uf1a9');
Icons.Add("fa-edge", '\uf282');
Icons.Add("fa-edit", '\uf044');
Icons.Add("fa-eercast", '\uf2da');
Icons.Add("fa-eject", '\uf052');
Icons.Add("fa-ellipsis-h", '\uf141');
Icons.Add("fa-ellipsis-v", '\uf142');
Icons.Add("fa-empire", '\uf1d1');
Icons.Add("fa-envelope", '\uf0e0');
Icons.Add("fa-envelope-o", '\uf003');
Icons.Add("fa-envelope-open", '\uf2b6');
Icons.Add("fa-envelope-open-o", '\uf2b7');
Icons.Add("fa-envelope-square", '\uf199');
Icons.Add("fa-envira", '\uf299');
Icons.Add("fa-eraser", '\uf12d');
Icons.Add("fa-etsy", '\uf2d7');
Icons.Add("fa-eur", '\uf153');
Icons.Add("fa-euro", '\uf153');
Icons.Add("fa-exchange", '\uf0ec');
Icons.Add("fa-exclamation", '\uf12a');
Icons.Add("fa-exclamation-circle", '\uf06a');
Icons.Add("fa-exclamation-triangle", '\uf071');
Icons.Add("fa-expand", '\uf065');
Icons.Add("fa-expeditedssl", '\uf23e');
Icons.Add("fa-external-link", '\uf08e');
Icons.Add("fa-external-link-square", '\uf14c');
Icons.Add("fa-eye", '\uf06e');
Icons.Add("fa-eye-slash", '\uf070');
Icons.Add("fa-eyedropper", '\uf1fb');
Icons.Add("fa-fa", '\uf2b4');
Icons.Add("fa-facebook", '\uf09a');
Icons.Add("fa-facebook-f", '\uf09a');
Icons.Add("fa-facebook-official", '\uf230');
Icons.Add("fa-facebook-square", '\uf082');
Icons.Add("fa-fast-backward", '\uf049');
Icons.Add("fa-fast-forward", '\uf050');
Icons.Add("fa-fax", '\uf1ac');
Icons.Add("fa-feed", '\uf09e');
Icons.Add("fa-female", '\uf182');
Icons.Add("fa-fighter-jet", '\uf0fb');
Icons.Add("fa-file", '\uf15b');
Icons.Add("fa-file-archive-o", '\uf1c6');
Icons.Add("fa-file-audio-o", '\uf1c7');
Icons.Add("fa-file-code-o", '\uf1c9');
Icons.Add("fa-file-excel-o", '\uf1c3');
Icons.Add("fa-file-image-o", '\uf1c5');
Icons.Add("fa-file-movie-o", '\uf1c8');
Icons.Add("fa-file-o", '\uf016');
Icons.Add("fa-file-pdf-o", '\uf1c1');
Icons.Add("fa-file-photo-o", '\uf1c5');
Icons.Add("fa-file-picture-o", '\uf1c5');
Icons.Add("fa-file-powerpoint-o", '\uf1c4');
Icons.Add("fa-file-sound-o", '\uf1c7');
Icons.Add("fa-file-text", '\uf15c');
Icons.Add("fa-file-text-o", '\uf0f6');
Icons.Add("fa-file-video-o", '\uf1c8');
Icons.Add("fa-file-word-o", '\uf1c2');
Icons.Add("fa-file-zip-o", '\uf1c6');
Icons.Add("fa-files-o", '\uf0c5');
Icons.Add("fa-film", '\uf008');
Icons.Add("fa-filter", '\uf0b0');
Icons.Add("fa-fire", '\uf06d');
Icons.Add("fa-fire-extinguisher", '\uf134');
Icons.Add("fa-firefox", '\uf269');
Icons.Add("fa-first-order", '\uf2b0');
Icons.Add("fa-flag", '\uf024');
Icons.Add("fa-flag-checkered", '\uf11e');
Icons.Add("fa-flag-o", '\uf11d');
Icons.Add("fa-flash", '\uf0e7');
Icons.Add("fa-flask", '\uf0c3');
Icons.Add("fa-flickr", '\uf16e');
Icons.Add("fa-floppy-o", '\uf0c7');
Icons.Add("fa-folder", '\uf07b');
Icons.Add("fa-folder-o", '\uf114');
Icons.Add("fa-folder-open", '\uf07c');
Icons.Add("fa-folder-open-o", '\uf115');
Icons.Add("fa-font", '\uf031');
Icons.Add("fa-font-awesome", '\uf2b4');
Icons.Add("fa-fonticons", '\uf280');
Icons.Add("fa-fort-awesome", '\uf286');
Icons.Add("fa-forumbee", '\uf211');
Icons.Add("fa-forward", '\uf04e');
Icons.Add("fa-foursquare", '\uf180');
Icons.Add("fa-free-code-camp", '\uf2c5');
Icons.Add("fa-frown-o", '\uf119');
Icons.Add("fa-futbol-o", '\uf1e3');
Icons.Add("fa-gamepad", '\uf11b');
Icons.Add("fa-gavel", '\uf0e3');
Icons.Add("fa-gbp", '\uf154');
Icons.Add("fa-ge", '\uf1d1');
Icons.Add("fa-gear", '\uf013');
Icons.Add("fa-gears", '\uf085');
Icons.Add("fa-genderless", '\uf22d');
Icons.Add("fa-get-pocket", '\uf265');
Icons.Add("fa-gg", '\uf260');
Icons.Add("fa-gg-circle", '\uf261');
Icons.Add("fa-gift", '\uf06b');
Icons.Add("fa-git", '\uf1d3');
Icons.Add("fa-git-square", '\uf1d2');
Icons.Add("fa-github", '\uf09b');
Icons.Add("fa-github-alt", '\uf113');
Icons.Add("fa-github-square", '\uf092');
Icons.Add("fa-gitlab", '\uf296');
Icons.Add("fa-gittip", '\uf184');
Icons.Add("fa-glass", '\uf000');
Icons.Add("fa-glide", '\uf2a5');
Icons.Add("fa-glide-g", '\uf2a6');
Icons.Add("fa-globe", '\uf0ac');
Icons.Add("fa-google", '\uf1a0');
Icons.Add("fa-google-plus", '\uf0d5');
Icons.Add("fa-google-plus-circle", '\uf2b3');
Icons.Add("fa-google-plus-official", '\uf2b3');
Icons.Add("fa-google-plus-square", '\uf0d4');
Icons.Add("fa-google-wallet", '\uf1ee');
Icons.Add("fa-graduation-cap", '\uf19d');
Icons.Add("fa-gratipay", '\uf184');
Icons.Add("fa-grav", '\uf2d6');
Icons.Add("fa-group", '\uf0c0');
Icons.Add("fa-h-square", '\uf0fd');
Icons.Add("fa-hacker-news", '\uf1d4');
Icons.Add("fa-hand-grab-o", '\uf255');
Icons.Add("fa-hand-lizard-o", '\uf258');
Icons.Add("fa-hand-o-down", '\uf0a7');
Icons.Add("fa-hand-o-left", '\uf0a5');
Icons.Add("fa-hand-o-right", '\uf0a4');
Icons.Add("fa-hand-o-up", '\uf0a6');
Icons.Add("fa-hand-paper-o", '\uf256');
Icons.Add("fa-hand-peace-o", '\uf25b');
Icons.Add("fa-hand-pointer-o", '\uf25a');
Icons.Add("fa-hand-rock-o", '\uf255');
Icons.Add("fa-hand-scissors-o", '\uf257');
Icons.Add("fa-hand-spock-o", '\uf259');
Icons.Add("fa-hand-stop-o", '\uf256');
Icons.Add("fa-handshake-o", '\uf2b5');
Icons.Add("fa-hard-of-hearing", '\uf2a4');
Icons.Add("fa-hashtag", '\uf292');
Icons.Add("fa-hdd-o", '\uf0a0');
Icons.Add("fa-header", '\uf1dc');
Icons.Add("fa-headphones", '\uf025');
Icons.Add("fa-heart", '\uf004');
Icons.Add("fa-heart-o", '\uf08a');
Icons.Add("fa-heartbeat", '\uf21e');
Icons.Add("fa-history", '\uf1da');
Icons.Add("fa-home", '\uf015');
Icons.Add("fa-hospital-o", '\uf0f8');
Icons.Add("fa-hotel", '\uf236');
Icons.Add("fa-hourglass", '\uf254');
Icons.Add("fa-hourglass-1", '\uf251');
Icons.Add("fa-hourglass-2", '\uf252');
Icons.Add("fa-hourglass-3", '\uf253');
Icons.Add("fa-hourglass-end", '\uf253');
Icons.Add("fa-hourglass-half", '\uf252');
Icons.Add("fa-hourglass-o", '\uf250');
Icons.Add("fa-hourglass-start", '\uf251');
Icons.Add("fa-houzz", '\uf27c');
Icons.Add("fa-html5", '\uf13b');
Icons.Add("fa-i-cursor", '\uf246');
Icons.Add("fa-id-badge", '\uf2c1');
Icons.Add("fa-id-card", '\uf2c2');
Icons.Add("fa-id-card-o", '\uf2c3');
Icons.Add("fa-ils", '\uf20b');
Icons.Add("fa-image", '\uf03e');
Icons.Add("fa-imdb", '\uf2d8');
Icons.Add("fa-inbox", '\uf01c');
Icons.Add("fa-indent", '\uf03c');
Icons.Add("fa-industry", '\uf275');
Icons.Add("fa-info", '\uf129');
Icons.Add("fa-info-circle", '\uf05a');
Icons.Add("fa-inr", '\uf156');
Icons.Add("fa-instagram", '\uf16d');
Icons.Add("fa-institution", '\uf19c');
Icons.Add("fa-internet-explorer", '\uf26b');
Icons.Add("fa-intersex", '\uf224');
Icons.Add("fa-ioxhost", '\uf208');
Icons.Add("fa-italic", '\uf033');
Icons.Add("fa-joomla", '\uf1aa');
Icons.Add("fa-jpy", '\uf157');
Icons.Add("fa-jsfiddle", '\uf1cc');
Icons.Add("fa-key", '\uf084');
Icons.Add("fa-keyboard-o", '\uf11c');
Icons.Add("fa-krw", '\uf159');
Icons.Add("fa-language", '\uf1ab');
Icons.Add("fa-laptop", '\uf109');
Icons.Add("fa-lastfm", '\uf202');
Icons.Add("fa-lastfm-square", '\uf203');
Icons.Add("fa-leaf", '\uf06c');
Icons.Add("fa-leanpub", '\uf212');
Icons.Add("fa-legal", '\uf0e3');
Icons.Add("fa-lemon-o", '\uf094');
Icons.Add("fa-level-down", '\uf149');
Icons.Add("fa-level-up", '\uf148');
Icons.Add("fa-life-bouy", '\uf1cd');
Icons.Add("fa-life-buoy", '\uf1cd');
Icons.Add("fa-life-ring", '\uf1cd');
Icons.Add("fa-life-saver", '\uf1cd');
Icons.Add("fa-lightbulb-o", '\uf0eb');
Icons.Add("fa-line-chart", '\uf201');
Icons.Add("fa-link", '\uf0c1');
Icons.Add("fa-linkedin", '\uf0e1');
Icons.Add("fa-linkedin-square", '\uf08c');
Icons.Add("fa-linode", '\uf2b8');
Icons.Add("fa-linux", '\uf17c');
Icons.Add("fa-list", '\uf03a');
Icons.Add("fa-list-alt", '\uf022');
Icons.Add("fa-list-ol", '\uf0cb');
Icons.Add("fa-list-ul", '\uf0ca');
Icons.Add("fa-location-arrow", '\uf124');
Icons.Add("fa-lock", '\uf023');
Icons.Add("fa-long-arrow-down", '\uf175');
Icons.Add("fa-long-arrow-left", '\uf177');
Icons.Add("fa-long-arrow-right", '\uf178');
Icons.Add("fa-long-arrow-up", '\uf176');
Icons.Add("fa-low-vision", '\uf2a8');
Icons.Add("fa-magic", '\uf0d0');
Icons.Add("fa-magnet", '\uf076');
Icons.Add("fa-mail-forward", '\uf064');
Icons.Add("fa-mail-reply", '\uf112');
Icons.Add("fa-mail-reply-all", '\uf122');
Icons.Add("fa-male", '\uf183');
Icons.Add("fa-map", '\uf279');
Icons.Add("fa-map-marker", '\uf041');
Icons.Add("fa-map-o", '\uf278');
Icons.Add("fa-map-pin", '\uf276');
Icons.Add("fa-map-signs", '\uf277');
Icons.Add("fa-mars", '\uf222');
Icons.Add("fa-mars-double", '\uf227');
Icons.Add("fa-mars-stroke", '\uf229');
Icons.Add("fa-mars-stroke-h", '\uf22b');
Icons.Add("fa-mars-stroke-v", '\uf22a');
Icons.Add("fa-maxcdn", '\uf136');
Icons.Add("fa-meanpath", '\uf20c');
Icons.Add("fa-medium", '\uf23a');
Icons.Add("fa-medkit", '\uf0fa');
Icons.Add("fa-meetup", '\uf2e0');
Icons.Add("fa-meh-o", '\uf11a');
Icons.Add("fa-mercury", '\uf223');
Icons.Add("fa-microchip", '\uf2db');
Icons.Add("fa-microphone", '\uf130');
Icons.Add("fa-microphone-slash", '\uf131');
Icons.Add("fa-minus", '\uf068');
Icons.Add("fa-minus-circle", '\uf056');
Icons.Add("fa-minus-square", '\uf146');
Icons.Add("fa-minus-square-o", '\uf147');
Icons.Add("fa-mixcloud", '\uf289');
Icons.Add("fa-mobile", '\uf10b');
Icons.Add("fa-mobile-phone", '\uf10b');
Icons.Add("fa-modx", '\uf285');
Icons.Add("fa-money", '\uf0d6');
Icons.Add("fa-moon-o", '\uf186');
Icons.Add("fa-mortar-board", '\uf19d');
Icons.Add("fa-motorcycle", '\uf21c');
Icons.Add("fa-mouse-pointer", '\uf245');
Icons.Add("fa-music", '\uf001');
Icons.Add("fa-navicon", '\uf0c9');
Icons.Add("fa-neuter", '\uf22c');
Icons.Add("fa-newspaper-o", '\uf1ea');
Icons.Add("fa-object-group", '\uf247');
Icons.Add("fa-object-ungroup", '\uf248');
Icons.Add("fa-odnoklassniki", '\uf263');
Icons.Add("fa-odnoklassniki-square", '\uf264');
Icons.Add("fa-opencart", '\uf23d');
Icons.Add("fa-openid", '\uf19b');
Icons.Add("fa-opera", '\uf26a');
Icons.Add("fa-optin-monster", '\uf23c');
Icons.Add("fa-outdent", '\uf03b');
Icons.Add("fa-pagelines", '\uf18c');
Icons.Add("fa-paint-brush", '\uf1fc');
Icons.Add("fa-paper-plane", '\uf1d8');
Icons.Add("fa-paper-plane-o", '\uf1d9');
Icons.Add("fa-paperclip", '\uf0c6');
Icons.Add("fa-paragraph", '\uf1dd');
Icons.Add("fa-paste", '\uf0ea');
Icons.Add("fa-pause", '\uf04c');
Icons.Add("fa-pause-circle", '\uf28b');
Icons.Add("fa-pause-circle-o", '\uf28c');
Icons.Add("fa-paw", '\uf1b0');
Icons.Add("fa-paypal", '\uf1ed');
Icons.Add("fa-pencil", '\uf040');
Icons.Add("fa-pencil-square", '\uf14b');
Icons.Add("fa-pencil-square-o", '\uf044');
Icons.Add("fa-percent", '\uf295');
Icons.Add("fa-phone", '\uf095');
Icons.Add("fa-phone-square", '\uf098');
Icons.Add("fa-photo", '\uf03e');
Icons.Add("fa-picture-o", '\uf03e');
Icons.Add("fa-pie-chart", '\uf200');
Icons.Add("fa-pied-piper", '\uf2ae');
Icons.Add("fa-pied-piper-alt", '\uf1a8');
Icons.Add("fa-pied-piper-pp", '\uf1a7');
Icons.Add("fa-pinterest", '\uf0d2');
Icons.Add("fa-pinterest-p", '\uf231');
Icons.Add("fa-pinterest-square", '\uf0d3');
Icons.Add("fa-plane", '\uf072');
Icons.Add("fa-play", '\uf04b');
Icons.Add("fa-play-circle", '\uf144');
Icons.Add("fa-play-circle-o", '\uf01d');
Icons.Add("fa-plug", '\uf1e6');
Icons.Add("fa-plus", '\uf067');
Icons.Add("fa-plus-circle", '\uf055');
Icons.Add("fa-plus-square", '\uf0fe');
Icons.Add("fa-plus-square-o", '\uf196');
Icons.Add("fa-podcast", '\uf2ce');
Icons.Add("fa-power-off", '\uf011');
Icons.Add("fa-print", '\uf02f');
Icons.Add("fa-product-hunt", '\uf288');
Icons.Add("fa-puzzle-piece", '\uf12e');
Icons.Add("fa-qq", '\uf1d6');
Icons.Add("fa-qrcode", '\uf029');
Icons.Add("fa-question", '\uf128');
Icons.Add("fa-question-circle", '\uf059');
Icons.Add("fa-question-circle-o", '\uf29c');
Icons.Add("fa-quora", '\uf2c4');
Icons.Add("fa-quote-left", '\uf10d');
Icons.Add("fa-quote-right", '\uf10e');
Icons.Add("fa-ra", '\uf1d0');
Icons.Add("fa-random", '\uf074');
Icons.Add("fa-ravelry", '\uf2d9');
Icons.Add("fa-rebel", '\uf1d0');
Icons.Add("fa-recycle", '\uf1b8');
Icons.Add("fa-reddit", '\uf1a1');
Icons.Add("fa-reddit-alien", '\uf281');
Icons.Add("fa-reddit-square", '\uf1a2');
Icons.Add("fa-refresh", '\uf021');
Icons.Add("fa-registered", '\uf25d');
Icons.Add("fa-remove", '\uf00d');
Icons.Add("fa-renren", '\uf18b');
Icons.Add("fa-reorder", '\uf0c9');
Icons.Add("fa-repeat", '\uf01e');
Icons.Add("fa-reply", '\uf112');
Icons.Add("fa-reply-all", '\uf122');
Icons.Add("fa-resistance", '\uf1d0');
Icons.Add("fa-retweet", '\uf079');
Icons.Add("fa-rmb", '\uf157');
Icons.Add("fa-road", '\uf018');
Icons.Add("fa-rocket", '\uf135');
Icons.Add("fa-rotate-left", '\uf0e2');
Icons.Add("fa-rotate-right", '\uf01e');
Icons.Add("fa-rouble", '\uf158');
Icons.Add("fa-rss", '\uf09e');
Icons.Add("fa-rss-square", '\uf143');
Icons.Add("fa-rub", '\uf158');
Icons.Add("fa-ruble", '\uf158');
Icons.Add("fa-rupee", '\uf156');
Icons.Add("fa-s15", '\uf2cd');
Icons.Add("fa-safari", '\uf267');
Icons.Add("fa-save", '\uf0c7');
Icons.Add("fa-scissors", '\uf0c4');
Icons.Add("fa-scribd", '\uf28a');
Icons.Add("fa-search", '\uf002');
Icons.Add("fa-search-minus", '\uf010');
Icons.Add("fa-search-plus", '\uf00e');
Icons.Add("fa-sellsy", '\uf213');
Icons.Add("fa-send", '\uf1d8');
Icons.Add("fa-send-o", '\uf1d9');
Icons.Add("fa-server", '\uf233');
Icons.Add("fa-share", '\uf064');
Icons.Add("fa-share-alt", '\uf1e0');
Icons.Add("fa-share-alt-square", '\uf1e1');
Icons.Add("fa-share-square", '\uf14d');
Icons.Add("fa-share-square-o", '\uf045');
Icons.Add("fa-shekel", '\uf20b');
Icons.Add("fa-sheqel", '\uf20b');
Icons.Add("fa-shield", '\uf132');
Icons.Add("fa-ship", '\uf21a');
Icons.Add("fa-shirtsinbulk", '\uf214');
Icons.Add("fa-shopping-bag", '\uf290');
Icons.Add("fa-shopping-basket", '\uf291');
Icons.Add("fa-shopping-cart", '\uf07a');
Icons.Add("fa-shower", '\uf2cc');
Icons.Add("fa-sign-in", '\uf090');
Icons.Add("fa-sign-language", '\uf2a7');
Icons.Add("fa-sign-out", '\uf08b');
Icons.Add("fa-signal", '\uf012');
Icons.Add("fa-signing", '\uf2a7');
Icons.Add("fa-simplybuilt", '\uf215');
Icons.Add("fa-sitemap", '\uf0e8');
Icons.Add("fa-skyatlas", '\uf216');
Icons.Add("fa-skype", '\uf17e');
Icons.Add("fa-slack", '\uf198');
Icons.Add("fa-sliders", '\uf1de');
Icons.Add("fa-slideshare", '\uf1e7');
Icons.Add("fa-smile-o", '\uf118');
Icons.Add("fa-snapchat", '\uf2ab');
Icons.Add("fa-snapchat-ghost", '\uf2ac');
Icons.Add("fa-snapchat-square", '\uf2ad');
Icons.Add("fa-snowflake-o", '\uf2dc');
Icons.Add("fa-soccer-ball-o", '\uf1e3');
Icons.Add("fa-sort", '\uf0dc');
Icons.Add("fa-sort-alpha-asc", '\uf15d');
Icons.Add("fa-sort-alpha-desc", '\uf15e');
Icons.Add("fa-sort-amount-asc", '\uf160');
Icons.Add("fa-sort-amount-desc", '\uf161');
Icons.Add("fa-sort-asc", '\uf0de');
Icons.Add("fa-sort-desc", '\uf0dd');
Icons.Add("fa-sort-down", '\uf0dd');
Icons.Add("fa-sort-numeric-asc", '\uf162');
Icons.Add("fa-sort-numeric-desc", '\uf163');
Icons.Add("fa-sort-up", '\uf0de');
Icons.Add("fa-soundcloud", '\uf1be');
Icons.Add("fa-space-shuttle", '\uf197');
Icons.Add("fa-spinner", '\uf110');
Icons.Add("fa-spoon", '\uf1b1');
Icons.Add("fa-spotify", '\uf1bc');
Icons.Add("fa-square", '\uf0c8');
Icons.Add("fa-square-o", '\uf096');
Icons.Add("fa-stack-exchange", '\uf18d');
Icons.Add("fa-stack-overflow", '\uf16c');
Icons.Add("fa-star", '\uf005');
Icons.Add("fa-star-half", '\uf089');
Icons.Add("fa-star-half-empty", '\uf123');
Icons.Add("fa-star-half-full", '\uf123');
Icons.Add("fa-star-half-o", '\uf123');
Icons.Add("fa-star-o", '\uf006');
Icons.Add("fa-steam", '\uf1b6');
Icons.Add("fa-steam-square", '\uf1b7');
Icons.Add("fa-step-backward", '\uf048');
Icons.Add("fa-step-forward", '\uf051');
Icons.Add("fa-stethoscope", '\uf0f1');
Icons.Add("fa-sticky-note", '\uf249');
Icons.Add("fa-sticky-note-o", '\uf24a');
Icons.Add("fa-stop", '\uf04d');
Icons.Add("fa-stop-circle", '\uf28d');
Icons.Add("fa-stop-circle-o", '\uf28e');
Icons.Add("fa-street-view", '\uf21d');
Icons.Add("fa-strikethrough", '\uf0cc');
Icons.Add("fa-stumbleupon", '\uf1a4');
Icons.Add("fa-stumbleupon-circle", '\uf1a3');
Icons.Add("fa-subscript", '\uf12c');
Icons.Add("fa-subway", '\uf239');
Icons.Add("fa-suitcase", '\uf0f2');
Icons.Add("fa-sun-o", '\uf185');
Icons.Add("fa-superpowers", '\uf2dd');
Icons.Add("fa-superscript", '\uf12b');
Icons.Add("fa-support", '\uf1cd');
Icons.Add("fa-table", '\uf0ce');
Icons.Add("fa-tablet", '\uf10a');
Icons.Add("fa-tachometer", '\uf0e4');
Icons.Add("fa-tag", '\uf02b');
Icons.Add("fa-tags", '\uf02c');
Icons.Add("fa-tasks", '\uf0ae');
Icons.Add("fa-taxi", '\uf1ba');
Icons.Add("fa-telegram", '\uf2c6');
Icons.Add("fa-television", '\uf26c');
Icons.Add("fa-tencent-weibo", '\uf1d5');
Icons.Add("fa-terminal", '\uf120');
Icons.Add("fa-text-height", '\uf034');
Icons.Add("fa-text-width", '\uf035');
Icons.Add("fa-th", '\uf00a');
Icons.Add("fa-th-large", '\uf009');
Icons.Add("fa-th-list", '\uf00b');
Icons.Add("fa-themeisle", '\uf2b2');
Icons.Add("fa-thermometer", '\uf2c7');
Icons.Add("fa-thermometer-0", '\uf2cb');
Icons.Add("fa-thermometer-1", '\uf2ca');
Icons.Add("fa-thermometer-2", '\uf2c9');
Icons.Add("fa-thermometer-3", '\uf2c8');
Icons.Add("fa-thermometer-4", '\uf2c7');
Icons.Add("fa-thermometer-empty", '\uf2cb');
Icons.Add("fa-thermometer-full", '\uf2c7');
Icons.Add("fa-thermometer-half", '\uf2c9');
Icons.Add("fa-thermometer-quarter", '\uf2ca');
Icons.Add("fa-thermometer-three-quarters", '\uf2c8');
Icons.Add("fa-thumb-tack", '\uf08d');
Icons.Add("fa-thumbs-down", '\uf165');
Icons.Add("fa-thumbs-o-down", '\uf088');
Icons.Add("fa-thumbs-o-up", '\uf087');
Icons.Add("fa-thumbs-up", '\uf164');
Icons.Add("fa-ticket", '\uf145');
Icons.Add("fa-times", '\uf00d');
Icons.Add("fa-times-circle", '\uf057');
Icons.Add("fa-times-circle-o", '\uf05c');
Icons.Add("fa-times-rectangle", '\uf2d3');
Icons.Add("fa-times-rectangle-o", '\uf2d4');
Icons.Add("fa-tint", '\uf043');
Icons.Add("fa-toggle-down", '\uf150');
Icons.Add("fa-toggle-left", '\uf191');
Icons.Add("fa-toggle-off", '\uf204');
Icons.Add("fa-toggle-on", '\uf205');
Icons.Add("fa-toggle-right", '\uf152');
Icons.Add("fa-toggle-up", '\uf151');
Icons.Add("fa-trademark", '\uf25c');
Icons.Add("fa-train", '\uf238');
Icons.Add("fa-transgender", '\uf224');
Icons.Add("fa-transgender-alt", '\uf225');
Icons.Add("fa-trash", '\uf1f8');
Icons.Add("fa-trash-o", '\uf014');
Icons.Add("fa-tree", '\uf1bb');
Icons.Add("fa-trello", '\uf181');
Icons.Add("fa-tripadvisor", '\uf262');
Icons.Add("fa-trophy", '\uf091');
Icons.Add("fa-truck", '\uf0d1');
Icons.Add("fa-try", '\uf195');
Icons.Add("fa-tty", '\uf1e4');
Icons.Add("fa-tumblr", '\uf173');
Icons.Add("fa-tumblr-square", '\uf174');
Icons.Add("fa-turkish-lira", '\uf195');
Icons.Add("fa-tv", '\uf26c');
Icons.Add("fa-twitch", '\uf1e8');
Icons.Add("fa-twitter", '\uf099');
Icons.Add("fa-twitter-square", '\uf081');
Icons.Add("fa-umbrella", '\uf0e9');
Icons.Add("fa-underline", '\uf0cd');
Icons.Add("fa-undo", '\uf0e2');
Icons.Add("fa-universal-access", '\uf29a');
Icons.Add("fa-university", '\uf19c');
Icons.Add("fa-unlink", '\uf127');
Icons.Add("fa-unlock", '\uf09c');
Icons.Add("fa-unlock-alt", '\uf13e');
Icons.Add("fa-unsorted", '\uf0dc');
Icons.Add("fa-upload", '\uf093');
Icons.Add("fa-usb", '\uf287');
Icons.Add("fa-usd", '\uf155');
Icons.Add("fa-user", '\uf007');
Icons.Add("fa-user-circle", '\uf2bd');
Icons.Add("fa-user-circle-o", '\uf2be');
Icons.Add("fa-user-md", '\uf0f0');
Icons.Add("fa-user-o", '\uf2c0');
Icons.Add("fa-user-plus", '\uf234');
Icons.Add("fa-user-secret", '\uf21b');
Icons.Add("fa-user-times", '\uf235');
Icons.Add("fa-users", '\uf0c0');
Icons.Add("fa-vcard", '\uf2bb');
Icons.Add("fa-vcard-o", '\uf2bc');
Icons.Add("fa-venus", '\uf221');
Icons.Add("fa-venus-double", '\uf226');
Icons.Add("fa-venus-mars", '\uf228');
Icons.Add("fa-viacoin", '\uf237');
Icons.Add("fa-viadeo", '\uf2a9');
Icons.Add("fa-viadeo-square", '\uf2aa');
Icons.Add("fa-video-camera", '\uf03d');
Icons.Add("fa-vimeo", '\uf27d');
Icons.Add("fa-vimeo-square", '\uf194');
Icons.Add("fa-vine", '\uf1ca');
Icons.Add("fa-vk", '\uf189');
Icons.Add("fa-volume-control-phone", '\uf2a0');
Icons.Add("fa-volume-down", '\uf027');
Icons.Add("fa-volume-off", '\uf026');
Icons.Add("fa-volume-up", '\uf028');
Icons.Add("fa-warning", '\uf071');
Icons.Add("fa-wechat", '\uf1d7');
Icons.Add("fa-weibo", '\uf18a');
Icons.Add("fa-weixin", '\uf1d7');
Icons.Add("fa-whatsapp", '\uf232');
Icons.Add("fa-wheelchair", '\uf193');
Icons.Add("fa-wheelchair-alt", '\uf29b');
Icons.Add("fa-wifi", '\uf1eb');
Icons.Add("fa-wikipedia-w", '\uf266');
Icons.Add("fa-window-close", '\uf2d3');
Icons.Add("fa-window-close-o", '\uf2d4');
Icons.Add("fa-window-maximize", '\uf2d0');
Icons.Add("fa-window-minimize", '\uf2d1');
Icons.Add("fa-window-restore", '\uf2d2');
Icons.Add("fa-windows", '\uf17a');
Icons.Add("fa-won", '\uf159');
Icons.Add("fa-wordpress", '\uf19a');
Icons.Add("fa-wpbeginner", '\uf297');
Icons.Add("fa-wpexplorer", '\uf2de');
Icons.Add("fa-wpforms", '\uf298');
Icons.Add("fa-wrench", '\uf0ad');
Icons.Add("fa-xing", '\uf168');
Icons.Add("fa-xing-square", '\uf169');
Icons.Add("fa-y-combinator", '\uf23b');
Icons.Add("fa-y-combinator-square", '\uf1d4');
Icons.Add("fa-yahoo", '\uf19e');
Icons.Add("fa-yc", '\uf23b');
Icons.Add("fa-yc-square", '\uf1d4');
Icons.Add("fa-yelp", '\uf1e9');
Icons.Add("fa-yen", '\uf157');
Icons.Add("fa-yoast", '\uf2b1');
Icons.Add("fa-youtube", '\uf167');
Icons.Add("fa-youtube-play", '\uf16a');
Icons.Add("fa-youtube-square", '\uf166');
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Text.RegularExpressions;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.World.AutoBackup
{
/// <summary>
/// Choose between ways of naming the backup files that are generated.
/// </summary>
/// <remarks>Time: OARs are named by a timestamp.
/// Sequential: OARs are named by counting (Region_1.oar, Region_2.oar, etc.)
/// Overwrite: Only one file per region is created; it's overwritten each time a backup is made.</remarks>
public enum NamingType
{
Time,
Sequential,
Overwrite
}
///<summary>
/// AutoBackupModule: save OAR region backups to disk periodically
/// </summary>
/// <remarks>
/// Config Settings Documentation.
/// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini.
/// If specified in Regions.ini, the settings should be within the region's section name.
/// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section.
/// Region-specific settings take precedence.
///
/// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
/// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
/// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
/// This is the only required option for enabling auto-backup; the other options have sane defaults.
/// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
/// If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality.
/// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
/// The number of minutes between each backup attempt.
/// If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
/// AutoBackupBusyCheck: True/False. Default: True.
/// If True, we will only take an auto-backup if a set of conditions are met.
/// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
/// AutoBackupSkipAssets
/// If true, assets are not saved to the oar file. Considerably reduces impact on simulator when backing up. Intended for when assets db is backed up separately
/// AutoBackupKeepFilesForDays
/// Backup files older than this value (in days) are deleted during the current backup process, 0 will disable this and keep all backup files indefinitely
/// AutoBackupScript: String. Default: not specified (disabled).
/// File path to an executable script or binary to run when an automatic backup is taken.
/// The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary.
/// Trying to "run" directories, or things with weird file associations on Win32, might cause unexpected results!
/// argv[1] of the executed file/script will be the file name of the generated OAR.
/// If the process can't be spawned for some reason (file not found, no execute permission, etc), write a warning to the console.
/// AutoBackupNaming: string. Default: Time.
/// One of three strings (case insensitive):
/// "Time": Current timestamp is appended to file name. An existing file will never be overwritten.
/// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
/// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
/// AutoBackupDir: String. Default: "." (the current directory).
/// A directory (absolute or relative) where backups should be saved.
/// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
/// If the time dilation is below this value, don't take a backup right now.
/// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
/// If the number of agents is greater than this value, don't take a backup right now
/// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
/// Also helps if you don't want AutoBackup at all.
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")]
public class AutoBackupModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Dictionary<Guid, IScene> m_pendingSaves = new Dictionary<Guid, IScene>(1);
private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
private readonly Dictionary<IScene, AutoBackupModuleState> m_states =
new Dictionary<IScene, AutoBackupModuleState>(1);
private readonly Dictionary<Timer, List<IScene>> m_timerMap =
new Dictionary<Timer, List<IScene>>(1);
private readonly Dictionary<double, Timer> m_timers = new Dictionary<double, Timer>(1);
private delegate T DefaultGetter<T>(string settingName, T defaultValue);
private bool m_enabled;
private ICommandConsole m_console;
private List<Scene> m_Scenes = new List<Scene> ();
/// <summary>
/// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
/// </summary>
private bool m_closed;
private IConfigSource m_configSource;
/// <summary>
/// Required by framework.
/// </summary>
public bool IsSharedModule
{
get { return true; }
}
#region ISharedRegionModule Members
/// <summary>
/// Identifies the module to the system.
/// </summary>
string IRegionModuleBase.Name
{
get { return "AutoBackupModule"; }
}
/// <summary>
/// We don't implement an interface, this is a single-use module.
/// </summary>
Type IRegionModuleBase.ReplaceableInterface
{
get { return null; }
}
/// <summary>
/// Called once in the lifetime of the module at startup.
/// </summary>
/// <param name="source">The input config source for OpenSim.ini.</param>
void IRegionModuleBase.Initialise(IConfigSource source)
{
// Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
this.m_configSource = source;
IConfig moduleConfig = source.Configs["AutoBackupModule"];
if (moduleConfig == null)
{
this.m_enabled = false;
return;
}
else
{
this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
if (this.m_enabled)
{
m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
}
else
{
return;
}
}
Timer defTimer = new Timer(43200000);
this.m_defaultState.Timer = defTimer;
this.m_timers.Add(43200000, defTimer);
defTimer.Elapsed += this.HandleElapsed;
defTimer.AutoReset = true;
defTimer.Start();
AutoBackupModuleState abms = this.ParseConfig(null, true);
m_log.Debug("[AUTO BACKUP]: Here is the default config:");
m_log.Debug(abms.ToString());
}
/// <summary>
/// Called once at de-init (sim shutting down).
/// </summary>
void IRegionModuleBase.Close()
{
if (!this.m_enabled)
{
return;
}
// We don't want any timers firing while the sim's coming down; strange things may happen.
this.StopAllTimers();
}
/// <summary>
/// Currently a no-op for AutoBackup because we have to wait for region to be fully loaded.
/// </summary>
/// <param name="scene"></param>
void IRegionModuleBase.AddRegion (Scene scene)
{
if (!this.m_enabled) {
return;
}
lock (m_Scenes) {
m_Scenes.Add (scene);
}
m_console = MainConsole.Instance;
m_console.Commands.AddCommand (
"AutoBackup", false, "dobackup",
"dobackup",
"do backup.", DoBackup);
}
/// <summary>
/// Here we just clean up some resources and stop the OAR backup (if any) for the given scene.
/// </summary>
/// <param name="scene">The scene (region) to stop performing AutoBackup on.</param>
void IRegionModuleBase.RemoveRegion(Scene scene)
{
if (!this.m_enabled)
{
return;
}
m_Scenes.Remove (scene);
if (this.m_states.ContainsKey(scene))
{
AutoBackupModuleState abms = this.m_states[scene];
// Remove this scene out of the timer map list
Timer timer = abms.Timer;
List<IScene> list = this.m_timerMap[timer];
list.Remove(scene);
// Shut down the timer if this was the last scene for the timer
if (list.Count == 0)
{
this.m_timerMap.Remove(timer);
this.m_timers.Remove(timer.Interval);
timer.Close();
}
this.m_states.Remove(scene);
}
}
/// <summary>
/// Most interesting/complex code paths in AutoBackup begin here.
/// We read lots of Nini config, maybe set a timer, add members to state tracking Dictionaries, etc.
/// </summary>
/// <param name="scene">The scene to (possibly) perform AutoBackup on.</param>
void IRegionModuleBase.RegionLoaded(Scene scene)
{
if (!this.m_enabled)
{
return;
}
// This really ought not to happen, but just in case, let's pretend it didn't...
if (scene == null)
{
return;
}
AutoBackupModuleState abms = this.ParseConfig(scene, false);
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
m_states.Add(scene, abms);
}
/// <summary>
/// Currently a no-op.
/// </summary>
void ISharedRegionModule.PostInitialise()
{
}
#endregion
private void DoBackup (string module, string[] args)
{
if (args.Length != 2) {
MainConsole.Instance.OutputFormat ("Usage: dobackup <regionname>");
return;
}
bool found = false;
string name = args [1];
lock (m_Scenes) {
foreach (Scene s in m_Scenes) {
string test = s.Name.ToString ();
if (test == name) {
found = true;
DoRegionBackup (s);
}
}
if (!found) {
MainConsole.Instance.OutputFormat ("No such region {0}. Nothing to backup", name);
}
}
}
/// <summary>
/// Set up internal state for a given scene. Fairly complex code.
/// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene.
/// </summary>
/// <param name="scene">The scene to look at.</param>
/// <param name="parseDefault">Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).</param>
/// <returns>An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.</returns>
private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
{
string sRegionName;
string sRegionLabel;
// string prepend;
AutoBackupModuleState state;
if (parseDefault)
{
sRegionName = null;
sRegionLabel = "DEFAULT";
// prepend = "";
state = this.m_defaultState;
}
else
{
sRegionName = scene.RegionInfo.RegionName;
sRegionLabel = sRegionName;
// prepend = sRegionName + ".";
state = null;
}
// Read the config settings and set variables.
IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
IConfig config = this.m_configSource.Configs["AutoBackupModule"];
if (config == null)
{
// defaultState would be disabled too if the section doesn't exist.
state = this.m_defaultState;
return state;
}
bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
if (state == null && tmpEnabled != this.m_defaultState.Enabled)
//Varies from default state
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Enabled = tmpEnabled;
}
// If you don't want AutoBackup, we stop.
if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
{
return state;
}
else
{
m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
}
// Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
double interval =
this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
config, regionConfig) * 60000.0;
if (state == null && interval != this.m_defaultState.IntervalMinutes * 60000.0)
{
state = new AutoBackupModuleState();
}
if (this.m_timers.ContainsKey(interval))
{
if (state != null)
{
state.Timer = this.m_timers[interval];
}
m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
sRegionLabel);
}
else
{
// 0 or negative interval == do nothing.
if (interval <= 0.0 && state != null)
{
state.Enabled = false;
return state;
}
if (state == null)
{
state = new AutoBackupModuleState();
}
Timer tim = new Timer(interval);
state.Timer = tim;
//Milliseconds -> minutes
this.m_timers.Add(interval, tim);
tim.Elapsed += this.HandleElapsed;
tim.AutoReset = true;
tim.Start();
}
// Add the current region to the list of regions tied to this timer.
if (scene != null)
{
if (state != null)
{
if (this.m_timerMap.ContainsKey(state.Timer))
{
this.m_timerMap[state.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(state.Timer, scns);
}
}
else
{
if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
{
this.m_timerMap[this.m_defaultState.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(this.m_defaultState.Timer, scns);
}
}
}
bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
this.m_defaultState.BusyCheck, config, regionConfig);
if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BusyCheck = tmpBusyCheck;
}
// Included Option To Skip Assets
bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
this.m_defaultState.SkipAssets, config, regionConfig);
if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.SkipAssets = tmpSkipAssets;
}
// How long to keep backup files in days, 0 Disables this feature
int tmpKeepFilesForDays = ResolveInt("AutoBackupKeepFilesForDays",
this.m_defaultState.KeepFilesForDays, config, regionConfig);
if (state == null && tmpKeepFilesForDays != this.m_defaultState.KeepFilesForDays)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.KeepFilesForDays = tmpKeepFilesForDays;
}
// Set file naming algorithm
string stmpNamingType = ResolveString("AutoBackupNaming",
this.m_defaultState.NamingType.ToString(), config, regionConfig);
NamingType tmpNamingType;
if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Time;
}
else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Sequential;
}
else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Overwrite;
}
else
{
m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
stmpNamingType);
tmpNamingType = NamingType.Time;
}
if (state == null && tmpNamingType != this.m_defaultState.NamingType)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.NamingType = tmpNamingType;
}
string tmpScript = ResolveString("AutoBackupScript",
this.m_defaultState.Script, config, regionConfig);
if (state == null && tmpScript != this.m_defaultState.Script)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Script = tmpScript;
}
string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BackupDir = tmpBackupDir;
// Let's give the user some convenience and auto-mkdir
if (state.BackupDir != ".")
{
try
{
DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
if (!dirinfo.Exists)
{
dirinfo.Create();
}
}
catch (Exception e)
{
m_log.Warn(
"[AUTO BACKUP]: BAD NEWS. You won't be able to save backups to directory " +
state.BackupDir +
" because it doesn't exist or there's a permissions issue with it. Here's the exception.",
e);
}
}
}
if(state == null)
return m_defaultState;
return state;
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
{
if(local != null)
{
return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
}
else
{
return global.GetBoolean(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
}
else
{
return global.GetDouble(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
}
else
{
return global.GetInt(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetString(settingName, global.GetString(settingName, defaultValue));
}
else
{
return global.GetString(settingName, defaultValue);
}
}
/// <summary>
/// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleElapsed(object sender, ElapsedEventArgs e)
{
// TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
// XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
// check whether the region is too busy! Especially on sims with LOTS of regions.
// Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
// but would allow us to be semantically correct while being easier on perf.
// Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
// Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
// Since this is pretty experimental, I haven't decided which alternative makes the most sense.
if (this.m_closed)
{
return;
}
bool heuristicsRun = false;
bool heuristicsPassed = false;
if (!this.m_timerMap.ContainsKey((Timer) sender))
{
m_log.Debug("[AUTO BACKUP]: Code-up error: timerMap doesn't contain timer " + sender);
}
List<IScene> tmap = this.m_timerMap[(Timer) sender];
if (tmap != null && tmap.Count > 0)
{
foreach (IScene scene in tmap)
{
AutoBackupModuleState state = this.m_states[scene];
bool heuristics = state.BusyCheck;
// Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
{
this.DoRegionBackup(scene);
// Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
}
else if (heuristicsRun)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
// Logical Deduction: heuristics are on but haven't been run
}
else
{
heuristicsPassed = this.RunHeuristics(scene);
heuristicsRun = true;
if (!heuristicsPassed)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
}
this.DoRegionBackup(scene);
}
// Remove Old Backups
this.RemoveOldFiles(state);
}
}
}
/// <summary>
/// Save an OAR, register for the callback for when it's done, then call the AutoBackupScript (if applicable).
/// </summary>
/// <param name="scene"></param>
private void DoRegionBackup(IScene scene)
{
if (!scene.Ready)
{
// We won't backup a region that isn't operating normally.
m_log.Warn("[AUTO BACKUP]: Not backing up region " + scene.RegionInfo.RegionName +
" because its status is " + scene.RegionStatus);
return;
}
AutoBackupModuleState state = this.m_states[scene];
IRegionArchiverModule iram = scene.RequestModuleInterface<IRegionArchiverModule>();
string savePath = BuildOarPath(scene.RegionInfo.RegionName,
state.BackupDir,
state.NamingType);
if (savePath == null)
{
m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
return;
}
Guid guid = Guid.NewGuid();
m_pendingSaves.Add(guid, scene);
state.LiveRequests.Add(guid, savePath);
((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
// Must pass options, even if dictionary is empty!
Dictionary<string, object> options = new Dictionary<string, object>();
if (state.SkipAssets)
options["noassets"] = true;
iram.ArchiveRegion(savePath, guid, options);
}
// For the given state, remove backup files older than the states KeepFilesForDays property
private void RemoveOldFiles(AutoBackupModuleState state)
{
// 0 Means Disabled, Keep Files Indefinitely
if (state.KeepFilesForDays > 0)
{
string[] files = Directory.GetFiles(state.BackupDir, "*.oar");
DateTime CuttOffDate = DateTime.Now.AddDays(0 - state.KeepFilesForDays);
foreach (string file in files)
{
try
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < CuttOffDate)
fi.Delete();
}
catch (Exception Ex)
{
m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
}
}
}
}
/// <summary>
/// Called by the Event Manager when the OnOarFileSaved event is fired.
/// </summary>
/// <param name="guid"></param>
/// <param name="message"></param>
void EventManager_OnOarFileSaved(Guid guid, string message)
{
// Ignore if the OAR save is being done by some other part of the system
if (m_pendingSaves.ContainsKey(guid))
{
AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
ExecuteScript(abms.Script, abms.LiveRequests[guid]);
m_pendingSaves.Remove(guid);
abms.LiveRequests.Remove(guid);
}
}
/// <summary>This format may turn out to be too unwieldy to keep...
/// Besides, that's what ctimes are for. But then how do I name each file uniquely without using a GUID?
/// Sequential numbers, right? We support those, too!</summary>
private static string GetTimeString()
{
StringWriter sw = new StringWriter();
sw.Write("_");
DateTime now = DateTime.Now;
sw.Write(now.Year);
sw.Write("y_");
sw.Write(now.Month);
sw.Write("M_");
sw.Write(now.Day);
sw.Write("d_");
sw.Write(now.Hour);
sw.Write("h_");
sw.Write(now.Minute);
sw.Write("m_");
sw.Write(now.Second);
sw.Write("s");
sw.Flush();
string output = sw.ToString();
sw.Close();
return output;
}
/// <summary>Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.</summary>
private bool RunHeuristics(IScene region)
{
try
{
return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
}
catch (Exception e)
{
m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
return false;
}
}
/// <summary>
/// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
/// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
/// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got worse time dilation than the threshold.</returns>
private bool RunTimeDilationHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
return region.TimeDilation >=
this.m_configSource.Configs["AutoBackupModule"].GetFloat(
regionName + ".AutoBackupDilationThreshold", 0.5f);
}
/// <summary>
/// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
/// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
/// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.</returns>
private bool RunAgentLimitHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
try
{
Scene scene = (Scene) region;
// TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
return scene.GetRootAgentCount() <=
this.m_configSource.Configs["AutoBackupModule"].GetInt(
regionName + ".AutoBackupAgentThreshold", 10);
}
catch (InvalidCastException ice)
{
m_log.Debug(
"[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
ice);
return true;
// Non-obstructionist safest answer...
}
}
/// <summary>
/// Run the script or executable specified by the "AutoBackupScript" config setting.
/// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
/// But there are plenty of other nasty things that can be done with an untrusted OpenSim.ini, such as running high threat level scripting functions.
/// </summary>
/// <param name="scriptName"></param>
/// <param name="savePath"></param>
private static void ExecuteScript(string scriptName, string savePath)
{
// Do nothing if there's no script.
if (scriptName == null || scriptName.Length <= 0)
{
return;
}
try
{
FileInfo fi = new FileInfo(scriptName);
if (fi.Exists)
{
ProcessStartInfo psi = new ProcessStartInfo(scriptName);
psi.Arguments = savePath;
psi.CreateNoWindow = true;
Process proc = Process.Start(psi);
proc.ErrorDataReceived += HandleProcErrorDataReceived;
}
}
catch (Exception e)
{
m_log.Warn(
"Exception encountered when trying to run script for oar backup " + savePath, e);
}
}
/// <summary>
/// Called if a running script process writes to stderr.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void HandleProcErrorDataReceived(object sender, DataReceivedEventArgs e)
{
m_log.Warn("ExecuteScript hook " + ((Process) sender).ProcessName +
" is yacking on stderr: " + e.Data);
}
/// <summary>
/// Quickly stop all timers from firing.
/// </summary>
private void StopAllTimers()
{
foreach (Timer t in this.m_timerMap.Keys)
{
t.Close();
}
this.m_closed = true;
}
/// <summary>
/// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static string GetNextFile(string dirName, string regionName)
{
FileInfo uniqueFile = null;
long biggestExistingFile = GetNextOarFileNumber(dirName, regionName);
biggestExistingFile++;
// We don't want to overwrite the biggest existing file; we want to write to the NEXT biggest.
uniqueFile =
new FileInfo(dirName + Path.DirectorySeparatorChar + regionName + "_" +
biggestExistingFile + ".oar");
return uniqueFile.FullName;
}
/// <summary>
/// Top-level method for creating an absolute path to an OAR backup file based on what naming scheme the user wants.
/// </summary>
/// <param name="regionName">Name of the region to save.</param>
/// <param name="baseDir">Absolute or relative path to the directory where the file should reside.</param>
/// <param name="naming">The naming scheme for the file name.</param>
/// <returns></returns>
private static string BuildOarPath(string regionName, string baseDir, NamingType naming)
{
FileInfo path = null;
switch (naming)
{
case NamingType.Overwrite:
path = new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName + ".oar");
return path.FullName;
case NamingType.Time:
path =
new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName +
GetTimeString() + ".oar");
return path.FullName;
case NamingType.Sequential:
// All codepaths in GetNextFile should return a file name ending in .oar
path = new FileInfo(GetNextFile(baseDir, regionName));
return path.FullName;
default:
m_log.Warn("VERY BAD: Unhandled case element " + naming);
break;
}
return null;
}
/// <summary>
/// Helper function for Sequential file naming type (see BuildOarPath and GetNextFile).
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static long GetNextOarFileNumber(string dirName, string regionName)
{
long retval = 1;
DirectoryInfo di = new DirectoryInfo(dirName);
FileInfo[] fi = di.GetFiles(regionName, SearchOption.TopDirectoryOnly);
Array.Sort(fi, (f1, f2) => StringComparer.CurrentCultureIgnoreCase.Compare(f1.Name, f2.Name));
if (fi.LongLength > 0)
{
long subtract = 1L;
bool worked = false;
Regex reg = new Regex(regionName + "_([0-9])+" + ".oar");
while (!worked && subtract <= fi.LongLength)
{
// Pick the file with the last natural ordering
string biggestFileName = fi[fi.LongLength - subtract].Name;
MatchCollection matches = reg.Matches(biggestFileName);
long l = 1;
if (matches.Count > 0 && matches[0].Groups.Count > 0)
{
try
{
long.TryParse(matches[0].Groups[1].Value, out l);
retval = l;
worked = true;
}
catch (FormatException fe)
{
m_log.Warn(
"[AUTO BACKUP]: Error: Can't parse long value from file name to determine next OAR backup file number!",
fe);
subtract++;
}
}
else
{
subtract++;
}
}
}
return retval;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// Represents an intrinsic debugger method with byref return type.
/// </summary>
internal sealed class PlaceholderMethodSymbol : MethodSymbol, Cci.ISignature
{
internal delegate ImmutableArray<TypeParameterSymbol> GetTypeParameters(PlaceholderMethodSymbol method);
internal delegate ImmutableArray<ParameterSymbol> GetParameters(PlaceholderMethodSymbol method);
internal delegate TypeSymbol GetReturnType(PlaceholderMethodSymbol method);
private readonly NamedTypeSymbol _container;
private readonly string _name;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly TypeSymbol _returnType;
private readonly ImmutableArray<ParameterSymbol> _parameters;
internal PlaceholderMethodSymbol(
NamedTypeSymbol container,
string name,
GetTypeParameters getTypeParameters,
GetReturnType getReturnType,
GetParameters getParameters)
{
_container = container;
_name = name;
_typeParameters = getTypeParameters(this);
_returnType = getReturnType(this);
_parameters = getParameters(this);
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override bool ReturnsVoid
{
get { return false; }
}
internal override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeSymbol ReturnType
{
get { return _returnType; }
}
bool Cci.ISignature.ReturnValueIsByRef
{
get { return true; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
return this.IsGenericMethod ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RectangleF.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Drawing {
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System;
using System.IO;
using Microsoft.Win32;
using System.ComponentModel;
using System.Drawing.Internal;
using System.Globalization;
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF"]/*' />
/// <devdoc>
/// <para>
/// Stores the location and size of a rectangular region. For
/// more advanced region functions use a <see cref='System.Drawing.Region'/>
/// object.
/// </para>
/// </devdoc>
[Serializable]
public struct RectangleF {
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Empty"]/*' />
/// <devdoc>
/// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/>
/// class.
/// </devdoc>
public static readonly RectangleF Empty = new RectangleF();
private float x;
private float y;
private float width;
private float height;
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.RectangleF"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/>
/// class with the specified location and size.
/// </para>
/// </devdoc>
public RectangleF(float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.RectangleF1"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/>
/// class with the specified location
/// and size.
/// </para>
/// </devdoc>
public RectangleF(PointF location, SizeF size) {
this.x = location.X;
this.y = location.Y;
this.width = size.Width;
this.height = size.Height;
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.FromLTRB"]/*' />
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Drawing.RectangleF'/> with
/// the specified location and size.
/// </para>
/// </devdoc>
// !! Not in C++ version
public static RectangleF FromLTRB(float left, float top, float right, float bottom) {
return new RectangleF(left,
top,
right - left,
bottom - top);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Location"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the coordinates of the upper-left corner of
/// the rectangular region represented by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
[Browsable(false)]
public PointF Location {
get {
return new PointF(X, Y);
}
set {
X = value.X;
Y = value.Y;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Size"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the size of this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
[Browsable(false)]
public SizeF Size {
get {
return new SizeF(Width, Height);
}
set {
this.Width = value.Width;
this.Height = value.Height;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.X"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the x-coordinate of the
/// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
public float X {
get {
return x;
}
set {
x = value;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Y"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the y-coordinate of the
/// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
public float Y {
get {
return y;
}
set {
y = value;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Width"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the width of the rectangular
/// region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
public float Width {
get {
return width;
}
set {
width = value;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Height"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the height of the
/// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
public float Height {
get {
return height;
}
set {
height = value;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Left"]/*' />
/// <devdoc>
/// <para>
/// Gets the x-coordinate of the upper-left corner of the
/// rectangular region defined by this <see cref='System.Drawing.RectangleF'/> .
/// </para>
/// </devdoc>
[Browsable(false)]
public float Left {
get {
return X;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Top"]/*' />
/// <devdoc>
/// <para>
/// Gets the y-coordinate of the upper-left corner of the
/// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
[Browsable(false)]
public float Top {
get {
return Y;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Right"]/*' />
/// <devdoc>
/// <para>
/// Gets the x-coordinate of the lower-right corner of the
/// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
[Browsable(false)]
public float Right {
get {
return X + Width;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Bottom"]/*' />
/// <devdoc>
/// <para>
/// Gets the y-coordinate of the lower-right corner of the
/// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
[Browsable(false)]
public float Bottom {
get {
return Y + Height;
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.IsEmpty"]/*' />
/// <devdoc>
/// <para>
/// Tests whether this <see cref='System.Drawing.RectangleF'/> has a <see cref='System.Drawing.RectangleF.Width'/> or a <see cref='System.Drawing.RectangleF.Height'/> of 0.
/// </para>
/// </devdoc>
[Browsable(false)]
public bool IsEmpty {
get {
return (Width <= 0 )|| (Height <= 0);
}
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Equals"]/*' />
/// <devdoc>
/// <para>
/// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.RectangleF'/> with the same location and size of this
/// <see cref='System.Drawing.RectangleF'/>.
/// </para>
/// </devdoc>
public override bool Equals(object obj) {
if (!(obj is RectangleF))
return false;
RectangleF comp = (RectangleF)obj;
return (comp.X == this.X) &&
(comp.Y == this.Y) &&
(comp.Width == this.Width) &&
(comp.Height == this.Height);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.operator=="]/*' />
/// <devdoc>
/// <para>
/// Tests whether two <see cref='System.Drawing.RectangleF'/>
/// objects have equal location and size.
/// </para>
/// </devdoc>
public static bool operator ==(RectangleF left, RectangleF right) {
return (left.X == right.X
&& left.Y == right.Y
&& left.Width == right.Width
&& left.Height == right.Height);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.operator!="]/*' />
/// <devdoc>
/// <para>
/// Tests whether two <see cref='System.Drawing.RectangleF'/>
/// objects differ in location or size.
/// </para>
/// </devdoc>
public static bool operator !=(RectangleF left, RectangleF right) {
return !(left == right);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Contains"]/*' />
/// <devdoc>
/// <para>
/// Determines if the specfied point is contained within the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </devdoc>
[Pure]
public bool Contains(float x, float y) {
return this.X <= x &&
x < this.X + this.Width &&
this.Y <= y &&
y < this.Y + this.Height;
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Contains1"]/*' />
/// <devdoc>
/// <para>
/// Determines if the specfied point is contained within the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </devdoc>
[Pure]
public bool Contains(PointF pt) {
return Contains(pt.X, pt.Y);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Contains2"]/*' />
/// <devdoc>
/// <para>
/// Determines if the rectangular region represented by
/// <paramref name="rect"/> is entirely contained within the rectangular region represented by
/// this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </devdoc>
[Pure]
public bool Contains(RectangleF rect) {
return (this.X <= rect.X) &&
((rect.X + rect.Width) <= (this.X + this.Width)) &&
(this.Y <= rect.Y) &&
((rect.Y + rect.Height) <= (this.Y + this.Height));
}
// !! Not in C++ version
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.GetHashCode"]/*' />
/// <devdoc>
/// Gets the hash code for this <see cref='System.Drawing.RectangleF'/>.
/// </devdoc>
public override int GetHashCode() {
return unchecked((int)((UInt32)X ^
(((UInt32)Y << 13) | ((UInt32)Y >> 19)) ^
(((UInt32)Width << 26) | ((UInt32)Width >> 6)) ^
(((UInt32)Height << 7) | ((UInt32)Height >> 25))));
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Inflate"]/*' />
/// <devdoc>
/// <para>
/// Inflates this <see cref='System.Drawing.Rectangle'/>
/// by the specified amount.
/// </para>
/// </devdoc>
public void Inflate(float x, float y) {
this.X -= x;
this.Y -= y;
this.Width += 2*x;
this.Height += 2*y;
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Inflate1"]/*' />
/// <devdoc>
/// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount.
/// </devdoc>
public void Inflate(SizeF size) {
Inflate(size.Width, size.Height);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Inflate2"]/*' />
/// <devdoc>
/// <para>
/// Creates a <see cref='System.Drawing.Rectangle'/>
/// that is inflated by the specified amount.
/// </para>
/// </devdoc>
// !! Not in C++
public static RectangleF Inflate(RectangleF rect, float x, float y) {
RectangleF r = rect;
r.Inflate(x, y);
return r;
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Intersect"]/*' />
/// <devdoc> Creates a Rectangle that represents the intersection between this Rectangle and rect.
/// </devdoc>
public void Intersect(RectangleF rect)
{
RectangleF result = RectangleF.Intersect(rect, this);
this.X = result.X;
this.Y = result.Y;
this.Width = result.Width;
this.Height = result.Height;
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Intersect1"]/*' />
/// <devdoc>
/// Creates a rectangle that represents the intersetion between a and
/// b. If there is no intersection, null is returned.
/// </devdoc>
[Pure]
public static RectangleF Intersect(RectangleF a, RectangleF b) {
float x1 = Math.Max(a.X, b.X);
float x2 = Math.Min(a.X + a.Width, b.X + b.Width);
float y1 = Math.Max(a.Y, b.Y);
float y2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if (x2 >= x1
&& y2 >= y1) {
return new RectangleF(x1, y1, x2 - x1, y2 - y1);
}
return RectangleF.Empty;
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.IntersectsWith"]/*' />
/// <devdoc>
/// Determines if this rectangle intersets with rect.
/// </devdoc>
[Pure]
public bool IntersectsWith(RectangleF rect) {
return (rect.X < this.X + this.Width) &&
(this.X < (rect.X + rect.Width)) &&
(rect.Y < this.Y + this.Height) &&
(this.Y < rect.Y + rect.Height);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Union"]/*' />
/// <devdoc>
/// Creates a rectangle that represents the union between a and
/// b.
/// </devdoc>
[Pure]
public static RectangleF Union(RectangleF a, RectangleF b) {
float x1 = Math.Min(a.X, b.X);
float x2 = Math.Max(a.X + a.Width, b.X + b.Width);
float y1 = Math.Min(a.Y, b.Y);
float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height);
return new RectangleF(x1, y1, x2 - x1, y2 - y1);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Offset"]/*' />
/// <devdoc>
/// Adjusts the location of this rectangle by the specified amount.
/// </devdoc>
public void Offset(PointF pos) {
Offset(pos.X, pos.Y);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.Offset1"]/*' />
/// <devdoc>
/// Adjusts the location of this rectangle by the specified amount.
/// </devdoc>
public void Offset(float x, float y) {
this.X += x;
this.Y += y;
}
/**
* Convert the current rectangle object into
* a GDI+ GPRECTF structure.
*/
internal GPRECTF ToGPRECTF() {
return new GPRECTF(X, Y, Width, Height);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.operatorRectangleF"]/*' />
/// <devdoc>
/// Converts the specified <see cref='System.Drawing.Rectangle'/> to a
/// <see cref='System.Drawing.RectangleF'/>.
/// </devdoc>
public static implicit operator RectangleF(Rectangle r) {
return new RectangleF(r.X, r.Y, r.Width, r.Height);
}
/// <include file='doc\RectangleF.uex' path='docs/doc[@for="RectangleF.ToString"]/*' />
/// <devdoc>
/// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/> of this <see cref='System.Drawing.RectangleF'/> to a
/// human-readable string.
/// </devdoc>
public override string ToString() {
return "{X=" + X.ToString(CultureInfo.CurrentCulture) + ",Y=" + Y.ToString(CultureInfo.CurrentCulture) +
",Width=" + Width.ToString(CultureInfo.CurrentCulture) +
",Height=" + Height.ToString(CultureInfo.CurrentCulture) + "}";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
namespace Microsoft.AspNetCore.HttpsPolicy.Tests
{
public class HttpsRedirectionMiddlewareTests
{
[Fact]
public async Task SetOptions_NotEnabledByDefault()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>,
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Warning, message.LogLevel);
Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString());
}
[Theory]
[InlineData(302, 5001, "https://localhost:5001/")]
[InlineData(307, 1, "https://localhost:1/")]
[InlineData(308, 3449, "https://localhost:3449/")]
[InlineData(301, 5050, "https://localhost:5050/")]
[InlineData(301, 443, "https://localhost/")]
public async Task SetOptions_SetStatusCodeHttpsPort(int statusCode, int? httpsPort, string expected)
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>,
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
services.Configure<HttpsRedirectionOptions>(options =>
{
options.RedirectStatusCode = statusCode;
options.HttpsPort = httpsPort;
});
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(expected, response.Headers.Location.ToString());
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal($"Redirecting to '{expected}'.", message.State.ToString());
}
[Theory]
[InlineData(302, 5001, "https://localhost:5001/")]
[InlineData(307, 1, "https://localhost:1/")]
[InlineData(308, 3449, "https://localhost:3449/")]
[InlineData(301, 5050, "https://localhost:5050/")]
[InlineData(301, 443, "https://localhost/")]
public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int statusCode, int? httpsPort, string expectedUrl)
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>,
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = statusCode;
options.HttpsPort = httpsPort;
});
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(expectedUrl, response.Headers.Location.ToString());
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal($"Redirecting to '{expectedUrl}'.", message.State.ToString());
}
[Theory]
[InlineData(null, null, "https://localhost:4444/", "https://localhost:4444/")]
[InlineData(null, null, "https://localhost:443/", "https://localhost/")]
[InlineData(null, null, "https://localhost/", "https://localhost/")]
[InlineData(null, "5000", "https://localhost:4444/", "https://localhost:5000/")]
[InlineData(null, "443", "https://localhost:4444/", "https://localhost/")]
[InlineData(443, "5000", "https://localhost:4444/", "https://localhost/")]
[InlineData(4000, "5000", "https://localhost:4444/", "https://localhost:4000/")]
[InlineData(5000, null, "https://localhost:4444/", "https://localhost:5000/")]
public async Task SetHttpsPortEnvironmentVariableAndServerFeature_ReturnsCorrectStatusCodeOnResponse(
int? optionsHttpsPort, string configHttpsPort, string serverAddressFeatureUrl, string expectedUrl)
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddHttpsRedirection(options =>
{
options.HttpsPort = optionsHttpsPort;
});
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
webHostBuilder.UseSetting("HTTPS_PORT", configHttpsPort);
}).Build();
var server = host.GetTestServer();
server.Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());
if (serverAddressFeatureUrl != null)
{
server.Features.Get<IServerAddressesFeature>().Addresses.Add(serverAddressFeatureUrl);
}
await host.StartAsync();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(expectedUrl, response.Headers.Location.ToString());
}
[Fact]
public async Task SetServerAddressesFeature_SingleHttpsAddress_Success()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>,
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
var server = host.GetTestServer();
server.Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://localhost:5050");
await host.StartAsync();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal("https://localhost:5050/", response.Headers.Location.ToString());
var logMessages = sink.Writes.ToList();
Assert.Equal(2, logMessages.Count);
var message = logMessages.First();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal("Https port '5050' discovered from server endpoints.", message.State.ToString());
message = logMessages.Skip(1).First();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal("Redirecting to 'https://localhost:5050/'.", message.State.ToString());
}
[Fact]
public async Task SetServerAddressesFeature_MultipleHttpsAddresses_Throws()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
var server = host.GetTestServer();
server.Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://localhost:5050");
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://localhost:5051");
await host.StartAsync();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
Assert.Equal("Cannot determine the https port from IServerAddressesFeature, multiple values were found. " +
"Set the desired port explicitly on HttpsRedirectionOptions.HttpsPort.", ex.Message);
}
[Fact]
public async Task SetServerAddressesFeature_MultipleHttpsAddressesWithSamePort_Success()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>,
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
var server = host.GetTestServer();
server.Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://localhost:5050");
server.Features.Get<IServerAddressesFeature>().Addresses.Add("https://example.com:5050");
await host.StartAsync();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal("https://localhost:5050/", response.Headers.Location.ToString());
var logMessages = sink.Writes.ToList();
Assert.Equal(2, logMessages.Count);
var message = logMessages.First();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal("Https port '5050' discovered from server endpoints.", message.State.ToString());
message = logMessages.Skip(1).First();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal("Redirecting to 'https://localhost:5050/'.", message.State.ToString());
}
[Fact]
public async Task NoServerAddressFeature_DoesNotThrow_DoesNotRedirect()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>,
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(200, (int)response.StatusCode);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.First();
Assert.Equal(LogLevel.Warning, message.LogLevel);
Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString());
}
[Fact]
public async Task SetNullAddressFeature_DoesNotThrow()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>,
TestSink.EnableWithTypeName<HttpsRedirectionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHttpsRedirection();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
var server = host.GetTestServer();
server.Features.Set<IServerAddressesFeature>(null);
await host.StartAsync();
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(200, (int)response.StatusCode);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.First();
Assert.Equal(LogLevel.Warning, message.LogLevel);
Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString());
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Timers;
using log4net;
using Nwc.XmlRpc;
using ProtoBuf;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Messages;
using OpenSim.Grid.Framework;
using Timer=System.Timers.Timer;
namespace OpenSim.Grid.MessagingServer.Modules
{
public class MessageService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MessageServerConfig m_cfg;
private UserDataBaseService m_userDataBaseService;
private IGridServiceCore m_messageCore;
private IInterServiceUserService m_userServerModule;
private IMessageRegionLookup m_regionModule;
// a dictionary of all current presences this server knows about
private Dictionary<UUID, UserPresenceData> m_presences = new Dictionary<UUID,UserPresenceData>();
public MessageService(MessageServerConfig cfg, IGridServiceCore messageCore, UserDataBaseService userDataBaseService)
{
m_cfg = cfg;
m_messageCore = messageCore;
m_userDataBaseService = userDataBaseService;
//???
UserConfig uc = new UserConfig();
uc.DatabaseConnect = cfg.DatabaseConnect;
uc.DatabaseProvider = cfg.DatabaseProvider;
}
public void Initialize()
{
}
public void PostInitialize()
{
IInterServiceUserService messageUserServer;
if (m_messageCore.TryGet<IInterServiceUserService>(out messageUserServer))
{
m_userServerModule = messageUserServer;
}
IMessageRegionLookup messageRegion;
if (m_messageCore.TryGet<IMessageRegionLookup>(out messageRegion))
{
m_regionModule = messageRegion;
}
}
public void RegisterHandlers()
{
//have these in separate method as some servers restart the http server and reregister all the handlers.
}
#region FriendList Methods
/// <summary>
/// Process Friendlist subscriptions for a user
/// The login method calls this for a User
/// </summary>
/// <param name="userpresence">The Agent we're processing the friendlist subscriptions for</param>
private void ProcessFriendListSubscriptions(UserPresenceData userpresence)
{
lock (m_presences)
{
m_presences[userpresence.agentData.AgentID] = userpresence;
}
Dictionary<UUID, FriendListItem> uFriendList = userpresence.friendData;
foreach (KeyValuePair<UUID, FriendListItem> pair in uFriendList)
{
UserPresenceData friendup = null;
lock (m_presences)
{
m_presences.TryGetValue(pair.Key, out friendup);
}
if (friendup != null)
{
SubscribeToPresenceUpdates(userpresence, friendup, pair.Value);
}
}
}
/// <summary>
/// Enqueues a presence update, sending info about user 'talkingAbout' to user 'receiver'.
/// </summary>
/// <param name="talkingAbout">We are sending presence information about this user.</param>
/// <param name="receiver">We are sending the presence update to this user</param>
private void enqueuePresenceUpdate(UserPresenceData talkingAbout, UserPresenceData receiver)
{
UserAgentData p2Handle = m_userDataBaseService.GetUserAgentData(receiver.agentData.AgentID);
if (p2Handle != null)
{
if (receiver.lookupUserRegionYN)
{
receiver.regionData.regionHandle = p2Handle.Handle;
}
else
{
receiver.lookupUserRegionYN = true; // TODO Huh?
}
PresenceInformer friendlistupdater = new PresenceInformer();
friendlistupdater.presence1 = talkingAbout;
friendlistupdater.presence2 = receiver;
friendlistupdater.OnGetRegionData += m_regionModule.GetRegionInfo;
friendlistupdater.OnDone += PresenceUpdateDone;
WaitCallback cb = new WaitCallback(friendlistupdater.go);
ThreadPool.QueueUserWorkItem(cb);
}
else
{
m_log.WarnFormat("[PRESENCE]: no data found for user {0}", receiver.agentData.AgentID);
// Skip because we can't find any data on the user
}
}
/// <summary>
/// Does the necessary work to subscribe one agent to another's presence notifications
/// Gets called by ProcessFriendListSubscriptions. You shouldn't call this directly
/// unless you know what you're doing
/// </summary>
/// <param name="userpresence">P1</param>
/// <param name="friendpresence">P2</param>
/// <param name="uFriendListItem"></param>
private void SubscribeToPresenceUpdates(UserPresenceData userpresence,
UserPresenceData friendpresence,
FriendListItem uFriendListItem)
{
// Can the friend see me online?
if ((uFriendListItem.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
{
// tell user to update friend about user's presence changes
if (!userpresence.subscriptionData.Contains(friendpresence.agentData.AgentID))
{
userpresence.subscriptionData.Add(friendpresence.agentData.AgentID);
}
// send an update about user's presence to the friend
enqueuePresenceUpdate(userpresence, friendpresence);
}
// Can I see the friend online?
if ((uFriendListItem.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0)
{
// tell friend to update user about friend's presence changes
if (!friendpresence.subscriptionData.Contains(userpresence.agentData.AgentID))
{
friendpresence.subscriptionData.Add(userpresence.agentData.AgentID);
}
// send an update about friend's presence to user.
enqueuePresenceUpdate(friendpresence, userpresence);
}
}
/// <summary>
/// Logoff Processor. Call this to clean up agent presence data and send logoff presence notifications
/// </summary>
/// <param name="AgentID"></param>
private void ProcessLogOff(UUID AgentID)
{
m_log.Info("[LOGOFF]: Processing Logoff");
UserPresenceData userPresence = null;
lock (m_presences)
{
m_presences.TryGetValue(AgentID, out userPresence);
}
if (userPresence != null) // found the user
{
List<UUID> AgentsNeedingNotification = userPresence.subscriptionData;
userPresence.OnlineYN = false;
for (int i = 0; i < AgentsNeedingNotification.Count; i++)
{
UserPresenceData friendPresence = null;
lock (m_presences)
{
m_presences.TryGetValue(AgentsNeedingNotification[i], out friendPresence);
}
// This might need to be enumerated and checked before we try to remove it.
if (friendPresence != null)
{
lock (friendPresence)
{
// no updates for this user anymore
friendPresence.subscriptionData.Remove(AgentID);
// set user's entry in the friend's list to offline (if it exists)
if (friendPresence.friendData.ContainsKey(AgentID))
{
friendPresence.friendData[AgentID].onlinestatus = false;
}
}
enqueuePresenceUpdate(userPresence, friendPresence);
}
}
}
}
#endregion
private void PresenceUpdateDone(PresenceInformer obj)
{
obj.OnGetRegionData -= m_regionModule.GetRegionInfo;
obj.OnDone -= PresenceUpdateDone;
}
#region UserServer Comms
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend
/// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID.
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param>
private Dictionary<UUID, FriendListItem> GetUserFriendListOld(UUID friendlistowner)
{
m_log.Warn("[FRIEND]: Calling Messaging/GetUserFriendListOld for " + friendlistowner.ToString());
Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID, FriendListItem>();
try
{
Hashtable param = new Hashtable();
param["ownerID"] = friendlistowner.ToString();
IList parameters = new ArrayList();
parameters.Add(param);
string methodName = "get_user_friend_list";
XmlRpcRequest req = new XmlRpcRequest(methodName, parameters);
XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_cfg.UserServerURL, methodName), 3000);
Hashtable respData = (Hashtable)resp.Value;
if (respData.Contains("avcount"))
{
buddies = ConvertXMLRPCDataToFriendListItemList(respData);
}
}
catch (WebException e)
{
m_log.Warn("[FRIEND]: Error when trying to fetch Avatar's friends list: " +
e.Message);
// Return Empty list (no friends)
}
return buddies;
}
/// <summary>
/// The response that will be returned from a command
/// </summary>
public enum GetUserFriendListResult
{
OK = 0,
ERROR = 1,
UNAUTHORIZED = 2,
INVALID = 3,
// NOTIMPLEMENTED means no such URL/operation (older servers return this when new commands are added)
NOTIMPLEMENTED = 4
}
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend
/// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID.
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param>
private GetUserFriendListResult GetUserFriendList2(UUID friendlistowner, out Dictionary<UUID, FriendListItem> results)
{
Util.SlowTimeReporter slowCheck = new Util.SlowTimeReporter("[FRIEND]: GetUserFriendList2 for " + friendlistowner.ToString() + " took", TimeSpan.FromMilliseconds(1000));
try
{
Dictionary<UUID, FriendListItem> EMPTY_RESULTS = new Dictionary<UUID, FriendListItem>();
string uri = m_cfg.UserServerURL + "/get_user_friend_list2/";
HttpWebRequest friendListRequest = (HttpWebRequest)WebRequest.Create(uri);
friendListRequest.Method = "POST";
friendListRequest.ContentType = "application/octet-stream";
friendListRequest.Timeout = FriendsListRequest.TIMEOUT;
// Default results are empty
results = EMPTY_RESULTS;
// m_log.WarnFormat("[FRIEND]: Msg/GetUserFriendList2({0}) using URI '{1}'", friendlistowner, uri);
FriendsListRequest request = FriendsListRequest.FromUUID(friendlistowner);
try
{
// send the Post
Stream os = friendListRequest.GetRequestStream();
ProtoBuf.Serializer.Serialize(os, request);
os.Flush();
os.Close();
}
catch (Exception e)
{
m_log.InfoFormat("[FRIEND]: GetUserFriendList2 call failed {0}", e);
return GetUserFriendListResult.ERROR;
}
// Let's wait for the response
try
{
HttpWebResponse webResponse = (HttpWebResponse)friendListRequest.GetResponse();
if (webResponse == null)
{
m_log.Error("[FRIEND]: Null reply on GetUserFriendList2 put");
return GetUserFriendListResult.ERROR;
}
//this will happen during the initial rollout and tells us we need to fall back to the old method
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
m_log.WarnFormat("[FRIEND]: NotFound on reply of GetUserFriendList2");
return GetUserFriendListResult.NOTIMPLEMENTED;
}
if (webResponse.StatusCode != HttpStatusCode.OK)
{
m_log.ErrorFormat("[FRIEND]: Error on reply of GetUserFriendList2 {0}", friendlistowner);
return GetUserFriendListResult.ERROR;
}
// We have a reply.
FriendsListResponse response = ProtoBuf.Serializer.Deserialize<FriendsListResponse>(webResponse.GetResponseStream());
if (response == null)
{
m_log.ErrorFormat("[FRIEND]: Could not deserialize reply of GetUserFriendList2");
return GetUserFriendListResult.ERROR;
}
// Request/response succeeded.
results = response.ToDict();
// m_log.InfoFormat("[FRIEND]: Returning {0} friends for {1}", results.Count, friendlistowner);
return GetUserFriendListResult.OK;
}
catch (WebException ex)
{
HttpWebResponse webResponse = ex.Response as HttpWebResponse;
if (webResponse != null)
{
//this will happen during the initial rollout and tells us we need to fall back to the
//old method
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
m_log.InfoFormat("[FRIEND]: NotFound exception on reply of GetUserFriendList2");
return GetUserFriendListResult.NOTIMPLEMENTED;
}
}
m_log.ErrorFormat("[FRIEND]: exception on reply of GetUserFriendList2 for {0}", request.FriendListOwner);
}
return GetUserFriendListResult.ERROR;
}
finally
{
slowCheck.Complete();
}
}
private Dictionary<UUID, FriendListItem> GetUserFriendList(UUID friendlistowner)
{
Dictionary<UUID, FriendListItem> results;
GetUserFriendListResult rc = GetUserFriendList2(friendlistowner, out results);
if (rc == GetUserFriendListResult.NOTIMPLEMENTED)
results = GetUserFriendListOld(friendlistowner);
return results;
}
/// <summary>
/// Converts XMLRPC Friend List to FriendListItem Object
/// </summary>
/// <param name="data">XMLRPC response data Hashtable</param>
/// <returns></returns>
public Dictionary<UUID, FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data)
{
Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
int buddycount = Convert.ToInt32((string)data["avcount"]);
for (int i = 0; i < buddycount; i++)
{
FriendListItem buddylistitem = new FriendListItem();
buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]);
buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]);
buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]);
buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]);
buddies.Add(buddylistitem.Friend, buddylistitem);
}
return buddies;
}
/// <summary>
/// UserServer sends an expect_user method
/// this handles the method and provisions the
/// necessary info for presence to work
/// </summary>
/// <param name="request">UserServer Data</param>
/// <returns></returns>
public XmlRpcResponse UserLoggedOn(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string)requestData["sessionid"]);
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
agentData.FirstName = (string)requestData["firstname"];
agentData.LastName = (string)requestData["lastname"];
agentData.AgentID = new UUID((string)requestData["agentid"]);
agentData.CircuitCode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
agentData.child = true;
}
else
{
agentData.startpos =
new Vector3(Convert.ToSingle(requestData["positionx"]),
Convert.ToSingle(requestData["positiony"]),
Convert.ToSingle(requestData["positionz"]));
agentData.child = false;
}
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
m_log.InfoFormat("[LOGON]: User {0} {1} logged into region {2} as {3} agent, building indexes for user",
agentData.FirstName, agentData.LastName, regionHandle, agentData.child ? "child" : "root");
UserPresenceData up = new UserPresenceData();
up.agentData = agentData;
up.friendData = GetUserFriendList(agentData.AgentID);
up.regionData = m_regionModule.GetRegionInfo(regionHandle);
up.OnlineYN = true;
up.lookupUserRegionYN = false;
ProcessFriendListSubscriptions(up);
return new XmlRpcResponse();
}
/// <summary>
/// The UserServer got a Logoff message
/// Cleanup time for that user. Send out presence notifications
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse UserLoggedOff(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[LOGOFF]: User logged off called");
Hashtable requestData = (Hashtable)request.Params[0];
UUID AgentID = new UUID((string)requestData["agentid"]);
ProcessLogOff(AgentID);
return new XmlRpcResponse();
}
#endregion
public XmlRpcResponse GetPresenceInfoBulk(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable paramHash = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
// TODO check access (recv_key/send_key)
IList list = (IList)paramHash["uuids"];
// convert into List<UUID>
List<UUID> uuids = new List<UUID>();
for (int i = 0; i < list.Count; ++i)
{
UUID uuid;
if (UUID.TryParse((string)list[i], out uuid))
{
uuids.Add(uuid);
}
}
try {
Dictionary<UUID, FriendRegionInfo> infos = m_userDataBaseService.GetFriendRegionInfos(uuids);
m_log.DebugFormat("[FRIEND]: Got {0} region entries back.", infos.Count);
int count = 0;
foreach (KeyValuePair<UUID, FriendRegionInfo> pair in infos)
{
result["uuid_" + count] = pair.Key.ToString();
result["isOnline_" + count] = pair.Value.isOnline;
result["regionHandle_" + count] = pair.Value.regionHandle.ToString(); // XML-RPC doesn't know ulongs
++count;
}
result["count"] = count;
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
catch(Exception e) {
m_log.Error("[PRESENCE]: Got exception:", e);
throw;
}
}
public XmlRpcResponse AgentLocation(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "agent_location"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse AgentLeaving(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "agent_leaving"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse ProcessRegionShutdown(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
UUID regionID;
if (UUID.TryParse((string)requestData["regionid"], out regionID))
{
m_log.DebugFormat("[PRESENCE]: Processing region shutdown for {0}", regionID);
result["success"] = "TRUE";
foreach (UserPresenceData up in m_presences.Values)
{
if (up.regionData.UUID == regionID)
{
if (up.OnlineYN)
{
m_log.DebugFormat("[PRESENCE]: Logging off {0} because the region they were in has gone", up.agentData.AgentID);
ProcessLogOff(up.agentData.AgentID);
}
}
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a constructor call that has a collection initializer.
/// </summary>
/// <remarks>
/// Use the <see cref="M:ListInit"/> factory methods to create a ListInitExpression.
/// The value of the NodeType property of a ListInitExpression is ListInit.
/// </remarks>
[DebuggerTypeProxy(typeof(Expression.ListInitExpressionProxy))]
public sealed class ListInitExpression : Expression
{
private readonly NewExpression _newExpression;
private readonly ReadOnlyCollection<ElementInit> _initializers;
internal ListInitExpression(NewExpression newExpression, ReadOnlyCollection<ElementInit> initializers)
{
_newExpression = newExpression;
_initializers = initializers;
}
/// <summary>
/// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.ListInit; }
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _newExpression.Type; }
}
/// <summary>
/// Gets a value that indicates whether the expression tree node can be reduced.
/// </summary>
public override bool CanReduce
{
get
{
return true;
}
}
/// <summary>
/// Gets the expression that contains a call to the constructor of a collection type.
/// </summary>
public NewExpression NewExpression
{
get { return _newExpression; }
}
/// <summary>
/// Gets the element initializers that are used to initialize a collection.
/// </summary>
public ReadOnlyCollection<ElementInit> Initializers
{
get { return _initializers; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitListInit(this);
}
/// <summary>
/// Reduces the binary expression node to a simpler expression.
/// If CanReduce returns true, this should return a valid expression.
/// This method is allowed to return another node which itself
/// must be reduced.
/// </summary>
/// <returns>The reduced expression.</returns>
public override Expression Reduce()
{
return MemberInitExpression.ReduceListInit(_newExpression, _initializers, true);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="newExpression">The <see cref="NewExpression" /> property of the result.</param>
/// <param name="initializers">The <see cref="Initializers" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public ListInitExpression Update(NewExpression newExpression, IEnumerable<ElementInit> initializers)
{
if (newExpression == NewExpression && initializers == Initializers)
{
return this;
}
return Expression.ListInit(newExpression, initializers);
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
{
return ListInit(newExpression, initializers as IEnumerable<Expression>);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
{
ContractUtils.RequiresNotNull(newExpression, nameof(newExpression));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
var initializerlist = initializers.ToReadOnly();
if (initializerlist.Count == 0)
{
return new ListInitExpression(newExpression, EmptyReadOnlyCollection<ElementInit>.Instance);
}
MethodInfo addMethod = FindMethod(newExpression.Type, "Add", null, new Expression[] { initializerlist[0] }, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return ListInit(newExpression, addMethod, initializers);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
/// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, params Expression[] initializers)
{
return ListInit(newExpression, addMethod, initializers as IEnumerable<Expression>);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the Initializers collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
{
if (addMethod == null)
{
return ListInit(newExpression, initializers);
}
ContractUtils.RequiresNotNull(newExpression, nameof(newExpression));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
var initializerlist = initializers.ToReadOnly();
ElementInit[] initList = new ElementInit[initializerlist.Count];
for (int i = 0; i < initializerlist.Count; i++)
{
initList[i] = ElementInit(addMethod, initializerlist[i]);
}
return ListInit(newExpression, new TrueReadOnlyCollection<ElementInit>(initList));
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An array that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>
/// A <see cref="ListInitExpression"/> that has the <see cref="P:Expressions.NodeType"/> property equal to ListInit
/// and the <see cref="P:ListInitExpression.NewExpression"/> and <see cref="P:ListInitExpression.Initializers"/> properties set to the specified values.
/// </returns>
/// <remarks>
/// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>.
/// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type.
/// </remarks>
public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers)
{
return ListInit(newExpression, (IEnumerable<ElementInit>)initializers);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</returns>
/// <remarks>
/// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>.
/// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type.
/// </remarks>
public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<ElementInit> initializers)
{
ContractUtils.RequiresNotNull(newExpression, nameof(newExpression));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
var initializerlist = initializers.ToReadOnly();
ValidateListInitArgs(newExpression.Type, initializerlist, nameof(newExpression));
return new ListInitExpression(newExpression, initializerlist);
}
}
}
| |
namespace LocalLingua.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Reset : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ChangeLogs",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserName = c.String(),
EntityName = c.String(),
EntityId = c.String(),
PropertyName = c.String(),
OldValue = c.String(),
NewValue = c.String(),
DateChanged = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Cities",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Encouragement = c.String(),
Description = c.String(),
ShortDescription = c.String(),
ImageUrl = c.String(),
CountryId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Countries", t => t.CountryId, cascadeDelete: true)
.Index(t => t.CountryId);
CreateTable(
"dbo.Countries",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Description = c.String(),
ImageUrl = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Trips",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Description = c.String(),
ImageUrl = c.String(),
Available = c.Boolean(nullable: false),
CountryId = c.Int(nullable: false),
CityId = c.Int(nullable: false),
GuideId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Cities", t => t.CityId)
.ForeignKey("dbo.Countries", t => t.CountryId)
.ForeignKey("dbo.Guides", t => t.GuideId, cascadeDelete: true)
.Index(t => t.CountryId)
.Index(t => t.CityId)
.Index(t => t.GuideId);
CreateTable(
"dbo.Guides",
c => new
{
Id = c.Int(nullable: false, identity: true),
Username = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Ranks",
c => new
{
Id = c.Int(nullable: false, identity: true),
Mark = c.Double(nullable: false),
Comment = c.String(),
AuthorUsername = c.String(),
TripId = c.Int(nullable: false),
Guide_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Trips", t => t.TripId, cascadeDelete: true)
.ForeignKey("dbo.Guides", t => t.Guide_Id)
.Index(t => t.TripId)
.Index(t => t.Guide_Id);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
IsAdministrator = c.Boolean(nullable: false),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.AspNetUserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.Conversations",
c => new
{
Id = c.Int(nullable: false, identity: true),
LastActivityDate = c.DateTime(nullable: false),
HasUnreadMessages = c.Boolean(nullable: false),
ShouldRead = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Messages",
c => new
{
Id = c.Int(nullable: false, identity: true),
ConversationId = c.Int(nullable: false),
Text = c.String(),
Author = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Conversations", t => t.ConversationId, cascadeDelete: true)
.Index(t => t.ConversationId);
CreateTable(
"dbo.AspNetUserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.Errors",
c => new
{
Id = c.Int(nullable: false, identity: true),
Logged = c.DateTime(nullable: false),
Level = c.String(),
Message = c.String(),
Callsite = c.String(),
Exception = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.MessageNotifications",
c => new
{
Id = c.Int(nullable: false, identity: true),
Receiver = c.String(),
Seen = c.Boolean(nullable: false),
Author = c.String(),
SelectedConversationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
CreateTable(
"dbo.StatisticsInformations",
c => new
{
Id = c.Int(nullable: false, identity: true),
ActionName = c.String(),
ControllerName = c.String(),
Ip = c.String(),
Date = c.DateTime(nullable: false),
IsAuthenticated = c.Boolean(nullable: false),
RequestCountry = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ConversationUsers",
c => new
{
Conversation_Id = c.Int(nullable: false),
User_Id = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.Conversation_Id, t.User_Id })
.ForeignKey("dbo.Conversations", t => t.Conversation_Id, cascadeDelete: true)
.ForeignKey("dbo.AspNetUsers", t => t.User_Id, cascadeDelete: true)
.Index(t => t.Conversation_Id)
.Index(t => t.User_Id);
CreateTable(
"dbo.UserCities",
c => new
{
User_Id = c.String(nullable: false, maxLength: 128),
City_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.User_Id, t.City_Id })
.ForeignKey("dbo.AspNetUsers", t => t.User_Id, cascadeDelete: true)
.ForeignKey("dbo.Cities", t => t.City_Id, cascadeDelete: true)
.Index(t => t.User_Id)
.Index(t => t.City_Id);
CreateTable(
"dbo.UserCountries",
c => new
{
User_Id = c.String(nullable: false, maxLength: 128),
Country_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.User_Id, t.Country_Id })
.ForeignKey("dbo.AspNetUsers", t => t.User_Id, cascadeDelete: true)
.ForeignKey("dbo.Countries", t => t.Country_Id, cascadeDelete: true)
.Index(t => t.User_Id)
.Index(t => t.Country_Id);
}
public override void Down()
{
DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles");
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.UserCountries", "Country_Id", "dbo.Countries");
DropForeignKey("dbo.UserCountries", "User_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.UserCities", "City_Id", "dbo.Cities");
DropForeignKey("dbo.UserCities", "User_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.ConversationUsers", "User_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.ConversationUsers", "Conversation_Id", "dbo.Conversations");
DropForeignKey("dbo.Messages", "ConversationId", "dbo.Conversations");
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.Trips", "GuideId", "dbo.Guides");
DropForeignKey("dbo.Ranks", "Guide_Id", "dbo.Guides");
DropForeignKey("dbo.Ranks", "TripId", "dbo.Trips");
DropForeignKey("dbo.Trips", "CountryId", "dbo.Countries");
DropForeignKey("dbo.Trips", "CityId", "dbo.Cities");
DropForeignKey("dbo.Cities", "CountryId", "dbo.Countries");
DropIndex("dbo.UserCountries", new[] { "Country_Id" });
DropIndex("dbo.UserCountries", new[] { "User_Id" });
DropIndex("dbo.UserCities", new[] { "City_Id" });
DropIndex("dbo.UserCities", new[] { "User_Id" });
DropIndex("dbo.ConversationUsers", new[] { "User_Id" });
DropIndex("dbo.ConversationUsers", new[] { "Conversation_Id" });
DropIndex("dbo.AspNetRoles", "RoleNameIndex");
DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" });
DropIndex("dbo.AspNetUserRoles", new[] { "UserId" });
DropIndex("dbo.AspNetUserLogins", new[] { "UserId" });
DropIndex("dbo.Messages", new[] { "ConversationId" });
DropIndex("dbo.AspNetUserClaims", new[] { "UserId" });
DropIndex("dbo.AspNetUsers", "UserNameIndex");
DropIndex("dbo.Ranks", new[] { "Guide_Id" });
DropIndex("dbo.Ranks", new[] { "TripId" });
DropIndex("dbo.Trips", new[] { "GuideId" });
DropIndex("dbo.Trips", new[] { "CityId" });
DropIndex("dbo.Trips", new[] { "CountryId" });
DropIndex("dbo.Cities", new[] { "CountryId" });
DropTable("dbo.UserCountries");
DropTable("dbo.UserCities");
DropTable("dbo.ConversationUsers");
DropTable("dbo.StatisticsInformations");
DropTable("dbo.AspNetRoles");
DropTable("dbo.MessageNotifications");
DropTable("dbo.Errors");
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.Messages");
DropTable("dbo.Conversations");
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.AspNetUsers");
DropTable("dbo.Ranks");
DropTable("dbo.Guides");
DropTable("dbo.Trips");
DropTable("dbo.Countries");
DropTable("dbo.Cities");
DropTable("dbo.ChangeLogs");
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.NodejsTools.Project.ImportWizard;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Nodejs;
namespace NodejsTests
{
[TestClass]
public class ImportWizardTests
{
[ClassInitialize]
public static void DoDeployment(TestContext context)
{
AssertListener.Initialize();
NodejsTestData.Deploy();
}
[TestMethod, Priority(0)]
public void ImportWizardSimple()
{
DispatcherTest(async () =>
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.js;*.njsproj";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
await Dispatcher.Yield();
Assert.AreEqual("server.js", settings.StartupFile);
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"server.js");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Content")).Select(x => x.Attribute("Include").Value),
"HelloWorld.njsproj");
});
}
[Ignore]
[TestMethod, Priority(0)]
public void ImportWizardSimpleApp()
{
DispatcherTest(async () =>
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorldApp\\");
settings.Filters = "*.js;*.njsproj";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
await Dispatcher.Yield();
Assert.AreEqual("app.js", settings.StartupFile);
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorldApp\\", proj.Descendant("ProjectHome").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"app.js");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Content")).Select(x => x.Attribute("Include").Value),
"HelloWorld.njsproj");
});
}
[Ignore]
[TestMethod, Priority(0)]
public void ImportWizardSimpleOther()
{
DispatcherTest(async () =>
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorldOther\\");
settings.Filters = "*.js;*.njsproj";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
await Dispatcher.Yield();
Assert.AreEqual("other.js", settings.StartupFile);
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorldOther\\", proj.Descendant("ProjectHome").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"other.js");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Content")).Select(x => x.Attribute("Include").Value),
"HelloWorld.njsproj");
});
}
[Ignore]
[TestMethod, Priority(0)]
public void ImportWizardFiltered()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.js";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"server.js");
Assert.AreEqual(0, proj.Descendants(proj.GetName("Content")).Count());
}
[TestMethod, Priority(0)]
public void ImportWizardFolders()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld2\\");
settings.Filters = "*";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorld2\\", proj.Descendant("ProjectHome").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"server.js",
"TestFolder\\SubItem.js",
"TestFolder2\\SubItem.js",
"TestFolder3\\SubItem.js");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"TestFolder",
"TestFolder2",
"TestFolder3");
}
[TestMethod, Priority(0)]
public void ImportWizardStartupFile()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.js;*.njsproj";
settings.StartupFile = "server.js";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("server.js", proj.Descendant("StartupFile").Value);
}
[TestMethod, Priority(0)]
public void ImportWizardExcludeNodeModules()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld3\\");
settings.Filters = "*.js;*.njsproj";
settings.StartupFile = "server.js";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"server.js");
}
[TestMethod, Priority(0)]
public void ImportWizardExcludeDotPrefixedFolders()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld5\\");
settings.Filters = "*.js;*.njsproj";
settings.StartupFile = "server.js";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"server.js",
"TestFolder\\SubItem.js",
"TestFolderWith.Extension\\SubItem.js");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"TestFolder",
"TestFolderWith.Extension");
}
[TestMethod, Priority(0)]
public void ImportWizardEmptyFolders()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld4");
settings.Filters = "*.js";
settings.StartupFile = "server.js";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"Baz");
}
[TestMethod, Priority(0)]
public void ImportWizardExcludeBowerComponents()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld6");
settings.Filters = "*.js";
settings.StartupFile = "server.js";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"Baz");
}
[TestMethod, Priority(0)]
public void ProjectFileAlreadyExists()
{
DispatcherTest(async () =>
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld3");
settings.Filters = "*.js";
settings.StartupFile = "server.js";
await Dispatcher.Yield();
Assert.AreEqual("HelloWorld31.njsproj", Path.GetFileName(settings.ProjectPath));
});
}
[TestMethod, Priority(0)]
public void ImportWizardTypeScript()
{
var settings = new ImportSettings();
settings.SourcePath = TestData.GetPath("TestData\\HelloWorldTypeScript\\");
settings.Filters = "*.ts;*.md;*.json";
settings.StartupFile = "server.ts";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\TsSubdirectory\\ProjectName.njsproj");
var path = settings.CreateRequestedProject();
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("TypeScriptCompile")).Select(x => x.Attribute("Include").Value),
"server.ts");
Assert.AreEqual("server.ts", proj.Descendant("StartupFile").Value);
}
/// <summary>
/// Creates a new window so that we have an active dispatcher for
/// test cases which depend upon posting async events back and having
/// them get processed at some point.
///
/// Test cases need to do a await Dispatcher.Yield() in order to have
/// any actual message processing occur.
/// </summary>
/// <param name="testCase"></param>
private static void DispatcherTest(Action testCase)
{
var window = new Window();
window.ShowInTaskbar = false;
window.MaxHeight = 0;
window.MaxWidth = 0;
window.WindowStyle = WindowStyle.None;
window.Activated += (sender, args) =>
{
testCase();
window.Close();
};
window.ShowDialog();
Dispatcher.CurrentDispatcher.InvokeShutdown();
}
}
}
| |
// 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.Linq;
using Xunit;
namespace Test
{
public class IntersectTests
{
private const int DuplicateFactor = 4;
public static IEnumerable<object[]> IntersectUnorderedData(object[] leftCounts, object[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => 0 - r / 2, rightCounts.Cast<int>()))
{
parms[4] = Math.Min((int)parms[1], ((int)parms[3] + 1) / 2);
yield return parms;
}
}
public static IEnumerable<object[]> IntersectData(object[] leftCounts, object[] rightCounts)
{
foreach (object[] parms in IntersectUnorderedData(leftCounts, rightCounts))
{
parms[0] = ((Labeled<ParallelQuery<int>>)parms[0]).Order();
yield return parms;
}
}
public static IEnumerable<object[]> IntersectSourceMultipleData(object[] counts)
{
foreach (int leftCount in counts.Cast<int>())
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered();
foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor * 2, leftCount), 2 * Math.Max(DuplicateFactor, leftCount * 2) })
{
int rightStart = 0 - rightCount / 2;
yield return new object[] { left, leftCount,
ParallelEnumerable.Range(rightStart, rightCount), rightCount, Math.Min(leftCount, (rightCount + 1) / 2) };
}
}
}
//
// Intersect
//
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in leftQuery.Intersect(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
seen.Add(i % (DuplicateFactor * 2));
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_Distinct(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Distinct(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectUnorderedData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })]
public static void Intersect_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectData", new int[] { 512, 1024 * 16 }, new int[] { 0, 1, 512, 1024 * 32 })]
public static void Intersect_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int count)
{
Intersect_Distinct_NotPipelined(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Intersect_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x /DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.AsUnordered().Intersect(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 512, 1024 * 16 }))]
public static void Intersect_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Intersect_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("IntersectSourceMultipleData", (object)(new int[] { 512, 1024 * 16 }))]
public static void Intersect_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Fact]
public static void Intersect_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
public static void Intersect_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1)));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Intersect(null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Intersect(null, EqualityComparer<int>.Default));
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Input;
using SDL2;
namespace osu.Framework.Platform.Sdl
{
public static class Sdl2Extensions
{
public static Key ToKey(this SDL.SDL_Keysym sdlKeysym)
{
switch (sdlKeysym.sym)
{
default:
case SDL.SDL_Keycode.SDLK_UNKNOWN:
return Key.Unknown;
case SDL.SDL_Keycode.SDLK_KP_COMMA:
return Key.Comma;
case SDL.SDL_Keycode.SDLK_KP_TAB:
return Key.Tab;
case SDL.SDL_Keycode.SDLK_KP_BACKSPACE:
return Key.BackSpace;
case SDL.SDL_Keycode.SDLK_KP_A:
return Key.A;
case SDL.SDL_Keycode.SDLK_KP_B:
return Key.B;
case SDL.SDL_Keycode.SDLK_KP_C:
return Key.C;
case SDL.SDL_Keycode.SDLK_KP_D:
return Key.D;
case SDL.SDL_Keycode.SDLK_KP_E:
return Key.E;
case SDL.SDL_Keycode.SDLK_KP_F:
return Key.F;
case SDL.SDL_Keycode.SDLK_KP_SPACE:
return Key.Space;
case SDL.SDL_Keycode.SDLK_KP_CLEAR:
return Key.Clear;
case SDL.SDL_Keycode.SDLK_RETURN:
return Key.Enter;
case SDL.SDL_Keycode.SDLK_ESCAPE:
return Key.Escape;
case SDL.SDL_Keycode.SDLK_BACKSPACE:
return Key.BackSpace;
case SDL.SDL_Keycode.SDLK_TAB:
return Key.Tab;
case SDL.SDL_Keycode.SDLK_SPACE:
return Key.Space;
case SDL.SDL_Keycode.SDLK_QUOTE:
return Key.Quote;
case SDL.SDL_Keycode.SDLK_COMMA:
return Key.Comma;
case SDL.SDL_Keycode.SDLK_MINUS:
return Key.Minus;
case SDL.SDL_Keycode.SDLK_PERIOD:
return Key.Period;
case SDL.SDL_Keycode.SDLK_SLASH:
return Key.Slash;
case SDL.SDL_Keycode.SDLK_0:
return Key.Number0;
case SDL.SDL_Keycode.SDLK_1:
return Key.Number1;
case SDL.SDL_Keycode.SDLK_2:
return Key.Number2;
case SDL.SDL_Keycode.SDLK_3:
return Key.Number3;
case SDL.SDL_Keycode.SDLK_4:
return Key.Number4;
case SDL.SDL_Keycode.SDLK_5:
return Key.Number5;
case SDL.SDL_Keycode.SDLK_6:
return Key.Number6;
case SDL.SDL_Keycode.SDLK_7:
return Key.Number7;
case SDL.SDL_Keycode.SDLK_8:
return Key.Number8;
case SDL.SDL_Keycode.SDLK_9:
return Key.Number9;
case SDL.SDL_Keycode.SDLK_SEMICOLON:
return Key.Semicolon;
case SDL.SDL_Keycode.SDLK_EQUALS:
return Key.Plus;
case SDL.SDL_Keycode.SDLK_LEFTBRACKET:
return Key.BracketLeft;
case SDL.SDL_Keycode.SDLK_BACKSLASH:
return Key.BackSlash;
case SDL.SDL_Keycode.SDLK_RIGHTBRACKET:
return Key.BracketRight;
case SDL.SDL_Keycode.SDLK_BACKQUOTE:
return Key.Tilde;
case SDL.SDL_Keycode.SDLK_a:
return Key.A;
case SDL.SDL_Keycode.SDLK_b:
return Key.B;
case SDL.SDL_Keycode.SDLK_c:
return Key.C;
case SDL.SDL_Keycode.SDLK_d:
return Key.D;
case SDL.SDL_Keycode.SDLK_e:
return Key.E;
case SDL.SDL_Keycode.SDLK_f:
return Key.F;
case SDL.SDL_Keycode.SDLK_g:
return Key.G;
case SDL.SDL_Keycode.SDLK_h:
return Key.H;
case SDL.SDL_Keycode.SDLK_i:
return Key.I;
case SDL.SDL_Keycode.SDLK_j:
return Key.J;
case SDL.SDL_Keycode.SDLK_k:
return Key.K;
case SDL.SDL_Keycode.SDLK_l:
return Key.L;
case SDL.SDL_Keycode.SDLK_m:
return Key.M;
case SDL.SDL_Keycode.SDLK_n:
return Key.N;
case SDL.SDL_Keycode.SDLK_o:
return Key.O;
case SDL.SDL_Keycode.SDLK_p:
return Key.P;
case SDL.SDL_Keycode.SDLK_q:
return Key.Q;
case SDL.SDL_Keycode.SDLK_r:
return Key.R;
case SDL.SDL_Keycode.SDLK_s:
return Key.S;
case SDL.SDL_Keycode.SDLK_t:
return Key.T;
case SDL.SDL_Keycode.SDLK_u:
return Key.U;
case SDL.SDL_Keycode.SDLK_v:
return Key.V;
case SDL.SDL_Keycode.SDLK_w:
return Key.W;
case SDL.SDL_Keycode.SDLK_x:
return Key.X;
case SDL.SDL_Keycode.SDLK_y:
return Key.Y;
case SDL.SDL_Keycode.SDLK_z:
return Key.Z;
case SDL.SDL_Keycode.SDLK_CAPSLOCK:
return Key.CapsLock;
case SDL.SDL_Keycode.SDLK_F1:
return Key.F1;
case SDL.SDL_Keycode.SDLK_F2:
return Key.F2;
case SDL.SDL_Keycode.SDLK_F3:
return Key.F3;
case SDL.SDL_Keycode.SDLK_F4:
return Key.F4;
case SDL.SDL_Keycode.SDLK_F5:
return Key.F5;
case SDL.SDL_Keycode.SDLK_F6:
return Key.F6;
case SDL.SDL_Keycode.SDLK_F7:
return Key.F7;
case SDL.SDL_Keycode.SDLK_F8:
return Key.F8;
case SDL.SDL_Keycode.SDLK_F9:
return Key.F9;
case SDL.SDL_Keycode.SDLK_F10:
return Key.F10;
case SDL.SDL_Keycode.SDLK_F11:
return Key.F11;
case SDL.SDL_Keycode.SDLK_F12:
return Key.F12;
case SDL.SDL_Keycode.SDLK_PRINTSCREEN:
return Key.PrintScreen;
case SDL.SDL_Keycode.SDLK_SCROLLLOCK:
return Key.ScrollLock;
case SDL.SDL_Keycode.SDLK_PAUSE:
return Key.Pause;
case SDL.SDL_Keycode.SDLK_INSERT:
return Key.Insert;
case SDL.SDL_Keycode.SDLK_HOME:
return Key.Home;
case SDL.SDL_Keycode.SDLK_PAGEUP:
return Key.PageUp;
case SDL.SDL_Keycode.SDLK_DELETE:
return Key.Delete;
case SDL.SDL_Keycode.SDLK_END:
return Key.End;
case SDL.SDL_Keycode.SDLK_PAGEDOWN:
return Key.PageDown;
case SDL.SDL_Keycode.SDLK_RIGHT:
return Key.Right;
case SDL.SDL_Keycode.SDLK_LEFT:
return Key.Left;
case SDL.SDL_Keycode.SDLK_DOWN:
return Key.Down;
case SDL.SDL_Keycode.SDLK_UP:
return Key.Up;
case SDL.SDL_Keycode.SDLK_NUMLOCKCLEAR:
return Key.NumLock;
case SDL.SDL_Keycode.SDLK_KP_DIVIDE:
return Key.KeypadDivide;
case SDL.SDL_Keycode.SDLK_KP_MULTIPLY:
return Key.KeypadMultiply;
case SDL.SDL_Keycode.SDLK_KP_MINUS:
return Key.KeypadMinus;
case SDL.SDL_Keycode.SDLK_KP_PLUS:
return Key.KeypadPlus;
case SDL.SDL_Keycode.SDLK_KP_ENTER:
return Key.KeypadEnter;
case SDL.SDL_Keycode.SDLK_KP_1:
return Key.Keypad1;
case SDL.SDL_Keycode.SDLK_KP_2:
return Key.Keypad2;
case SDL.SDL_Keycode.SDLK_KP_3:
return Key.Keypad3;
case SDL.SDL_Keycode.SDLK_KP_4:
return Key.Keypad4;
case SDL.SDL_Keycode.SDLK_KP_5:
return Key.Keypad5;
case SDL.SDL_Keycode.SDLK_KP_6:
return Key.Keypad6;
case SDL.SDL_Keycode.SDLK_KP_7:
return Key.Keypad7;
case SDL.SDL_Keycode.SDLK_KP_8:
return Key.Keypad8;
case SDL.SDL_Keycode.SDLK_KP_9:
return Key.Keypad9;
case SDL.SDL_Keycode.SDLK_KP_0:
return Key.Keypad0;
case SDL.SDL_Keycode.SDLK_KP_PERIOD:
return Key.KeypadPeriod;
case SDL.SDL_Keycode.SDLK_F13:
return Key.F13;
case SDL.SDL_Keycode.SDLK_F14:
return Key.F14;
case SDL.SDL_Keycode.SDLK_F15:
return Key.F15;
case SDL.SDL_Keycode.SDLK_F16:
return Key.F16;
case SDL.SDL_Keycode.SDLK_F17:
return Key.F17;
case SDL.SDL_Keycode.SDLK_F18:
return Key.F18;
case SDL.SDL_Keycode.SDLK_F19:
return Key.F19;
case SDL.SDL_Keycode.SDLK_F20:
return Key.F20;
case SDL.SDL_Keycode.SDLK_F21:
return Key.F21;
case SDL.SDL_Keycode.SDLK_F22:
return Key.F22;
case SDL.SDL_Keycode.SDLK_F23:
return Key.F23;
case SDL.SDL_Keycode.SDLK_F24:
return Key.F24;
case SDL.SDL_Keycode.SDLK_MENU:
return Key.Menu;
case SDL.SDL_Keycode.SDLK_STOP:
return Key.Stop;
case SDL.SDL_Keycode.SDLK_MUTE:
return Key.Mute;
case SDL.SDL_Keycode.SDLK_VOLUMEUP:
return Key.VolumeUp;
case SDL.SDL_Keycode.SDLK_VOLUMEDOWN:
return Key.VolumeDown;
case SDL.SDL_Keycode.SDLK_CLEAR:
return Key.Clear;
case SDL.SDL_Keycode.SDLK_DECIMALSEPARATOR:
return Key.KeypadDecimal;
case SDL.SDL_Keycode.SDLK_LCTRL:
return Key.ControlLeft;
case SDL.SDL_Keycode.SDLK_LSHIFT:
return Key.ShiftLeft;
case SDL.SDL_Keycode.SDLK_LALT:
return Key.AltLeft;
case SDL.SDL_Keycode.SDLK_LGUI:
return Key.WinLeft;
case SDL.SDL_Keycode.SDLK_RCTRL:
return Key.ControlRight;
case SDL.SDL_Keycode.SDLK_RSHIFT:
return Key.ShiftRight;
case SDL.SDL_Keycode.SDLK_RALT:
return Key.AltRight;
case SDL.SDL_Keycode.SDLK_RGUI:
return Key.WinRight;
case SDL.SDL_Keycode.SDLK_AUDIONEXT:
return Key.TrackNext;
case SDL.SDL_Keycode.SDLK_AUDIOPREV:
return Key.TrackPrevious;
case SDL.SDL_Keycode.SDLK_AUDIOSTOP:
return Key.Stop;
case SDL.SDL_Keycode.SDLK_AUDIOPLAY:
return Key.PlayPause;
case SDL.SDL_Keycode.SDLK_AUDIOMUTE:
return Key.Mute;
case SDL.SDL_Keycode.SDLK_SLEEP:
return Key.Sleep;
}
}
public static WindowState ToWindowState(this SDL.SDL_WindowFlags windowFlags)
{
// NOTE: on macOS, SDL2 does not differentiate between "maximised" and "fullscreen desktop"
if (windowFlags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP) ||
windowFlags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS) && windowFlags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN) ||
windowFlags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED) && RuntimeInfo.OS == RuntimeInfo.Platform.MacOsx)
return WindowState.FullscreenBorderless;
if (windowFlags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_MINIMIZED))
return WindowState.Minimised;
if (windowFlags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN))
return WindowState.Fullscreen;
if (windowFlags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED))
return WindowState.Maximised;
return WindowState.Normal;
}
public static SDL.SDL_WindowFlags ToFlags(this WindowState state)
{
switch (state)
{
case WindowState.Normal:
return 0;
case WindowState.Fullscreen:
return SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN;
case WindowState.Maximised:
return RuntimeInfo.OS == RuntimeInfo.Platform.MacOsx
? SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP
: SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED;
case WindowState.Minimised:
return SDL.SDL_WindowFlags.SDL_WINDOW_MINIMIZED;
case WindowState.FullscreenBorderless:
return SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP;
}
return 0;
}
}
}
| |
// MsdnDocumenter.cs - a MSDN-like documenter
// Copyright (C) 2001 Kral Ferch, Jason Diamond
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Globalization;
using NDoc.Core;
using NDoc.Core.Reflection;
namespace NDoc.Documenter.Msdn2
{
/// <summary>The MsdnDocumenter class.</summary>
public class Msdn2Documenter : BaseReflectionDocumenter
{
enum WhichType
{
Class,
Interface,
Structure,
Enumeration,
Delegate,
Unknown
};
private HtmlHelp htmlHelp;
private XmlDocument xmlDocumentation;
private XPathDocument xpathDocument;
private Hashtable lowerCaseTypeNames;
private Hashtable mixedCaseTypeNames;
private StringDictionary fileNames;
private StringDictionary elemNames;
private MsdnXsltUtilities utilities;
private StyleSheetCollection stylesheets;
private Encoding currentFileEncoding;
private ArrayList documentedNamespaces;
private Workspace workspace;
/// <summary>
/// Initializes a new instance of the <see cref="Msdn2Documenter" />
/// class.
/// </summary>
public Msdn2Documenter( Msdn2DocumenterConfig config ) : base( config )
{
lowerCaseTypeNames = new Hashtable();
lowerCaseTypeNames.Add(WhichType.Class, "class");
lowerCaseTypeNames.Add(WhichType.Interface, "interface");
lowerCaseTypeNames.Add(WhichType.Structure, "structure");
lowerCaseTypeNames.Add(WhichType.Enumeration, "enumeration");
lowerCaseTypeNames.Add(WhichType.Delegate, "delegate");
mixedCaseTypeNames = new Hashtable();
mixedCaseTypeNames.Add(WhichType.Class, "Class");
mixedCaseTypeNames.Add(WhichType.Interface, "Interface");
mixedCaseTypeNames.Add(WhichType.Structure, "Structure");
mixedCaseTypeNames.Add(WhichType.Enumeration, "Enumeration");
mixedCaseTypeNames.Add(WhichType.Delegate, "Delegate");
fileNames = new StringDictionary();
elemNames = new StringDictionary();
}
/// <summary>See <see cref="IDocumenter"/>.</summary>
public override string MainOutputFile
{
get
{
if ((MyConfig.OutputTarget & OutputType.HtmlHelp) > 0)
{
return Path.Combine(MyConfig.OutputDirectory,
MyConfig.HtmlHelpName + ".chm");
}
else
{
return Path.Combine(MyConfig.OutputDirectory, "index.html");
}
}
}
/// <summary>See <see cref="IDocumenter"/>.</summary>
public override string CanBuild(Project project, bool checkInputOnly)
{
string result = base.CanBuild(project, checkInputOnly);
if (result != null)
{
return result;
}
string AdditionalContentResourceDirectory = MyConfig.AdditionalContentResourceDirectory;
if ( AdditionalContentResourceDirectory.Length != 0 && !Directory.Exists( AdditionalContentResourceDirectory ) )
return string.Format( "The Additional Content Resource Directory {0} could not be found", AdditionalContentResourceDirectory );
string ExtensibilityStylesheet = MyConfig.ExtensibilityStylesheet;
if ( ExtensibilityStylesheet.Length != 0 && !File.Exists( ExtensibilityStylesheet ) )
return string.Format( "The Extensibility Stylesheet file {0} could not be found", ExtensibilityStylesheet );
if (checkInputOnly)
{
return null;
}
if (MyConfig.HtmlHelpName==null || MyConfig.HtmlHelpName.Length==0)
{
return "HtmlHelpName must be specified.";
}
string path = Path.Combine(MyConfig.OutputDirectory,
MyConfig.HtmlHelpName + ".chm");
string temp = Path.Combine(MyConfig.OutputDirectory, "~chm.tmp");
try
{
if (File.Exists(path))
{
//if we can move the file, then it is not open...
File.Move(path, temp);
File.Move(temp, path);
}
}
catch (Exception)
{
result = "The compiled HTML Help file is probably open.\nPlease close it and try again.";
}
return result;
}
/// <summary>See <see cref="IDocumenter"/>.</summary>
public override void Build(Project project)
{
try
{
OnDocBuildingStep(0, "Initializing...");
//Get an Encoding for the current LangID
CultureInfo ci = new CultureInfo(MyConfig.LangID);
currentFileEncoding = Encoding.GetEncoding(ci.TextInfo.ANSICodePage);
// the workspace class is responsible for maintaining the outputdirectory
// and compile intermediate locations
workspace = new MsdnWorkspace( Path.GetFullPath( MyConfig.OutputDirectory ) );
workspace.Clean();
workspace.Prepare();
// Write the embedded css files to the html output directory
EmbeddedResources.WriteEmbeddedResources(
this.GetType().Module.Assembly,
"NDoc.Documenter.Msdn2.css",
workspace.WorkingDirectory);
// Write the embedded icons to the html output directory
EmbeddedResources.WriteEmbeddedResources(
this.GetType().Module.Assembly,
"NDoc.Documenter.Msdn2.images",
workspace.WorkingDirectory);
// Write the embedded scripts to the html output directory
EmbeddedResources.WriteEmbeddedResources(
this.GetType().Module.Assembly,
"NDoc.Documenter.Msdn2.scripts",
workspace.WorkingDirectory);
if ( ((string)MyConfig.AdditionalContentResourceDirectory).Length > 0 )
workspace.ImportContentDirectory( MyConfig.AdditionalContentResourceDirectory );
// Write the external files (FilesToInclude) to the html output directory
foreach( string srcFilePattern in MyConfig.FilesToInclude.Split( '|' ) )
{
if ((srcFilePattern == null) || (srcFilePattern.Length == 0))
continue;
string path = Path.GetDirectoryName(srcFilePattern);
string pattern = Path.GetFileName(srcFilePattern);
// Path.GetDirectoryName can return null in some cases.
// Treat this as an empty string.
if (path == null)
path = string.Empty;
// Make sure we have a fully-qualified path name
if (!Path.IsPathRooted(path))
path = Path.Combine(Environment.CurrentDirectory, path);
// Directory.GetFiles does not accept null or empty string
// for the searchPattern parameter. When no pattern was
// specified, assume all files (*) are wanted.
if ((pattern == null) || (pattern.Length == 0))
pattern = "*";
foreach(string srcFile in Directory.GetFiles(path, pattern))
{
string dstFile = Path.Combine(workspace.WorkingDirectory, Path.GetFileName(srcFile));
File.Copy(srcFile, dstFile, true);
File.SetAttributes(dstFile, FileAttributes.Archive);
}
}
OnDocBuildingStep(10, "Merging XML documentation...");
// Will hold the name of the file name containing the XML doc
string tempFileName = null;
try
{
// determine temp file name
tempFileName = Path.GetTempFileName();
// Let the Documenter base class do it's thing.
MakeXmlFile(project, tempFileName);
// Load the XML documentation into DOM and XPATH doc.
using (FileStream tempFile = File.Open(tempFileName, FileMode.Open, FileAccess.Read))
{
FilteringXmlTextReader fxtr = new FilteringXmlTextReader(tempFile);
xmlDocumentation = new XmlDocument();
xmlDocumentation.Load(fxtr);
tempFile.Seek(0,SeekOrigin.Begin);
XmlTextReader reader = new XmlTextReader(tempFile);
xpathDocument = new XPathDocument(reader, XmlSpace.Preserve);
}
}
finally
{
if (tempFileName != null && File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
}
XmlNodeList typeNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace/*[name()!='documentation']");
if (typeNodes.Count == 0)
{
throw new DocumenterException("There are no documentable types in this project.\n\nAny types that exist in the assemblies you are documenting have been excluded by the current visibility settings.\nFor example, you are attempting to document an internal class, but the 'DocumentInternals' visibility setting is set to False.\n\nNote: C# defaults to 'internal' if no accessibilty is specified, which is often the case for Console apps created in VS.NET...");
}
XmlNodeList namespaceNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace");
int[] indexes = SortNodesByAttribute(namespaceNodes, "name");
XmlNode defaultNamespace = namespaceNodes[indexes[0]];;
string defaultNamespaceName = (string)defaultNamespace.Attributes["name"].Value;
string defaultTopic = defaultNamespaceName + ".html";
// setup for root page
string rootPageFileName = null;
string rootPageTOCName = "Overview";
if ((MyConfig.RootPageFileName != null) && (MyConfig.RootPageFileName != string.Empty))
{
rootPageFileName = MyConfig.RootPageFileName;
defaultTopic = "default.html";
// what to call the top page in the table of contents?
if ((MyConfig.RootPageTOCName != null) && (MyConfig.RootPageTOCName != string.Empty))
{
rootPageTOCName = MyConfig.RootPageTOCName;
}
}
htmlHelp = new HtmlHelp(
workspace.WorkingDirectory,
MyConfig.HtmlHelpName,
defaultTopic,
((MyConfig.OutputTarget & OutputType.HtmlHelp) == 0));
htmlHelp.IncludeFavorites = MyConfig.IncludeFavorites;
htmlHelp.BinaryTOC = MyConfig.BinaryTOC;
htmlHelp.LangID=MyConfig.LangID;
OnDocBuildingStep(25, "Building file mapping...");
MakeFilenames();
string DocLangCode = Enum.GetName(typeof(SdkLanguage),MyConfig.SdkDocLanguage).Replace("_","-");
utilities = new MsdnXsltUtilities(fileNames, elemNames, MyConfig.SdkDocVersion, DocLangCode, MyConfig.SdkLinksOnWeb, currentFileEncoding);
OnDocBuildingStep(30, "Loading XSLT files...");
stylesheets = StyleSheetCollection.LoadStyleSheets(MyConfig.ExtensibilityStylesheet);
OnDocBuildingStep(40, "Generating HTML pages...");
htmlHelp.OpenProjectFile();
//ensure images added to html via script are included
htmlHelp.AddFileToProject("Filter1a.gif");
htmlHelp.AddFileToProject("filter1b.gif");
htmlHelp.AddFileToProject("filter1c.gif");
htmlHelp.AddFileToProject("Requirements1a.gif");
htmlHelp.AddFileToProject("requirements1b.gif");
htmlHelp.AddFileToProject("requirements1c.gif");
htmlHelp.AddFileToProject("seealso1a.gif");
htmlHelp.AddFileToProject("seealso1b.gif");
htmlHelp.AddFileToProject("seealso1c.gif");
htmlHelp.OpenContentsFile(string.Empty, true);
try
{
if (MyConfig.CopyrightHref != null && MyConfig.CopyrightHref != String.Empty)
{
if (!MyConfig.CopyrightHref.StartsWith("http:"))
{
string copyrightFile = Path.Combine(workspace.WorkingDirectory, Path.GetFileName(MyConfig.CopyrightHref));
File.Copy(MyConfig.CopyrightHref, copyrightFile, true);
File.SetAttributes(copyrightFile, FileAttributes.Archive);
htmlHelp.AddFileToProject(Path.GetFileName(MyConfig.CopyrightHref));
}
}
// add root page if requested
if (rootPageFileName != null)
{
if (!File.Exists(rootPageFileName))
{
throw new DocumenterException("Cannot find the documentation's root page file:\n"
+ rootPageFileName);
}
// add the file
string rootPageOutputName = Path.Combine(workspace.WorkingDirectory, "default.html");
if (Path.GetFullPath(rootPageFileName) != Path.GetFullPath(rootPageOutputName))
{
File.Copy(rootPageFileName, rootPageOutputName, true);
File.SetAttributes(rootPageOutputName, FileAttributes.Archive);
}
htmlHelp.AddFileToProject(Path.GetFileName(rootPageOutputName));
htmlHelp.AddFileToContents(rootPageTOCName,
Path.GetFileName(rootPageOutputName));
// depending on peer setting, make root page the container
if (MyConfig.RootPageContainsNamespaces) htmlHelp.OpenBookInContents();
}
documentedNamespaces = new ArrayList();
MakeHtmlForAssemblies();
// close root book if applicable
if (rootPageFileName != null)
{
if (MyConfig.RootPageContainsNamespaces) htmlHelp.CloseBookInContents();
}
}
finally
{
htmlHelp.CloseContentsFile();
htmlHelp.CloseProjectFile();
}
htmlHelp.WriteEmptyIndexFile();
if ((MyConfig.OutputTarget & OutputType.Web) > 0)
{
OnDocBuildingStep(75, "Generating HTML content file...");
// Write the embedded online templates to the html output directory
EmbeddedResources.WriteEmbeddedResources(
this.GetType().Module.Assembly,
"NDoc.Documenter.Msdn2.onlinefiles",
workspace.WorkingDirectory);
using (TemplateWriter indexWriter = new TemplateWriter(
Path.Combine(workspace.WorkingDirectory, "index.html"),
new StreamReader(this.GetType().Module.Assembly.GetManifestResourceStream(
"NDoc.Documenter.Msdn2.onlinetemplates.index.html"))))
{
indexWriter.CopyToLine("\t\t<title><%TITLE%></title>");
indexWriter.WriteLine("\t\t<title>" + MyConfig.HtmlHelpName + "</title>");
indexWriter.CopyToLine("\t\t<frame name=\"main\" src=\"<%HOME_PAGE%>\" frameborder=\"1\">");
indexWriter.WriteLine("\t\t<frame name=\"main\" src=\"" + defaultTopic + "\" frameborder=\"1\">");
indexWriter.CopyToEnd();
indexWriter.Close();
}
Trace.WriteLine("transform the HHC contents file into html");
#if DEBUG
int start = Environment.TickCount;
#endif
//transform the HHC contents file into html
using(StreamReader contentsFile = new StreamReader(htmlHelp.GetPathToContentsFile(),Encoding.Default))
{
xpathDocument=new XPathDocument(contentsFile);
}
using ( StreamWriter streamWriter = new StreamWriter(
File.Open(Path.Combine(workspace.WorkingDirectory, "contents.html"), FileMode.CreateNew, FileAccess.Write, FileShare.None ), Encoding.Default ) )
{
#if(NET_1_0)
//Use overload that is obsolete in v1.1
stylesheets["htmlcontents"].Transform(xpathDocument, null, streamWriter);
#else
//Use new overload so we don't get obsolete warnings - clean compile :)
stylesheets["htmlcontents"].Transform(xpathDocument, null, streamWriter, null);
#endif
}
#if DEBUG
Trace.WriteLine((Environment.TickCount - start).ToString() + " msec.");
#endif
}
if ((MyConfig.OutputTarget & OutputType.HtmlHelp) > 0)
{
OnDocBuildingStep(85, "Compiling HTML Help file...");
htmlHelp.CompileProject();
}
else
{
#if !DEBUG
//remove .hhc file
File.Delete(htmlHelp.GetPathToContentsFile());
#endif
}
OnDocBuildingStep(90, "Writing documentation to output path");
// if we're only building a CHM, copy that to the Outpur dir
if ((MyConfig.OutputTarget & OutputType.HtmlHelp) > 0 && (MyConfig.OutputTarget & OutputType.Web) == 0)
{
workspace.SaveOutputs( "*.chm" );
}
else
{
// otherwise copy everything to the output dir (cause the help file is all the html, not just one chm)
workspace.SaveOutputs( "*.*" );
}
if ( MyConfig.CleanIntermediates )
workspace.CleanIntermediates();
OnDocBuildingStep(100, "Done.");
}
catch(Exception ex)
{
throw new DocumenterException(ex.Message, ex);
}
finally
{
xmlDocumentation = null;
xpathDocument = null;
stylesheets = null;
workspace.RemoveResourceDirectory();
}
}
private Msdn2DocumenterConfig MyConfig
{
get
{
return (Msdn2DocumenterConfig)Config;
}
}
private void MakeFilenames()
{
XmlNodeList namespaces = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace");
foreach (XmlElement namespaceNode in namespaces)
{
string namespaceName = namespaceNode.Attributes["name"].Value;
string namespaceId = "N:" + namespaceName;
fileNames[namespaceId] = GetFilenameForNamespace(namespaceName);
elemNames[namespaceId] = namespaceName;
XmlNodeList types = namespaceNode.SelectNodes("*[@id]");
foreach (XmlElement typeNode in types)
{
string typeId = typeNode.Attributes["id"].Value;
fileNames[typeId] = GetFilenameForType(typeNode);
elemNames[typeId] = typeNode.Attributes["name"].Value;
XmlNodeList members = typeNode.SelectNodes("*[@id]");
foreach (XmlElement memberNode in members)
{
string id = memberNode.Attributes["id"].Value;
switch (memberNode.Name)
{
case "constructor":
fileNames[id] = GetFilenameForConstructor(memberNode);
elemNames[id] = elemNames[typeId];
break;
case "field":
if (typeNode.Name == "enumeration")
fileNames[id] = GetFilenameForType(typeNode);
else
fileNames[id] = GetFilenameForField(memberNode);
elemNames[id] = memberNode.Attributes["name"].Value;
break;
case "property":
fileNames[id] = GetFilenameForProperty(memberNode);
elemNames[id] = memberNode.Attributes["name"].Value;
break;
case "method":
fileNames[id] = GetFilenameForMethod(memberNode);
elemNames[id] = memberNode.Attributes["name"].Value;
break;
case "operator":
fileNames[id] = GetFilenameForOperator(memberNode);
elemNames[id] = memberNode.Attributes["name"].Value;
break;
case "event":
fileNames[id] = GetFilenameForEvent(memberNode);
elemNames[id] = memberNode.Attributes["name"].Value;
break;
}
}
}
}
}
private WhichType GetWhichType(XmlNode typeNode)
{
WhichType whichType;
switch (typeNode.Name)
{
case "class":
whichType = WhichType.Class;
break;
case "interface":
whichType = WhichType.Interface;
break;
case "structure":
whichType = WhichType.Structure;
break;
case "enumeration":
whichType = WhichType.Enumeration;
break;
case "delegate":
whichType = WhichType.Delegate;
break;
default:
whichType = WhichType.Unknown;
break;
}
return whichType;
}
private void MakeHtmlForAssemblies()
{
#if DEBUG
int start = Environment.TickCount;
#endif
MakeHtmlForAssembliesSorted();
#if DEBUG
Trace.WriteLine("Making Html: " + ((Environment.TickCount - start)/1000.0).ToString() + " sec.");
#endif
}
private void MakeHtmlForAssembliesSorted()
{
XmlNodeList assemblyNodes = xmlDocumentation.SelectNodes("/ndoc/assembly");
bool heirTOC = (this.MyConfig.NamespaceTOCStyle == TOCStyle.Hierarchical);
int level = 0;
int[] indexes = SortNodesByAttribute(assemblyNodes, "name");
string[] last = new string[0];
System.Collections.Specialized.NameValueCollection namespaceAssemblies
= new System.Collections.Specialized.NameValueCollection();
int nNodes = assemblyNodes.Count;
for (int i = 0; i < nNodes; i++)
{
XmlNode assemblyNode = assemblyNodes[indexes[i]];
if (assemblyNode.ChildNodes.Count > 0)
{
string assemblyName = (string)assemblyNode.Attributes["name"].Value;
GetNamespacesFromAssembly(assemblyName, namespaceAssemblies);
}
}
string [] namespaces = namespaceAssemblies.AllKeys;
Array.Sort(namespaces);
nNodes = namespaces.Length;
for (int i = 0; i < nNodes; i++)
{
OnDocBuildingProgress(i*100/nNodes);
if (heirTOC)
{
string[] split = namespaces[i].Split('.');
for (level = last.Length; level >= 0 &&
ArrayEquals(split, 0, last, 0, level) == false; level--)
{
if (level > last.Length)
continue;
MakeHtmlForTypes(string.Join(".", last, 0, level));
htmlHelp.CloseBookInContents();
}
if (level < 0) level = 0;
for (; level < split.Length; level++)
{
string ns = string.Join(".", split, 0, level + 1);
if (Array.BinarySearch(namespaces, ns) < 0)
MakeHtmlForNamespace(split[level], ns, false);
else
MakeHtmlForNamespace(split[level], ns, true);
htmlHelp.OpenBookInContents();
}
last = split;
}
else
{
MakeHtmlForNamespace(namespaces[i], namespaces[i], true);
htmlHelp.OpenBookInContents();
MakeHtmlForTypes(namespaces[i]);
htmlHelp.CloseBookInContents();
}
}
if (heirTOC && last.Length > 0)
{
for (; level >= 1; level--)
{
MakeHtmlForTypes(string.Join(".", last, 0, level));
htmlHelp.CloseBookInContents();
}
}
OnDocBuildingProgress(100);
}
private bool ArrayEquals(string[] array1, int from1, string[] array2, int from2, int count)
{
for (int i = 0; i < count; i++)
{
if (array1[from1 + i] != array2[from2 + i])
return false;
}
return true;
}
private void GetNamespacesFromAssembly(string assemblyName, System.Collections.Specialized.NameValueCollection namespaceAssemblies)
{
XmlNodeList namespaceNodes = xmlDocumentation.SelectNodes("/ndoc/assembly[@name=\"" + assemblyName + "\"]/module/namespace");
foreach (XmlNode namespaceNode in namespaceNodes)
{
string namespaceName = (string)namespaceNode.Attributes["name"].Value;
namespaceAssemblies.Add(namespaceName, assemblyName);
}
}
/// <summary>
/// Add the namespace elements to the output
/// </summary>
/// <remarks>
/// The namespace
/// </remarks>
/// <param name="namespacePart">If nested, the namespace part will be the current
/// namespace element being documented</param>
/// <param name="namespaceName">The full namespace name being documented</param>
/// <param name="addDocumentation">If true, the namespace will be documented, if false
/// the node in the TOC will not link to a page</param>
private void MakeHtmlForNamespace(string namespacePart, string namespaceName,
bool addDocumentation)
{
if (documentedNamespaces.Contains(namespaceName))
return;
documentedNamespaces.Add(namespaceName);
if (addDocumentation)
{
string fileName = GetFilenameForNamespace(namespaceName);
htmlHelp.AddFileToContents(namespacePart, fileName);
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("namespace", String.Empty, namespaceName);
TransformAndWriteResult("namespace", arguments, fileName);
arguments = new XsltArgumentList();
arguments.AddParam("namespace", String.Empty, namespaceName);
TransformAndWriteResult(
"namespacehierarchy",
arguments,
fileName.Insert(fileName.Length - 5, "Hierarchy"));
}
else
htmlHelp.AddFileToContents(namespacePart);
}
private void MakeHtmlForTypes(string namespaceName)
{
XmlNodeList typeNodes =
xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace[@name=\"" + namespaceName + "\"]/*[local-name()!='documentation' and local-name()!='typeHierarchy']");
int[] indexes = SortNodesByAttribute(typeNodes, "id");
int nNodes = typeNodes.Count;
for (int i = 0; i < nNodes; i++)
{
XmlNode typeNode = typeNodes[indexes[i]];
WhichType whichType = GetWhichType(typeNode);
switch(whichType)
{
case WhichType.Class:
MakeHtmlForInterfaceOrClassOrStructure(whichType, typeNode);
break;
case WhichType.Interface:
MakeHtmlForInterfaceOrClassOrStructure(whichType, typeNode);
break;
case WhichType.Structure:
MakeHtmlForInterfaceOrClassOrStructure(whichType, typeNode);
break;
case WhichType.Enumeration:
MakeHtmlForEnumerationOrDelegate(whichType, typeNode);
break;
case WhichType.Delegate:
MakeHtmlForEnumerationOrDelegate(whichType, typeNode);
break;
default:
break;
}
}
}
private void MakeHtmlForEnumerationOrDelegate(WhichType whichType, XmlNode typeNode)
{
string typeName = typeNode.Attributes["name"].Value;
string typeID = typeNode.Attributes["id"].Value;
string fileName = GetFilenameForType(typeNode);
htmlHelp.AddFileToContents(typeName + " " + mixedCaseTypeNames[whichType], fileName, HtmlHelpIcon.Page );
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("type-id", String.Empty, typeID);
TransformAndWriteResult("type", arguments, fileName);
}
private void MakeHtmlForInterfaceOrClassOrStructure(
WhichType whichType,
XmlNode typeNode)
{
string typeName = typeNode.Attributes["name"].Value;
string typeID = typeNode.Attributes["id"].Value;
string fileName = GetFilenameForType(typeNode);
htmlHelp.AddFileToContents(typeName + " " + mixedCaseTypeNames[whichType], fileName);
bool hasMembers = typeNode.SelectNodes("constructor|field|property|method|operator|event").Count > 0;
if (hasMembers)
{
htmlHelp.OpenBookInContents();
}
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("type-id", String.Empty, typeID);
TransformAndWriteResult("type", arguments, fileName);
if ( typeNode.SelectNodes( "derivedBy" ).Count > 5 )
{
fileName = GetFilenameForTypeHierarchy(typeNode);
arguments = new XsltArgumentList();
arguments.AddParam("type-id", String.Empty, typeID);
TransformAndWriteResult("typehierarchy", arguments, fileName);
}
if (hasMembers)
{
fileName = GetFilenameForTypeMembers(typeNode);
htmlHelp.AddFileToContents(typeName + " Members",
fileName,
HtmlHelpIcon.Page);
arguments = new XsltArgumentList();
arguments.AddParam("id", String.Empty, typeID);
TransformAndWriteResult("allmembers", arguments, fileName);
MakeHtmlForConstructors(whichType, typeNode);
MakeHtmlForFields(whichType, typeNode);
MakeHtmlForProperties(whichType, typeNode);
MakeHtmlForMethods(whichType, typeNode);
MakeHtmlForOperators(whichType, typeNode);
MakeHtmlForEvents(whichType, typeNode);
htmlHelp.CloseBookInContents();
}
}
private void MakeHtmlForConstructors(WhichType whichType, XmlNode typeNode)
{
XmlNodeList constructorNodes;
string constructorID;
string typeName;
//string typeID;
string fileName;
typeName = typeNode.Attributes["name"].Value;
//typeID = typeNode.Attributes["id"].Value;
constructorNodes = typeNode.SelectNodes("constructor[@contract!='Static']");
// If the constructor is overloaded then make an overload page.
if (constructorNodes.Count > 1)
{
fileName = GetFilenameForConstructors(typeNode);
htmlHelp.AddFileToContents(typeName + " Constructor", fileName);
htmlHelp.OpenBookInContents();
constructorID = constructorNodes[0].Attributes["id"].Value;
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, constructorID);
TransformAndWriteResult("memberoverload", arguments, fileName);
}
foreach (XmlNode constructorNode in constructorNodes)
{
constructorID = constructorNode.Attributes["id"].Value;
fileName = GetFilenameForConstructor(constructorNode);
if (constructorNodes.Count > 1)
{
XmlNodeList parameterNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace/" + lowerCaseTypeNames[whichType] + "[@name=\"" + typeName + "\"]/constructor[@id=\"" + constructorID + "\"]/parameter");
htmlHelp.AddFileToContents(typeName + " Constructor " + GetParamList(parameterNodes), fileName,
HtmlHelpIcon.Page );
}
else
{
htmlHelp.AddFileToContents(typeName + " Constructor", fileName, HtmlHelpIcon.Page );
}
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, constructorID);
TransformAndWriteResult("member", arguments, fileName);
}
if (constructorNodes.Count > 1)
{
htmlHelp.CloseBookInContents();
}
XmlNode staticConstructorNode = typeNode.SelectSingleNode("constructor[@contract='Static']");
if (staticConstructorNode != null)
{
constructorID = staticConstructorNode.Attributes["id"].Value;
fileName = GetFilenameForConstructor(staticConstructorNode);
htmlHelp.AddFileToContents(typeName + " Static Constructor", fileName, HtmlHelpIcon.Page);
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, constructorID);
TransformAndWriteResult("member", arguments, fileName);
}
}
private void MakeHtmlForFields(WhichType whichType, XmlNode typeNode)
{
XmlNodeList fields = typeNode.SelectNodes("field[not(@declaringType)]");
if (fields.Count > 0)
{
//string typeName = typeNode.Attributes["name"].Value;
string typeID = typeNode.Attributes["id"].Value;
string fileName = GetFilenameForFields(whichType, typeNode);
htmlHelp.AddFileToContents("Fields", fileName);
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("id", String.Empty, typeID);
arguments.AddParam("member-type", String.Empty, "field");
TransformAndWriteResult("individualmembers", arguments, fileName);
htmlHelp.OpenBookInContents();
int[] indexes = SortNodesByAttribute(fields, "id");
foreach (int index in indexes)
{
XmlNode field = fields[index];
string fieldName = field.Attributes["name"].Value;
string fieldID = field.Attributes["id"].Value;
fileName = GetFilenameForField(field);
htmlHelp.AddFileToContents(fieldName + " Field", fileName, HtmlHelpIcon.Page );
arguments = new XsltArgumentList();
arguments.AddParam("field-id", String.Empty, fieldID);
TransformAndWriteResult("field", arguments, fileName);
}
htmlHelp.CloseBookInContents();
}
}
private void MakeHtmlForProperties(WhichType whichType, XmlNode typeNode)
{
XmlNodeList declaredPropertyNodes = typeNode.SelectNodes("property[not(@declaringType)]");
if (declaredPropertyNodes.Count > 0)
{
XmlNodeList propertyNodes;
XmlNode propertyNode;
string propertyName;
string propertyID;
string previousPropertyName;
string nextPropertyName;
bool bOverloaded = false;
string typeName;
string typeID;
string fileName;
int nNodes;
int[] indexes;
int i;
typeName = typeNode.Attributes["name"].Value;
typeID = typeNode.Attributes["id"].Value;
propertyNodes = typeNode.SelectNodes("property[not(@declaringType)]");
nNodes = propertyNodes.Count;
indexes = SortNodesByAttribute(propertyNodes, "id");
fileName = GetFilenameForProperties(whichType, typeNode);
htmlHelp.AddFileToContents("Properties", fileName);
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("id", String.Empty, typeID);
arguments.AddParam("member-type", String.Empty, "property");
TransformAndWriteResult("individualmembers", arguments, fileName);
htmlHelp.OpenBookInContents();
for (i = 0; i < nNodes; i++)
{
propertyNode = propertyNodes[indexes[i]];
propertyName = (string)propertyNode.Attributes["name"].Value;
propertyID = (string)propertyNode.Attributes["id"].Value;
// If the method is overloaded then make an overload page.
previousPropertyName = ((i - 1 < 0) || (propertyNodes[indexes[i - 1]].Attributes.Count == 0))
? "" : propertyNodes[indexes[i - 1]].Attributes[0].Value;
nextPropertyName = ((i + 1 == nNodes) || (propertyNodes[indexes[i + 1]].Attributes.Count == 0))
? "" : propertyNodes[indexes[i + 1]].Attributes[0].Value;
if ((previousPropertyName != propertyName) && (nextPropertyName == propertyName))
{
fileName = GetFilenameForPropertyOverloads(typeNode, propertyNode);
htmlHelp.AddFileToContents(propertyName + " Property", fileName);
arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, propertyID);
TransformAndWriteResult("memberoverload", arguments, fileName);
htmlHelp.OpenBookInContents();
bOverloaded = true;
}
fileName = GetFilenameForProperty(propertyNode);
if (bOverloaded)
{
XmlNodeList parameterNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace/" + lowerCaseTypeNames[whichType] + "[@name=\"" + typeName + "\"]/property[@id=\"" + propertyID + "\"]/parameter");
htmlHelp.AddFileToContents(propertyName + " Property " + GetParamList(parameterNodes), fileName,
HtmlHelpIcon.Page );
}
else
{
htmlHelp.AddFileToContents(propertyName + " Property", fileName,
HtmlHelpIcon.Page );
}
XsltArgumentList arguments2 = new XsltArgumentList();
arguments2.AddParam("property-id", String.Empty, propertyID);
TransformAndWriteResult("property", arguments2, fileName);
if ((previousPropertyName == propertyName) && (nextPropertyName != propertyName))
{
htmlHelp.CloseBookInContents();
bOverloaded = false;
}
}
htmlHelp.CloseBookInContents();
}
}
private string GetPreviousMethodName(XmlNodeList methodNodes, int[] indexes, int index)
{
while (--index >= 0)
{
if (methodNodes[indexes[index]].Attributes["declaringType"] == null)
return methodNodes[indexes[index]].Attributes["name"].Value;
}
return null;
}
private string GetNextMethodName(XmlNodeList methodNodes, int[] indexes, int index)
{
while (++index < methodNodes.Count)
{
if (methodNodes[indexes[index]].Attributes["declaringType"] == null)
return methodNodes[indexes[index]].Attributes["name"].Value;
}
return null;
}
// returns true, if method is neither overload of a method in the same class,
// nor overload of a method in the base class.
private bool IsMethodAlone(XmlNodeList methodNodes, int[] indexes, int index)
{
string name = methodNodes[indexes[index]].Attributes["name"].Value;
int lastIndex = methodNodes.Count - 1;
if (lastIndex <= 0)
return true;
bool previousNameDifferent = (index == 0)
|| (methodNodes[indexes[index - 1]].Attributes["name"].Value != name);
bool nextNameDifferent = (index == lastIndex)
|| (methodNodes[indexes[index + 1]].Attributes["name"].Value != name);
return (previousNameDifferent && nextNameDifferent);
}
private bool IsMethodFirstOverload(XmlNodeList methodNodes, int[] indexes, int index)
{
if ((methodNodes[indexes[index]].Attributes["declaringType"] != null)
|| IsMethodAlone(methodNodes, indexes, index))
return false;
string name = methodNodes[indexes[index]].Attributes["name"].Value;
string previousName = GetPreviousMethodName(methodNodes, indexes, index);
return previousName != name;
}
private bool IsMethodLastOverload(XmlNodeList methodNodes, int[] indexes, int index)
{
if ((methodNodes[indexes[index]].Attributes["declaringType"] != null)
|| IsMethodAlone(methodNodes, indexes, index))
return false;
string name = methodNodes[indexes[index]].Attributes["name"].Value;
string nextName = GetNextMethodName(methodNodes, indexes, index);
return nextName != name;
}
private void MakeHtmlForMethods(WhichType whichType, XmlNode typeNode)
{
XmlNodeList declaredMethodNodes = typeNode.SelectNodes("method[not(@declaringType)]");
if (declaredMethodNodes.Count > 0)
{
bool bOverloaded = false;
string fileName;
string typeName = typeNode.Attributes["name"].Value;
string typeID = typeNode.Attributes["id"].Value;
XmlNodeList methodNodes = typeNode.SelectNodes("method");
int nNodes = methodNodes.Count;
int[] indexes = SortNodesByAttribute(methodNodes, "id");
fileName = GetFilenameForMethods(whichType, typeNode);
htmlHelp.AddFileToContents("Methods", fileName);
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("id", String.Empty, typeID);
arguments.AddParam("member-type", String.Empty, "method");
TransformAndWriteResult("individualmembers", arguments, fileName);
htmlHelp.OpenBookInContents();
for (int i = 0; i < nNodes; i++)
{
XmlNode methodNode = methodNodes[indexes[i]];
string methodName = (string)methodNode.Attributes["name"].Value;
string methodID = (string)methodNode.Attributes["id"].Value;
if (IsMethodFirstOverload(methodNodes, indexes, i))
{
bOverloaded = true;
fileName = GetFilenameForMethodOverloads(typeNode, methodNode);
htmlHelp.AddFileToContents(methodName + " Method", fileName);
arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, methodID);
TransformAndWriteResult("memberoverload", arguments, fileName);
htmlHelp.OpenBookInContents();
}
if (methodNode.Attributes["declaringType"] == null)
{
fileName = GetFilenameForMethod(methodNode);
if (bOverloaded)
{
XmlNodeList parameterNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace/" + lowerCaseTypeNames[whichType] + "[@name=\"" + typeName + "\"]/method[@id=\"" + methodID + "\"]/parameter");
htmlHelp.AddFileToContents(methodName + " Method " + GetParamList(parameterNodes), fileName,
HtmlHelpIcon.Page );
}
else
{
htmlHelp.AddFileToContents(methodName + " Method", fileName,
HtmlHelpIcon.Page );
}
XsltArgumentList arguments2 = new XsltArgumentList();
arguments2.AddParam("member-id", String.Empty, methodID);
TransformAndWriteResult("member", arguments2, fileName);
}
if (bOverloaded && IsMethodLastOverload(methodNodes, indexes, i))
{
bOverloaded = false;
htmlHelp.CloseBookInContents();
}
}
htmlHelp.CloseBookInContents();
}
}
private void MakeHtmlForOperators(WhichType whichType, XmlNode typeNode)
{
XmlNodeList operators = typeNode.SelectNodes("operator");
if (operators.Count > 0)
{
string typeName = (string)typeNode.Attributes["name"].Value;
string typeID = (string)typeNode.Attributes["id"].Value;
XmlNodeList opNodes = typeNode.SelectNodes("operator");
string fileName = GetFilenameForOperators(whichType, typeNode);
bool bOverloaded = false;
bool bHasOperators = (typeNode.SelectSingleNode("operator[@name != 'op_Explicit' and @name != 'op_Implicit']") != null);;
bool bHasConverters = (typeNode.SelectSingleNode("operator[@name = 'op_Explicit' or @name = 'op_Implicit']") != null);
string title="";
if (bHasOperators)
{
if (bHasConverters)
{
title = "Operators and Type Conversions";
}
else
{
title = "Operators";
}
}
else
{
if (bHasConverters)
{
title = "Type Conversions";
}
}
htmlHelp.AddFileToContents(title, fileName);
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("id", String.Empty, typeID);
arguments.AddParam("member-type", String.Empty, "operator");
TransformAndWriteResult("individualmembers", arguments, fileName);
htmlHelp.OpenBookInContents();
int[] indexes = SortNodesByAttribute(operators, "id");
int nNodes = opNodes.Count;
//operators first
for (int i = 0; i < nNodes; i++)
{
XmlNode operatorNode = operators[indexes[i]];
string operatorID = operatorNode.Attributes["id"].Value;
string opName = (string)operatorNode.Attributes["name"].Value;
if ((opName != "op_Implicit") && (opName != "op_Explicit"))
{
if (IsMethodFirstOverload(opNodes, indexes, i))
{
bOverloaded = true;
fileName = GetFilenameForOperatorsOverloads(typeNode, operatorNode);
htmlHelp.AddFileToContents(GetOperatorName(operatorNode), fileName);
arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, operatorID);
TransformAndWriteResult("memberoverload", arguments, fileName);
htmlHelp.OpenBookInContents();
}
fileName = GetFilenameForOperator(operatorNode);
if (bOverloaded)
{
XmlNodeList parameterNodes = xmlDocumentation.SelectNodes("/ndoc/assembly/module/namespace/" + lowerCaseTypeNames[whichType] + "[@name=\"" + typeName + "\"]/operator[@id=\"" + operatorID + "\"]/parameter");
htmlHelp.AddFileToContents(GetOperatorName(operatorNode) + GetParamList(parameterNodes), fileName,
HtmlHelpIcon.Page);
}
else
{
htmlHelp.AddFileToContents(GetOperatorName(operatorNode), fileName,
HtmlHelpIcon.Page );
}
arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, operatorID);
TransformAndWriteResult("member", arguments, fileName);
if (bOverloaded && IsMethodLastOverload(opNodes, indexes, i))
{
bOverloaded = false;
htmlHelp.CloseBookInContents();
}
}
}
//type converters
for (int i = 0; i < nNodes; i++)
{
XmlNode operatorNode = operators[indexes[i]];
string operatorID = operatorNode.Attributes["id"].Value;
string opName = (string)operatorNode.Attributes["name"].Value;
if ((opName == "op_Implicit") || (opName == "op_Explicit"))
{
fileName = GetFilenameForOperator(operatorNode);
htmlHelp.AddFileToContents(GetOperatorName(operatorNode), fileName,
HtmlHelpIcon.Page );
arguments = new XsltArgumentList();
arguments.AddParam("member-id", String.Empty, operatorID);
TransformAndWriteResult("member", arguments, fileName);
}
}
htmlHelp.CloseBookInContents();
}
}
private string GetOperatorName(XmlNode operatorNode)
{
string name = operatorNode.Attributes["name"].Value;
switch (name)
{
case "op_Decrement": return "Decrement Operator";
case "op_Increment": return "Increment Operator";
case "op_UnaryNegation": return "Unary Negation Operator";
case "op_UnaryPlus": return "Unary Plus Operator";
case "op_LogicalNot": return "Logical Not Operator";
case "op_True": return "True Operator";
case "op_False": return "False Operator";
case "op_AddressOf": return "Address Of Operator";
case "op_OnesComplement": return "Ones Complement Operator";
case "op_PointerDereference": return "Pointer Dereference Operator";
case "op_Addition": return "Addition Operator";
case "op_Subtraction": return "Subtraction Operator";
case "op_Multiply": return "Multiplication Operator";
case "op_Division": return "Division Operator";
case "op_Modulus": return "Modulus Operator";
case "op_ExclusiveOr": return "Exclusive Or Operator";
case "op_BitwiseAnd": return "Bitwise And Operator";
case "op_BitwiseOr": return "Bitwise Or Operator";
case "op_LogicalAnd": return "LogicalAnd Operator";
case "op_LogicalOr": return "Logical Or Operator";
case "op_Assign": return "Assignment Operator";
case "op_LeftShift": return "Left Shift Operator";
case "op_RightShift": return "Right Shift Operator";
case "op_SignedRightShift": return "Signed Right Shift Operator";
case "op_UnsignedRightShift": return "Unsigned Right Shift Operator";
case "op_Equality": return "Equality Operator";
case "op_GreaterThan": return "Greater Than Operator";
case "op_LessThan": return "Less Than Operator";
case "op_Inequality": return "Inequality Operator";
case "op_GreaterThanOrEqual": return "Greater Than Or Equal Operator";
case "op_LessThanOrEqual": return "Less Than Or Equal Operator";
case "op_UnsignedRightShiftAssignment": return "Unsigned Right Shift Assignment Operator";
case "op_MemberSelection": return "Member Selection Operator";
case "op_RightShiftAssignment": return "Right Shift Assignment Operator";
case "op_MultiplicationAssignment": return "Multiplication Assignment Operator";
case "op_PointerToMemberSelection": return "Pointer To Member Selection Operator";
case "op_SubtractionAssignment": return "Subtraction Assignment Operator";
case "op_ExclusiveOrAssignment": return "Exclusive Or Assignment Operator";
case "op_LeftShiftAssignment": return "Left Shift Assignment Operator";
case "op_ModulusAssignment": return "Modulus Assignment Operator";
case "op_AdditionAssignment": return "Addition Assignment Operator";
case "op_BitwiseAndAssignment": return "Bitwise And Assignment Operator";
case "op_BitwiseOrAssignment": return "Bitwise Or Assignment Operator";
case "op_Comma": return "Comma Operator";
case "op_DivisionAssignment": return "Division Assignment Operator";
case "op_Explicit":
XmlNode parameterNode = operatorNode.SelectSingleNode("parameter");
string from = parameterNode.Attributes["type"].Value;
string to = operatorNode.Attributes["returnType"].Value;
return "Explicit " + StripNamespace(from) + " to " + StripNamespace(to) + " Conversion";
case "op_Implicit":
XmlNode parameterNode2 = operatorNode.SelectSingleNode("parameter");
string from2 = parameterNode2.Attributes["type"].Value;
string to2 = operatorNode.Attributes["returnType"].Value;
return "Implicit " + StripNamespace(from2) + " to " + StripNamespace(to2) + " Conversion";
default:
return "ERROR";
}
}
private string StripNamespace(string name)
{
string result = name;
int lastDot = name.LastIndexOf('.');
if (lastDot != -1)
{
result = name.Substring(lastDot + 1);
}
return result;
}
private void MakeHtmlForEvents(WhichType whichType, XmlNode typeNode)
{
XmlNodeList declaredEventNodes = typeNode.SelectNodes("event[not(@declaringType)]");
if (declaredEventNodes.Count > 0)
{
XmlNodeList events = typeNode.SelectNodes("event");
if (events.Count > 0)
{
//string typeName = (string)typeNode.Attributes["name"].Value;
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = GetFilenameForEvents(whichType, typeNode);
htmlHelp.AddFileToContents("Events", fileName);
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("id", String.Empty, typeID);
arguments.AddParam("member-type", String.Empty, "event");
TransformAndWriteResult("individualmembers", arguments, fileName);
htmlHelp.OpenBookInContents();
int[] indexes = SortNodesByAttribute(events, "id");
foreach (int index in indexes)
{
XmlNode eventElement = events[index];
if (eventElement.Attributes["declaringType"] == null)
{
string eventName = (string)eventElement.Attributes["name"].Value;
string eventID = (string)eventElement.Attributes["id"].Value;
fileName = GetFilenameForEvent(eventElement);
htmlHelp.AddFileToContents(eventName + " Event",
fileName,
HtmlHelpIcon.Page);
arguments = new XsltArgumentList();
arguments.AddParam("event-id", String.Empty, eventID);
TransformAndWriteResult("event", arguments, fileName);
}
}
htmlHelp.CloseBookInContents();
}
}
}
private string GetParamList(XmlNodeList parameterNodes)
{
int numberOfNodes = parameterNodes.Count;
int nodeIndex = 1;
string paramList = "(";
foreach (XmlNode parameterNode in parameterNodes)
{
paramList += StripNamespace(parameterNode.Attributes["type"].Value);
if (nodeIndex < numberOfNodes)
{
paramList += ", ";
}
nodeIndex++;
}
paramList += ")";
return paramList;
}
private int[] SortNodesByAttribute(XmlNodeList nodes, string attributeName)
{
int length = nodes.Count;
string[] names = new string[length];
int[] indexes = new int[length];
int i = 0;
foreach (XmlNode node in nodes)
{
names[i] = (string)node.Attributes[attributeName].Value;
indexes[i] = i++;
}
Array.Sort(names, indexes);
return indexes;
}
private void TransformAndWriteResult(
string transformName,
XsltArgumentList arguments,
string filename)
{
Trace.WriteLine(filename);
#if DEBUG
int start = Environment.TickCount;
#endif
ExternalHtmlProvider htmlProvider = new ExternalHtmlProvider(MyConfig, filename);
StreamWriter streamWriter = null;
try
{
using (streamWriter = new StreamWriter(
File.Open(Path.Combine(workspace.WorkingDirectory, filename), FileMode.Create),
currentFileEncoding))
{
arguments.AddParam("ndoc-title", String.Empty, MyConfig.Title);
arguments.AddParam("ndoc-omit-object-tags", String.Empty, ((MyConfig.OutputTarget & OutputType.HtmlHelp) == 0));
arguments.AddParam("ndoc-document-attributes", String.Empty, MyConfig.DocumentAttributes);
arguments.AddParam("ndoc-documented-attributes", String.Empty, MyConfig.DocumentedAttributes);
arguments.AddParam( "ndoc-net-framework-version", "", utilities.FrameworkVersion );
arguments.AddParam( "ndoc-version", "", MyConfig.Version );
arguments.AddParam("ndoc-sdk-doc-base-url", String.Empty, utilities.SdkDocBaseUrl);
arguments.AddParam("ndoc-sdk-doc-file-ext", String.Empty, utilities.SdkDocExt);
arguments.AddExtensionObject("urn:NDocUtil", utilities);
arguments.AddExtensionObject("urn:NDocExternalHtml", htmlProvider);
//reset overloads testing
utilities.Reset();
XslTransform transform = stylesheets[transformName];
#if (NET_1_0)
//Use overload that is now obsolete
transform.Transform(xpathDocument, arguments, streamWriter);
#else
//Use new overload so we don't get obsolete warnings - clean compile :)
transform.Transform(xpathDocument, arguments, streamWriter, null);
#endif
}
}
catch(PathTooLongException e)
{
throw new PathTooLongException(e.Message + "\nThe file that NDoc was trying to create had the following name:\n" + Path.Combine(workspace.WorkingDirectory, filename));
}
#if DEBUG
Debug.WriteLine((Environment.TickCount - start).ToString() + " msec.");
#endif
htmlHelp.AddFileToProject(filename);
}
private string GetFilenameForNamespace(string namespaceName)
{
string fileName = namespaceName + ".html";
return fileName;
}
private string GetFilenameForType(XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + ".html";
return fileName;
}
private string GetFilenameForTypeHierarchy(XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Hierarchy.html";
return fileName;
}
private string GetFilenameForTypeMembers(XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Members.html";
return fileName;
}
private string GetFilenameForConstructors(XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Constructor.html";
return fileName;
}
private string GetFilenameForConstructor(XmlNode constructorNode)
{
string constructorID = (string)constructorNode.Attributes["id"].Value;
int dotHash = constructorID.IndexOf(".#"); // constructors could be #ctor or #cctor
string fileName = constructorID.Substring(2, dotHash - 2);
if (constructorNode.Attributes["contract"].Value == "Static")
fileName += "Static";
fileName += "Constructor";
if (constructorNode.Attributes["overload"] != null)
{
fileName += (string)constructorNode.Attributes["overload"].Value;
}
fileName += ".html";
return fileName;
}
private string GetFilenameForFields(WhichType whichType, XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Fields.html";
return fileName;
}
private string GetFilenameForField(XmlNode fieldNode)
{
string fieldID = (string)fieldNode.Attributes["id"].Value;
string fileName = fieldID.Substring(2) + ".html";
fileName = fileName.Replace("#",".");
return fileName;
}
private string GetFilenameForOperators(WhichType whichType, XmlNode typeNode)
{
string typeID = typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Operators.html";
return fileName;
}
private string GetFilenameForOperatorsOverloads(XmlNode typeNode, XmlNode opNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string opName = (string)opNode.Attributes["name"].Value;
string fileName = typeID.Substring(2) + "." + opName + "_overloads.html";
return fileName;
}
private string GetFilenameForOperator(XmlNode operatorNode)
{
string operatorID = operatorNode.Attributes["id"].Value;
string fileName = operatorID.Substring(2);
int leftParenIndex = fileName.IndexOf('(');
if (leftParenIndex != -1)
{
fileName = fileName.Substring(0, leftParenIndex);
}
if (operatorNode.Attributes["overload"] != null)
{
fileName += "_overload_" + operatorNode.Attributes["overload"].Value;
}
fileName += ".html";
fileName = fileName.Replace("#",".");
return fileName;
}
private string GetFilenameForEvents(WhichType whichType, XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Events.html";
return fileName;
}
private string GetFilenameForEvent(XmlNode eventNode)
{
string eventID = (string)eventNode.Attributes["id"].Value;
string fileName = eventID.Substring(2) + ".html";
fileName = fileName.Replace("#",".");
return fileName;
}
private string GetFilenameForProperties(WhichType whichType, XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Properties.html";
return fileName;
}
private string GetFilenameForPropertyOverloads(XmlNode typeNode, XmlNode propertyNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string propertyName = (string)propertyNode.Attributes["name"].Value;
string fileName = typeID.Substring(2) + propertyName + ".html";
fileName = fileName.Replace("#",".");
return fileName;
}
private string GetFilenameForProperty(XmlNode propertyNode)
{
string propertyID = (string)propertyNode.Attributes["id"].Value;
string fileName = propertyID.Substring(2);
int leftParenIndex = fileName.IndexOf('(');
if (leftParenIndex != -1)
{
fileName = fileName.Substring(0, leftParenIndex);
}
if (propertyNode.Attributes["overload"] != null)
{
fileName += (string)propertyNode.Attributes["overload"].Value;
}
fileName += ".html";
fileName = fileName.Replace("#",".");
return fileName;
}
private string GetFilenameForMethods(WhichType whichType, XmlNode typeNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string fileName = typeID.Substring(2) + "Methods.html";
return fileName;
}
private string GetFilenameForMethodOverloads(XmlNode typeNode, XmlNode methodNode)
{
string typeID = (string)typeNode.Attributes["id"].Value;
string methodName = (string)methodNode.Attributes["name"].Value;
string fileName = typeID.Substring(2) + "." + methodName + "_overloads.html";
return fileName;
}
private string GetFilenameForMethod(XmlNode methodNode)
{
string methodID = (string)methodNode.Attributes["id"].Value;
string fileName = methodID.Substring(2);
int leftParenIndex = fileName.IndexOf('(');
if (leftParenIndex != -1)
{
fileName = fileName.Substring(0, leftParenIndex);
}
fileName = fileName.Replace("#",".");
if (methodNode.Attributes["overload"] != null)
{
fileName += "_overload_" + (string)methodNode.Attributes["overload"].Value;
}
fileName += ".html";
return fileName;
}
/// <summary>
/// This custom reader is used to load the XmlDocument. It removes elements that are not required *before*
/// they are loaded into memory, and hence lowers memory requirements significantly.
/// </summary>
private class FilteringXmlTextReader:XmlTextReader
{
object oNamespaceHierarchy;
object oDocumentation;
object oImplements;
object oAttribute;
public FilteringXmlTextReader(System.IO.Stream file):base(file)
{
base.WhitespaceHandling=WhitespaceHandling.None;
oNamespaceHierarchy = base.NameTable.Add("namespaceHierarchy");
oDocumentation = base.NameTable.Add("documentation");
oImplements = base.NameTable.Add("implements");
oAttribute = base.NameTable.Add("attribute");
}
private bool ShouldSkipElement()
{
return
(
base.Name.Equals(oNamespaceHierarchy)||
base.Name.Equals(oDocumentation)||
base.Name.Equals(oImplements)||
base.Name.Equals(oAttribute)
);
}
public override bool Read()
{
bool notEndOfDoc=base.Read();
if (!notEndOfDoc) return false;
while (notEndOfDoc && (base.NodeType == XmlNodeType.Element) && ShouldSkipElement() )
{
notEndOfDoc=SkipElement(this.Depth);
}
return notEndOfDoc;
}
private bool SkipElement(int startDepth)
{
if (base.IsEmptyElement) return base.Read();
bool notEndOfDoc=true;
while (notEndOfDoc)
{
notEndOfDoc=base.Read();
if ((base.NodeType == XmlNodeType.EndElement) && (this.Depth==startDepth) )
break;
}
if (notEndOfDoc) notEndOfDoc=base.Read();
return notEndOfDoc;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace WindowsGame1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
double angle = 0;
const float FLY_SPEED = 10.0f;
const float RATE_CLOUDS = 0.1f;
const float RATE_CITY_BACKGROUND = 0.2f;
const float RATE_CITY_FOREGROUND = 0.3f;
const float RATE_TREES = 0.4f;
const float RATE_PLAYER = 1.0f;
BackgroundTile bgClouds;
BackgroundTile bgCityBG;
BackgroundTile bgCityFG;
Texture2D texSolidColor;
Rectangle rectGrass;
Color colGrass = Color.DarkGreen;
Texture2D texJoeFly;
Texture2D texJoeHover;
Texture2D texJoeKick;
Texture2D texJoeCurrent;
Vector2 locJoe;
Texture2D texEnemy;
Vector2 locEnemy;
List<Texture2D> texTrees = new List<Texture2D>();
List<Vector2> locTrees = new List<Vector2>();
int ScreenWidth;
int ScreenHeight;
public Game1()
{
ScreenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
ScreenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = true;
graphics.PreferredBackBufferWidth = ScreenWidth;
graphics.PreferredBackBufferHeight = ScreenHeight;
rectGrass = new Rectangle(0, 512, ScreenWidth, ScreenHeight - 256);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
texSolidColor = Content.Load<Texture2D>("images/SolidColor");
texJoeFly = Content.Load<Texture2D>("images/JoeFly");
texJoeHover = Content.Load<Texture2D>("images/JoeHover");
texJoeKick = Content.Load<Texture2D>("images/JoeKick");
texJoeCurrent = texJoeHover;
locJoe = Vector2.Zero;
texEnemy = Content.Load<Texture2D>("images/EnemyRed");
locEnemy = Vector2.Zero;
bgClouds = new BackgroundTile(
RATE_CLOUDS,
Content.Load<Texture2D>("images/Clouds"),
Vector2.Zero,
new Color(0x66, 0x66, 0x66, 0x66));
bgCityBG = new BackgroundTile(
RATE_CITY_BACKGROUND,
Content.Load<Texture2D>("images/City2"),
new Vector2(0, 256),
new Color(0x44, 0x44, 0x66, 0xff));
bgCityFG = new BackgroundTile(
RATE_CITY_FOREGROUND,
Content.Load<Texture2D>("images/City1"),
new Vector2(0, 256),
new Color(0x00, 0x00, 0x33, 0xff));
texTrees.Add(Content.Load<Texture2D>("images/Tree1"));
texTrees.Add(Content.Load<Texture2D>("images/Tree2"));
texTrees.Add(Content.Load<Texture2D>("images/Tree3"));
texTrees.Add(Content.Load<Texture2D>("images/Tree4"));
List<Vector2> locTrees = new List<Vector2>();
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
var gamepad1 = GamePad.GetState(PlayerIndex.One);
var keystate = Keyboard.GetState();
bool exit =
gamepad1.Buttons.Back == ButtonState.Pressed ||
keystate.IsKeyDown(Keys.Escape);
if (exit) { this.Exit(); }
float dx = gamepad1.ThumbSticks.Left.X * FLY_SPEED;
float dy = gamepad1.ThumbSticks.Left.Y * FLY_SPEED;
if (keystate.IsKeyDown(Keys.Up))
{
dy = FLY_SPEED;
}
else if (keystate.IsKeyDown(Keys.Down))
{
dy = -FLY_SPEED;
}
if (keystate.IsKeyDown(Keys.Left))
{
dx = -FLY_SPEED;
}
else if (keystate.IsKeyDown(Keys.Right))
{
dx = FLY_SPEED;
}
bgClouds.deltaX(dx);
bgCityBG.deltaX(dx);
bgCityFG.deltaX(dx);
locJoe.Y -= dy;
locEnemy.X = 200;
locEnemy.Y = 200.0f + 200.0f * (float)Math.Sin(angle);
angle += 0.01;
if (dx < 0)
{
texJoeCurrent = texJoeKick;
}
else if (dx > 0)
{
texJoeCurrent = texJoeFly;
}
else
{
texJoeCurrent = texJoeHover;
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
bgClouds.Draw(spriteBatch, ScreenWidth);
bgCityBG.Draw(spriteBatch, ScreenWidth);
bgCityFG.Draw(spriteBatch, ScreenWidth);
spriteBatch.Draw(texSolidColor, rectGrass, colGrass);
spriteBatch.Draw(texJoeCurrent, locJoe, Color.White);
spriteBatch.Draw(texEnemy, locEnemy, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
using System;
namespace NAudio.Wave
{
/// <summary>
/// Represents Channel for the WaveMixerStream
/// 32 bit output and 16 bit input
/// It's output is always stereo
/// The input stream can be panned
/// </summary>
public class WaveChannel32 : WaveStream, ISampleNotifier
{
private WaveStream sourceStream;
private readonly WaveFormat waveFormat;
private readonly long length;
private readonly int destBytesPerSample;
private readonly int sourceBytesPerSample;
private volatile float volume;
private volatile float pan;
private long position;
/// <summary>
/// Creates a new WaveChannel32
/// </summary>
/// <param name="sourceStream">the source stream</param>
/// <param name="volume">stream volume (1 is 0dB)</param>
/// <param name="pan">pan control (-1 to 1)</param>
public WaveChannel32(WaveStream sourceStream, float volume, float pan)
{
PadWithZeroes = true;
if (sourceStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
throw new ApplicationException("Only PCM supported");
if (sourceStream.WaveFormat.BitsPerSample != 16)
throw new ApplicationException("Only 16 bit audio supported");
// always outputs stereo 32 bit
waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sourceStream.WaveFormat.SampleRate, 2);
destBytesPerSample = 8; // includes stereo factoring
this.sourceStream = sourceStream;
this.volume = volume;
this.pan = pan;
sourceBytesPerSample = sourceStream.WaveFormat.Channels * sourceStream.WaveFormat.BitsPerSample / 8;
length = SourceToDest(sourceStream.Length);
position = 0;
}
private long SourceToDest(long sourceBytes)
{
return (sourceBytes / sourceBytesPerSample) * destBytesPerSample;
}
private long DestToSource(long destBytes)
{
return (destBytes / destBytesPerSample) * sourceBytesPerSample;
}
/// <summary>
/// Creates a WaveChannel32 with default settings
/// </summary>
/// <param name="sourceStream">The source stream</param>
public WaveChannel32(WaveStream sourceStream)
:
this(sourceStream, 1.0f, 0.0f)
{
}
/// <summary>
/// Gets the block alignment for this WaveStream
/// </summary>
public override int BlockAlign
{
get
{
return (int)SourceToDest(sourceStream.BlockAlign);
}
}
/// <summary>
/// Returns the stream length
/// </summary>
public override long Length
{
get
{
return length;
}
}
/// <summary>
/// Gets or sets the current position in the stream
/// </summary>
public override long Position
{
get
{
return position;
}
set
{
lock (this)
{
// make sure we don't get out of sync
value -= (value % BlockAlign);
if (value < 0)
{
sourceStream.Position = 0;
}
else
{
sourceStream.Position = DestToSource(value);
}
// source stream may not have accepted the reposition we gave it
position = SourceToDest(sourceStream.Position);
}
}
}
byte[] sourceBuffer;
/// <summary>
/// Helper function to avoid creating a new buffer every read
/// </summary>
byte[] GetSourceBuffer(int bytesRequired)
{
if (sourceBuffer == null || sourceBuffer.Length < bytesRequired)
{
sourceBuffer = new byte[bytesRequired];
}
return sourceBuffer;
}
/// <summary>
/// Reads bytes from this wave stream
/// </summary>
/// <param name="destBuffer">The destination buffer</param>
/// <param name="offset">Offset into the destination buffer</param>
/// <param name="numBytes">Number of bytes read</param>
/// <returns>Number of bytes read.</returns>
public override int Read(byte[] destBuffer, int offset, int numBytes)
{
int bytesWritten = 0;
// 1. fill with silence
if (position < 0)
{
bytesWritten = (int)Math.Min(numBytes, 0 - position);
for (int n = 0; n < bytesWritten; n++)
destBuffer[n + offset] = 0;
}
if (bytesWritten < numBytes)
{
if (sourceStream.WaveFormat.Channels == 1)
{
int sourceBytesRequired = (numBytes - bytesWritten) / 4;
byte[] sourceBuffer = GetSourceBuffer(sourceBytesRequired);
int read = sourceStream.Read(sourceBuffer, 0, sourceBytesRequired);
MonoToStereo(destBuffer, offset + bytesWritten, sourceBuffer, read);
bytesWritten += (read * 4);
}
else
{
int sourceBytesRequired = (numBytes - bytesWritten) / 2;
byte[] sourceBuffer = GetSourceBuffer(sourceBytesRequired);
int read = sourceStream.Read(sourceBuffer, 0, sourceBytesRequired);
AdjustVolume(destBuffer, offset + bytesWritten, sourceBuffer, read);
bytesWritten += (read * 2);
}
}
// 3. Fill out with zeroes
if (PadWithZeroes && bytesWritten < numBytes)
{
Array.Clear(destBuffer, offset + bytesWritten, numBytes - bytesWritten);
bytesWritten = numBytes;
}
position += bytesWritten;
return bytesWritten;
}
/// <summary>
/// If true, Read always returns the number of bytes requested
/// </summary>
public bool PadWithZeroes { get; set; }
/// <summary>
/// Converts Mono to stereo, adjusting volume and pan
/// </summary>
private unsafe void MonoToStereo(byte[] destBuffer, int offset, byte[] sourceBuffer, int bytesRead)
{
fixed (byte* pDestBuffer = &destBuffer[offset],
pSourceBuffer = &sourceBuffer[0])
{
float* pfDestBuffer = (float*)pDestBuffer;
short* psSourceBuffer = (short*)pSourceBuffer;
// implement better panning laws.
float leftVolume = (pan <= 0) ? volume : (volume * (1 - pan) / 2.0f);
float rightVolume = (pan >= 0) ? volume : (volume * (pan + 1) / 2.0f);
leftVolume = leftVolume / 32768f;
rightVolume = rightVolume / 32768f;
int samplesRead = bytesRead / 2;
for (int n = 0; n < samplesRead; n++)
{
pfDestBuffer[n * 2] = psSourceBuffer[n] * leftVolume;
pfDestBuffer[n * 2 + 1] = psSourceBuffer[n] * rightVolume;
if (Sample != null) RaiseSample(pfDestBuffer[n * 2], pfDestBuffer[n * 2 + 1]);
}
}
}
/// <summary>
/// Converts stereo to stereo
/// </summary>
private unsafe void AdjustVolume(byte[] destBuffer, int offset, byte[] sourceBuffer, int bytesRead)
{
fixed (byte* pDestBuffer = &destBuffer[offset],
pSourceBuffer = &sourceBuffer[0])
{
float* pfDestBuffer = (float*)pDestBuffer;
short* psSourceBuffer = (short*)pSourceBuffer;
// implement better panning laws.
float leftVolume = (pan <= 0) ? volume : (volume * (1 - pan) / 2.0f);
float rightVolume = (pan >= 0) ? volume : (volume * (pan + 1) / 2.0f);
leftVolume = leftVolume / 32768f;
rightVolume = rightVolume / 32768f;
//float leftVolume = (volume * (1 - pan) / 2.0f) / 32768f;
//float rightVolume = (volume * (pan + 1) / 2.0f) / 32768f;
int samplesRead = bytesRead / 2;
for (int n = 0; n < samplesRead; n += 2)
{
pfDestBuffer[n] = psSourceBuffer[n] * leftVolume;
pfDestBuffer[n + 1] = psSourceBuffer[n + 1] * rightVolume;
if (Sample != null) RaiseSample(pfDestBuffer[n], pfDestBuffer[n + 1]);
}
}
}
/// <summary>
/// <see cref="WaveStream.WaveFormat"/>
/// </summary>
public override WaveFormat WaveFormat
{
get
{
return waveFormat;
}
}
/// <summary>
/// Volume of this channel. 1.0 = full scale
/// </summary>
public float Volume
{
get
{
return volume;
}
set
{
volume = value;
}
}
/// <summary>
/// Pan of this channel (from -1 to 1)
/// </summary>
public float Pan
{
get
{
return pan;
}
set
{
pan = value;
}
}
/// <summary>
/// Determines whether this channel has any data to play
/// to allow optimisation to not read, but bump position forward
/// </summary>
public override bool HasData(int count)
{
// Check whether the source stream has data.
bool sourceHasData = sourceStream.HasData(count);
if (sourceHasData)
{
if (position + count < 0)
return false;
return (position < length) && (volume != 0);
}
return false;
}
/// <summary>
/// Disposes this WaveStream
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (sourceStream != null)
{
sourceStream.Dispose();
sourceStream = null;
}
}
else
{
System.Diagnostics.Debug.Assert(false, "WaveChannel32 was not Disposed");
}
base.Dispose(disposing);
}
/// <summary>
/// Block
/// </summary>
public event EventHandler Block;
private void RaiseBlock()
{
var handler = Block;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
/// <summary>
/// Sample
/// </summary>
public event EventHandler<SampleEventArgs> Sample;
// reuse the same object every time to avoid making lots of work for the garbage collector
private SampleEventArgs sampleEventArgs = new SampleEventArgs(0,0);
/// <summary>
/// Raise the sample event (no check for null because it has already been done)
/// </summary>
private void RaiseSample(float left, float right)
{
sampleEventArgs.Left = left;
sampleEventArgs.Right = right;
Sample(this, sampleEventArgs);
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace GuruComponents.Netrix.UserInterface.ColorPicker
{
/// <summary>
/// A helper class for very fast bitmap operations.
/// </summary>
public unsafe class BitmapUnsafe
{
Bitmap bitmap;
// three elements used for MakeGreyUnsafe
int width;
BitmapData bitmapData = null;
Byte* pBase = null;
/// <summary>
/// Ctor
/// </summary>
/// <param name="bitmap">Bitmap the content is stored in.</param>
public BitmapUnsafe(Bitmap bitmap)
{
this.bitmap = bitmap;
}
/// <summary>
/// Save to bitmap.
/// </summary>
/// <param name="filename"></param>
public void Save(string filename)
{
bitmap.Save(filename, ImageFormat.Jpeg);
}
/// <summary>
/// Dispose bitmap.
/// </summary>
public void Dispose()
{
bitmap.Dispose();
}
/// <summary>
/// Access to related bitmap.
/// </summary>
public Bitmap Bitmap
{
get
{
return(bitmap);
}
}
/// <summary>
/// Size of bitmap.
/// </summary>
public Point PixelSize
{
get
{
GraphicsUnit unit = GraphicsUnit.Pixel;
RectangleF bounds = bitmap.GetBounds(ref unit);
return new Point((int) bounds.Width, (int) bounds.Height);
}
}
/// <summary>
/// Convert all pixels to gray.
/// </summary>
public void MakeGrey()
{
Point size = PixelSize;
LockBitmap();
for (int y = 0; y < size.Y; y++)
{
PixelData* pPixel = PixelAt(0, y);
for (int x = 0; x < size.X; x++)
{
byte value = (byte) ((pPixel->red + pPixel->green + pPixel->blue) / 3);
pPixel->red = value;
pPixel->green = value;
pPixel->blue = value;
pPixel++;
}
}
UnlockBitmap();
}
/// <summary>
/// Make the red palette.
/// </summary>
/// <param name="redValue">The fixed value.</param>
public void MakeRedPalette(byte redValue)
{
LockBitmap();
for (byte y = 0; y < 255; y++)
{
PixelData* pPixel = PixelAt(0, y);
for (byte x = 0; x < 255; x++)
{
pPixel->red = redValue;
pPixel->green = x;
pPixel->blue = y;
pPixel++;
}
}
UnlockBitmap();
}
/// <summary>
/// Make the blue palette.
/// </summary>
/// <param name="blueValue">The fixed value.</param>
public void MakeBluePalette(byte blueValue)
{
LockBitmap();
for (byte y = 0; y < 255; y++)
{
PixelData* pPixel = PixelAt(0, y);
for (byte x = 0; x < 255; x++)
{
pPixel->red = x;
pPixel->green = y;
pPixel->blue = blueValue;
pPixel++;
}
}
UnlockBitmap();
}
/// <summary>
/// Make the green palette.
/// </summary>
/// <param name="greenValue">The fixed value.</param>
public void MakeGreenPalette(byte greenValue)
{
LockBitmap();
for (byte y = 0; y < 255; y++)
{
PixelData* pPixel = PixelAt(0, y);
for (byte x = 0; x < 255; x++)
{
pPixel->red = x;
pPixel->green = greenValue;
pPixel->blue = y;
pPixel++;
}
}
UnlockBitmap();
}
/// <summary>
/// Lock the bitmap.
/// </summary>
public void LockBitmap()
{
GraphicsUnit unit = GraphicsUnit.Pixel;
RectangleF boundsF = bitmap.GetBounds(ref unit);
Rectangle bounds = new Rectangle((int) boundsF.X,
(int) boundsF.Y,
(int) boundsF.Width,
(int) boundsF.Height);
// Figure out the number of bytes in a row
// This is rounded up to be a multiple of 4
// bytes, since a scan line in an image must always be a multiple of 4 bytes
// in length.
width = (int) boundsF.Width * sizeof(PixelData);
if (width % 4 != 0)
{
width = 4 * (width / 4 + 1);
}
bitmapData =
bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
pBase = (Byte*) bitmapData.Scan0.ToPointer();
}
/// <summary>
/// Retrieve a pixel at specified location.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public PixelData* PixelAt(int x, int y)
{
return (PixelData*) (pBase + y * width + x * sizeof(PixelData));
}
/// <summary>
/// Unlock the bitmap.
/// </summary>
public void UnlockBitmap()
{
bitmap.UnlockBits(bitmapData);
bitmapData = null;
pBase = null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace GuestConfiguration.Tests.ScenarioTests
{
using GuestConfiguration.Tests.Helpers;
using GuestConfiguration.Tests.TestSupport;
using Microsoft.Azure.Management.GuestConfiguration;
using Microsoft.Azure.Management.GuestConfiguration.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Xunit;
public class AutomationTest
{
private const string ResourceGroupName = "GuestConfigurationSDKTestRecord";
private const string AzureVMName = "SDKTestRecordVM002";
private const string HybridRG = "gehuan-arc0010";
private const string HybridMachineName = "IamPretendingTo";
private const string AssignmentName = "AuditSecureProtocol";
private const string VMSSRG = "aashishDeleteRG";
private const string VMSSName = "vmss3";
private const string VMSSAssignmentName = "EnforcePasswordHistory$pid5im35hvyml6ow";
[Fact]
public void CanCreateGetUpdateGuestConfigurationAssignment()
{
using (var context = MockContext.Start(this.GetType()))
{
using (var testFixture = new GuestConfigurationTestBase(context))
{
var gcAssignmentToCreateDefinition = new GuestConfigurationAssignmentForPutDefinition(
ResourceGroupName,
AzureVMName,
new GuestConfigurationAssignment(name: AssignmentName,
location: "westcentralus",
properties: new GuestConfigurationAssignmentProperties()
{
Context = "Azure policy A",
GuestConfiguration = new GuestConfigurationNavigation()
{
Name = AssignmentName,
Version = "1.0.0.3"
}
})
);
// create a new guest configuration assignment
var gcAssignmentCreated = GuestConfigurationAssignmentsOperationsExtensions.CreateOrUpdate(testFixture.GuestConfigurationClient.GuestConfigurationAssignments,
gcAssignmentToCreateDefinition.Parameters.Name,
gcAssignmentToCreateDefinition.Parameters,
gcAssignmentToCreateDefinition.ResourceGroupName,
gcAssignmentToCreateDefinition.VmName);
Assert.NotNull(gcAssignmentCreated);
// Get created guest configuration assignment
var gcAssignmentRetrieved = GuestConfigurationAssignmentsOperationsExtensions.Get(testFixture.GuestConfigurationClient.GuestConfigurationAssignments,
gcAssignmentToCreateDefinition.ResourceGroupName,
gcAssignmentToCreateDefinition.Parameters.Name,
gcAssignmentToCreateDefinition.VmName);
Assert.NotNull(gcAssignmentRetrieved);
Assert.Equal(gcAssignmentToCreateDefinition.Parameters.Name, gcAssignmentRetrieved.Name);
// update guest configuration assignment
var updateParameters = gcAssignmentToCreateDefinition.GetParametersForUpdate();
var gcAssignmentUpdated = GuestConfigurationAssignmentsOperationsExtensions.CreateOrUpdate(testFixture.GuestConfigurationClient.GuestConfigurationAssignments,
updateParameters.Name,
updateParameters,
gcAssignmentToCreateDefinition.ResourceGroupName,
gcAssignmentToCreateDefinition.VmName);
Assert.NotNull(gcAssignmentUpdated);
Assert.Equal(updateParameters.Properties.Context, gcAssignmentUpdated.Properties.Context);
}
}
}
[Fact]
public void CanCreateGetUpdateGuestConfigurationHCRPAssignment()
{
using (var context = MockContext.Start(this.GetType()))
{
using (var testFixture = new GuestConfigurationTestBase(context))
{
var gcAssignmentToCreateDefinition = new GuestConfigurationAssignmentForPutDefinition(
HybridRG,
HybridMachineName,
new GuestConfigurationAssignment(name: AssignmentName,
location: "westcentralus",
properties: new GuestConfigurationAssignmentProperties()
{
Context = "Azure policy A",
GuestConfiguration = new GuestConfigurationNavigation()
{
Name = AssignmentName,
Version = "1.0.0.3"
}
})
);
// create a new guest configuration assignment
var gcHCRPAssignmentCreated = GuestConfigurationHCRPAssignmentsOperationsExtensions.CreateOrUpdate(testFixture.GuestConfigurationClient.GuestConfigurationHCRPAssignments,
gcAssignmentToCreateDefinition.Parameters.Name,
gcAssignmentToCreateDefinition.Parameters,
gcAssignmentToCreateDefinition.ResourceGroupName,
gcAssignmentToCreateDefinition.VmName);
Assert.NotNull(gcHCRPAssignmentCreated);
// Get created guest configuration assignment
var gcHCRPAssignmentRetrieved = GuestConfigurationHCRPAssignmentsOperationsExtensions.Get(testFixture.GuestConfigurationClient.GuestConfigurationHCRPAssignments,
gcAssignmentToCreateDefinition.ResourceGroupName,
gcAssignmentToCreateDefinition.Parameters.Name,
gcAssignmentToCreateDefinition.VmName);
Assert.NotNull(gcHCRPAssignmentRetrieved);
Assert.Equal(gcAssignmentToCreateDefinition.Parameters.Name, gcHCRPAssignmentRetrieved.Name);
// update guest configuration assignment
var updateParameters = gcAssignmentToCreateDefinition.GetParametersForUpdate();
var gcHCRPAssignmentUpdated = GuestConfigurationHCRPAssignmentsOperationsExtensions.CreateOrUpdate(testFixture.GuestConfigurationClient.GuestConfigurationHCRPAssignments,
updateParameters.Name,
updateParameters,
gcAssignmentToCreateDefinition.ResourceGroupName,
gcAssignmentToCreateDefinition.VmName);
Assert.NotNull(gcHCRPAssignmentUpdated);
Assert.Equal(updateParameters.Properties.Context, gcHCRPAssignmentUpdated.Properties.Context);
}
}
}
[Fact]
public void CanGetGuestConfigurationAssignmentReports()
{
using (var context = MockContext.Start(this.GetType()))
{
using (var testFixture = new GuestConfigurationTestBase(context))
{
// get guest configuration assignment
var gcAssignment = GuestConfigurationAssignmentsOperationsExtensions.Get(testFixture.GuestConfigurationClient.GuestConfigurationAssignments,
ResourceGroupName,
AssignmentName,
AzureVMName);
Assert.NotNull(gcAssignment);
// Get reports
var gcAssignmentReportsRetrieved = GuestConfigurationAssignmentReportsOperationsExtensions.List(testFixture.GuestConfigurationClient.GuestConfigurationAssignmentReports,
ResourceGroupName,
AssignmentName,
AzureVMName);
Assert.NotNull(gcAssignmentReportsRetrieved);
Assert.True(gcAssignmentReportsRetrieved.Value.Count >= 0);
}
}
}
[Fact]
public void CanGetGuestConfigurationHCRPAssignmentReports()
{
using (var context = MockContext.Start(this.GetType()))
{
using (var testFixture = new GuestConfigurationTestBase(context))
{
// get guest configuration assignment
var gcHCRPAssignment = GuestConfigurationHCRPAssignmentsOperationsExtensions.Get(testFixture.GuestConfigurationClient.GuestConfigurationHCRPAssignments,
HybridRG,
AssignmentName,
HybridMachineName);
Assert.NotNull(gcHCRPAssignment);
// Get reports
var gcHCRPAssignmentReportsRetrieved = GuestConfigurationHCRPAssignmentReportsOperationsExtensions.List(testFixture.GuestConfigurationClient.GuestConfigurationHCRPAssignmentReports,
HybridRG,
AssignmentName,
HybridMachineName);
Assert.NotNull(gcHCRPAssignmentReportsRetrieved);
Assert.True(gcHCRPAssignmentReportsRetrieved.Value.Count >= 0);
}
}
}
[Fact]
public void CanListAllGuestConfigurationAssignments()
{
using (var context = MockContext.Start(this.GetType()))
{
using (var testFixture = new GuestConfigurationTestBase(context))
{
// get guest configuration assignment
var gcAssignments = GuestConfigurationAssignmentsOperationsExtensions.List(testFixture.GuestConfigurationClient.GuestConfigurationAssignments,
ResourceGroupName,
AzureVMName);
Assert.NotNull(gcAssignments);
Assert.True(gcAssignments.IsAny());
}
}
}
[Fact]
public void CanListAllGuestConfigurationHCRPAssignments()
{
using (var context = MockContext.Start(this.GetType()))
{
using (var testFixture = new GuestConfigurationTestBase(context))
{
// get guest configuration assignment
var gcHCRPAssignments = GuestConfigurationHCRPAssignmentsOperationsExtensions.List(testFixture.GuestConfigurationClient.GuestConfigurationHCRPAssignments,
HybridRG,
HybridMachineName);
Assert.NotNull(gcHCRPAssignments);
Assert.True(gcHCRPAssignments.IsAny());
}
}
}
[Fact]
public void CanGetVMSSAssignment()
{
using (var context = MockContext.Start(this.GetType()))
{
using (var testFixture = new GuestConfigurationTestBase(context))
{
var gcVMSSAssignment = GuestConfigurationAssignmentsVMSSOperationsExtensions.Get(testFixture.GuestConfigurationClient.GuestConfigurationAssignmentsVMSS, VMSSRG, VMSSAssignmentName, VMSSName);
Assert.NotNull(gcVMSSAssignment);
var gcVMSSAssignmentReport = GuestConfigurationAssignmentReportsVMSSOperationsExtensions.Get(testFixture.GuestConfigurationClient.GuestConfigurationAssignmentReportsVMSS, VMSSRG, VMSSAssignmentName, "93b97ae8-1e02-466e-af61-2eb6c506d9ec", VMSSName);
Assert.NotNull(gcVMSSAssignmentReport);
}
}
}
}
}
| |
#pragma warning disable 1591
using AjaxControlToolkit.Design;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxControlToolkit {
/// <summary>
/// AutoComplete extends any ASP.NET TextBox control. It associates that control with a
/// popup panel to display words that begin with the prefix that is entered into the text box.
/// </summary>
[Designer(typeof(AutoCompleteExtenderDesigner))]
[ClientScriptResource("Sys.Extended.UI.AutoCompleteBehavior", Constants.AutoCompleteName)]
[RequiredScript(typeof(CommonToolkitScripts))]
[RequiredScript(typeof(PopupExtender))]
[RequiredScript(typeof(TimerScript))]
[RequiredScript(typeof(AnimationExtender))]
[TargetControlType(typeof(TextBox))]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.AutoCompleteName + Constants.IconPostfix)]
public class AutoCompleteExtender : AnimationExtenderControlBase {
/// <summary>
/// Minimum length of text before the webservice provides suggestions.
/// The default is 3
/// </summary>
[DefaultValue(3)]
[ExtenderControlProperty]
[ClientPropertyName("minimumPrefixLength")]
public virtual int MinimumPrefixLength {
get { return GetPropertyValue("MinimumPrefixLength", 3); }
set { SetPropertyValue("MinimumPrefixLength", value); }
}
/// <summary>
/// Time in milliseconds when the timer will kick in to get suggestions using the web service.
/// The default is 1000
/// </summary>
[DefaultValue(1000)]
[ExtenderControlProperty]
[ClientPropertyName("completionInterval")]
public virtual int CompletionInterval {
get { return GetPropertyValue("CompletionInterval", 1000); }
set { SetPropertyValue("CompletionInterval", value); }
}
/// <summary>
/// A number of suggestions to be provided.
/// The default is 10
/// </summary>
[DefaultValue(10)]
[ExtenderControlProperty]
[ClientPropertyName("completionSetCount")]
public virtual int CompletionSetCount {
get { return GetPropertyValue("CompletionSetCount", 10); }
set { SetPropertyValue("CompletionSetCount", value); }
}
/// <summary>
/// ID of an element that will serve as the completion list.
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("completionListElementID")]
[IDReferenceProperty(typeof(WebControl))]
[Obsolete("Instead of passing in CompletionListElementID, use the default flyout and style that using the CssClass properties.")]
public virtual string CompletionListElementID {
get { return GetPropertyValue("CompletionListElementID", String.Empty); }
set { SetPropertyValue("CompletionListElementID", value); }
}
/// <summary>
/// The web service method to be called
/// </summary>
[DefaultValue("")]
[RequiredProperty]
[ExtenderControlProperty]
[ClientPropertyName("serviceMethod")]
public virtual string ServiceMethod {
get { return GetPropertyValue("ServiceMethod", String.Empty); }
set { SetPropertyValue("ServiceMethod", value); }
}
/// <summary>
/// The path to the web service that the extender will pull the
/// word/sentence completions from. If this is not provided, the
/// service method should be a page method.
/// </summary>
[UrlProperty]
[ExtenderControlProperty]
[TypeConverter(typeof(ServicePathConverter))]
[ClientPropertyName("servicePath")]
public virtual string ServicePath {
get { return GetPropertyValue("ServicePath", String.Empty); }
set { SetPropertyValue("ServicePath", value); }
}
/// <summary>
/// User/page specific context provided to an optional overload of the web method described by ServiceMethod/ServicePath.
/// If the context key is used, it should have the same signature with an additional parameter named contextKey of a string type.
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("contextKey")]
[DefaultValue(null)]
public string ContextKey {
get { return GetPropertyValue<string>("ContextKey", null); }
set {
SetPropertyValue<string>("ContextKey", value);
UseContextKey = true;
}
}
/// <summary>
/// Whether or not the ContextKey property should be used.
/// This will be automatically enabled if the ContextKey property is ever set (on either the client or the server).
/// If the context key is used, it should have the same signature with an additional parameter named contextKey of a string type.
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("useContextKey")]
[DefaultValue(false)]
public bool UseContextKey {
get { return GetPropertyValue<bool>("UseContextKey", false); }
set { SetPropertyValue<bool>("UseContextKey", value); }
}
/// <summary>
/// A CSS class that will be used to style the completion list flyout.
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("completionListCssClass")]
public string CompletionListCssClass {
get { return GetPropertyValue("CompletionListCssClass", String.Empty); }
set { SetPropertyValue("CompletionListCssClass", value); }
}
/// <summary>
/// A CSS class that will be used to style an item in the autocomplete list.
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("completionListItemCssClass")]
public string CompletionListItemCssClass {
get { return GetPropertyValue("CompletionListItemCssClass", String.Empty); }
set { SetPropertyValue("CompletionListItemCssClass", value); }
}
/// <summary>
/// A CSS class that will be used to style a highlighted item in the autocomplete list.
/// </summary>
[DefaultValue("")]
[ExtenderControlProperty]
[ClientPropertyName("highlightedItemCssClass")]
public string CompletionListHighlightedItemCssClass {
get { return GetPropertyValue("CompletionListHighlightedItemCssClass", String.Empty); }
set { SetPropertyValue("CompletionListHighlightedItemCssClass", value); }
}
/// <summary>
/// A flag to denote whether client-side caching is enabled.
/// The default is true.
/// </summary>
[DefaultValue(true)]
[ExtenderControlProperty]
[ClientPropertyName("enableCaching")]
public virtual bool EnableCaching {
get { return GetPropertyValue("EnableCaching", true); }
set { SetPropertyValue("EnableCaching", value); }
}
/// <summary>
/// The character(s) used to separate words for autocomplete
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("delimiterCharacters")]
public virtual string DelimiterCharacters {
get { return GetPropertyValue("DelimiterCharacters", String.Empty); }
set { SetPropertyValue("DelimiterCharacters", value); }
}
/// <summary>
/// Determines if the first row of the Search Results is selected by default.
/// The default is false.
/// </summary>
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("firstRowSelected")]
public virtual bool FirstRowSelected {
get { return GetPropertyValue("FirstRowSelected", false); }
set { SetPropertyValue("FirstRowSelected", value); }
}
/// <summary>
/// If delimiter characters are specified and ShowOnlyCurrentWordInCompletionListItem is set to true,
/// then the completion list displays suggestions just for the current word,
/// otherwise, it displays the whole string that will show up in the TextBox
/// if that item is selected, which is the current default.
/// The default is false.
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("showOnlyCurrentWordInCompletionListItem")]
[DefaultValue(false)]
public bool ShowOnlyCurrentWordInCompletionListItem {
get { return GetPropertyValue<bool>("ShowOnlyCurrentWordInCompletionListItem", false); }
set { SetPropertyValue<bool>("ShowOnlyCurrentWordInCompletionListItem", value); }
}
/// <summary>
/// OnShow animation
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("onShow")]
[Browsable(false)]
[DefaultValue(null)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Animation OnShow {
get { return GetAnimation(ref _onShow, "OnShow"); }
set { SetAnimation(ref _onShow, "OnShow", value); }
}
Animation _onShow;
/// <summary>
/// OnHide animation
/// </summary>
[ExtenderControlProperty]
[ClientPropertyName("onHide")]
[Browsable(false)]
[DefaultValue(null)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Animation OnHide {
get { return GetAnimation(ref _onHide, "OnHide"); }
set { SetAnimation(ref _onHide, "OnHide", value); }
}
Animation _onHide;
/// <summary>
/// A handler attached to the client-side populating event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("populating")]
public string OnClientPopulating {
get { return GetPropertyValue("OnClientPopulating", String.Empty); }
set { SetPropertyValue("OnClientPopulating", value); }
}
/// <summary>
/// A handler attached to the client-side populated event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("populated")]
public string OnClientPopulated {
get { return GetPropertyValue("OnClientPopulated", String.Empty); }
set { SetPropertyValue("OnClientPopulated", value); }
}
/// <summary>
/// A handler attached to the client-side showing event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("showing")]
public string OnClientShowing {
get { return GetPropertyValue("OnClientShowing", String.Empty); }
set { SetPropertyValue("OnClientShowing", value); }
}
/// <summary>
/// A handler attached to the client-side shown event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("shown")]
public string OnClientShown {
get { return GetPropertyValue("OnClientShown", String.Empty); }
set { SetPropertyValue("OnClientShown", value); }
}
/// <summary>
/// A handler attached to the client-side hiding event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("hiding")]
public string OnClientHiding {
get { return GetPropertyValue("OnClientHiding", String.Empty); }
set { SetPropertyValue("OnClientHiding", value); }
}
/// <summary>
/// A handler attached to the client-side hidden event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("hidden")]
public string OnClientHidden {
get { return GetPropertyValue("OnClientHidden", String.Empty); }
set { SetPropertyValue("OnClientHidden", value); }
}
/// <summary>
/// A handler attached to the client-side itemSelected event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("itemSelected")]
public string OnClientItemSelected {
get { return GetPropertyValue("OnClientItemSelected", String.Empty); }
set { SetPropertyValue("OnClientItemSelected", value); }
}
/// <summary>
/// A handler attached to the client-side itemOver event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("itemOver")]
public string OnClientItemOver {
get { return GetPropertyValue("OnClientItemOver", String.Empty); }
set { SetPropertyValue("OnClientItemOver", value); }
}
/// <summary>
/// A handler attached to the client-side itemOut event
/// </summary>
[DefaultValue("")]
[ExtenderControlEvent]
[ClientPropertyName("itemOut")]
public string OnClientItemOut {
get { return GetPropertyValue("OnClientItemOut", String.Empty); }
set { SetPropertyValue("OnClientItemOut", value); }
}
// Convert server IDs into ClientIDs for animations
protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
ResolveControlIDs(_onShow);
ResolveControlIDs(_onHide);
}
/// <summary>
/// Creates a serialized JSON object representing a text/value pair that can
/// be returned by the webservice
/// </summary>
/// <param name="text" type="String">Text part</param>
/// <param name="value" type="String">Value part</param>
/// <returns>Serialized JSON</returns>
public static string CreateAutoCompleteItem(string text, string value) {
return new JavaScriptSerializer().Serialize(new Pair(text, value));
}
}
}
#pragma warning restore 1591
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace Alchemi.Core.EndPointUtils
{
/// <summary>
/// The control for advanced setting of EndPoint element.
/// </summary>
public partial class AdvancedEndPointControl : UserControl
{
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public AdvancedEndPointControl()
{
InitializeComponent();
CustomInit();
}
#endregion
#region Properties
#region Private
#region AllowedProtocols
private System.Collections.Generic.List<string> _allowedProtocols = null;
private System.Collections.Generic.List<string> AllowedProtocols
{
get
{
if (_allowedProtocols == null)
_allowedProtocols = new System.Collections.Generic.List<string>();
return _allowedProtocols;
}
}
#endregion
#endregion
#region Public
#region SelectedRemotingMechanism
/// <summary>
/// Selected remoting Mechanism.
/// </summary>
public RemotingMechanism SelectedRemotingMechanism
{
get
{
RemotingMechanism rm = RemotingMechanism.TcpBinary; //set default remoting mechanism
switch (cbRemotingMechanism.Text)
{
case "TcpBinary(Remoting)":
{
rm = RemotingMechanism.TcpBinary;
break;
}
case "Custom(WCF)":
{
rm = RemotingMechanism.WCFCustom;
break;
}
case "Tcp(WCF)":
{
rm = RemotingMechanism.WCFTcp;
break;
}
case "Http(WCF)":
{
rm = RemotingMechanism.WCFHttp;
break;
}
case "WCF":
{
rm = RemotingMechanism.WCF;
break;
}
}
return rm;
}
set
{
switch (value)
{
case RemotingMechanism.TcpBinary:
{
SetTextToComboBox("TcpBinary(Remoting)", cbRemotingMechanism);
break;
}
case RemotingMechanism.WCFCustom:
{
SetTextToComboBox("Custom(WCF)", cbRemotingMechanism);
break;
}
case RemotingMechanism.WCFHttp:
{
SetTextToComboBox("Http(WCF)", cbRemotingMechanism);
break;
}
case RemotingMechanism.WCFTcp:
{
SetTextToComboBox("Tcp(WCF)", cbRemotingMechanism);
break;
}
case RemotingMechanism.WCF:
{
SetTextToComboBox("WCF", cbRemotingMechanism);
break;
}
}
}
}
#endregion
#region Protocol
public string Protocol
{
get
{
return cbProtocol.Text;
}
set
{
SetTextToComboBox(value, cbProtocol);
}
}
#endregion
#region Host
public string Host
{
get
{
return txHost.Text;
}
set
{
txHost.Text = value;
}
}
#endregion
#region Port
/// <summary>
/// Selected port number.
/// </summary>
public int Port
{
get
{
int port;
try
{
port = int.Parse(txPort.Text);
}
catch (System.FormatException)
{
MessageBox.Show("Invalid name for 'Port' field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return 0;
}
return port;
}
set
{
txPort.Text = value.ToString();
}
}
#endregion
#region AddressPart
public string AddressPart
{
get
{
return txAddresPart.Text;
}
set
{
txAddresPart.Text = value;
}
}
#endregion
#region FullAddress
public string FullAddress
{
get
{
return txFullAddress.Text;
}
set
{
txFullAddress.Text = value;
SetOthersFromFullAddress();
}
}
#endregion
#region RemotingMechanisms
private List<RemotingMechanism> _remotingMechanisms;
public List<RemotingMechanism> RemotingMechanisms
{
get
{
if (_remotingMechanisms == null)
{
_remotingMechanisms = new List<RemotingMechanism>();
_remotingMechanisms.Add(RemotingMechanism.TcpBinary);
_remotingMechanisms.Add(RemotingMechanism.WCFCustom);
_remotingMechanisms.Add(RemotingMechanism.WCFHttp);
_remotingMechanisms.Add(RemotingMechanism.WCFTcp);
_remotingMechanisms.Add(RemotingMechanism.WCF);
}
return _remotingMechanisms;
}
set
{
_remotingMechanisms = value;
}
}
#endregion
#region WCFBinding
public WCFBinding WCFBinding
{
get
{
WCFBinding bind = WCFBinding.None;
switch (cbBinding.Text)
{
case "BasicHttpBinding":
bind = WCFBinding.BasicHttpBinding;
break;
case "WSHttpBinding":
bind = WCFBinding.WSHttpBinding;
break;
case "WSDualHttpBinding":
bind = WCFBinding.WSDualHttpBinding;
break;
case "WSFederationHttpBinding":
bind = WCFBinding.WSFederationHttpBinding;
break;
case "NetTcpBinding":
bind = WCFBinding.NetTcpBinding;
break;
case "NetNamedPipeBinding":
bind = WCFBinding.NetNamedPipeBinding;
break;
case "NetMsmqBinding":
bind = WCFBinding.NetMsmqBinding;
break;
case "NetPeerTcpBinding":
bind = WCFBinding.NetPeerTcpBinding;
break;
case "MsmqIntegrationBinding":
bind = WCFBinding.MsmqIntegrationBinding;
break;
}
return bind;
}
set
{
switch (value)
{
case WCFBinding.BasicHttpBinding:
SetTextToComboBox("BasicHttpBinding", cbBinding);
break;
case WCFBinding.WSHttpBinding:
SetTextToComboBox("WSHttpBinding", cbBinding);
break;
case WCFBinding.WSDualHttpBinding:
SetTextToComboBox("WSDualHttpBinding", cbBinding);
break;
case WCFBinding.WSFederationHttpBinding:
SetTextToComboBox("WSFederationHttpBinding", cbBinding);
break;
case WCFBinding.NetTcpBinding:
SetTextToComboBox("NetTcpBinding", cbBinding);
break;
case WCFBinding.NetNamedPipeBinding:
SetTextToComboBox("NetNamedPipeBinding", cbBinding);
break;
case WCFBinding.NetMsmqBinding:
SetTextToComboBox("NetMsmqBinding", cbBinding);
break;
case WCFBinding.NetPeerTcpBinding:
SetTextToComboBox("NetPeerTcpBinding", cbBinding);
break;
case WCFBinding.MsmqIntegrationBinding:
SetTextToComboBox("MsmqIntegrationBinding", cbBinding);
break;
case WCFBinding.None:
SetTextToComboBox("", cbBinding);
break;
default:
SetTextToComboBox("", cbBinding);
break;
}
}
}
#endregion
#region FixedAddressPart
private bool _fixedAddressPart = false;
/// <summary>
/// Shuld the AddressPart be read only ( executor shuld have predefined AddresPart ).
/// </summary>
public bool FixedAddressPart
{
get
{
return _fixedAddressPart;
}
set
{
_fixedAddressPart = value;
txAddresPart.Enabled = !_fixedAddressPart;
}
}
#endregion
#region HostNameForPublishing
public string HostNameForPublishing
{
get
{
return txtHostNameForPublish.Text;
}
set
{
txtHostNameForPublish.Text = value;
}
}
#endregion
#region BindingSettingType
public WCFBindingSettingType BindingSettingType
{
get
{
WCFBindingSettingType ret = WCFBindingSettingType.None;
switch (cbBindingSettingsType.Text)
{
case "Default":
ret = WCFBindingSettingType.Default;
break;
case "Config File":
ret = WCFBindingSettingType.UseConfigFile;
break;
}
return ret;
}
set
{
switch (value)
{
case WCFBindingSettingType.Default:
cbBindingSettingsType.Text = "Default";
break;
case WCFBindingSettingType.UseConfigFile:
cbBindingSettingsType.Text = "Config File";
break;
}
}
}
#endregion
#region BindingConfigurationName
public string BindingConfigurationName
{
get
{
return txtBindingConfigurationName.Text;
}
set
{
txtBindingConfigurationName.Text = value;
}
}
#endregion
#region ServiceConfigurationName
public string ServiceConfigurationName
{
get
{
return txtServiceConfigurationName.Text;
}
set
{
txtServiceConfigurationName.Text = value;
}
}
#endregion
#endregion
#endregion
#region Methods
#region Private
//set form for selected remoting mechanism
#region ShowForCustomWCF
private void ShowForCustomWCF()
{
txAddresPart.Enabled = false;
cbProtocol.Enabled = false;
txFullAddress.Enabled = false;
txHost.Enabled = false;
txPort.Enabled = false;
WCFBinding = WCFBinding.None;
cbBinding.Enabled = false;
txtServiceConfigurationName.Enabled = true;
cbBindingSettingsType.Enabled = false;
txtBindingConfigurationName.Enabled = false;
txtHostNameForPublish.Enabled = false;
cbProtocol.Items.Clear();
cbProtocol.Items.Add("net.pipe");
cbProtocol.Items.Add("http");
cbProtocol.Items.Add("https");
cbProtocol.Items.Add("net.p2p");
cbProtocol.Items.Add("net.msmq");
cbProtocol.Items.Add("net.tcp");
AllowedProtocols.Clear();
AllowedProtocols.Add("<none>");
AllowedProtocols.Add("net.pipe");
AllowedProtocols.Add("http");
AllowedProtocols.Add("https");
AllowedProtocols.Add("net.p2p");
AllowedProtocols.Add("net.msmq");
AllowedProtocols.Add("net.tcp");
SetFullAddressFromOther();
}
#endregion
#region ShowForWCFTcp
private void ShowForWCFTcp()
{
txAddresPart.Enabled = !_fixedAddressPart;
cbProtocol.Enabled = false;
txFullAddress.Enabled = true;
txPort.Enabled = true;
txHost.Enabled = true;
txtServiceConfigurationName.Enabled = false;
cbBindingSettingsType.Enabled = true;
txtBindingConfigurationName.Enabled = (BindingSettingType == WCFBindingSettingType.UseConfigFile);
txtHostNameForPublish.Enabled = true;
WCFBinding = WCFBinding.NetTcpBinding;
cbBinding.Enabled = false;
AllowedProtocols.Clear();
AllowedProtocols.Add("net.tcp");
cbProtocol.Text = "net.tcp";
SetFullAddressFromOther();
}
#endregion
#region ShowForWCFHttp
private void ShowForWCFHttp()
{
txAddresPart.Enabled = !_fixedAddressPart;
cbProtocol.Enabled = true;
txFullAddress.Enabled = true;
txPort.Enabled = true;
txHost.Enabled = true;
txtServiceConfigurationName.Enabled = false;
cbBindingSettingsType.Enabled = true;
txtBindingConfigurationName.Enabled = (BindingSettingType == WCFBindingSettingType.UseConfigFile);
txtHostNameForPublish.Enabled = true;
WCFBinding = WCFBinding.WSHttpBinding;
cbBinding.Enabled = false;
cbProtocol.Items.Clear();
cbProtocol.Items.Add("http");
cbProtocol.Items.Add("https");
cbProtocol.Text = "http";
AllowedProtocols.Clear();
AllowedProtocols.Add("http");
AllowedProtocols.Add("https");
SetFullAddressFromOther();
}
#endregion
#region ShowForWCF
private void ShowForWCF()
{
txAddresPart.Enabled = true;
cbProtocol.Enabled = true;
txFullAddress.Enabled = true;
txPort.Enabled = true;
txHost.Enabled = true;
cbBinding.Enabled = true;
txtServiceConfigurationName.Enabled = false;
cbBindingSettingsType.Enabled = true;
txtBindingConfigurationName.Enabled = (BindingSettingType == WCFBindingSettingType.UseConfigFile);
txtHostNameForPublish.Enabled = true;
cbProtocol.Items.Clear();
cbProtocol.Items.Add("net.pipe");
cbProtocol.Items.Add("http");
cbProtocol.Items.Add("https");
cbProtocol.Items.Add("net.p2p");
cbProtocol.Items.Add("net.msmq");
cbProtocol.Items.Add("net.tcp");
AllowedProtocols.Clear();
AllowedProtocols.Add("<none>");
AllowedProtocols.Add("net.pipe");
AllowedProtocols.Add("http");
AllowedProtocols.Add("https");
AllowedProtocols.Add("net.p2p");
AllowedProtocols.Add("net.msmq");
AllowedProtocols.Add("net.tcp");
SetFullAddressFromOther();
}
#endregion
#region ShowForTcpBinaryRemoting
private void ShowForTcpBinaryRemoting()
{
txHost.Enabled = true;
txPort.Enabled = true;
txAddresPart.Enabled = false;
cbProtocol.Enabled = false;
txFullAddress.Enabled = false;
txtServiceConfigurationName.Enabled = false;
cbBindingSettingsType.Enabled = false;
txtBindingConfigurationName.Enabled = false;
txtHostNameForPublish.Enabled = false;
WCFBinding = WCFBinding.None;
cbBinding.Enabled = false;
}
#endregion
//Helper methods for parsing full address from address part and the other way
#region SetFullAddressFromOther
private void SetFullAddressFromOther()
{
txFullAddress.Text = Utility.WCFUtils.ComposeAddress(cbProtocol.Text, txHost.Text, Port, txAddresPart.Text, WCFBinding);
}
#endregion
#region SetOthersFromFullAddress
private void SetOthersFromFullAddress()
{
string _protocol = "<none>";
string _host = "<none>";
int _port = 0;
string _pathOnServer = string.Empty;
Utility.WCFUtils.BreakAddress(txFullAddress.Text, out _protocol, out _host, out _port, out _pathOnServer);
txHost.Text = _host;
txPort.Text = _port.ToString();
cbProtocol.Text = _protocol;
txAddresPart.Text = _pathOnServer;
}
#endregion
//other helper functions
#region CustomInit
private void CustomInit()
{
BindRemotingMechanisms();
BindWCFBindings();
Clear();
}
#endregion
#region CalculateLastMatchIndex
int CalculateLastMatchIndex(string input, string word)
{
int index = 0;
int checkLen = word.Length + 1;
if (input.Length + 1 < checkLen)
checkLen = input.Length + 1;
for (int i = 1; i < checkLen; i++)
{
if (input.ToLower().Substring(0, i) == word.ToLower().Substring(0, i))
index = i;
}
return index;
}
#endregion
#region AddRemotingMechanismToCb
private void AddRemotingMechanismToCb(RemotingMechanism remotingMechanism)
{
string fName = string.Empty;
switch (remotingMechanism)
{
case RemotingMechanism.TcpBinary:
fName = "TcpBinary(Remoting)";
break;
case RemotingMechanism.WCFCustom:
fName = "Custom(WCF)";
break;
case RemotingMechanism.WCFHttp:
fName = "Http(WCF)";
break;
case RemotingMechanism.WCFTcp:
fName = "Tcp(WCF)";
break;
case RemotingMechanism.WCF:
fName = "WCF";
break;
}
cbRemotingMechanism.Items.Add(fName);
}
#endregion
#region BindWCFBindings
private void BindWCFBindings()
{
cbBinding.Items.Clear();
cbBinding.Items.Add("BasicHttpBinding");
cbBinding.Items.Add("WSHttpBinding");
cbBinding.Items.Add("WSDualHttpBinding");
cbBinding.Items.Add("WSFederationHttpBinding");
cbBinding.Items.Add("NetTcpBinding");
cbBinding.Items.Add("NetNamedPipeBinding");
cbBinding.Items.Add("NetMsmqBinding");
cbBinding.Items.Add("NetPeerTcpBinding");
cbBinding.Items.Add("MsmqIntegrationBinding");
}
#endregion
#endregion
#region Public
#region BindRemotingMechanisms
/// <summary>
/// Need to call after setting RemotingMechanisms list, for the control to get updated.
/// </summary>
/// <remarks>Functions AddRemotingMechanism and RemoveRemotingMechanism call this functios internaly.</remarks>
public void BindRemotingMechanisms()
{
cbRemotingMechanism.Items.Clear();
for (int i = 0; i < RemotingMechanisms.Count; i++)
{
AddRemotingMechanismToCb(RemotingMechanisms[i]);
}
}
#endregion
#region AddRemotingMechanism
/// <summary>
/// Adds another remoting mechanism.
/// </summary>
/// <param name="remotingMechanism">The remoting mechanism to add.</param>
public void AddRemotingMechanism(RemotingMechanism remotingMechanism)
{
if (!RemotingMechanisms.Contains(remotingMechanism))
RemotingMechanisms.Add(remotingMechanism);
BindRemotingMechanisms();
}
#endregion
#region RemoveRemotingMechanism
/// <summary>
/// Remove an existing remoting mechanism.
/// </summary>
/// <param name="remotingMechanism">The remoting mechanism to remove.</param>
public void RemoveRemotingMechanism(RemotingMechanism remotingMechanism)
{
if (RemotingMechanisms.Contains(remotingMechanism))
RemotingMechanisms.Remove(remotingMechanism);
BindRemotingMechanisms();
}
#endregion
#region Clear
/// <summary>
/// Reset the control to default values.
/// </summary>
public void Clear()
{
this.Host = "localhost";
this.Port = 0;
this.AddressPart = string.Empty;
this.SelectedRemotingMechanism = RemotingMechanism.WCF;
this.Protocol = string.Empty;
this.WCFBinding = WCFBinding.None;
this.HostNameForPublishing = "localhost";
this.BindingSettingType = WCFBindingSettingType.Default;
this.BindingConfigurationName = string.Empty;
this.ServiceConfigurationName = string.Empty;
}
#endregion
#endregion
#endregion
#region Handlers
#region txPort_KeyDown
private void txPort_KeyDown(object sender, KeyEventArgs e)
{
char c = Convert.ToChar(e.KeyCode);
if (!Char.IsPunctuation(c) && !Char.IsNumber(c) && !Char.IsControl(c))
e.SuppressKeyPress = true;
}
#endregion
#region cbRemotingMechanism_SelectedIndexChanged
private void cbRemotingMechanism_SelectedIndexChanged(object sender, EventArgs e)
{
switch (SelectedRemotingMechanism)
{
case RemotingMechanism.TcpBinary:
{
ShowForTcpBinaryRemoting();
break;
}
case RemotingMechanism.WCFCustom:
{
ShowForCustomWCF();
break;
}
case RemotingMechanism.WCFHttp:
{
ShowForWCFHttp();
break;
}
case RemotingMechanism.WCFTcp:
{
ShowForWCFTcp();
break;
}
case RemotingMechanism.WCF:
{
ShowForWCF();
break;
}
}
}
#endregion
#region cbProtocol_SelectedIndexChanged
private void cbProtocol_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txHost_TextChanged
private void txHost_TextChanged(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txPort_TextChanged
private void txPort_TextChanged(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txAddresPart_TextChanged
private void txAddresPart_TextChanged(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txFullAddress_TextChanged
private void txFullAddress_TextChanged(object sender, EventArgs e)
{
if (isInEvent)
return;
int curLocation = txFullAddress.SelectionStart;
string willBeStr = txFullAddress.Text;
int protCount = AllowedProtocols.Count;
if (protCount > 0)
{
int lastCorrectIndex = 0;
bool isOfType = false;
for (int i = 0; i < protCount && !isOfType; i++)
{
string word = String.Format("{0}://", AllowedProtocols[i]);
int wordLen = word.Length;
if (willBeStr.Length < wordLen)
wordLen = willBeStr.Length;
if (curLocation < wordLen)
wordLen = curLocation;
if (willBeStr.Substring(0, wordLen).ToLower() == word.Substring(0, wordLen).ToLower())
{
isOfType = true;
}
else
{
int curCorIndex = CalculateLastMatchIndex(previousText, word);
if (curCorIndex > lastCorrectIndex)
lastCorrectIndex = curCorIndex;
}
}
if (!isOfType)
{
isInEvent = true;
txFullAddress.Text = previousText;
isInEvent = false;
txFullAddress.SelectionStart = lastCorrectIndex;
}
else
{
previousText = txFullAddress.Text;
}
}
}
//event helper members
string previousText = string.Empty;
bool isInEvent = false;
#endregion
#region cbProtocol_Leave
private void cbProtocol_Leave(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txHost_Leave
private void txHost_Leave(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txPort_Leave
private void txPort_Leave(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txAddresPart_Leave
private void txAddresPart_Leave(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetFullAddressFromOther();
}
#endregion
#region txFullAddress_Leave
private void txFullAddress_Leave(object sender, EventArgs e)
{
if (SelectedRemotingMechanism != RemotingMechanism.TcpBinary)
SetOthersFromFullAddress();
}
#endregion
#region cbBindingSettingsType_TabIndexChanged
private void cbBindingSettingsType_TabIndexChanged(object sender, EventArgs e)
{
txtBindingConfigurationName.Enabled = (BindingSettingType == WCFBindingSettingType.UseConfigFile);
}
#endregion
#endregion
#region Cross-thred helpers
private delegate void SetTextToComboBoxDel(string text, ComboBox cbControl);
private void SetTextToComboBox(string text, ComboBox cbControl)
{
if (cbControl.InvokeRequired)
{
SetTextToComboBoxDel method = new SetTextToComboBoxDel(SetTextToComboBox);
cbControl.Invoke(method, text, cbControl);
}
else
{
cbControl.Text = text;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace MonJobs.Tests
{
internal class MongoJobQueryCountServiceTests : MongoTestBase
{
[Test]
public async Task QueryCount_QueryByQueueIdOnly_YieldsAllResults()
{
var exampleQueueId = QueueId.Parse("ExampleQueue");
var exampleQuery = new JobQuery
{
QueueId = exampleQueueId
};
var existingJobs = new[] { new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
}, new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
}, new Job
{
Id = JobId.Generate(),
QueueId = QueueId.Parse(Guid.NewGuid().ToString("N"))
} };
await RunInMongoLand(async database =>
{
var jobs = database.GetJobCollection();
await jobs.InsertManyAsync(existingJobs).ConfigureAwait(false);
var sut = new MongoJobQueryCountService(database);
var results = (await sut.QueryCount(exampleQuery).ConfigureAwait(false));
long expected = 2;
Assert.That(results, Is.Not.Null);
Assert.AreEqual(results, expected);
}).ConfigureAwait(false);
}
[Test]
public async Task QueryCount_QueryBySingleAttribute_YieldMatchingResults()
{
var exampleQueueId = QueueId.Parse("ExampleQueue");
var exampleQuery = new JobQuery
{
QueueId = exampleQueueId,
HasAttributes = new JobAttributes
{
{ "DataCenter", "CAL01"},
}
};
var matchingJob1 = JobId.Generate();
var matchingJob2 = JobId.Generate();
var unmatchedJob1 = JobId.Generate();
var existingJobs = new[] { new Job
{
Id = matchingJob1,
QueueId = exampleQueueId,
Attributes = new JobAttributes
{
{ "DataCenter", "CAL01"},
}
}, new Job
{
Id = matchingJob2,
QueueId = exampleQueueId,
Attributes = new JobAttributes
{
{ "DataCenter", "CAL01"},
{ "Geo", "USA"},
}
}, new Job
{
Id = unmatchedJob1,
QueueId = exampleQueueId,
Attributes = new JobAttributes
{
{ "Geo", "USA"},
}
}
};
await RunInMongoLand(async database =>
{
var jobs = database.GetJobCollection();
await jobs.InsertManyAsync(existingJobs).ConfigureAwait(false);
var sut = new MongoJobQueryCountService(database);
var results = (await sut.QueryCount(exampleQuery).ConfigureAwait(false));
long expected = 2;
Assert.That(results, Is.Not.Null);
Assert.AreEqual(results, expected);
}).ConfigureAwait(false);
}
[Test]
public async Task QueryCount_QueryByMultiAttributes_YieldMatchingResults()
{
var exampleQueueId = QueueId.Parse("ExampleQueue");
var exampleQuery = new JobQuery
{
QueueId = exampleQueueId,
HasAttributes = new JobAttributes
{
{ "DataCenter", "CAL01"},
{ "Geo", "USA"}
}
};
var matchingJob1 = JobId.Generate();
var unmatchedJob1 = JobId.Generate();
var unmatchedJob2 = JobId.Generate();
var existingJobs = new[] { new Job
{
Id = unmatchedJob1,
QueueId = exampleQueueId,
Attributes = new JobAttributes
{
{ "DataCenter", "CAL01"},
}
}, new Job
{
Id = matchingJob1,
QueueId = exampleQueueId,
Attributes = new JobAttributes
{
{ "DataCenter", "CAL01"},
{ "Geo", "USA"}
}
}, new Job
{
Id = unmatchedJob2,
QueueId = exampleQueueId,
Attributes = new JobAttributes
{
{ "Geo", "USA"},
}
}
};
await RunInMongoLand(async database =>
{
var jobs = database.GetJobCollection();
await jobs.InsertManyAsync(existingJobs).ConfigureAwait(false);
var sut = new MongoJobQueryCountService(database);
var results = (await sut.QueryCount(exampleQuery).ConfigureAwait(false));
long expected = 1;
Assert.That(results, Is.Not.Null);
Assert.AreEqual(results, expected);
}).ConfigureAwait(false);
}
[Test]
public async Task QueryCount_Limit_YieldsLimit()
{
var exampleQueueId = QueueId.Parse("ExampleQueue");
var exampleQuery = new JobQuery
{
QueueId = exampleQueueId,
Limit = 2,
};
var existingJobs = new[] { new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
}, new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
}, new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
} };
await RunInMongoLand(async database =>
{
var jobs = database.GetJobCollection();
await jobs.InsertManyAsync(existingJobs).ConfigureAwait(false);
var sut = new MongoJobQueryCountService(database);
var results = (await sut.QueryCount(exampleQuery).ConfigureAwait(false));
long expected = 3;
Assert.That(results, Is.Not.Null);
Assert.AreEqual(results, expected);
}).ConfigureAwait(false);
}
[Test]
public async Task QueryCount_Skip_YieldSkipped()
{
var exampleQueueId = QueueId.Parse("ExampleQueue");
var exampleQuery = new JobQuery
{
QueueId = exampleQueueId,
Skip = 2,
};
var existingJobs = new[] { new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
}, new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
}, new Job
{
Id = JobId.Generate(),
QueueId = exampleQueueId
} };
await RunInMongoLand(async database =>
{
var jobs = database.GetJobCollection();
await jobs.InsertManyAsync(existingJobs).ConfigureAwait(false);
var sut = new MongoJobQueryCountService(database);
var results = (await sut.QueryCount(exampleQuery).ConfigureAwait(false));
long expected = 3;
Assert.That(results, Is.Not.Null);
Assert.AreEqual(results, expected);
}).ConfigureAwait(false);
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using Frapid.Configuration;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.DbPolicy;
using Frapid.Framework.Extensions;
using Npgsql;
using Frapid.NPoco;
using Serilog;
namespace Frapid.WebsiteBuilder.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "website.menu_items".
/// </summary>
public class MenuItem : DbAccess, IMenuItemRepository
{
/// <summary>
/// The schema of this table. Returns literal "website".
/// </summary>
public override string _ObjectNamespace => "website";
/// <summary>
/// The schema unqualified name of this table. Returns literal "menu_items".
/// </summary>
public override string _ObjectName => "menu_items";
/// <summary>
/// Login id of application user accessing this table.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Performs SQL count on the table "website.menu_items".
/// </summary>
/// <returns>Returns the number of rows of the table "website.menu_items".</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long Count()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"MenuItem\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM website.menu_items;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "website.menu_items" to return all instances of the "MenuItem" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "MenuItem" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItem> GetAll()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"MenuItem\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items ORDER BY menu_item_id;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "website.menu_items" to return all instances of the "MenuItem" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "MenuItem" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<dynamic> Export()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"MenuItem\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items ORDER BY menu_item_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "website.menu_items" with a where filter on the column "menu_item_id" to return a single instance of the "MenuItem" class.
/// </summary>
/// <param name="menuItemId">The column "menu_item_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "MenuItem" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.WebsiteBuilder.Entities.MenuItem Get(int menuItemId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get entity \"MenuItem\" filtered by \"MenuItemId\" with value {MenuItemId} was denied to the user with Login ID {_LoginId}", menuItemId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items WHERE menu_item_id=@0;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql, menuItemId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "website.menu_items".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "MenuItem" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.WebsiteBuilder.Entities.MenuItem GetFirst()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the first record of entity \"MenuItem\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items ORDER BY menu_item_id LIMIT 1;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "website.menu_items" sorted by menuItemId.
/// </summary>
/// <param name="menuItemId">The column "menu_item_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "MenuItem" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.WebsiteBuilder.Entities.MenuItem GetPrevious(int menuItemId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the previous entity of \"MenuItem\" by \"MenuItemId\" with value {MenuItemId} was denied to the user with Login ID {_LoginId}", menuItemId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items WHERE menu_item_id < @0 ORDER BY menu_item_id DESC LIMIT 1;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql, menuItemId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "website.menu_items" sorted by menuItemId.
/// </summary>
/// <param name="menuItemId">The column "menu_item_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "MenuItem" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.WebsiteBuilder.Entities.MenuItem GetNext(int menuItemId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the next entity of \"MenuItem\" by \"MenuItemId\" with value {MenuItemId} was denied to the user with Login ID {_LoginId}", menuItemId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items WHERE menu_item_id > @0 ORDER BY menu_item_id LIMIT 1;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql, menuItemId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "website.menu_items".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "MenuItem" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public Frapid.WebsiteBuilder.Entities.MenuItem GetLast()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the get the last record of entity \"MenuItem\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items ORDER BY menu_item_id DESC LIMIT 1;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "website.menu_items" with a where filter on the column "menu_item_id" to return a multiple instances of the "MenuItem" class.
/// </summary>
/// <param name="menuItemIds">Array of column "menu_item_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "MenuItem" class mapped to the database row.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItem> Get(int[] menuItemIds)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to entity \"MenuItem\" was denied to the user with Login ID {LoginId}. menuItemIds: {menuItemIds}.", this._LoginId, menuItemIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items WHERE menu_item_id IN (@0);";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql, menuItemIds);
}
/// <summary>
/// Custom fields are user defined form elements for website.menu_items.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table website.menu_items</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get custom fields for entity \"MenuItem\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
string sql;
if (string.IsNullOrWhiteSpace(resourceId))
{
sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='website.menu_items' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('website.menu_items'::text, @0::text) ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId);
}
/// <summary>
/// Displayfields provide a minimal name/value context for data binding the row collection of website.menu_items.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table website.menu_items</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>();
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return displayFields;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to get display field for entity \"MenuItem\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT menu_item_id AS key, title as value FROM website.menu_items;";
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
using (DataTable table = DbOperation.GetDataTable(this._Catalog, command))
{
if (table?.Rows == null || table.Rows.Count == 0)
{
return displayFields;
}
foreach (DataRow row in table.Rows)
{
if (row != null)
{
DisplayField displayField = new DisplayField
{
Key = row["key"].ToString(),
Value = row["value"].ToString()
};
displayFields.Add(displayField);
}
}
}
}
return displayFields;
}
/// <summary>
/// Inserts or updates the instance of MenuItem class on the database table "website.menu_items".
/// </summary>
/// <param name="menuItem">The instance of "MenuItem" class to insert or update.</param>
/// <param name="customFields">The custom field collection.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object AddOrEdit(dynamic menuItem, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
menuItem.audit_user_id = this._UserId;
menuItem.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = menuItem.menu_item_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
this.Update(menuItem, Cast.To<int>(primaryKeyValue));
}
else
{
primaryKeyValue = this.Add(menuItem);
}
string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" +
"SELECT custom_field_setup_id " +
"FROM config.custom_field_setup " +
"WHERE form_name=config.get_custom_field_form_name('website.menu_items')" +
");";
Factory.NonQuery(this._Catalog, sql);
if (customFields == null)
{
return primaryKeyValue;
}
foreach (var field in customFields)
{
sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " +
"SELECT config.get_custom_field_setup_id_by_table_name('website.menu_items', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of MenuItem class on the database table "website.menu_items".
/// </summary>
/// <param name="menuItem">The instance of "MenuItem" class to insert.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public object Add(dynamic menuItem)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to add entity \"MenuItem\" was denied to the user with Login ID {LoginId}. {MenuItem}", this._LoginId, menuItem);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, menuItem, "website.menu_items", "menu_item_id");
}
/// <summary>
/// Inserts or updates multiple instances of MenuItem class on the database table "website.menu_items";
/// </summary>
/// <param name="menuItems">List of "MenuItem" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> menuItems)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"MenuItem\" was denied to the user with Login ID {LoginId}. {menuItems}", this._LoginId, menuItems);
throw new UnauthorizedException("Access is denied.");
}
}
var result = new List<object>();
int line = 0;
try
{
using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName))
{
using (ITransaction transaction = db.GetTransaction())
{
foreach (dynamic menuItem in menuItems)
{
line++;
menuItem.audit_user_id = this._UserId;
menuItem.audit_ts = System.DateTime.UtcNow;
object primaryKeyValue = menuItem.menu_item_id;
if (Cast.To<int>(primaryKeyValue) > 0)
{
result.Add(menuItem.menu_item_id);
db.Update("website.menu_items", "menu_item_id", menuItem, menuItem.menu_item_id);
}
else
{
result.Add(db.Insert("website.menu_items", "menu_item_id", menuItem));
}
}
transaction.Complete();
}
return result;
}
}
catch (NpgsqlException ex)
{
string errorMessage = $"Error on line {line} ";
if (ex.Code.StartsWith("P"))
{
errorMessage += Factory.GetDbErrorResource(ex);
throw new DataAccessException(errorMessage, ex);
}
errorMessage += ex.Message;
throw new DataAccessException(errorMessage, ex);
}
catch (System.Exception ex)
{
string errorMessage = $"Error on line {line} ";
throw new DataAccessException(errorMessage, ex);
}
}
/// <summary>
/// Updates the row of the table "website.menu_items" with an instance of "MenuItem" class against the primary key value.
/// </summary>
/// <param name="menuItem">The instance of "MenuItem" class to update.</param>
/// <param name="menuItemId">The value of the column "menu_item_id" which will be updated.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Update(dynamic menuItem, int menuItemId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to edit entity \"MenuItem\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {MenuItem}", menuItemId, this._LoginId, menuItem);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, menuItem, menuItemId, "website.menu_items", "menu_item_id");
}
/// <summary>
/// Deletes the row of the table "website.menu_items" against the primary key value.
/// </summary>
/// <param name="menuItemId">The value of the column "menu_item_id" which will be deleted.</param>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public void Delete(int menuItemId)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to delete entity \"MenuItem\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", menuItemId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM website.menu_items WHERE menu_item_id=@0;";
Factory.NonQuery(this._Catalog, sql, menuItemId);
}
/// <summary>
/// Performs a select statement on table "website.menu_items" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "MenuItem" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItem> GetPaginatedResult()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the first page of the entity \"MenuItem\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.menu_items ORDER BY menu_item_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "website.menu_items" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "MenuItem" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItem> GetPaginatedResult(long pageNumber)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the entity \"MenuItem\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
const string sql = "SELECT * FROM website.menu_items ORDER BY menu_item_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql, offset);
}
public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName)
{
const string sql = "SELECT * FROM config.filters WHERE object_name='website.menu_items' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "website.menu_items".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "MenuItem" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"MenuItem\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM website.menu_items WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.MenuItem(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "website.menu_items" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of "MenuItem" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItem> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"MenuItem\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM website.menu_items WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.MenuItem(), filters);
sql.OrderBy("menu_item_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "website.menu_items".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "MenuItem" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountFiltered(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"MenuItem\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM website.menu_items WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.MenuItem(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "website.menu_items" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of "MenuItem" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItem> GetFiltered(long pageNumber, string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"MenuItem\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM website.menu_items WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.MenuItem(), filters);
sql.OrderBy("menu_item_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.WebsiteBuilder.Entities.MenuItem>(this._Catalog, sql);
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// OrderItemOption
/// </summary>
[DataContract]
public partial class OrderItemOption : IEquatable<OrderItemOption>, IValidatableObject
{
/// <summary>
/// How the additional dimensions are applied to the item.
/// </summary>
/// <value>How the additional dimensions are applied to the item.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum AdditionalDimensionApplicationEnum
{
/// <summary>
/// Enum None for value: none
/// </summary>
[EnumMember(Value = "none")]
None = 1,
/// <summary>
/// Enum Setitemto for value: set item to
/// </summary>
[EnumMember(Value = "set item to")]
Setitemto = 2,
/// <summary>
/// Enum Additem for value: add item
/// </summary>
[EnumMember(Value = "add item")]
Additem = 3
}
/// <summary>
/// How the additional dimensions are applied to the item.
/// </summary>
/// <value>How the additional dimensions are applied to the item.</value>
[DataMember(Name="additional_dimension_application", EmitDefaultValue=false)]
public AdditionalDimensionApplicationEnum? AdditionalDimensionApplication { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="OrderItemOption" /> class.
/// </summary>
/// <param name="additionalDimensionApplication">How the additional dimensions are applied to the item..</param>
/// <param name="costChange">costChange.</param>
/// <param name="fileAttachment">fileAttachment.</param>
/// <param name="height">height.</param>
/// <param name="hidden">True if this option is hidden from display on the order.</param>
/// <param name="label">Label.</param>
/// <param name="length">length.</param>
/// <param name="oneTimeFee">True if the cost associated with this option is a one time fee or multiplied by the quantity of the item.</param>
/// <param name="value">Value.</param>
/// <param name="weightChange">weightChange.</param>
/// <param name="width">width.</param>
public OrderItemOption(AdditionalDimensionApplicationEnum? additionalDimensionApplication = default(AdditionalDimensionApplicationEnum?), Currency costChange = default(Currency), OrderItemOptionFileAttachment fileAttachment = default(OrderItemOptionFileAttachment), Distance height = default(Distance), bool? hidden = default(bool?), string label = default(string), Distance length = default(Distance), bool? oneTimeFee = default(bool?), string value = default(string), Weight weightChange = default(Weight), Distance width = default(Distance))
{
this.AdditionalDimensionApplication = additionalDimensionApplication;
this.CostChange = costChange;
this.FileAttachment = fileAttachment;
this.Height = height;
this.Hidden = hidden;
this.Label = label;
this.Length = length;
this.OneTimeFee = oneTimeFee;
this.Value = value;
this.WeightChange = weightChange;
this.Width = width;
}
/// <summary>
/// Gets or Sets CostChange
/// </summary>
[DataMember(Name="cost_change", EmitDefaultValue=false)]
public Currency CostChange { get; set; }
/// <summary>
/// Gets or Sets FileAttachment
/// </summary>
[DataMember(Name="file_attachment", EmitDefaultValue=false)]
public OrderItemOptionFileAttachment FileAttachment { get; set; }
/// <summary>
/// Gets or Sets Height
/// </summary>
[DataMember(Name="height", EmitDefaultValue=false)]
public Distance Height { get; set; }
/// <summary>
/// True if this option is hidden from display on the order
/// </summary>
/// <value>True if this option is hidden from display on the order</value>
[DataMember(Name="hidden", EmitDefaultValue=false)]
public bool? Hidden { get; set; }
/// <summary>
/// Label
/// </summary>
/// <value>Label</value>
[DataMember(Name="label", EmitDefaultValue=false)]
public string Label { get; set; }
/// <summary>
/// Gets or Sets Length
/// </summary>
[DataMember(Name="length", EmitDefaultValue=false)]
public Distance Length { get; set; }
/// <summary>
/// True if the cost associated with this option is a one time fee or multiplied by the quantity of the item
/// </summary>
/// <value>True if the cost associated with this option is a one time fee or multiplied by the quantity of the item</value>
[DataMember(Name="one_time_fee", EmitDefaultValue=false)]
public bool? OneTimeFee { get; set; }
/// <summary>
/// Value
/// </summary>
/// <value>Value</value>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// Gets or Sets WeightChange
/// </summary>
[DataMember(Name="weight_change", EmitDefaultValue=false)]
public Weight WeightChange { get; set; }
/// <summary>
/// Gets or Sets Width
/// </summary>
[DataMember(Name="width", EmitDefaultValue=false)]
public Distance Width { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OrderItemOption {\n");
sb.Append(" AdditionalDimensionApplication: ").Append(AdditionalDimensionApplication).Append("\n");
sb.Append(" CostChange: ").Append(CostChange).Append("\n");
sb.Append(" FileAttachment: ").Append(FileAttachment).Append("\n");
sb.Append(" Height: ").Append(Height).Append("\n");
sb.Append(" Hidden: ").Append(Hidden).Append("\n");
sb.Append(" Label: ").Append(Label).Append("\n");
sb.Append(" Length: ").Append(Length).Append("\n");
sb.Append(" OneTimeFee: ").Append(OneTimeFee).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" WeightChange: ").Append(WeightChange).Append("\n");
sb.Append(" Width: ").Append(Width).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as OrderItemOption);
}
/// <summary>
/// Returns true if OrderItemOption instances are equal
/// </summary>
/// <param name="input">Instance of OrderItemOption to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OrderItemOption input)
{
if (input == null)
return false;
return
(
this.AdditionalDimensionApplication == input.AdditionalDimensionApplication ||
(this.AdditionalDimensionApplication != null &&
this.AdditionalDimensionApplication.Equals(input.AdditionalDimensionApplication))
) &&
(
this.CostChange == input.CostChange ||
(this.CostChange != null &&
this.CostChange.Equals(input.CostChange))
) &&
(
this.FileAttachment == input.FileAttachment ||
(this.FileAttachment != null &&
this.FileAttachment.Equals(input.FileAttachment))
) &&
(
this.Height == input.Height ||
(this.Height != null &&
this.Height.Equals(input.Height))
) &&
(
this.Hidden == input.Hidden ||
(this.Hidden != null &&
this.Hidden.Equals(input.Hidden))
) &&
(
this.Label == input.Label ||
(this.Label != null &&
this.Label.Equals(input.Label))
) &&
(
this.Length == input.Length ||
(this.Length != null &&
this.Length.Equals(input.Length))
) &&
(
this.OneTimeFee == input.OneTimeFee ||
(this.OneTimeFee != null &&
this.OneTimeFee.Equals(input.OneTimeFee))
) &&
(
this.Value == input.Value ||
(this.Value != null &&
this.Value.Equals(input.Value))
) &&
(
this.WeightChange == input.WeightChange ||
(this.WeightChange != null &&
this.WeightChange.Equals(input.WeightChange))
) &&
(
this.Width == input.Width ||
(this.Width != null &&
this.Width.Equals(input.Width))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AdditionalDimensionApplication != null)
hashCode = hashCode * 59 + this.AdditionalDimensionApplication.GetHashCode();
if (this.CostChange != null)
hashCode = hashCode * 59 + this.CostChange.GetHashCode();
if (this.FileAttachment != null)
hashCode = hashCode * 59 + this.FileAttachment.GetHashCode();
if (this.Height != null)
hashCode = hashCode * 59 + this.Height.GetHashCode();
if (this.Hidden != null)
hashCode = hashCode * 59 + this.Hidden.GetHashCode();
if (this.Label != null)
hashCode = hashCode * 59 + this.Label.GetHashCode();
if (this.Length != null)
hashCode = hashCode * 59 + this.Length.GetHashCode();
if (this.OneTimeFee != null)
hashCode = hashCode * 59 + this.OneTimeFee.GetHashCode();
if (this.Value != null)
hashCode = hashCode * 59 + this.Value.GetHashCode();
if (this.WeightChange != null)
hashCode = hashCode * 59 + this.WeightChange.GetHashCode();
if (this.Width != null)
hashCode = hashCode * 59 + this.Width.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Label (string) maxLength
if(this.Label != null && this.Label.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Label, length must be less than 50.", new [] { "Label" });
}
// Value (string) maxLength
if(this.Value != null && this.Value.Length > 1024)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Value, length must be less than 1024.", new [] { "Value" });
}
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using Xunit;
namespace System.Data.Tests
{
public class DataSetReadXmlSchemaTest : RemoteExecutorTestBase
{
private DataSet CreateTestSet()
{
var ds = new DataSet();
ds.Tables.Add("Table1");
ds.Tables.Add("Table2");
ds.Tables[0].Columns.Add("Column1_1");
ds.Tables[0].Columns.Add("Column1_2");
ds.Tables[0].Columns.Add("Column1_3");
ds.Tables[1].Columns.Add("Column2_1");
ds.Tables[1].Columns.Add("Column2_2");
ds.Tables[1].Columns.Add("Column2_3");
ds.Tables[0].Rows.Add(new object[] { "ppp", "www", "xxx" });
ds.Relations.Add("Rel1", ds.Tables[0].Columns[2], ds.Tables[1].Columns[0]);
return ds;
}
[Fact]
public void SingleElementTreatmentDifference()
{
// This is one of the most complicated case. When the content
// type particle of 'Root' element is a complex element, it
// is DataSet element. Otherwise, it is just a data table.
//
// But also note that there is another test named
// LocaleOnRootWithoutIsDataSet(), that tests if locale on
// the (mere) data table modifies *DataSet's* locale.
// Moreover, when the schema contains another element
// (regardless of its schema type), the elements will
// never be treated as a DataSet.
string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'>
<xs:element name='Root'> <!-- When simple, it becomes table. When complex, it becomes DataSet -->
<xs:complexType>
<xs:choice>
{0}
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>";
string xsbase2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'>
<xs:element name='Root'> <!-- When simple, it becomes table. When complex, it becomes DataSet -->
<xs:complexType>
<xs:choice>
{0}
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name='more' type='xs:string' />
</xs:schema>";
string simple = "<xs:element name='Child' type='xs:string' />";
string complex = @"<xs:element name='Child'>
<xs:complexType>
<xs:attribute name='a1' />
<xs:attribute name='a2' type='xs:integer' />
</xs:complexType>
</xs:element>";
string elref = "<xs:element ref='more' />";
string xs2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'>
<xs:element name='Root' type='RootType' />
<xs:complexType name='RootType'>
<xs:choice>
<xs:element name='Child'>
<xs:complexType>
<xs:attribute name='a1' />
<xs:attribute name='a2' type='xs:integer' />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:schema>";
var ds = new DataSet();
string xs = string.Format(xsbase, simple);
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("simple", ds, "hoge", 1, 0);
DataSetAssertion.AssertDataTable("simple", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
// reference to global complex type
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs2));
DataSetAssertion.AssertDataSet("external complexType", ds, "hoge", 2, 1);
DataSetAssertion.AssertDataTable("external Tab1", ds.Tables[0], "Root", 1, 0, 0, 1, 1, 1);
DataSetAssertion.AssertDataTable("external Tab2", ds.Tables[1], "Child", 3, 0, 1, 0, 1, 0);
// xsbase2 + complex -> datatable
ds = new DataSet();
xs = string.Format(xsbase2, complex);
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("complex", ds, "hoge", 2, 1);
DataSetAssertion.AssertDataTable("complex", ds.Tables[0], "Root", 1, 0, 0, 1, 1, 1);
DataTable dt = ds.Tables[1];
DataSetAssertion.AssertDataTable("complex", dt, "Child", 3, 0, 1, 0, 1, 0);
DataSetAssertion.AssertDataColumn("a1", dt.Columns["a1"], "a1", true, false, 0, 1, "a1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("a2", dt.Columns["a2"], "a2", true, false, 0, 1, "a2", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("Root_Id", dt.Columns[2], "Root_Id", true, false, 0, 1, "Root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 2, string.Empty, false, false);
// xsbase + complex -> dataset
ds = new DataSet();
xs = string.Format(xsbase, complex);
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("complex", ds, "Root", 1, 0);
ds = new DataSet();
xs = string.Format(xsbase2, elref);
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("complex", ds, "hoge", 1, 0);
DataSetAssertion.AssertDataTable("complex", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
}
[Fact]
public void SuspiciousDataSetElement()
{
string schema = @"<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:attribute name='foo' type='xsd:string'/>
<xsd:attribute name='bar' type='xsd:string'/>
<xsd:complexType name='attRef'>
<xsd:attribute name='att1' type='xsd:int'/>
<xsd:attribute name='att2' type='xsd:string'/>
</xsd:complexType>
<xsd:element name='doc'>
<xsd:complexType>
<xsd:choice>
<xsd:element name='elem' type='attRef'/>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(schema));
DataSetAssertion.AssertDataSet("ds", ds, "doc", 1, 0);
DataSetAssertion.AssertDataTable("table", ds.Tables[0], "elem", 2, 0, 0, 0, 0, 0);
}
[Fact]
public void UnusedComplexTypesIgnored()
{
string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'>
<xs:element name='Root'>
<xs:complexType>
<xs:sequence>
<xs:element name='Child' type='xs:string' />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name='unusedType'>
<xs:sequence>
<xs:element name='Orphan' type='xs:string' />
</xs:sequence>
</xs:complexType>
</xs:schema>";
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
// Here "unusedType" table is never imported.
DataSetAssertion.AssertDataSet("ds", ds, "hoge", 1, 0);
DataSetAssertion.AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
}
[Fact]
public void SimpleTypeComponentsIgnored()
{
string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Root' type='xs:string'/>
<xs:attribute name='Attr' type='xs:string'/>
</xs:schema>";
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
// nothing is imported.
DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 0, 0);
}
[Fact]
public void IsDataSetAndTypeIgnored()
{
string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
<xs:element name='Root' type='unusedType' msdata:IsDataSet='{0}'>
</xs:element>
<xs:complexType name='unusedType'>
<xs:sequence>
<xs:element name='Child' type='xs:string' />
</xs:sequence>
</xs:complexType>
</xs:schema>";
// Even if a global element uses a complexType, it will be
// ignored if the element has msdata:IsDataSet='true'
string xs = string.Format(xsbase, "true");
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("ds", ds, "Root", 0, 0); // name is "Root"
// But when explicit msdata:IsDataSet value is "false", then
// treat as usual.
xs = string.Format(xsbase, "false");
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 1, 0);
}
[Fact]
public void NestedReferenceNotAllowed()
{
string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
<xs:element name='Root' type='unusedType' msdata:IsDataSet='true'>
</xs:element>
<xs:complexType name='unusedType'>
<xs:sequence>
<xs:element name='Child' type='xs:string' />
</xs:sequence>
</xs:complexType>
<xs:element name='Foo'>
<xs:complexType>
<xs:sequence>
<xs:element ref='Root' />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
// DataSet element cannot be converted into a DataTable.
// (i.e. cannot be referenced in any other elements)
var ds = new DataSet();
AssertExtensions.Throws<ArgumentException>(null, () =>
{
ds.ReadXmlSchema(new StringReader(xs));
});
}
[Fact]
public void IsDataSetOnLocalElementIgnored()
{
string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
<xs:element name='Root' type='unusedType'>
</xs:element>
<xs:complexType name='unusedType'>
<xs:sequence>
<xs:element name='Child' type='xs:string' msdata:IsDataSet='True' />
</xs:sequence>
</xs:complexType>
</xs:schema>";
// msdata:IsDataSet does not affect even if the value is invalid
string xs = string.Format(xsbase, "true");
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
// Child should not be regarded as DataSet element
DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 1, 0);
}
[Fact]
public void LocaleOnRootWithoutIsDataSet()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = new CultureInfo("fi-FI");
string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
<xs:element name='Root' msdata:Locale='ja-JP'>
<xs:complexType>
<xs:sequence>
<xs:element name='Child' type='xs:string' />
</xs:sequence>
<xs:attribute name='Attr' type='xs:integer' />
</xs:complexType>
</xs:element>
</xs:schema>";
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 1, 0);
Assert.Equal("fi-FI", ds.Locale.Name); // DataSet's Locale comes from current thread
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0);
Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale
DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void ElementHasIdentityConstraint()
{
string constraints = @"
<xs:key name='key'>
<xs:selector xpath='./any/string_is_OK/R1'/>
<xs:field xpath='Child2'/>
</xs:key>
<xs:keyref name='kref' refer='key'>
<xs:selector xpath='.//R2'/>
<xs:field xpath='Child2'/>
</xs:keyref>";
string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
<xs:element name='DS' msdata:IsDataSet='true'>
<xs:complexType>
<xs:choice>
<xs:element ref='R1' />
<xs:element ref='R2' />
</xs:choice>
</xs:complexType>
{0}
</xs:element>
<xs:element name='R1' type='RootType'>
{1}
</xs:element>
<xs:element name='R2' type='RootType'>
</xs:element>
<xs:complexType name='RootType'>
<xs:choice>
<xs:element name='Child1' type='xs:string'>
{2}
</xs:element>
<xs:element name='Child2' type='xs:string' />
</xs:choice>
<xs:attribute name='Attr' type='xs:integer' />
</xs:complexType>
</xs:schema>";
// Constraints on DataSet element.
// Note that in xs:key xpath is crazy except for the last step
string xs = string.Format(xsbase, constraints, string.Empty, string.Empty);
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
Assert.Equal(1, ds.Relations.Count);
// Constraints on another global element - just ignored
xs = string.Format(xsbase, string.Empty, constraints, string.Empty);
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
Assert.Equal(0, ds.Relations.Count);
// Constraints on local element - just ignored
xs = string.Format(xsbase, string.Empty, string.Empty, constraints);
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
Assert.Equal(0, ds.Relations.Count);
}
[Fact]
public void PrefixedTargetNS()
{
string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:x='urn:foo' targetNamespace='urn:foo' elementFormDefault='qualified'>
<xs:element name='DS' msdata:IsDataSet='true'>
<xs:complexType>
<xs:choice>
<xs:element ref='x:R1' />
<xs:element ref='x:R2' />
</xs:choice>
</xs:complexType>
<xs:key name='key'>
<xs:selector xpath='./any/string_is_OK/x:R1'/>
<xs:field xpath='x:Child2'/>
</xs:key>
<xs:keyref name='kref' refer='x:key'>
<xs:selector xpath='.//x:R2'/>
<xs:field xpath='x:Child2'/>
</xs:keyref>
</xs:element>
<xs:element name='R3' type='x:RootType' />
<xs:complexType name='extracted'>
<xs:choice>
<xs:element ref='x:R1' />
<xs:element ref='x:R2' />
</xs:choice>
</xs:complexType>
<xs:element name='R1' type='x:RootType'>
<xs:unique name='Rkey'>
<xs:selector xpath='.//x:Child1'/>
<xs:field xpath='.'/>
</xs:unique>
<xs:keyref name='Rkref' refer='x:Rkey'>
<xs:selector xpath='.//x:Child2'/>
<xs:field xpath='.'/>
</xs:keyref>
</xs:element>
<xs:element name='R2' type='x:RootType'>
</xs:element>
<xs:complexType name='RootType'>
<xs:choice>
<xs:element name='Child1' type='xs:string'>
</xs:element>
<xs:element name='Child2' type='xs:string' />
</xs:choice>
<xs:attribute name='Attr' type='xs:integer' />
</xs:complexType>
</xs:schema>";
// No prefixes on tables and columns
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(xs));
DataSetAssertion.AssertDataSet("ds", ds, "DS", 3, 1);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("R3", dt, "R3", 3, 0, 0, 0, 0, 0);
DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
}
[Fact]
public void ReadTest1()
{
DataSet ds = CreateTestSet();
StringWriter sw = new StringWriter();
ds.WriteXmlSchema(sw);
string schema = sw.ToString();
// ReadXmlSchema()
ds = new DataSet();
ds.ReadXmlSchema(new XmlTextReader(schema, XmlNodeType.Document, null));
ReadTest1Check(ds);
// ReadXml() should also be the same
ds = new DataSet();
ds.ReadXml(new XmlTextReader(schema, XmlNodeType.Document, null));
ReadTest1Check(ds);
}
private void ReadTest1Check(DataSet ds)
{
DataSetAssertion.AssertDataSet("dataset", ds, "NewDataSet", 2, 1);
DataSetAssertion.AssertDataTable("tbl1", ds.Tables[0], "Table1", 3, 0, 0, 1, 1, 0);
DataSetAssertion.AssertDataTable("tbl2", ds.Tables[1], "Table2", 3, 0, 1, 0, 1, 0);
DataRelation rel = ds.Relations[0];
DataSetAssertion.AssertDataRelation("rel", rel, "Rel1", false,
new string[] { "Column1_3" },
new string[] { "Column2_1" }, true, true);
DataSetAssertion.AssertUniqueConstraint("uc", rel.ParentKeyConstraint,
"Constraint1", false, new string[] { "Column1_3" });
DataSetAssertion.AssertForeignKeyConstraint("fk", rel.ChildKeyConstraint, "Rel1",
AcceptRejectRule.None, Rule.Cascade, Rule.Cascade,
new string[] { "Column2_1" },
new string[] { "Column1_3" });
}
[Fact]
// 001-004
public void TestSampleFileNoTables()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><!-- empty --></xs:schema>"));
DataSetAssertion.AssertDataSet("001", ds, "NewDataSet", 0, 0);
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:element name='foo' /></xs:schema>"));
DataSetAssertion.AssertDataSet("002", ds, "NewDataSet", 0, 0);
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='foo' type='xs:integer' />
<xs:element name='bar' type='xs:string' />
</xs:schema>"));
DataSetAssertion.AssertDataSet("003", ds, "NewDataSet", 0, 0);
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='foo' type='st' />
<xs:simpleType name='st'>
<xs:restriction base='xs:string'>
<xs:maxLength value='5' />
</xs:restriction>
</xs:simpleType>
</xs:schema>"));
DataSetAssertion.AssertDataSet("004", ds, "NewDataSet", 0, 0);
}
[Fact]
public void TestSampleFileSimpleTables()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='foo' type='ct' />
<xs:complexType name='ct'>
<xs:simpleContent>
<xs:extension base='xs:integer'>
<xs:attribute name='attr' />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:schema>"));
DataSetAssertion.AssertDataSet("005", ds, "NewDataSet", 1, 0);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0);
DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "attr", true, false, 0, 1, "attr", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("text", dt.Columns[1], "foo_text", false, false, 0, 1, "foo_text", MappingType.SimpleContent, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='foo' type='st' />
<xs:complexType name='st'>
<xs:attribute name='att1' />
<xs:attribute name='att2' type='xs:int' default='2' />
</xs:complexType>
</xs:schema>"));
DataSetAssertion.AssertDataSet("006", ds, "NewDataSet", 1, 0);
dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0);
DataSetAssertion.AssertDataColumn("att1", dt.Columns["att1"], "att1", true, false, 0, 1, "att1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("att2", dt.Columns["att2"], "att2", true, false, 0, 1, "att2", MappingType.Attribute, typeof(int), 2, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false);
}
[Fact]
public void TestSampleFileComplexTables()
{
// Nested simple type element
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<!-- nested tables, root references to complex type -->
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' xmlns:x='urn:foo'>
<xs:element name='uno' type='x:t' />
<xs:complexType name='t'>
<xs:sequence>
<xs:element name='des'>
<xs:complexType>
<xs:sequence>
<xs:element name='tres' />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>"));
DataSetAssertion.AssertDataSet("007", ds, "NewDataSet", 2, 1);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("tab1", dt, "uno", 1, 0, 0, 1, 1, 1);
DataSetAssertion.AssertDataColumn("id", dt.Columns[0], "uno_Id", false, true, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, "urn:foo", 0, string.Empty, false, true);
dt = ds.Tables[1];
DataSetAssertion.AssertDataTable("tab2", dt, "des", 2, 0, 1, 0, 1, 0);
DataSetAssertion.AssertDataColumn("child", dt.Columns[0], "tres", false, false, 0, 1, "tres", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("id", dt.Columns[1], "uno_Id", true, false, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
// External simple type element
ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<!-- reference to external simple element -->
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' xmlns:x='urn:foo'>
<xs:element name='uno' type='x:t' />
<xs:element name='tres' type='xs:string' />
<xs:complexType name='t'>
<xs:sequence>
<xs:element name='des'>
<xs:complexType>
<xs:sequence>
<xs:element ref='x:tres' />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>"));
DataSetAssertion.AssertDataSet("008", ds, "NewDataSet", 2, 1);
dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("tab1", dt, "uno", 1, 0, 0, 1, 1, 1);
DataSetAssertion.AssertDataColumn("id", dt.Columns[0], "uno_Id", false, true, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, "urn:foo", 0, string.Empty, false, true);
dt = ds.Tables[1];
DataSetAssertion.AssertDataTable("tab2", dt, "des", 2, 0, 1, 0, 1, 0);
DataSetAssertion.AssertDataColumn("child", dt.Columns[0], "tres", false, false, 0, 1, "tres", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, "urn:foo", 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("id", dt.Columns[1], "uno_Id", true, false, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
}
[Fact]
public void TestSampleFileComplexTables3()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<!-- Modified w3ctests attQ014.xsd -->
<xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://xsdtesting"" xmlns:x=""http://xsdtesting"">
<xsd:element name=""root"">
<xsd:complexType>
<xsd:sequence>
<xsd:element name=""e"">
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base=""xsd:decimal"">
<xsd:attribute name=""a"" type=""xsd:string""/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>"));
DataSetAssertion.AssertDataSet("013", ds, "root", 1, 0);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("root", dt, "e", 2, 0, 0, 0, 0, 0);
DataSetAssertion.AssertDataColumn("attr", dt.Columns[0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("simple", dt.Columns[1], "e_text", false, false, 0, 1, "e_text", MappingType.SimpleContent, typeof(decimal), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
}
[Fact]
public void TestSampleFileXPath()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<xs:schema targetNamespace=""http://neurosaudio.com/Tracks.xsd"" xmlns=""http://neurosaudio.com/Tracks.xsd"" xmlns:mstns=""http://neurosaudio.com/Tracks.xsd"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" elementFormDefault=""qualified"" id=""Tracks"">
<xs:element name=""Tracks"">
<xs:complexType>
<xs:sequence>
<xs:element name=""Track"" minOccurs=""0"" maxOccurs=""unbounded"">
<xs:complexType>
<xs:sequence>
<xs:element name=""Title"" type=""xs:string"" />
<xs:element name=""Artist"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""Album"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""Performer"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""Sequence"" type=""xs:unsignedInt"" minOccurs=""0"" />
<xs:element name=""Genre"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""Comment"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""Year"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""Duration"" type=""xs:unsignedInt"" minOccurs=""0"" />
<xs:element name=""Path"" type=""xs:string"" />
<xs:element name=""DevicePath"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""FileSize"" type=""xs:unsignedInt"" minOccurs=""0"" />
<xs:element name=""Source"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""FlashStatus"" type=""xs:unsignedInt"" />
<xs:element name=""HDStatus"" type=""xs:unsignedInt"" />
</xs:sequence>
<xs:attribute name=""ID"" type=""xs:unsignedInt"" msdata:AutoIncrement=""true"" msdata:AutoIncrementSeed=""1"" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:key name=""TrackPK"" msdata:PrimaryKey=""true"">
<xs:selector xpath="".//mstns:Track"" />
<xs:field xpath=""@ID"" />
</xs:key>
</xs:element>
</xs:schema>"));
}
[Fact]
public void TestAnnotatedRelation1()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xs:schema xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
<xs:element name=""root"" msdata:IsDataSet=""true"">
<xs:complexType>
<xs:choice maxOccurs=""unbounded"">
<xs:element name=""p"">
<xs:complexType>
<xs:sequence>
<xs:element name=""pk"" type=""xs:string"" />
<xs:element name=""name"" type=""xs:string"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""c"">
<xs:complexType>
<xs:sequence>
<xs:element name=""fk"" type=""xs:string"" />
<xs:element name=""count"" type=""xs:int"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:annotation>
<xs:appinfo>
<msdata:Relationship name=""rel""
msdata:parent=""p""
msdata:child=""c""
msdata:parentkey=""pk""
msdata:childkey=""fk""/>
</xs:appinfo>
</xs:annotation>
</xs:schema>"));
DataSetAssertion.AssertDataSet("101", ds, "root", 2, 1);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("parent_table", dt, "p", 2, 0, 0, 1, 0, 0);
DataSetAssertion.AssertDataColumn("pk", dt.Columns[0], "pk", false, false, 0, 1, "pk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
dt = ds.Tables[1];
DataSetAssertion.AssertDataTable("child_table", dt, "c", 2, 0, 1, 0, 0, 0);
DataSetAssertion.AssertDataColumn("fk", dt.Columns[0], "fk", false, false, 0, 1, "fk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataRelation("rel", ds.Relations[0], "rel", false, new string[] { "pk" }, new string[] { "fk" }, false, false);
}
[Fact]
public void TestAnnotatedRelation2()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
<!-- just modified MSDN example -->
<xs:element name=""ds"" msdata:IsDataSet=""true"">
<xs:complexType>
<xs:choice maxOccurs=""unbounded"">
<xs:element name=""p"">
<xs:complexType>
<xs:sequence>
<xs:element name=""pk"" type=""xs:string"" />
<xs:element name=""name"" type=""xs:string"" />
<xs:element name=""c"">
<xs:annotation>
<xs:appinfo>
<msdata:Relationship name=""rel""
msdata:parent=""p""
msdata:child=""c""
msdata:parentkey=""pk""
msdata:childkey=""fk""/>
</xs:appinfo>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name=""fk"" type=""xs:string"" />
<xs:element name=""count"" type=""xs:int"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>"));
DataSetAssertion.AssertDataSet("102", ds, "ds", 2, 1);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("parent_table", dt, "p", 2, 0, 0, 1, 0, 0);
DataSetAssertion.AssertDataColumn("pk", dt.Columns[0], "pk", false, false, 0, 1, "pk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
dt = ds.Tables[1];
DataSetAssertion.AssertDataTable("child_table", dt, "c", 2, 0, 1, 0, 0, 0);
DataSetAssertion.AssertDataColumn("fk", dt.Columns[0], "fk", false, false, 0, 1, "fk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataRelation("rel", ds.Relations[0], "rel", true, new string[] { "pk" }, new string[] { "fk" }, false, false);
}
[Fact]
public void RepeatableSimpleElement()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<!-- empty -->
<xs:element name='Foo' type='FooType' />
<!-- defining externally to avoid being regarded as dataset element -->
<xs:complexType name='FooType'>
<xs:sequence>
<xs:element name='Bar' maxOccurs='2' />
</xs:sequence>
</xs:complexType>
</xs:schema>"));
DataSetAssertion.AssertDataSet("012", ds, "NewDataSet", 2, 1);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("parent", dt, "Foo", 1, 0, 0, 1, 1, 1);
DataSetAssertion.AssertDataColumn("key", dt.Columns[0], "Foo_Id", false, true, 0, 1, "Foo_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, true);
dt = ds.Tables[1];
DataSetAssertion.AssertDataTable("repeated", dt, "Bar", 2, 0, 1, 0, 1, 0);
DataSetAssertion.AssertDataColumn("data", dt.Columns[0], "Bar_Column", false, false, 0, 1, "Bar_Column", MappingType.SimpleContent, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("refkey", dt.Columns[1], "Foo_Id", true, false, 0, 1, "Foo_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
DataSetAssertion.AssertDataRelation("rel", ds.Relations[0], "Foo_Bar", true, new string[] { "Foo_Id" }, new string[] { "Foo_Id" }, true, true);
}
[Fact]
public void TestMoreThanOneRepeatableColumns()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<xsd:element name=""root"">
<xsd:complexType>
<xsd:sequence>
<xsd:element name=""x"" maxOccurs=""2"" />
<xsd:element ref=""y"" maxOccurs=""unbounded"" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name=""y"" />
</xsd:schema>"));
DataSetAssertion.AssertDataSet("014", ds, "NewDataSet", 3, 2);
DataTable dt = ds.Tables[0];
DataSetAssertion.AssertDataTable("parent", dt, "root", 1, 0, 0, 2, 1, 1);
DataSetAssertion.AssertDataColumn("key", dt.Columns[0], "root_Id", false, true, 0, 1, "root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, true);
dt = ds.Tables[1];
DataSetAssertion.AssertDataTable("repeated", dt, "x", 2, 0, 1, 0, 1, 0);
DataSetAssertion.AssertDataColumn("data_1", dt.Columns[0], "x_Column", false, false, 0, 1, "x_Column", MappingType.SimpleContent, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("refkey_1", dt.Columns[1], "root_Id", true, false, 0, 1, "root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
dt = ds.Tables[2];
DataSetAssertion.AssertDataTable("repeated", dt, "y", 2, 0, 1, 0, 1, 0);
DataSetAssertion.AssertDataColumn("data", dt.Columns[0], "y_Column", false, false, 0, 1, "y_Column", MappingType.SimpleContent, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
DataSetAssertion.AssertDataColumn("refkey", dt.Columns[1], "root_Id", true, false, 0, 1, "root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
DataSetAssertion.AssertDataRelation("rel", ds.Relations[0], "root_x", true, new string[] { "root_Id" }, new string[] { "root_Id" }, true, true);
DataSetAssertion.AssertDataRelation("rel", ds.Relations[1], "root_y", true, new string[] { "root_Id" }, new string[] { "root_Id" }, true, true);
}
[Fact]
public void AutoIncrementStep()
{
DataSet ds = new DataSet("testds");
DataTable tbl = ds.Tables.Add("testtbl");
DataColumn col = tbl.Columns.Add("id", typeof(int));
col.AutoIncrement = true;
col.AutoIncrementSeed = -1;
col.AutoIncrementStep = -1;
tbl.Columns.Add("data", typeof(string));
Assert.True(ds.GetXmlSchema().IndexOf("AutoIncrementStep") > 0);
}
[Fact]
public void ReadConstraints()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
<xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:Locale=""en-US"">
<xs:complexType>
<xs:choice maxOccurs=""unbounded"">
<xs:element name=""Table1"">
<xs:complexType>
<xs:sequence>
<xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""Table2"">
<xs:complexType>
<xs:sequence>
<xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
<xs:unique name=""Constraint1"">
<xs:selector xpath="".//Table1"" />
<xs:field xpath=""col1"" />
</xs:unique>
<xs:keyref name=""fk1"" refer=""Constraint1"" msdata:ConstraintOnly=""true"">
<xs:selector xpath="".//Table2"" />
<xs:field xpath=""col1"" />
</xs:keyref>
</xs:element>
</xs:schema>"));
Assert.Equal(0, ds.Relations.Count);
Assert.Equal(1, ds.Tables[0].Constraints.Count);
Assert.Equal(1, ds.Tables[1].Constraints.Count);
Assert.Equal("fk1", ds.Tables[1].Constraints[0].ConstraintName);
}
[Fact]
public void ReadAnnotatedRelations_MultipleColumns()
{
var ds = new DataSet();
ds.ReadXmlSchema(new StringReader(
@"<?xml version=""1.0"" standalone=""yes""?>
<xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
<xs:element name=""NewDataSet"" msdata:IsDataSet=""true"">
<xs:complexType>
<xs:choice maxOccurs=""unbounded"">
<xs:element name=""Table1"">
<xs:complexType>
<xs:sequence>
<xs:element name=""col_x0020_1"" type=""xs:int"" minOccurs=""0"" />
<xs:element name=""col2"" type=""xs:int"" minOccurs=""0"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""Table2"">
<xs:complexType>
<xs:sequence>
<xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" />
<xs:element name=""col_x0020__x0020_2"" type=""xs:int"" minOccurs=""0"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:annotation>
<xs:appinfo>
<msdata:Relationship name=""rel"" msdata:parent=""Table1"" msdata:child=""Table2"" msdata:parentkey=""col_x0020_1 col2"" msdata:childkey=""col1 col_x0020__x0020_2"" />
</xs:appinfo>
</xs:annotation>
</xs:schema>"));
Assert.Equal(1, ds.Relations.Count);
Assert.Equal("rel", ds.Relations[0].RelationName);
Assert.Equal(2, ds.Relations[0].ParentColumns.Length);
Assert.Equal(2, ds.Relations[0].ChildColumns.Length);
Assert.Equal(0, ds.Tables[0].Constraints.Count);
Assert.Equal(0, ds.Tables[1].Constraints.Count);
DataSetAssertion.AssertDataRelation("TestRel", ds.Relations[0], "rel", false, new string[] { "col 1", "col2" },
new string[] { "col1", "col 2" }, false, false);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel.Tokens
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Runtime.CompilerServices;
public class RsaSecurityToken : SecurityToken
{
string id;
DateTime effectiveTime;
ReadOnlyCollection<SecurityKey> rsaKey;
RSA rsa;
CspKeyContainerInfo keyContainerInfo;
GCHandle rsaHandle;
public RsaSecurityToken(RSA rsa)
: this(rsa, SecurityUniqueId.Create().Value)
{
}
public RsaSecurityToken(RSA rsa, string id)
{
if (rsa == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");
if (id == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");
this.rsa = rsa;
this.id = id;
this.effectiveTime = DateTime.UtcNow;
GC.SuppressFinalize(this);
}
// This is defense-in-depth.
// Rsa finalizer can throw and bring down the process if in finalizer context.
// This internal ctor is used by SM's IssuedSecurityTokenProvider.
// If ownsRsa=true, this class will take ownership of the Rsa object and provides
// a reliable finalizing/disposing of Rsa object. The GCHandle is used to ensure
// order in finalizer sequence.
RsaSecurityToken(RSACryptoServiceProvider rsa, bool ownsRsa)
{
if (rsa == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");
this.rsa = rsa;
this.id = SecurityUniqueId.Create().Value;
this.effectiveTime = DateTime.UtcNow;
if (ownsRsa)
{
// This also key pair generation.
// This must be called before PersistKeyInCsp to avoid a handle to go out of scope.
this.keyContainerInfo = rsa.CspKeyContainerInfo;
// We will handle key file deletion
rsa.PersistKeyInCsp = true;
this.rsaHandle = GCHandle.Alloc(rsa);
}
else
{
GC.SuppressFinalize(this);
}
}
~RsaSecurityToken()
{
Dispose(false);
}
internal void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (this.rsaHandle.IsAllocated)
{
try
{
// keyContainerInfo is a wrapper over a member of Rsa.
// this is to be safe that rsa.Dispose won't clean up that member.
string keyContainerName = this.keyContainerInfo.KeyContainerName;
string providerName = this.keyContainerInfo.ProviderName;
uint providerType = (uint)this.keyContainerInfo.ProviderType;
((IDisposable)this.rsa).Dispose();
// Best effort delete key file in user context
SafeProvHandle provHandle;
if (!NativeMethods.CryptAcquireContextW(out provHandle,
keyContainerName,
providerName,
providerType,
NativeMethods.CRYPT_DELETEKEYSET))
{
int error = Marshal.GetLastWin32Error();
try
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.FailedToDeleteKeyContainerFile), new Win32Exception(error)));
}
catch (InvalidOperationException ex)
{
DiagnosticUtility.TraceHandledException(ex, TraceEventType.Warning);
}
}
System.ServiceModel.Diagnostics.Utility.CloseInvalidOutSafeHandle(provHandle);
}
finally
{
this.rsaHandle.Free();
}
}
}
internal static RsaSecurityToken CreateSafeRsaSecurityToken(int keySize)
{
RsaSecurityToken token;
RSACryptoServiceProvider rsa = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
try
{
}
finally
{
rsa = new RSACryptoServiceProvider(keySize);
}
token = new RsaSecurityToken(rsa, true);
rsa = null;
}
finally
{
if (rsa != null)
{
((IDisposable)rsa).Dispose();
}
}
return token;
}
public override string Id
{
get { return this.id; }
}
public override DateTime ValidFrom
{
get { return this.effectiveTime; }
}
public override DateTime ValidTo
{
// Never expire
get { return SecurityUtils.MaxUtcDateTime; }
}
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
if (this.rsaKey == null)
{
List<SecurityKey> keys = new List<SecurityKey>(1);
keys.Add(new RsaSecurityKey(this.rsa));
this.rsaKey = keys.AsReadOnly();
}
return this.rsaKey;
}
}
public RSA Rsa
{
get { return this.rsa; }
}
public override bool CanCreateKeyIdentifierClause<T>()
{
return typeof(T) == typeof(RsaKeyIdentifierClause);
}
public override T CreateKeyIdentifierClause<T>()
{
if (typeof(T) == typeof(RsaKeyIdentifierClause))
return (T)((object)new RsaKeyIdentifierClause(this.rsa));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
SR.GetString(SR.TokenDoesNotSupportKeyIdentifierClauseCreation, GetType().Name, typeof(T).Name)));
}
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
RsaKeyIdentifierClause rsaKeyIdentifierClause = keyIdentifierClause as RsaKeyIdentifierClause;
if (rsaKeyIdentifierClause != null)
return rsaKeyIdentifierClause.Matches(this.rsa);
return false;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="XmlWrapper.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.AI.BehaviorTrees.Editor
{
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Slash.AI.BehaviorTrees.Implementations;
using Slash.AI.BehaviorTrees.Interfaces;
using Slash.Xml;
/// <summary>
/// Called when an unknown task should be read from a xml document.
/// </summary>
/// <param name="reader"> Xml reader. </param>
/// <param name="task"> Task which is read. </param>
public delegate void XmlSerializationReadDelegate(XmlReader reader, out ITask task);
/// <summary>
/// Xml wrapper to serialize a decider, even when it's unknown.
/// </summary>
public class XmlWrapper : IXmlSerializable
{
#region Static Fields
/// <summary>
/// Called when an unknown task is read from a xml document.
/// </summary>
public static XmlSerializationReadDelegate OnXmlReadUnknownTask;
#endregion
#region Fields
/// <summary>
/// Wrapped task.
/// </summary>
private ITask task;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="XmlWrapper" /> class. Constructor.
/// </summary>
public XmlWrapper()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlWrapper" /> class. Constructor.
/// </summary>
/// <param name="task"> Task to wrap. </param>
public XmlWrapper(ITask task)
{
this.task = task;
}
#endregion
#region Public Properties
/// <summary>
/// Wrapped task.
/// </summary>
public ITask Task
{
get
{
return this.task;
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// The equals.
/// </summary>
/// <param name="other"> The other. </param>
/// <returns> The System.Boolean. </returns>
public bool Equals(XmlWrapper other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.task, this.task);
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="obj"> The obj. </param>
/// <returns> The System.Boolean. </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(XmlWrapper))
{
return false;
}
return this.Equals((XmlWrapper)obj);
}
/// <summary>
/// The get hash code.
/// </summary>
/// <returns> The System.Int32. </returns>
public override int GetHashCode()
{
return this.task != null ? this.task.GetHashCode() : 0;
}
/// <summary>
/// The get schema.
/// </summary>
/// <returns> The System.Xml.Schema.XmlSchema. </returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// The read xml.
/// </summary>
/// <param name="reader"> The reader. </param>
public void ReadXml(XmlReader reader)
{
try
{
XmlAnything<ITask> xmlWrapper = new XmlAnything<ITask>();
xmlWrapper.ReadXml(reader);
this.task = xmlWrapper.Value;
}
catch (InvalidCastException)
{
if (OnXmlReadUnknownTask != null)
{
OnXmlReadUnknownTask(reader, out this.task);
}
else
{
throw;
}
}
}
/// <summary>
/// The write xml.
/// </summary>
/// <param name="writer"> The writer. </param>
public void WriteXml(XmlWriter writer)
{
// Special case for reference decider.
// TODO(co): Would be nice to capsule this inside the ReferenceTask class, but the xml node is written
// before the ReferenceTask object gets the control.
ReferenceTask referenceTask = this.task as ReferenceTask;
if (referenceTask != null)
{
string typeString = referenceTask.TaskDescription != null
? referenceTask.TaskDescription.TypeName
: typeof(ReferenceTask).AssemblyQualifiedName;
writer.WriteAttributeString("type", typeString);
string elementName = referenceTask.TaskDescription != null
? referenceTask.TaskDescription.ClassName
: typeof(ReferenceTask).Name;
XmlSerializer serializer = new XmlSerializer(typeof(ReferenceTask), new XmlRootAttribute(elementName));
serializer.Serialize(writer, referenceTask);
}
else
{
XmlAnything<ITask> xmlWrapper = new XmlAnything<ITask>(this.task);
xmlWrapper.WriteXml(writer);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AccountOperations operations.
/// </summary>
internal partial class AccountOperations : IServiceOperations<DataLakeAnalyticsAccountManagementClient>, IAccountOperations
{
/// <summary>
/// Tests whether the specified Azure Storage account is linked to the given Data
/// Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Analytics
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// Azure storage account existence.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure Storage account for which to test for existence.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> StorageAccountExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (storageAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storageAccountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("storageAccountName", storageAccountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStorageAccount", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/StorageAccounts/{storageAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{storageAccountName}", Uri.EscapeDataString(storageAccountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests the existence of the specified Azure Storage container associated with the
/// given Data Lake Analytics and Azure Storage accounts.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account for which to retrieve
/// blob container.
/// </param>
/// <param name='storageAccountName'>
/// The name of the Azure storage account from which to test the
/// blob container's existence.
/// </param>
/// <param name='containerName'>
/// The name of the Azure storage container to test for existence.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> StorageContainerExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string storageAccountName, string containerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (storageAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storageAccountName");
}
if (containerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "containerName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("storageAccountName", storageAccountName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStorageContainer", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/StorageAccounts/{storageAccountName}/Containers/{containerName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{storageAccountName}", Uri.EscapeDataString(storageAccountName));
_url = _url.Replace("{containerName}", Uri.EscapeDataString(containerName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests whether the specified Data Lake Store account is linked to the
/// specified Data Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account from which to test
/// the existence of the Data Lake Store account.
/// </param>
/// <param name='dataLakeStoreAccountName'>
/// The name of the Data Lake Store account to test for existence
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> DataLakeStoreAccountExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (dataLakeStoreAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetDataLakeStoreAccount", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{dataLakeStoreAccountName}", Uri.EscapeDataString(dataLakeStoreAccountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests for the existence of the specified Data Lake Analytics account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Analytics account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Analytics account to test existence of.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> ExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility001.accessibility001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility001.accessibility001;
public class Test
{
private int this[int x]
{
set
{
Status = 0;
}
}
public static int Status = -1;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test b = new Test();
dynamic x = int.MaxValue;
b[x] = 1;
return Status;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility002.accessibility002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility002.accessibility002;
public class Test
{
protected int this[int x]
{
set
{
Status = 0;
}
}
public static int Status = -1;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
var b = new Test();
dynamic x = int.MaxValue;
b[x] = 1;
return Status;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility005.accessibility005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility005.accessibility005;
public class Test
{
private class Base
{
public int this[int x]
{
set
{
Test.Status = 1;
}
}
}
public static int Status;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b[x] = 1;
if (Test.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility006.accessibility006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility006.accessibility006;
public class Test
{
protected class Base
{
public int this[int x]
{
set
{
Test.Status = 1;
}
}
}
public static int Status;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b[x] = 1;
if (Test.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility007.accessibility007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility007.accessibility007;
public class Test
{
internal class Base
{
public int this[int x]
{
set
{
Test.Status = 1;
}
}
}
public static int Status;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b[x] = 1;
if (Test.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility011.accessibility011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility011.accessibility011;
public class Test
{
public static int Status;
public class Higher
{
private class Base
{
public int this[int x]
{
set
{
Test.Status = 1;
}
}
}
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b[x] = 1;
if (Test.Status == 1)
return 0;
return 1;
}
}
}
// </Code>
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using NPOI.Util;
using System.Text;
using System;
/**
* Title: NAMECMT Record (0x0894)
* Description: Defines a comment associated with a specified name.
* REFERENCE:
*
* @author Andrew Shirley (aks at corefiling.co.uk)
*/
public class NameCommentRecord : StandardRecord
{
public const short sid = 0x0894;
private short field_1_record_type;
private short field_2_frt_cell_ref_flag;
private long field_3_reserved;
//private short field_4_name_Length;
//private short field_5_comment_Length;
private String field_6_name_text;
private String field_7_comment_text;
public NameCommentRecord(string name, String comment)
{
field_1_record_type = 0;
field_2_frt_cell_ref_flag = 0;
field_3_reserved = 0;
field_6_name_text = name;
field_7_comment_text = comment;
}
public override void Serialize(ILittleEndianOutput out1)
{
int field_4_name_length = field_6_name_text.Length;
int field_5_comment_length = field_7_comment_text.Length;
out1.WriteShort(field_1_record_type);
out1.WriteShort(field_2_frt_cell_ref_flag);
out1.WriteLong(field_3_reserved);
out1.WriteShort(field_4_name_length);
out1.WriteShort(field_5_comment_length);
//out1.WriteByte(0);
//StringUtil.PutCompressedUnicode(field_6_name_text,out1);
//out1.WriteByte(0);
//StringUtil.PutCompressedUnicode(field_7_comment_text, out1);
bool isNameMultiByte = StringUtil.HasMultibyte(field_6_name_text);
out1.WriteByte(isNameMultiByte ? 1 : 0);
if (isNameMultiByte)
{
StringUtil.PutUnicodeLE(field_6_name_text, out1);
}
else
{
StringUtil.PutCompressedUnicode(field_6_name_text, out1);
}
bool isCommentMultiByte = StringUtil.HasMultibyte(field_7_comment_text);
out1.WriteByte(isCommentMultiByte ? 1 : 0);
if (isCommentMultiByte)
{
StringUtil.PutUnicodeLE(field_7_comment_text, out1);
}
else
{
StringUtil.PutCompressedUnicode(field_7_comment_text, out1);
}
}
protected override int DataSize
{
get
{
return 18 // 4 shorts + 1 long + 2 spurious 'nul's
+ (StringUtil.HasMultibyte(field_6_name_text) ? field_6_name_text.Length * 2 : field_6_name_text.Length)
+ (StringUtil.HasMultibyte(field_7_comment_text) ? field_7_comment_text.Length * 2 : field_7_comment_text.Length);
}
}
/**
* @param ris the RecordInputstream to read the record from
*/
public NameCommentRecord(RecordInputStream ris)
{
ILittleEndianInput in1 = ris;
field_1_record_type = in1.ReadShort();
field_2_frt_cell_ref_flag = in1.ReadShort();
field_3_reserved = in1.ReadLong();
int field_4_name_length = in1.ReadShort();
int field_5_comment_length = in1.ReadShort();
if (in1.ReadByte() == 0)
{
field_6_name_text = StringUtil.ReadCompressedUnicode(in1, field_4_name_length);
}
else
{
field_6_name_text = StringUtil.ReadUnicodeLE(in1, field_4_name_length);
}
if (in1.ReadByte() == 0)
{
field_7_comment_text = StringUtil.ReadCompressedUnicode(in1, field_5_comment_length);
}
else
{
field_7_comment_text = StringUtil.ReadUnicodeLE(in1, field_5_comment_length);
}
}
/**
* return the non static version of the id for this record.
*/
public override short Sid
{
get
{
return sid;
}
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[NAMECMT]\n");
sb.Append(" .record type = ").Append(HexDump.ShortToHex(field_1_record_type)).Append("\n");
sb.Append(" .frt cell ref flag = ").Append(HexDump.ByteToHex(field_2_frt_cell_ref_flag)).Append("\n");
sb.Append(" .reserved = ").Append(field_3_reserved).Append("\n");
sb.Append(" .name length = ").Append(field_6_name_text.Length).Append("\n");
sb.Append(" .comment length = ").Append(field_7_comment_text.Length).Append("\n");
sb.Append(" .name = ").Append(field_6_name_text).Append("\n");
sb.Append(" .comment = ").Append(field_7_comment_text).Append("\n");
sb.Append("[/NAMECMT]\n");
return sb.ToString();
}
/**
* @return the name of the NameRecord to which this comment applies.
*/
public String NameText
{
get
{
return field_6_name_text;
}
set
{
field_6_name_text = value;
}
}
/**
* @return the text of the comment.
*/
public String CommentText
{
get
{
return field_7_comment_text;
}
set
{
field_7_comment_text = value;
}
}
public short RecordType
{
get
{
return field_1_record_type;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;
namespace Qwack.Utils.Parallel
{
public sealed class ParallelUtils : IDisposable
{
private static readonly object _lock = new();
private static ParallelUtils _instance;
public static ParallelUtils Instance
{
get
{
if(_instance==null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new ParallelUtils();
}
}
}
return _instance;
}
}
public bool MultiThreaded { get; set; } = true;
private int _activeThreadCount = 0;
private static readonly int numThreads = Environment.ProcessorCount;
private ParallelUtils()
{
if (MultiThreaded)
{
for (var i = 0; i < numThreads; i++)
{
StartThread();
}
}
}
private void StartThread()
{
var thread = new Thread(ThreadStart)
{
IsBackground = true,
Name = $"ParallelUtilsThread{_activeThreadCount}"
};
Interlocked.Increment(ref _activeThreadCount);
thread.Start();
}
private void ThreadStart()
{
foreach(var item in _taskQueue.GetConsumingEnumerable())
{
if (item.TaskCompletion != null)
{
try
{
item.Action();
item.TaskCompletion.SetResult(true);
}
catch (Exception ex)
{
item.TaskCompletion.SetException(ex);
}
}
else
{
try
{
item.TaskToRun.RunSynchronously();
}
catch
{
}
}
if (_killQueue.TryTake(out var killTask, 0))
{
killTask.ResetEvent.Release();
break;
}
}
Interlocked.Decrement(ref _activeThreadCount);
}
private readonly BlockingCollection<WorkItem> _taskQueue = new();
private readonly BlockingCollection<WorkItem> _killQueue = new();
public async Task Foreach<T>(IList<T> values, Action<T> code, bool overrideMTFlag = false)
{
if (!overrideMTFlag && !string.IsNullOrEmpty(Thread.CurrentThread.Name) && Thread.CurrentThread.Name.StartsWith("ParallelUtilsThread"))
{
StartThread();
await RunOptimistically(values, code);
var exploder = new WorkItem()
{
IsExploder = true,
ResetEvent = new SemaphoreSlim(1)
};
var waitTask = exploder.ResetEvent.WaitAsync();
_killQueue.Add(exploder);
await waitTask;
return;
}
if (overrideMTFlag || !MultiThreaded)
{
RunInSeries(values, code);
return;
}
await RunOptimistically(values, code);
return;
}
private struct WorkItem
{
public Action Action;
public TaskCompletionSource<bool> TaskCompletion;
public Task TaskToRun;
public SemaphoreSlim ResetEvent;
public bool IsExploder;
}
public Task For(int startInclusive, int endExclusive, int step, Action<int> code, bool overrideMTFlag = false)
{
var sequence = new List<int>();
for (var v = startInclusive; v < endExclusive; v += step)
sequence.Add(v);
return Foreach(sequence, code, overrideMTFlag);
}
private static void RunInSeries<T>(IList<T> values, Action<T> code)
{
foreach (var v in values)
code(v);
}
private async Task RunOptimistically<T>(IList<T> values, Action<T> code)
{
var taskList = new List<Task>();
foreach (var v in values)
{
var tcs = new TaskCompletionSource<bool>();
var task = tcs.Task;
void action() => code(v);
var workItem = new WorkItem() { Action = action, TaskCompletion = tcs };
if (_taskQueue.TryAdd(workItem))
{
taskList.Add(tcs.Task);
}
else
{
action();
}
}
try
{
await Task.WhenAll(taskList.ToArray());
}
catch(AggregateException ex)
{
throw ex.InnerExceptions.First();
}
}
public async Task QueueAndRunTasks(IEnumerable<Task> tasks)
{
var taskList = new List<Task>();
foreach (var t in tasks)
{
var workItem = new WorkItem() { TaskToRun = t };
if (MultiThreaded && _taskQueue.TryAdd(workItem))
{
taskList.Add(t);
}
else
t.RunSynchronously();
}
await Task.WhenAll(taskList.ToArray());
}
public void Dispose() => _taskQueue.CompleteAdding();
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Reflection
{
using System;
using System.Reflection;
////using System.Reflection.Cache;
////using System.Reflection.Emit;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
////using System.Security.Permissions;
////using System.Collections;
////using System.Security;
////using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
////using System.Runtime.InteropServices;
////using System.Runtime.Serialization;
////using System.Runtime.Versioning;
////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
////using CorElementType = System.Reflection.CorElementType;
////using MdToken = System.Reflection.MetadataToken;
[Serializable]
public unsafe class ParameterInfo /*: ICustomAttributeProvider*/
{
#region Static Members
//// internal unsafe static ParameterInfo[] GetParameters( MethodBase method, MemberInfo member, Signature sig )
//// {
//// ParameterInfo dummy;
////
//// return GetParameters( method, member, sig, out dummy, false );
//// }
////
//// internal unsafe static ParameterInfo GetReturnParameter( MethodBase method, MemberInfo member, Signature sig )
//// {
//// ParameterInfo returnParameter;
////
//// GetParameters( method, member, sig, out returnParameter, true );
////
//// return returnParameter;
//// }
////
//// internal unsafe static ParameterInfo[] GetParameters( MethodBase method ,
//// MemberInfo member ,
//// Signature sig ,
//// out ParameterInfo returnParameter ,
//// bool fetchReturnParameter )
//// {
//// returnParameter = null;
////
//// RuntimeMethodHandle methodHandle = method.GetMethodHandle();
//// int sigArgCount = sig.Arguments.Length;
//// ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount];
////
//// int tkMethodDef = methodHandle.GetMethodDef();
//// int cParamDefs = 0;
////
//// // Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they
//// // are generated on the fly by the runtime.
//// if(!MdToken.IsNullToken( tkMethodDef ))
//// {
//// MetadataImport scope = methodHandle.GetDeclaringType().GetModuleHandle().GetMetadataImport();
////
//// cParamDefs = scope.EnumParamsCount( tkMethodDef );
////
//// int* tkParamDefs = stackalloc int[cParamDefs];
////
//// scope.EnumParams( tkMethodDef, tkParamDefs, cParamDefs );
////
//// // Not all parameters have tokens. Parameters may have no token
//// // if they have no name and no attributes.
//// ASSERT.CONSISTENCY_CHECK( cParamDefs <= sigArgCount + 1 /* return type */);
////
////
//// for(uint i = 0; i < cParamDefs; i++)
//// {
//// #region Populate ParameterInfos
//// ParameterAttributes attr;
//// int position;
//// int tkParamDef = tkParamDefs[i];
////
//// scope.GetParamDefProps( tkParamDef, out position, out attr );
////
//// position--;
////
//// if(fetchReturnParameter == true && position == -1)
//// {
//// ASSERT.CONSISTENCY_CHECK( returnParameter == null );
//// returnParameter = new ParameterInfo( sig, scope, tkParamDef, position, attr, member );
//// }
//// else if(fetchReturnParameter == false && position >= 0)
//// {
//// ASSERT.CONSISTENCY_CHECK( position < sigArgCount );
//// args[position] = new ParameterInfo( sig, scope, tkParamDef, position, attr, member );
//// }
//// #endregion
//// }
//// }
////
//// // Fill in empty ParameterInfos for those without tokens
//// if(fetchReturnParameter)
//// {
//// if(returnParameter == null)
//// {
//// returnParameter = new ParameterInfo( sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member );
//// }
//// }
//// else
//// {
//// if(cParamDefs < args.Length + 1)
//// {
//// for(int i = 0; i < args.Length; i++)
//// {
//// if(args[i] != null)
//// {
//// continue;
//// }
////
//// args[i] = new ParameterInfo( sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member );
//// }
//// }
//// }
////
//// return args;
//// }
#endregion
#region Private Statics
//// private static readonly Type s_DecimalConstantAttributeType = typeof( DecimalConstantAttribute );
//// private static readonly Type s_CustomConstantAttributeType = typeof( CustomConstantAttribute );
//// private static Type ParameterInfoType = typeof( System.Reflection.ParameterInfo );
#endregion
#region Definitions
//// [Flags]
//// private enum WhatIsCached
//// {
//// Nothing = 0x0,
//// Name = 0x1,
//// ParameterType = 0x2,
//// DefaultValue = 0x4,
//// All = Name | ParameterType | DefaultValue
//// }
#endregion
#region Legacy Protected Members
//// protected String NameImpl;
//// protected Type ClassImpl;
//// protected int PositionImpl;
//// protected ParameterAttributes AttrsImpl;
//// protected Object DefaultValueImpl; // cannot cache this as it may be non agile user defined enum
//// protected MemberInfo MemberImpl;
#endregion
#region Legacy Private Members
// These are here only for backwards compatibility -- they are not set
// until this instance is serialized, so don't rely on their values from
// arbitrary code.
#pragma warning disable 414
//// private IntPtr _importer;
//// private int _token;
//// private bool bExtraConstChecked;
#pragma warning restore 414
#endregion
#region Private Data Members
//// // These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility.
//// [NonSerialized]
//// private int m_tkParamDef;
//// [NonSerialized]
//// private MetadataImport m_scope;
//// [NonSerialized]
//// private Signature m_signature;
//// [NonSerialized]
//// private volatile bool m_nameIsCached = false;
//// [NonSerialized]
//// private readonly bool m_noDefaultValue = false;
#endregion
#region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints.
//// [OnSerializing]
//// private void OnSerializing( StreamingContext context )
//// {
//// // We could be serializing for consumption by a pre-Whidbey
//// // endpoint. Therefore we set up all the serialized fields to look
//// // just like a v1.0/v1.1 instance.
////
//// // First force all the protected fields (*Impl) which are computed
//// // to be set if they aren't already.
//// Object dummy;
//// dummy = ParameterType;
//// dummy = Name;
//// DefaultValueImpl = DefaultValue;
////
//// // Now set the legacy fields that the current implementation doesn't
//// // use any more. Note that _importer is a raw pointer that should
//// // never have been serialized in V1. We set it to zero here; if the
//// // deserializer uses it (by calling GetCustomAttributes() on this
//// // instance) they'll AV, but at least it will be a well defined
//// // exception and not a random AV.
//// _importer = IntPtr.Zero;
//// _token = m_tkParamDef;
//// bExtraConstChecked = false;
//// }
////
//// [OnDeserialized]
//// private void OnDeserialized( StreamingContext context )
//// {
//// // Once all the serializable fields have come in we can setup this
//// // instance based on just two of them (MemberImpl and PositionImpl).
//// // Use these members to lookup a template ParameterInfo then clone
//// // that instance into this one.
////
//// ParameterInfo targetInfo = null;
////
//// if(MemberImpl == null)
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_InsufficientState ) );
//// }
////
//// ParameterInfo[] args = null;
////
//// switch(MemberImpl.MemberType)
//// {
//// case MemberTypes.Constructor:
//// case MemberTypes.Method:
//// if(PositionImpl == -1)
//// {
//// if(MemberImpl.MemberType == MemberTypes.Method)
//// {
//// targetInfo = ((MethodInfo)MemberImpl).ReturnParameter;
//// }
//// else
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) );
//// }
//// }
//// else
//// {
//// args = ((MethodBase)MemberImpl).GetParametersNoCopy();
////
//// if(args != null && PositionImpl < args.Length)
//// {
//// targetInfo = args[PositionImpl];
//// }
//// else
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) );
//// }
//// }
//// break;
////
//// case MemberTypes.Property:
//// args = ((PropertyInfo)MemberImpl).GetIndexParameters();
////
//// if(args != null && PositionImpl > -1 && PositionImpl < args.Length)
//// {
//// targetInfo = args[PositionImpl];
//// }
//// else
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) );
//// }
//// break;
////
//// default:
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_NoParameterInfo ) );
//// }
////
//// // We've got a ParameterInfo that matches the incoming information,
//// // clone it into ourselves. We really only need to copy the private
//// // members we didn't receive via serialization.
//// ASSERT.PRECONDITION( targetInfo != null );
////
//// m_tkParamDef = targetInfo.m_tkParamDef;
//// m_scope = targetInfo.m_scope;
//// m_signature = targetInfo.m_signature;
//// m_nameIsCached = true;
//// }
#endregion
#region Constructor
//// protected ParameterInfo()
//// {
//// m_nameIsCached = true;
//// m_noDefaultValue = true;
//// }
////
//// internal ParameterInfo( ParameterInfo accessor, RuntimePropertyInfo property ) : this( accessor, (MemberInfo)property )
//// {
//// m_signature = property.Signature;
//// }
////
//// internal ParameterInfo( ParameterInfo accessor, MethodBuilderInstantiation method ) : this( accessor, (MemberInfo)method )
//// {
//// m_signature = accessor.m_signature;
////
//// if(ClassImpl.IsGenericParameter)
//// {
//// ClassImpl = method.GetGenericArguments()[ClassImpl.GenericParameterPosition];
//// }
//// }
////
//// private ParameterInfo( ParameterInfo accessor, MemberInfo member )
//// {
//// // Change ownership
//// MemberImpl = member;
////
//// // Populate all the caches -- we inherit this behavior from RTM
//// NameImpl = accessor.Name;
//// m_nameIsCached = true;
//// ClassImpl = accessor.ParameterType;
//// PositionImpl = accessor.Position;
//// AttrsImpl = accessor.Attributes;
////
//// // Strictly speeking, property's don't contain paramter tokens
//// // However we need this to make ca's work... oh well...
//// m_tkParamDef = MdToken.IsNullToken( accessor.MetadataToken ) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken;
//// m_scope = accessor.m_scope;
//// }
////
//// private ParameterInfo( Signature signature ,
//// MetadataImport scope ,
//// int tkParamDef,
//// int position ,
//// ParameterAttributes attributes,
//// MemberInfo member )
//// {
//// ASSERT.PRECONDITION( member != null );
//// ASSERT.PRECONDITION( LOGIC.BIJECTION( MdToken.IsNullToken( tkParamDef ), scope.Equals( null ) ) );
//// ASSERT.PRECONDITION( LOGIC.IMPLIES( !MdToken.IsNullToken( tkParamDef ), MdToken.IsTokenOfType( tkParamDef, MetadataTokenType.ParamDef ) ) );
////
//// PositionImpl = position;
//// MemberImpl = member;
//// m_signature = signature;
//// m_tkParamDef = MdToken.IsNullToken( tkParamDef ) ? (int)MetadataTokenType.ParamDef : tkParamDef;
//// m_scope = scope;
//// AttrsImpl = attributes;
////
//// ClassImpl = null;
//// NameImpl = null;
//// }
////
//// // ctor for no metadata MethodInfo
//// internal ParameterInfo( MethodInfo owner, String name, RuntimeType parameterType, int position )
//// {
//// MemberImpl = owner;
//// NameImpl = name;
//// m_nameIsCached = true;
//// m_noDefaultValue = true;
//// ClassImpl = parameterType;
//// PositionImpl = position;
//// AttrsImpl = ParameterAttributes.None;
//// m_tkParamDef = (int)MetadataTokenType.ParamDef;
//// m_scope = MetadataImport.EmptyImport;
//// }
#endregion
#region Private Members
//// private bool IsLegacyParameterInfo
//// {
//// get
//// {
//// return GetType() != typeof( ParameterInfo );
//// }
//// }
#endregion
#region Internal Members
//// // this is an internal api for DynamicMethod. A better solution is to change the relationship
//// // between ParameterInfo and ParameterBuilder so that a ParameterBuilder can be seen as a writer
//// // api over a ParameterInfo. However that is a possible breaking change so it needs to go through some process first
//// internal void SetName( String name )
//// {
//// NameImpl = name;
//// }
////
//// internal void SetAttributes( ParameterAttributes attributes )
//// {
//// AttrsImpl = attributes;
//// }
#endregion
#region Public Methods
public extern virtual Type ParameterType
{
[MethodImpl( MethodImplOptions.InternalCall )]
get;
//// {
//// // only instance of ParameterInfo has ClassImpl, all its subclasses don't
//// if(ClassImpl == null && this.GetType() == typeof( ParameterInfo ))
//// {
//// RuntimeTypeHandle parameterTypeHandle;
//// if(PositionImpl == -1)
//// {
//// parameterTypeHandle = m_signature.ReturnTypeHandle;
//// }
//// else
//// {
//// parameterTypeHandle = m_signature.Arguments[PositionImpl];
//// }
////
//// ASSERT.CONSISTENCY_CHECK( !parameterTypeHandle.IsNullHandle() );
//// // different thread could only write ClassImpl to the same value, so race is not a problem here
//// ClassImpl = parameterTypeHandle.GetRuntimeType();
//// }
////
//// BCLDebug.Assert( ClassImpl != null || this.GetType() != typeof( ParameterInfo ), "ClassImple should already be initialized for ParameterInfo class" );
////
//// return ClassImpl;
//// }
}
//// public virtual String Name
//// {
//// get
//// {
//// if(!m_nameIsCached)
//// {
//// if(!MdToken.IsNullToken( m_tkParamDef ))
//// {
//// string name = m_scope.GetName( m_tkParamDef ).ToString();
////
//// NameImpl = name;
//// }
////
//// // other threads could only write it to true, so race is OK
//// // this field is volatile, so the write ordering is guaranteed
//// m_nameIsCached = true;
//// }
////
//// // name may be null
//// return NameImpl;
//// }
//// }
////
//// public virtual Object DefaultValue
//// {
//// get
//// {
//// return GetDefaultValue( false );
//// }
//// }
////
//// public virtual Object RawDefaultValue
//// {
//// get
//// {
//// return GetDefaultValue( true );
//// }
//// }
////
//// internal Object GetDefaultValue( bool raw )
//// {
//// // Cannot cache because default value could be non-agile user defined enumeration.
//// object defaultValue = null;
////
//// // for dynamic method we pretend to have cached the value so we do not go to metadata
//// if(!m_noDefaultValue)
//// {
//// if(ParameterType == typeof( DateTime ))
//// {
//// if(raw)
//// {
//// CustomAttributeTypedArgument value = CustomAttributeData.Filter( CustomAttributeData.GetCustomAttributes( this ), typeof( DateTimeConstantAttribute ), 0 );
////
//// if(value.ArgumentType != null)
//// {
//// return new DateTime( (long)value.Value );
//// }
//// }
//// else
//// {
//// object[] dt = GetCustomAttributes( typeof( DateTimeConstantAttribute ), false );
////
//// if(dt != null && dt.Length != 0)
//// {
//// return ((DateTimeConstantAttribute)dt[0]).Value;
//// }
//// }
//// }
////
//// #region Look for a default value in metadata
//// if(!MdToken.IsNullToken( m_tkParamDef ))
//// {
//// defaultValue = MdConstant.GetValue( m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw );
//// }
//// #endregion
////
//// if(defaultValue == DBNull.Value)
//// {
//// #region Look for a default value in the custom attributes
//// if(raw)
//// {
//// System.Collections.Generic.IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes( this );
//// CustomAttributeTypedArgument value = CustomAttributeData.Filter( attrs, s_CustomConstantAttributeType, "Value" );
////
//// if(value.ArgumentType == null)
//// {
//// value = CustomAttributeData.Filter( attrs, s_DecimalConstantAttributeType, "Value" );
////
////
//// if(value.ArgumentType == null)
//// {
//// for(int i = 0; i < attrs.Count; i++)
//// {
//// if(attrs[i].Constructor.DeclaringType == s_DecimalConstantAttributeType)
//// {
//// ParameterInfo[] parameters = attrs[i].Constructor.GetParameters();
////
//// if(parameters.Length != 0)
//// {
//// if(parameters[2].ParameterType == typeof( uint ))
//// {
//// System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attrs[i].ConstructorArguments;
////
//// int low = (int)(UInt32)args[4].Value;
//// int mid = (int)(UInt32)args[3].Value;
//// int hi = (int)(UInt32)args[2].Value;
//// byte sign = (byte)args[1].Value;
//// byte scale = (byte)args[0].Value;
////
//// value = new CustomAttributeTypedArgument( new System.Decimal( low, mid, hi, (sign != 0), scale ) );
//// }
//// else
//// {
//// System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attrs[i].ConstructorArguments;
////
//// int low = (int)args[4].Value;
//// int mid = (int)args[3].Value;
//// int hi = (int)args[2].Value;
//// byte sign = (byte)args[1].Value;
//// byte scale = (byte)args[0].Value;
////
//// value = new CustomAttributeTypedArgument( new System.Decimal( low, mid, hi, (sign != 0), scale ) );
//// }
//// }
//// }
//// }
//// }
//// }
////
//// if(value.ArgumentType != null)
//// {
//// defaultValue = value.Value;
//// }
//// }
//// else
//// {
//// Object[] CustomAttrs = GetCustomAttributes( s_CustomConstantAttributeType, false );
//// if(CustomAttrs.Length != 0)
//// {
//// defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value;
//// }
//// else
//// {
//// CustomAttrs = GetCustomAttributes( s_DecimalConstantAttributeType, false );
//// if(CustomAttrs.Length != 0)
//// {
//// defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value;
//// }
//// }
//// }
//// #endregion
//// }
////
//// if(defaultValue == DBNull.Value)
//// {
//// #region Handle case if no default value was found
//// if(IsOptional)
//// {
//// // If the argument is marked as optional then the default value is Missing.Value.
//// defaultValue = Type.Missing;
//// }
//// #endregion
//// }
//// }
////
//// return defaultValue;
//// }
////
//// public virtual int Position
//// {
//// get
//// {
//// return PositionImpl;
//// }
//// }
////
//// public virtual ParameterAttributes Attributes
//// {
//// get
//// {
//// return AttrsImpl;
//// }
//// }
////
//// public virtual MemberInfo Member
//// {
//// get
//// {
//// return MemberImpl;
//// }
//// }
////
//// public bool IsIn
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.In) != 0);
//// }
//// }
////
//// public bool IsOut
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Out) != 0);
//// }
//// }
////
//// public bool IsLcid
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Lcid) != 0);
//// }
//// }
////
//// public bool IsRetval
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Retval) != 0);
//// }
//// }
////
//// public bool IsOptional
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Optional) != 0);
//// }
//// }
////
//// public int MetadataToken
//// {
//// get
//// {
//// return m_tkParamDef;
//// }
//// }
////
//// public virtual Type[] GetRequiredCustomModifiers()
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return new Type[0];
//// }
////
//// return m_signature.GetCustomModifiers( PositionImpl + 1, true );
//// }
////
//// public virtual Type[] GetOptionalCustomModifiers()
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return new Type[0];
//// }
////
//// return m_signature.GetCustomModifiers( PositionImpl + 1, false );
//// }
////
#endregion
#region Object Overrides
//// public override String ToString()
//// {
//// return ParameterType.SigToString() + " " + Name;
//// }
#endregion
#region ICustomAttributeProvider
//// public virtual Object[] GetCustomAttributes( bool inherit )
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return null;
//// }
////
//// if(MdToken.IsNullToken( m_tkParamDef ))
//// {
//// return new object[0];
//// }
////
//// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType );
//// }
////
//// public virtual Object[] GetCustomAttributes( Type attributeType, bool inherit )
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return null;
//// }
////
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// if(MdToken.IsNullToken( m_tkParamDef ))
//// {
//// return new object[0];
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" );
//// }
////
//// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType );
//// }
////
//// public virtual bool IsDefined( Type attributeType, bool inherit )
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return false;
//// }
////
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// if(MdToken.IsNullToken( m_tkParamDef ))
//// {
//// return false;
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" );
//// }
////
//// return CustomAttribute.IsDefined( this, attributeRuntimeType );
//// }
#endregion
#region Remoting Cache
//// private InternalCache m_cachedData;
////
//// internal InternalCache Cache
//// {
//// get
//// {
//// // This grabs an internal copy of m_cachedData and uses
//// // that instead of looking at m_cachedData directly because
//// // the cache may get cleared asynchronously. This prevents
//// // us from having to take a lock.
//// InternalCache cache = m_cachedData;
//// if(cache == null)
//// {
//// cache = new InternalCache( "ParameterInfo" );
//// InternalCache ret = Interlocked.CompareExchange( ref m_cachedData, cache, null );
//// if(ret != null)
//// {
//// cache = ret;
//// }
////
//// GC.ClearCache += new ClearCacheHandler( OnCacheClear );
//// }
////
//// return cache;
//// }
//// }
////
//// internal void OnCacheClear( Object sender, ClearCacheEventArgs cacheEventArgs )
//// {
//// m_cachedData = null;
//// }
#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 RestaurantSystem.API.Areas.HelpPage.ModelDescriptions;
using RestaurantSystem.API.Areas.HelpPage.Models;
namespace RestaurantSystem.API.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.
/***************************************************************************\
*
* Purpose: Class for compiling Xaml.
*
\***************************************************************************/
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Globalization;
using MS.Utility;
using System.Runtime.InteropServices;
using MS.Internal;
// Disabling 1634 and 1691:
// In order to avoid generating warnings about unknown message numbers and
// unknown pragmas when compiling C# source code with the C# compiler,
// you need to disable warnings 1634 and 1691. (Presharp Documentation)
#pragma warning disable 1634, 1691
#if PBTCOMPILER
namespace MS.Internal.Markup
#else
using System.Windows;
namespace System.Windows.Markup
#endif
{
#region enums
/// <summary>
/// Parser modes. indicates if the Xaml should be parsed sync or async.
/// currently public so test can set these values.
/// </summary>
internal enum XamlParseMode
{
/// <summary>
/// Not initialized
/// </summary>
Uninitialized,
/// <summary>
/// Sync
/// </summary>
Synchronous,
/// <summary>
/// Async
/// </summary>
Asynchronous,
}
#endregion enums
/// <summary>
/// XamlParser class. This class is used internally
/// </summary>
internal class XamlParser
{
#if PBTCOMPILER
#region Constructors
/// <summary>
/// Constructor that takes a stream and creates an XmlCompatibilityReader on it.
/// </summary>
public XamlParser(
ParserContext parserContext,
BamlRecordWriter bamlWriter,
Stream xamlStream,
bool multipleRoots) : this(parserContext, bamlWriter,
new XmlTextReader(xamlStream,
multipleRoots ? XmlNodeType.Element : XmlNodeType.Document,
(XmlParserContext)parserContext) )
{
}
protected XamlParser(
ParserContext parserContext,
BamlRecordWriter bamlWriter,
XmlTextReader textReader) : this(parserContext, bamlWriter)
{
// When the XML 1.0 specification was authored, security was not a top concern, and as a result DTDs have the
// unfortunate capability of severe Denial of Service (DoS) attacks, typically through the use of an internal
// entity expansion technique. In System.Xml V2.0, in order to provide protection against DTD DoS attacks there
// is the capability of turning off DTD parsing through the use of the ProhibitDtd property.
#pragma warning disable 0618
// CS0618: A class member was marked with the Obsolete attribute, such that a warning
// will be issued when the class member is referenced.
textReader.ProhibitDtd = true;
#pragma warning enable 0618
XmlCompatibilityReader xcr = new XmlCompatibilityReader(textReader,
new IsXmlNamespaceSupportedCallback(IsXmlNamespaceSupported),
_predefinedNamespaces );
TokenReader = new XamlReaderHelper(this,parserContext,xcr);
}
protected XamlParser(
ParserContext parserContext,
BamlRecordWriter bamlWriter)
{
_parserContext = parserContext;
_bamlWriter = bamlWriter;
}
// Default constructor to aid in subclassing
protected XamlParser()
{
}
#endregion Constructors
#region PublicMethods
/// <summary>
/// Main method to Parse the XAML.
/// When in synchronous mode the entire file is parsed before
/// this method returns.
/// In asynchronous mode at least the root tag is parsed. This
/// is necessary for the way binders currently work.
/// </summary>
public void Parse()
{
// if parseMode hasn't been set then set it now to synchronous.
if (XamlParseMode == XamlParseMode.Uninitialized)
{
XamlParseMode = XamlParseMode.Synchronous;
}
_Parse();
}
/// <summary>
/// Main function called by the XamlCompiler on a Compile.
/// If singleRecordMode is true the Read returns after each item read.
/// </summary>
/// <returns>True if more nodes to read</returns>
// !! Review - now that have separate out into XamlReaderHelper
// review if still need all the virtuals or the caller of the TokenReader
// can dispatch as they feel appropriate.
public bool ReadXaml(bool singleRecordMode)
{
XamlNode xamlNode = null;
bool cleanup = !singleRecordMode;
bool done = false;
try // What do we do with Exceptions we catch on this thread?.
{
while (TokenReader.Read(ref xamlNode))
{
SetParserAction(xamlNode);
if (ParserAction == ParserAction.Normal)
{
// If processing of the xaml node determines that we are done,
// then stop now. This can happen if ProcessXamlNode is
// overridden (such as when processing styles) and the parsed
// block is finished, but the overall file is not. In that
// case exit this parser, but leave everything intact.
ProcessXamlNode(xamlNode, ref cleanup, ref done);
if (done)
{
break;
}
// return here in single record mode since we don't want
// to set the parser loop to Done.
if (singleRecordMode)
{
return true;
}
}
}
}
catch (Exception e)
{
if (CriticalExceptions.IsCriticalException(e))
{
throw;
}
else
{
if (e is XamlParseException)
{
throw;
}
// If the exception was a XamlParse exception on the other
// side of a Reflection Invoke, then just pull up the Parse exception.
if (e is TargetInvocationException && e.InnerException is XamlParseException)
{
throw e.InnerException;
}
int lineNumber = 0;
int linePosition = 0;
string newMessage = null;
if (e is XmlException)
{
XmlException xmlEx = (XmlException)e;
lineNumber = xmlEx.LineNumber;
linePosition = xmlEx.LinePosition;
newMessage = xmlEx.Message;
}
else
{
// generic exception, If have a xamlNode then use the
// nodes values for the line Numbers.
if (null != xamlNode)
{
lineNumber = xamlNode.LineNumber;
linePosition = xamlNode.LinePosition;
}
newMessage = e.Message + " " + SR.Get(SRID.ParserLineAndOffset,
lineNumber.ToString(CultureInfo.CurrentCulture),
linePosition.ToString(CultureInfo.CurrentCulture));
}
XamlParseException parseException = new XamlParseException(newMessage, lineNumber, linePosition, e);
ParseError(parseException);
// Recurse on error
cleanup = true;
throw parseException;
}
}
finally
{
// Perform cleanup only if we encountered a non-recoverable error, or
// we're finished reading the stream (EndDocument reached in single
// record mode, or end of stream reached in multi-record mode)
if (cleanup)
{
// Close the reader, which will close the underlying stream.
TokenReader.Close();
}
}
return false;
}
/// <summary>
/// Big switch to handle all the records.
/// </summary>
/// <param name="xamlNode"> Node received from TokenReader to process</param>
/// <param name="cleanup"> True if end of stream reached and document is
/// totally finished and should be closed </param>
/// <param name="done"> True if done processing and want to exit. Doesn't
/// necessarily mean document is finished (see cleanup) </param>
internal virtual void ProcessXamlNode(
XamlNode xamlNode,
ref bool cleanup,
ref bool done)
{
switch(xamlNode.TokenType)
{
case XamlNodeType.DocumentStart:
XamlDocumentStartNode xamlDocumentStartNode =
(XamlDocumentStartNode) xamlNode;
WriteDocumentStart(xamlDocumentStartNode);
break;
case XamlNodeType.DocumentEnd:
XamlDocumentEndNode xamlEndDocumentNode =
(XamlDocumentEndNode) xamlNode;
cleanup = true;
done = true;
WriteDocumentEnd(xamlEndDocumentNode);
break;
case XamlNodeType.ElementStart:
XamlElementStartNode xamlElementNode =
(XamlElementStartNode) xamlNode;
WriteElementStart(xamlElementNode);
break;
case XamlNodeType.ElementEnd:
XamlElementEndNode xamlEndElementNode =
(XamlElementEndNode) xamlNode;
WriteElementEnd(xamlEndElementNode);
break;
case XamlNodeType.UnknownTagStart:
XamlUnknownTagStartNode xamlUnknownTagStartNode =
(XamlUnknownTagStartNode) xamlNode;
WriteUnknownTagStart(xamlUnknownTagStartNode);
break;
case XamlNodeType.UnknownTagEnd:
XamlUnknownTagEndNode xamlUnknownTagEndNode =
(XamlUnknownTagEndNode) xamlNode;
WriteUnknownTagEnd(xamlUnknownTagEndNode);
break;
case XamlNodeType.XmlnsProperty:
XamlXmlnsPropertyNode xamlXmlnsPropertyNode =
(XamlXmlnsPropertyNode) xamlNode;
WriteNamespacePrefix(xamlXmlnsPropertyNode);
break;
case XamlNodeType.Property:
XamlPropertyNode xamlPropertyNode =
(XamlPropertyNode) xamlNode;
if (xamlPropertyNode.AttributeUsage == BamlAttributeUsage.RuntimeName)
{
_parserContext.XamlTypeMapper.ValidateNames(
xamlPropertyNode.Value,
xamlPropertyNode.LineNumber,
xamlPropertyNode.LinePosition);
}
WriteProperty(xamlPropertyNode);
break;
case XamlNodeType.PropertyWithExtension:
XamlPropertyWithExtensionNode xamlPropertyWithExtensionNode =
(XamlPropertyWithExtensionNode)xamlNode;
WritePropertyWithExtension(xamlPropertyWithExtensionNode);
break;
case XamlNodeType.PropertyWithType:
XamlPropertyWithTypeNode xamlPropertyWithTypeNode =
(XamlPropertyWithTypeNode) xamlNode;
WritePropertyWithType(xamlPropertyWithTypeNode);
break;
case XamlNodeType.UnknownAttribute:
XamlUnknownAttributeNode xamlUnknownAttributeNode =
(XamlUnknownAttributeNode) xamlNode;
WriteUnknownAttribute(xamlUnknownAttributeNode);
break;
case XamlNodeType.PropertyComplexStart:
XamlPropertyComplexStartNode xamlPropertyComplexStartNode =
(XamlPropertyComplexStartNode) xamlNode;
WritePropertyComplexStart(xamlPropertyComplexStartNode);
break;
case XamlNodeType.PropertyComplexEnd:
XamlPropertyComplexEndNode xamlPropertyComplexEndNode =
(XamlPropertyComplexEndNode) xamlNode;
WritePropertyComplexEnd(xamlPropertyComplexEndNode);
break;
case XamlNodeType.LiteralContent:
XamlLiteralContentNode xamlLiteralContentNode =
(XamlLiteralContentNode) xamlNode;
WriteLiteralContent(xamlLiteralContentNode);
break;
case XamlNodeType.Text:
XamlTextNode xamlTextNode =
(XamlTextNode) xamlNode;
WriteText(xamlTextNode);
break;
case XamlNodeType.ClrEvent:
XamlClrEventNode xamlClrEventNode =
(XamlClrEventNode) xamlNode;
WriteClrEvent(xamlClrEventNode);
break;
case XamlNodeType.PropertyArrayStart:
XamlPropertyArrayStartNode xamlPropertyArrayStartNode =
(XamlPropertyArrayStartNode) xamlNode;
WritePropertyArrayStart(xamlPropertyArrayStartNode);
break;
case XamlNodeType.PropertyArrayEnd:
XamlPropertyArrayEndNode xamlPropertyArrayEndNode =
(XamlPropertyArrayEndNode) xamlNode;
WritePropertyArrayEnd(xamlPropertyArrayEndNode);
break;
case XamlNodeType.PropertyIListStart:
XamlPropertyIListStartNode xamlPropertyIListStartNode =
(XamlPropertyIListStartNode) xamlNode;
WritePropertyIListStart(xamlPropertyIListStartNode);
break;
case XamlNodeType.PropertyIListEnd:
XamlPropertyIListEndNode xamlPropertyIListEndNode =
(XamlPropertyIListEndNode) xamlNode;
WritePropertyIListEnd(xamlPropertyIListEndNode);
break;
case XamlNodeType.PropertyIDictionaryStart:
XamlPropertyIDictionaryStartNode xamlPropertyIDictionaryStartNode =
(XamlPropertyIDictionaryStartNode) xamlNode;
WritePropertyIDictionaryStart(xamlPropertyIDictionaryStartNode);
break;
case XamlNodeType.PropertyIDictionaryEnd:
XamlPropertyIDictionaryEndNode xamlPropertyIDictionaryEndNode =
(XamlPropertyIDictionaryEndNode) xamlNode;
WritePropertyIDictionaryEnd(xamlPropertyIDictionaryEndNode);
break;
case XamlNodeType.DefTag:
XamlDefTagNode xamlDefTagNode =
(XamlDefTagNode) xamlNode;
WriteDefTag(xamlDefTagNode);
break;
case XamlNodeType.DefKeyTypeAttribute:
XamlDefAttributeKeyTypeNode xamlDefAttributeKeyTypeNode =
(XamlDefAttributeKeyTypeNode) xamlNode;
WriteDefAttributeKeyType(xamlDefAttributeKeyTypeNode);
break;
case XamlNodeType.DefAttribute:
XamlDefAttributeNode xamlDefAttributeNode =
(XamlDefAttributeNode) xamlNode;
if (xamlDefAttributeNode.AttributeUsage == BamlAttributeUsage.RuntimeName)
{
_parserContext.XamlTypeMapper.ValidateNames(
xamlDefAttributeNode.Value,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
}
WriteDefAttributeCore(xamlDefAttributeNode);
break;
case XamlNodeType.PresentationOptionsAttribute:
XamlPresentationOptionsAttributeNode xamlPresentationOptionsAttributeNode =
(XamlPresentationOptionsAttributeNode) xamlNode;
WritePresentationOptionsAttribute(xamlPresentationOptionsAttributeNode);
break;
case XamlNodeType.PIMapping:
XamlPIMappingNode xamlPIMappingNode =
(XamlPIMappingNode) xamlNode;
WritePIMapping(xamlPIMappingNode);
break;
// The following tokens that are used primarily by the markup compiler
case XamlNodeType.EndAttributes:
XamlEndAttributesNode xamlEndAttributesNode =
(XamlEndAttributesNode) xamlNode;
// if first tag and haven't alredy set the ParseMode
// set it to synchronous.
if (0 == xamlEndAttributesNode.Depth)
{
if (XamlParseMode == XamlParseMode.Uninitialized)
{
XamlParseMode = XamlParseMode.Synchronous;
}
}
WriteEndAttributes(xamlEndAttributesNode);
break;
case XamlNodeType.KeyElementStart:
XamlKeyElementStartNode xamlKeyElementStartNode =
(XamlKeyElementStartNode) xamlNode;
WriteKeyElementStart(xamlKeyElementStartNode);
break;
case XamlNodeType.KeyElementEnd:
XamlKeyElementEndNode xamlKeyElementEndNode =
(XamlKeyElementEndNode) xamlNode;
WriteKeyElementEnd(xamlKeyElementEndNode);
break;
case XamlNodeType.ConstructorParametersEnd:
XamlConstructorParametersEndNode xamlConstructorParametersEndNode =
(XamlConstructorParametersEndNode) xamlNode;
WriteConstructorParametersEnd(xamlConstructorParametersEndNode);
break;
case XamlNodeType.ConstructorParametersStart:
XamlConstructorParametersStartNode xamlConstructorParametersStartNode =
(XamlConstructorParametersStartNode) xamlNode;
WriteConstructorParametersStart(xamlConstructorParametersStartNode);
break;
case XamlNodeType.ContentProperty:
XamlContentPropertyNode xamlContentPropertyNode =
(XamlContentPropertyNode)xamlNode;
WriteContentProperty(xamlContentPropertyNode);
break;
case XamlNodeType.ConstructorParameterType:
XamlConstructorParameterTypeNode xamlConstructorParameterTypeNode =
(XamlConstructorParameterTypeNode)xamlNode;
WriteConstructorParameterType(xamlConstructorParameterTypeNode);
break;
default:
Debug.Assert(false,"Unknown Xaml Token.");
break;
}
}
#endregion // PublicMethods
#region Virtuals
/// <summary>
/// Called when parsing begins
/// </summary>
public virtual void WriteDocumentStart(XamlDocumentStartNode XamlDocumentStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDocumentStart(XamlDocumentStartNode);
}
}
/// <summary>
/// Called when parsing ends
/// </summary>
public virtual void WriteDocumentEnd(XamlDocumentEndNode xamlEndDocumentNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDocumentEnd(xamlEndDocumentNode);
}
}
/// <summary>
/// Write Start of an Element, which is a tag of the form /<Classname />
/// </summary>
public virtual void WriteElementStart(XamlElementStartNode xamlElementStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteElementStart(xamlElementStartNode);
}
}
/// <summary>
/// Write start of an unknown tag
/// </summary>
public virtual void WriteUnknownTagStart(XamlUnknownTagStartNode xamlUnknownTagStartNode)
{
// The default action for unknown tags is throw an exception.
ThrowException(SRID.ParserUnknownTag ,
xamlUnknownTagStartNode.Value,
xamlUnknownTagStartNode.XmlNamespace,
xamlUnknownTagStartNode.LineNumber,
xamlUnknownTagStartNode.LinePosition);
}
/// <summary>
/// Write end of an unknown tag
/// </summary>
public virtual void WriteUnknownTagEnd(XamlUnknownTagEndNode xamlUnknownTagEndNode)
{
// The default action for unknown tags is throw an exception. This should never
// get here unless there is a coding error, since it would first hit
// WriteUnknownTagStart
ThrowException(SRID.ParserUnknownTag ,
"???",
xamlUnknownTagEndNode.LineNumber,
xamlUnknownTagEndNode.LinePosition);
}
/// <summary>
/// Write End Element
/// </summary>
public virtual void WriteElementEnd(XamlElementEndNode xamlElementEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteElementEnd(xamlElementEndNode);
}
}
/// <summary>
/// Called when parsing hits literal content.
/// </summary>
public virtual void WriteLiteralContent(XamlLiteralContentNode xamlLiteralContentNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteLiteralContent(xamlLiteralContentNode);
}
}
/// <summary>
/// Write Start Complex Property, where the tag is of the
/// form /<Classname.PropertyName/>
/// </summary>
public virtual void WritePropertyComplexStart(
XamlPropertyComplexStartNode xamlPropertyComplexStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyComplexStart(xamlPropertyComplexStartNode);
}
}
/// <summary>
/// Write End Complex Property
/// </summary>
public virtual void WritePropertyComplexEnd(
XamlPropertyComplexEndNode xamlPropertyComplexEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyComplexEnd(xamlPropertyComplexEndNode);
}
}
/// <summary>
/// Write Start element for a dictionary key section.
/// </summary>
public virtual void WriteKeyElementStart(
XamlElementStartNode xamlKeyElementStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteKeyElementStart(xamlKeyElementStartNode);
}
}
/// <summary>
/// Write End element for a dictionary key section
/// </summary>
public virtual void WriteKeyElementEnd(
XamlElementEndNode xamlKeyElementEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteKeyElementEnd(xamlKeyElementEndNode);
}
}
/// <summary>
/// Write unknown attribute
/// </summary>
public virtual void WriteUnknownAttribute(XamlUnknownAttributeNode xamlUnknownAttributeNode)
{
// The default action for unknown attributes is throw an exception.
ThrowException(SRID.ParserUnknownAttribute ,
xamlUnknownAttributeNode.Name,
xamlUnknownAttributeNode.XmlNamespace,
xamlUnknownAttributeNode.LineNumber,
xamlUnknownAttributeNode.LinePosition);
}
/// <summary>
/// Write a Property, which has the form in markup of property="value".
/// </summary>
/// <remarks>
/// Note that for DependencyProperties, the assemblyName, TypeFullName, PropIdName
/// refer to DependencyProperty field
/// that the property was found on. This may be different from the ownerType
/// of the propId if the property was registered as an alias so if the
/// callback is persisting we want to persist the information that the propId
/// was found on in case the alias is a private or internal field.
/// </remarks>
public virtual void WriteProperty(XamlPropertyNode xamlPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteProperty(xamlPropertyNode);
}
}
internal void WriteBaseProperty(XamlPropertyNode xamlPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.BaseWriteProperty(xamlPropertyNode);
}
}
/// <summary>
/// Write a Property, which has the form in markup of property="value".
/// </summary>
/// <remarks>
/// Note that for DependencyProperties, the assemblyName, TypeFullName, PropIdName
/// refer to DependencyProperty field
/// that the property was found on. This may be different from the ownerType
/// of the propId if the property was registered as an alias so if the
/// callback is persisting we want to persist the information that the propId
/// was found on in case the alias is a private or internal field.
/// </remarks>
public virtual void WritePropertyWithType(XamlPropertyWithTypeNode xamlPropertyNode)
{
if (BamlRecordWriter != null)
{
if (xamlPropertyNode.ValueElementType == null)
{
ThrowException(SRID.ParserNoType,
xamlPropertyNode.ValueTypeFullName,
xamlPropertyNode.LineNumber,
xamlPropertyNode.LinePosition);
}
BamlRecordWriter.WritePropertyWithType(xamlPropertyNode);
}
}
public virtual void WritePropertyWithExtension(XamlPropertyWithExtensionNode xamlPropertyWithExtensionNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyWithExtension(xamlPropertyWithExtensionNode);
}
}
/// <summary>
/// Write out Text, currently don't keep track if originally CData or Text
/// </summary>
public virtual void WriteText(XamlTextNode xamlTextNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteText(xamlTextNode);
}
}
/// <summary>
/// Write a new namespacePrefix to NamespaceURI map
/// </summary>
public virtual void WriteNamespacePrefix(XamlXmlnsPropertyNode xamlXmlnsPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteNamespacePrefix(xamlXmlnsPropertyNode);
}
}
/// <summary>
/// Xml - Clr namespace mapping
/// </summary>
public virtual void WritePIMapping(XamlPIMappingNode xamlPIMappingNode)
{
// The only case when the assembly name can be empty is when there is a local assembly
// specified in the Mapping PI, but the compiler extension should have resolved it by
// now. So if we are still seeing an empty string here that means we in the pure xaml
// parsing scenario and should throw.
if (xamlPIMappingNode.AssemblyName.Length == 0)
{
ThrowException(SRID.ParserMapPIMissingKey, xamlPIMappingNode.LineNumber, xamlPIMappingNode.LinePosition);
}
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePIMapping(xamlPIMappingNode);
}
}
/// <summary>
/// Write out the Clr event.
/// </summary>
public virtual void WriteClrEvent(XamlClrEventNode xamlClrEventNode)
{
// Parser currently doesn't support hooking up Events directly from
// XAML so throw an exception. In the compile case this method
// is overriden.
if (null == ParserHooks)
{
ThrowException(SRID.ParserNoEvents,
xamlClrEventNode.LineNumber,
xamlClrEventNode.LinePosition);
}
else if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteClrEvent(xamlClrEventNode);
}
}
/// <summary>
/// Write Property Array Start
/// </summary>
public virtual void WritePropertyArrayStart(XamlPropertyArrayStartNode xamlPropertyArrayStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyArrayStart(xamlPropertyArrayStartNode);
}
}
/// <summary>
/// Write Property Array End
/// </summary>
public virtual void WritePropertyArrayEnd(XamlPropertyArrayEndNode xamlPropertyArrayEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyArrayEnd(xamlPropertyArrayEndNode);
}
}
/// <summary>
/// Write Property IList Start
/// </summary>
public virtual void WritePropertyIListStart(XamlPropertyIListStartNode xamlPropertyIListStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIListStart(xamlPropertyIListStartNode);
}
}
/// <summary>
/// Write Property IList End
/// </summary>
public virtual void WritePropertyIListEnd(XamlPropertyIListEndNode xamlPropertyIListEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIListEnd(xamlPropertyIListEndNode);
}
}
/// <summary>
/// Write Property IDictionary Start
/// </summary>
public virtual void WritePropertyIDictionaryStart(XamlPropertyIDictionaryStartNode xamlPropertyIDictionaryStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIDictionaryStart(xamlPropertyIDictionaryStartNode);
}
}
/// <summary>
/// Write Property IDictionary End
/// </summary>
public virtual void WritePropertyIDictionaryEnd(XamlPropertyIDictionaryEndNode xamlPropertyIDictionaryEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIDictionaryEnd(xamlPropertyIDictionaryEndNode);
}
}
/// <summary>
/// WriteEndAttributes occurs after the last attribute (property, complex property or
/// def record) is written. Note that if there are none of the above, then WriteEndAttributes
/// is not called for a normal start tag.
/// </summary>
public virtual void WriteEndAttributes(XamlEndAttributesNode xamlEndAttributesNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteEndAttributes(xamlEndAttributesNode);
}
}
/// <summary>
/// WriteDefTag occurs when a x:Whatever tag is encountered.
/// Superclasses must interprete this since the base class doesn't understand
/// any of them.
/// </summary>
public virtual void WriteDefTag(XamlDefTagNode xamlDefTagNode)
{
ThrowException(SRID.ParserDefTag,
xamlDefTagNode.Value,
xamlDefTagNode.LineNumber,
xamlDefTagNode.LinePosition);
}
/// <summary>
/// Write out a key to a dictionary that has been resolved at compile or parse
/// time to a Type object.
/// </summary>
public virtual void WriteDefAttributeKeyType(XamlDefAttributeKeyTypeNode xamlDefNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttributeKeyType(xamlDefNode);
}
}
/// <summary>
/// WriteDefAttribute when attributes of the form x:Whatever are encountered
/// </summary>
public virtual void WriteDefAttribute(XamlDefAttributeNode xamlDefAttributeNode)
{
string attributeValue = xamlDefAttributeNode.Value;
// There are several known def attributes, and these are checked for
// correctness by running the known type converters.
switch(xamlDefAttributeNode.Name)
{
case XamlReaderHelper.DefinitionSynchronousMode:
if (BamlRecordWriter != null)
{
if (xamlDefAttributeNode.Value == "Async")
{
ThrowException(SRID.ParserNoBamlAsync, "Async",
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
}
}
break;
case XamlReaderHelper.DefinitionAsyncRecords:
// Update the AsyncRecords and don't store this as a def attribute
ThrowException(SRID.ParserNoBamlAsync, xamlDefAttributeNode.Name,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
break;
case XamlReaderHelper.DefinitionShared:
Boolean.Parse(attributeValue); // For validation only.
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttribute(xamlDefAttributeNode);
}
break;
case XamlReaderHelper.DefinitionUid:
case XamlReaderHelper.DefinitionRuntimeName:
//Error if x:Uid or x:Name are markup extensions
if (MarkupExtensionParser.LooksLikeAMarkupExtension(attributeValue))
{
string message = SR.Get(SRID.ParserBadUidOrNameME, attributeValue);
message += " ";
message += SR.Get(SRID.ParserLineAndOffset,
xamlDefAttributeNode.LineNumber.ToString(CultureInfo.CurrentCulture),
xamlDefAttributeNode.LinePosition.ToString(CultureInfo.CurrentCulture));
XamlParseException parseException = new XamlParseException(message,
xamlDefAttributeNode.LineNumber, xamlDefAttributeNode.LinePosition);
throw parseException;
}
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttribute(xamlDefAttributeNode);
}
break;
case XamlReaderHelper.DefinitionName:
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttribute(xamlDefAttributeNode);
}
break;
default:
string errorID;
errorID = SRID.ParserUnknownDefAttribute;
ThrowException(errorID,
xamlDefAttributeNode.Name,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
break;
}
}
/// <summary>
/// Write attributes of the form PresentationOptions:Whatever to Baml
/// </summary>
public virtual void WritePresentationOptionsAttribute(XamlPresentationOptionsAttributeNode xamlPresentationOptionsAttributeNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePresentationOptionsAttribute(xamlPresentationOptionsAttributeNode);
}
}
/// <summary>
/// Write the start of a constructor parameter section
/// </summary>
public virtual void WriteConstructorParametersStart(XamlConstructorParametersStartNode xamlConstructorParametersStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConstructorParametersStart(xamlConstructorParametersStartNode);
}
}
public virtual void WriteContentProperty(XamlContentPropertyNode xamlContentPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteContentProperty(xamlContentPropertyNode);
}
}
/// <summary>
/// Write the constructor parameter record where the parameter is a compile time
/// resolved Type object.
/// </summary>
public virtual void WriteConstructorParameterType(
XamlConstructorParameterTypeNode xamlConstructorParameterTypeNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConstructorParameterType(xamlConstructorParameterTypeNode);
}
}
/// <summary>
/// Write the end of a constructor parameter section
/// </summary>
public virtual void WriteConstructorParametersEnd(XamlConstructorParametersEndNode xamlConstructorParametersEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConstructorParametersEnd(xamlConstructorParametersEndNode);
}
}
/// <summary>
/// Can be used by ac to return the type of the element if a class attribute is
/// present. If want to override default Type because of class= attribute can do so here.
/// Should leave the XmlReader positioned at the Element so if read attributes
/// to determine type need to call XmlReader.MoveToElement()
/// </summary>
public virtual bool GetElementType(
XmlReader reader,
string localName,
string namespaceUri,
ref string assemblyName,
ref string typeFullName,
ref Type baseType,
ref Type serializerType)
{
bool result = false;
assemblyName = string.Empty;
typeFullName = string.Empty;
serializerType = null;
baseType = null;
// if no namespaceURI or local name don't bother
if (null == namespaceUri || null == localName)
{
return false;
}
TypeAndSerializer typeAndSerializer =
XamlTypeMapper.GetTypeAndSerializer(namespaceUri, localName, null);
if (typeAndSerializer != null &&
typeAndSerializer.ObjectType != null)
{
serializerType = typeAndSerializer.SerializerType;
baseType = typeAndSerializer.ObjectType;
typeFullName = baseType.FullName;
assemblyName = baseType.Assembly.FullName;
result = true;
Debug.Assert(null != assemblyName, "assembly name returned from GetBaseElement is null");
Debug.Assert(null != typeFullName, "Type name returned from GetBaseElement is null");
}
return result;
}
#endregion Virtuals
/// <summary>
/// Write a Connector Id for compiler.
/// </summary>
protected internal void WriteConnectionId(Int32 connectionId)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConnectionId(connectionId);
}
}
/// <summary>
/// A def attribute was encountered. Perform synchonous mode checking
/// prior to calling the virtual that may be overridden.
/// </summary>
void WriteDefAttributeCore(XamlDefAttributeNode xamlDefAttributeNode)
{
string attributeValue = xamlDefAttributeNode.Value;
switch(xamlDefAttributeNode.Name)
{
case XamlReaderHelper.DefinitionSynchronousMode:
XamlParseMode documentParseMode = XamlParseMode.Synchronous;
if (attributeValue.Equals("Async"))
{
documentParseMode = XamlParseMode.Asynchronous;
}
else if (attributeValue.Equals("Sync"))
{
documentParseMode = XamlParseMode.Synchronous;
}
else
{
ThrowException(SRID.ParserBadSyncMode,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition );
}
// if we haven't initialized the the parseMode yet set it
if (XamlParseMode == XamlParseMode.Uninitialized)
{
XamlParseMode = documentParseMode;
}
break;
default:
break;
}
WriteDefAttribute(xamlDefAttributeNode);
}
#region Methods
// virtuals to override the default implementation. used by the compiler
// for internal virtuals review why not public as the others?
// Used when an exception is thrown.The default action is to shutdown the parser
// and throw the exception.
internal virtual void ParseError(XamlParseException e)
{
}
/// <summary>
/// Called when the parse was cancelled by the user.
/// </summary>
internal virtual void ParseCancelled()
{
}
/// <summary>
/// called when the parse has been completed successfully.
/// </summary>
internal virtual void ParseCompleted()
{
}
/// <summary>
/// Default parsing is to synchronously read all the xaml nodes
/// until done.
/// </summary>
internal virtual void _Parse()
{
ReadXaml(false /* want to parse the entire thing */);
}
/// <summary>
/// If there are ParserHooks, call it with the current xamlNode and perform
/// as directed by the callback.
/// </summary>
private void SetParserAction(XamlNode xamlNode)
{
// if no ParserHooks then process as normal
if (null == ParserHooks)
{
ParserAction = ParserAction.Normal;
return;
}
// if ParserHooks want to skip the current node and its children,
// check for end of scope where it asked to be skipped.
if (ParserAction == ParserAction.Skip)
{
if (xamlNode.Depth <= SkipActionDepthCount &&
xamlNode.TokenType == SkipActionToken)
{
// We found the end token at the correct depth. Reset the depth count
// so that in the next call we won't skip calling the ParserHooks. Don't
// reset the ParserAction since we want to skip this end token.
SkipActionDepthCount = -1;
SkipActionToken = XamlNodeType.Unknown;
return;
}
else if (SkipActionDepthCount >= 0)
{
return;
}
}
// If we get to here, the ParserHooks want to be called.
ParserAction = ParserHooks.LoadNode(xamlNode);
// if the ParserHooks want to skip the current node and its children then
// set the callback depth so that we'll know when to start processing again.
if (ParserAction == ParserAction.Skip)
{
// For tokens with no scope (eg = attributes), don't set the depth so
// that we will only skip once
Debug.Assert(SkipActionDepthCount == -1);
int tokenIndex = ((IList)XamlNode.ScopeStartTokens).IndexOf(xamlNode.TokenType);
if (tokenIndex != -1)
{
SkipActionDepthCount = xamlNode.Depth;
SkipActionToken = XamlNode.ScopeEndTokens[tokenIndex];
}
}
}
// Return true if the passed namespace is known, meaning that it maps
// to a set of assemblies and clr namespaces
internal bool IsXmlNamespaceSupported(string xmlNamespace, out string newXmlNamespace)
{
newXmlNamespace = null;
if (xmlNamespace.StartsWith(XamlReaderHelper.MappingProtocol, StringComparison.Ordinal))
{
return true;
}
else if (xmlNamespace == XamlReaderHelper.PresentationOptionsNamespaceURI)
{
// PresentationOptions is expected to be marked as 'ignorable' in most Xaml
// so that other Xaml parsers don't have to interpret it, but this parser
// does handle it to support it's Freeze attribute.
return true;
}
else
{
return XamlTypeMapper.IsXmlNamespaceKnown(xmlNamespace, out newXmlNamespace) ||
TokenReader.IsXmlDataIsland();
}
}
#endregion Methods
#region Properties
/// <summary>
/// TokenReader that is being used.
/// </summary>
internal XamlReaderHelper TokenReader
{
get { return _xamlTokenReader; }
set { _xamlTokenReader = value; }
}
/// <summary>
/// ParserHooks implementation that any parse time callbacks
/// should be called on.
/// </summary>
internal ParserHooks ParserHooks
{
get { return _parserHooks; }
set { _parserHooks = value; }
}
// Set the depth count for how deep we are within
// a ParserAction.Skip reference.
int SkipActionDepthCount
{
get { return _skipActionDepthCount; }
set { _skipActionDepthCount = value; }
}
// Set and get the token to watch for when skipping a
// section of a xaml file
XamlNodeType SkipActionToken
{
get { return _skipActionToken; }
set { _skipActionToken = value; }
}
// set the operation mode of the parser as determined
// by attached ParserHooks
ParserAction ParserAction
{
get { return _parserAction; }
set { _parserAction = value; }
}
/// <summary>
/// Instance of the XamlTypeMapper
/// </summary>
internal XamlTypeMapper XamlTypeMapper
{
get { return _parserContext.XamlTypeMapper; }
}
/// <summary>
/// Instance of the BamlMapTable
/// </summary>
internal BamlMapTable MapTable
{
get { return _parserContext.MapTable; }
}
/// <summary>
/// BamlRecordWriter being used by the Parser
/// </summary>
public BamlRecordWriter BamlRecordWriter
{
get { return _bamlWriter; }
set
{
Debug.Assert(null == _bamlWriter || null == value, "XamlParser already had a bamlWriter");
_bamlWriter = value;
}
}
/// <summary>
/// ParseMode the Parser is in.
/// </summary>
internal XamlParseMode XamlParseMode
{
get { return _xamlParseMode; }
set { _xamlParseMode = value; }
}
/// <summary>
/// Parser context
/// </summary>
internal ParserContext ParserContext
{
get { return _parserContext; }
set { _parserContext = value; }
}
internal virtual bool CanResolveLocalAssemblies()
{
return false;
}
// Used to determine if strict or loose parsing rules should be enforced. The TokenReader
// does some validations that are difficult for the XamlParser to do and in strict parsing
// mode the TokenReader should throw exceptions of standard Xaml rules are violated.
internal virtual bool StrictParsing
{
get { return true; }
}
#endregion Properties
#region Data
// private Data
XamlReaderHelper _xamlTokenReader;
ParserContext _parserContext;
XamlParseMode _xamlParseMode;
BamlRecordWriter _bamlWriter;
// ParserHooks related
ParserHooks _parserHooks;
ParserAction _parserAction = ParserAction.Normal;
int _skipActionDepthCount = -1; // skip mode depth count.
XamlNodeType _skipActionToken = XamlNodeType.Unknown;
static private string [] _predefinedNamespaces = new string [3] {
XamlReaderHelper.DefinitionNamespaceURI,
XamlReaderHelper.DefaultNamespaceURI,
XamlReaderHelper.DefinitionMetroNamespaceURI
};
#endregion Data
#endif
// helper method called to throw an exception.
internal static void ThrowException(string id, int lineNumber, int linePosition)
{
string message = SR.Get(id);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
// helper method called to throw an exception.
internal static void ThrowException(string id, string value, int lineNumber, int linePosition)
{
string message = SR.Get(id, value);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
// helper method called to throw an exception.
internal static void ThrowException(string id, string value1, string value2, int lineNumber, int linePosition)
{
string message = SR.Get(id, value1, value2);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
internal static void ThrowException(string id, string value1, string value2, string value3, int lineNumber, int linePosition)
{
string message = SR.Get(id, value1, value2, value3);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
internal static void ThrowException(string id, string value1, string value2, string value3, string value4, int lineNumber, int linePosition)
{
string message = SR.Get(id, value1, value2, value3, value4);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
private static void ThrowExceptionWithLine(string message, int lineNumber, int linePosition)
{
message += " ";
message += SR.Get(SRID.ParserLineAndOffset,
lineNumber.ToString(CultureInfo.CurrentCulture),
linePosition.ToString(CultureInfo.CurrentCulture));
XamlParseException parseException = new XamlParseException(message,
lineNumber, linePosition);
throw parseException;
}
}
}
| |
using System;
using System.IO;
using System.Xml;
using bv.common.Core;
using bv.common.Diagnostics;
using System.Collections.Generic;
namespace bv.common.Configuration
{
/// -----------------------------------------------------------------------------
/// <summary>
/// Reads and writes the information form the xml configuration files
/// </summary>
/// <remarks>
/// By default <i>ConfigWriter</i> reads/writes the settings of the configuration file <b>appSettings</b> section.
/// If configuration file name is not specified, it works with application config file (app.config)
/// Shared <i>Instance</i> method always works to the <i>ConfigWriter</i> instance related with application config file.
/// </remarks>
/// <history>
/// [Mike] 22.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public class ConfigWriter
{
public delegate ConfigWriter CreateConfigWriterDelegate();
protected static CreateConfigWriterDelegate Creator { get; set; }
private List<string> m_RestrictedKeys = null;
private class NodeAttribute
{
public string Name;
public string Value;
public NodeAttribute(string aName, string aValue)
{
Name = aName;
Value = aValue;
}
}
private static ConfigWriter s_Instance;
private readonly XmlDocument m_AppConfig = new XmlDocument();
private string m_FileName;
private bool m_Initialized;
private bool m_Modified;
private readonly string m_DefaultConfigFileName = Utils.GetExecutingPath() + Utils.GetConfigFileName();
private XmlNamespaceManager m_Namespaces;
private string m_Prefix;
public ConfigWriter()
{
}
public ConfigWriter(List<string> keys, string fileName)
{
Config.InitSettings();
m_RestrictedKeys = keys;
foreach (string key in Config.m_Settings.Keys)
{
SetItem(key, Config.m_Settings[key]);
}
m_Modified = false;
m_Initialized = true;
if (!string.IsNullOrEmpty(Path.GetFileName(fileName)))
m_FileName = fileName;
else
m_FileName = m_DefaultConfigFileName;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Defines whether <i>ConfigWriter</i> initialized by reading configuration file
/// </summary>
/// <returns>
/// returns <b>True</b> if <i>Read</i> method was called successfully and <b>False</b> in other case.
/// </returns>
/// <remarks>
/// Use this method to indicate was the data successfully read from configuration file or no.
/// If <i>Read</i> method was called for absent configuration file for example the property will return <b>False</b>.
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public bool IsInitialized
{
get { return m_Initialized; }
}
public string FileName
{
get { return m_FileName; }
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Returns the default instance of <i>ConfigWriter</i> related with application configuration file.
/// </summary>
/// <returns>
/// Returns the default instance of <i>ConfigWriter</i> related with application configuration file.
/// </returns>
/// <remarks>
/// When requested first time the instance of <i>ConfigWriter</i> related with application configuration file is created and read.
/// Any next call of this property returns this created instance and no additional read is performed.
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
private static object g_lock = new object();
public static ConfigWriter Instance
{
get
{
lock (g_lock)
{
if (s_Instance == null)
{
s_Instance = Creator == null ? new ConfigWriter() : Creator();
s_Instance.Read(null);
}
}
return s_Instance;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Reads the configuration file and stores xml document inside the class
/// </summary>
/// <param name="fileName">
/// Xml file name to read
/// </param>
/// <remarks>
/// If <i>fileName</i> is not passed (or set to <b>Nothing</b>) the default application config file is read.
/// If specified file doesn't exist new xml document with <i><configuration>/<appConfig></i> section is created.
/// </remarks>
/// <history>
/// [Mike] 22.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public void Read(string fileName)
{
//Save settings in app config file
if (string.IsNullOrEmpty(fileName))
{
if (string.IsNullOrEmpty(m_FileName))
{
Config.FindLocalConfigFile();
m_FileName = Config.FileName;
if (fileName == null)
m_FileName = m_DefaultConfigFileName;
}
}
else
{
m_FileName = fileName;
}
if (File.Exists(m_FileName) == false)
{
GetAppSettingsNode();
return;
}
m_Namespaces = null;
m_NamespaceInitialized = false;
m_AppConfig.Load(m_FileName);
InitNamespace();
m_Modified = false;
m_Initialized = true;
}
private bool m_NamespaceInitialized = false;
private void InitNamespace()
{
if (!m_NamespaceInitialized)
{
if (m_AppConfig != null && m_AppConfig.DocumentElement != null)
{
XmlAttribute xmlnsAttribute = m_AppConfig.DocumentElement.Attributes["xmlns"];
m_Prefix = "";
if (xmlnsAttribute != null)
{
m_Prefix = "ns";
m_Namespaces = new XmlNamespaceManager(m_AppConfig.NameTable);
m_Namespaces.AddNamespace(m_Prefix, xmlnsAttribute.Value);
//Re-configure xPath with included the prefix
m_Prefix = String.Concat(m_Prefix, ":");
}
m_NamespaceInitialized = true;
}
}
}
private XmlNode _GetAppSettingsNode()
{
if (m_AppConfig != null && m_AppConfig.DocumentElement != null)
{
var xPath = string.Format("/{0}configuration/{0}appSettings", m_Prefix);
return m_AppConfig.SelectSingleNode(xPath, m_Namespaces);
}
return null;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Sets the value for specific setting defined by parent node and setting's key.
/// </summary>
/// <param name="appSettingsNode">
/// defines the <b>XmlNode</b> that contains the setting nodes.
/// </param>
/// <param name="nodeName">
/// the value of <i>key</i> attribute of setting node
/// </param>
/// <param name="value">
/// the string that should be assigned to the <i>value</i> attribute of setting node
/// </param>
/// <returns>
/// Returns <b>True</b> if setting node was modified and <b>False</b> in other case
/// </returns>
/// <remarks>
/// This method is used to set the values of setting nodes with predefined node parameters: <br/>
/// <i>add</i> - the tag name of setting node
/// <b>key</b> - the attribute that defines the unique node identifier
/// <b>value</b> - the attribute that defines the setting value <br/>
/// If requested setting is absent the new setting node is added to the parent <b>XmlNode</b>
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
private bool SetAttributeValue(XmlNode appSettingsNode, string nodeName, string value)
{
XmlNode node = FindNodeByAttribute(appSettingsNode, "add", "key", nodeName);
if (node == null && appSettingsNode != null && appSettingsNode.OwnerDocument != null)
{
node = appSettingsNode.OwnerDocument.CreateElement("add");
node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute("key"));
node.Attributes["key"].InnerText = nodeName;
node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute("value"));
node.Attributes["value"].InnerText = value;
appSettingsNode.AppendChild(node);
Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value {0} for node {1} is added ", value,
nodeName);
return true;
}
if (node.Attributes["value"].InnerText != value)
{
Dbg.ConditionalDebug(DebugDetalizationLevel.High,
"attribute value for node {0} was changed from {1} to {2} ", nodeName,
node.Attributes["value"].InnerText, value);
node.Attributes["value"].InnerText = value;
return true;
}
Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value for node {0} was changed not changed",
nodeName);
return false;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Searches the <b>XmlNode</b> with specific name and specific attribute value in the section defined by <i>appSettingsNode</i> parameter.
/// </summary>
/// <param name="appSettingsNode">
/// parent <b>XmlNode</b> node. The result node will be searched among the children of this node.
/// </param>
/// <param name="nodeName">
/// the tag name of xml node to search
/// </param>
/// <param name="attrName">
/// the name of key attribute
/// </param>
/// <param name="attrValue">
/// the value of key attribute
/// </param>
/// <returns>
/// Returns the first <b>XmlNode</b> that match to specified conditions or <b>Nothing</b> if node is not found
/// </returns>
/// <remarks>
/// Use this method to find <b>XmlNode</b> with arbitrary tag name and key attribute
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public XmlNode FindNodeByAttribute(XmlNode appSettingsNode, string nodeName, string attrName, string attrValue)
{
if (appSettingsNode == null)
{
appSettingsNode = _GetAppSettingsNode();
}
if (appSettingsNode != null)
{
string xPath = string.Format("descendant::{0}{1}[@{2}=\'{3}\']", m_Prefix,
nodeName, attrName,
attrValue);
return
appSettingsNode.SelectSingleNode(xPath, m_Namespaces);
}
return null;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Searches the <b>XmlNode</b> with specific name and specific attribute value in descendant nodes of parent node and sets values for the set of node attributes.
/// </summary>
/// <param name="appSettingsNode">
/// parent <b>XmlNode</b> node. The node that should be modified will be searched among the children of this node.
/// </param>
/// <param name="nodeName">
/// the tag name of xml node that should be modified
/// </param>
/// <param name="attr">
/// the array of <i>NodeAttribute</i> objects that defines the name/value pairs for modified attributes
/// </param>
/// <returns>
/// Returns <b>True</b> if any of the passed attributes values was modified or new node was created and <b>False</b> in other case.
/// </returns>
/// <remarks>
/// Call this method if you need to modify several attributes of <i>XmlNode</i> with custom node name.
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
private bool SetAttributeValue(XmlNode appSettingsNode, string nodeName, NodeAttribute[] attr)
{
if (attr.Length == 0)
{
return false;
}
XmlNode node = FindNodeByAttribute(appSettingsNode, nodeName, attr[0].Name, attr[0].Value);
if (node == null && appSettingsNode != null && appSettingsNode.OwnerDocument != null)
{
node = appSettingsNode.OwnerDocument.CreateElement(nodeName);
for (int i = 0; i <= attr.Length - 1; i++)
{
node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute(attr[i].Name));
node.Attributes[attr[i].Name].InnerText = attr[i].Value;
Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value {0} for node {1} is added ",
attr[i].Value, attr[i].Name);
}
appSettingsNode.AppendChild(node);
m_Modified = true;
return true;
}
for (int i = 1; i <= attr.Length - 1; i++)
{
if (node.Attributes[attr[i].Name] == null)
{
node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute(attr[i].Name));
Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value {0} for node {1} is added ",
attr[i].Value, attr[i].Name);
m_Modified = true;
}
if (node.Attributes[attr[i].Name].InnerText != attr[i].Value)
{
Dbg.ConditionalDebug(DebugDetalizationLevel.High,
"attribute value for node {0} was changed from {1} to {2} ", attr[i].Name,
node.Attributes[attr[i].Name].InnerText, attr[i].Value);
node.Attributes[attr[i].Name].InnerText = attr[i].Value;
m_Modified = true;
}
}
return m_Modified;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Sets several attribute values for the specific <b>XmlNode</b>.
/// </summary>
/// <param name="node">
/// the <b>XmlNode</b> that should be modified
/// </param>
/// <param name="attr">
/// the array of <i>NodeAttribute</i> objects that defines the name/value pairs for modified attributes
/// </param>
/// <returns>
/// Returns <b>True</b> if any of the passed attributes values was modified or new node was created and <b>False</b> in other case.
/// </returns>
/// <remarks>
/// Call this method if you need to modify several attributes of the specific <i>XmlNode</i>.
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
private bool SetAttributeValue(XmlNode node, NodeAttribute[] attr)
{
if (attr.Length == 0)
{
return false;
}
if (node != null)
{
for (int i = 0; i <= attr.Length - 1; i++)
{
if (node.Attributes[attr[i].Name] == null)
{
node.Attributes.Append(node.OwnerDocument.CreateAttribute(attr[i].Name));
}
if (node.Attributes[attr[i].Name].InnerText != attr[i].Value)
{
node.Attributes[attr[i].Name].InnerText = attr[i].Value;
m_Modified = true;
}
}
return true;
}
return false;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets or sets the specific setting in the appSettings section of configuration file
/// </summary>
/// <param name="keyValue">
/// the value key attribute of the appSettings node
/// </param>
/// <returns>
/// the value attribute of the appSettings node
/// </returns>
/// <remarks>
/// If requested settings node doesn't exist the <b>Nothing</b> is returned. If you set value for non existing setting node, the new setting is created.
/// </remarks>
/// <history>
/// [Mike] 22.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public string GetItem(string keyValue)
{
if (m_AppConfig == null)
return "";
XmlNode root = m_AppConfig.DocumentElement;
if (root != null)
{
XmlNode appSettingsNode = _GetAppSettingsNode();
if (appSettingsNode == null || appSettingsNode.OwnerDocument == null)
{
return "";
}
XmlNode node = FindNodeByAttribute(appSettingsNode, "add", "key", keyValue);
if (node != null)
{
return node.Attributes["value"].InnerText;
}
}
return "";
}
public void SetItem(string keyValue, string value)
{
if (m_RestrictedKeys != null && !m_RestrictedKeys.Contains(keyValue))
return;
XmlNode appSettingsNode = GetAppSettingsNode();
m_Modified = m_Modified | SetAttributeValue(appSettingsNode, keyValue, value);
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Searches and returns <b>XmlNode</b> defined by node name and attribute name/value pair in the <b>appSettings</b> section of configuration file.
/// </summary>
/// <param name="nodeName">
/// xml node name to find
/// </param>
/// <param name="attrName">
/// the key attribute name
/// </param>
/// <param name="attrValue">
/// the key attribute value
/// </param>
/// <returns>
/// Returns <b>XmlNode</b> with specific node name and attribute name/value pair or <b>Nothing</b> is node is not found.
/// </returns>
/// <remarks>
/// The node is searched inside <b>appSettings</b> section of configuration file only.
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public XmlNode GetNode(string nodeName, string attrName, string attrValue)
{
return GetNode(null, nodeName, attrName, attrValue);
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Searches and returns <b>XmlNode</b> defined by node name and attribute name/value pair in the specific section of configuration file.
/// </summary>
/// <param name="parentNode">
/// <b>XmlNode</b> of section to search
/// </param>
/// <param name="nodeName">
/// xml node name to find
/// </param>
/// <param name="attrName">
/// the key attribute name
/// </param>
/// <param name="attrValue">
/// the key attribute value
/// </param>
/// <returns>
/// Returns <b>XmlNode</b> with specific node name and attribute name/value pair or <b>Nothing</b> is node is not found.
/// </returns>
/// <remarks>
/// The node is searched inside section of configuration file defined by <i>parentNode</i>.
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public XmlNode GetNode(XmlNode parentNode, string nodeName, string attrName, string attrValue)
{
if (parentNode == null)
{
parentNode = _GetAppSettingsNode();
if (parentNode == null)
return null;
}
XmlNode sectionNode = FindNodeByAttribute(parentNode, nodeName, attrName, attrValue);
if (sectionNode != null)
{
return sectionNode;
}
sectionNode = parentNode.OwnerDocument.CreateElement(nodeName);
SetAttributeValue(sectionNode, new NodeAttribute[] { new NodeAttribute(attrName, attrValue) });
parentNode.AppendChild(sectionNode);
m_Modified = true;
return sectionNode;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Returns the string value of specific attribute for passed <b>XmlNode</b>
/// </summary>
/// <param name="node">
/// <b>XmlNode</b> that contains the attribute
/// </param>
/// <param name="attrName">
/// the attribute name
/// </param>
/// <returns>
/// the string representation of the requested attribute
/// </returns>
/// <remarks>
/// No additional checks for existence of passed node or attribute is performed. If <i>node</i> is <b>Nothing</b> or contains no requested attribute the exception will be thrown
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public string GetAttributeValue(XmlNode node, string attrName)
{
return node.Attributes[attrName].InnerText;
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Saves the configuration file previously read using <i>Read</i> method.
/// </summary>
/// <returns>
/// Returns <b>False</b> if error occur during saving or <b>True</b> in other case.
/// </returns>
/// <remarks>
/// When the application is run from VS IDE the changes for default application configuration
/// file are saved not only to configuration file in the <b>bin</b> folder but to the original
/// <b>app.config</b> file too. If error occurs during saving the error is written to
/// the application log but no error reported to end user
/// </remarks>
/// <history>
/// [Mike] 23.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public bool Save(bool forceSaving = false, bool throwExeption = false)
{
if (!m_Modified && !forceSaving)
{
Dbg.ConditionalDebug(DebugDetalizationLevel.High,
"configuration file {0} is not saved, there is no changes", m_FileName);
return true;
}
//!!We should never update web.config from code. Only manual changes are allowed
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(m_FileName);
if (fileNameWithoutExtension != null && fileNameWithoutExtension.ToLowerInvariant() == "web")
return true;
bool ret = true;
try
{
if (!File.Exists(FileName))
{
Utils.ForceDirectories(Path.GetDirectoryName(FileName));
FileStream fs = File.Create(FileName);
fs.Close();
}
FileAttributes attr = File.GetAttributes(FileName);
if ((attr & FileAttributes.ReadOnly) != 0)
{
attr = attr & (~FileAttributes.ReadOnly);
File.SetAttributes(FileName, attr);
}
m_AppConfig.Save(m_FileName);
m_Modified = false;
}
catch (Exception ex)
{
ret = false;
Dbg.Debug("the changes to configuration file {0} was not written, {1}",
m_FileName, ex.Message);
if (throwExeption)
throw;
}
string appConfigFileName = "";
try
{
if (m_FileName == m_DefaultConfigFileName)
{
appConfigFileName = Utils.GetExecutingPath() + "\\..\\app.config";
if (File.Exists(appConfigFileName))
{
m_AppConfig.Save(appConfigFileName);
}
}
}
catch (Exception ex)
{
ret = false;
Dbg.Debug("the changes to configuration file {0} was not written, {1}",
appConfigFileName, ex.Message);
if (throwExeption)
throw;
}
//Config.ReloadSettings();
//Instance.Read(null);
return ret;
}
public bool SaveAs(string fileName, bool forceSaving = false, bool throwExeption = false)
{
m_FileName = fileName;
return Save(forceSaving, throwExeption);
}
private XmlNode GetAppSettingsNode()
{
XmlNode appSettingsNode = _GetAppSettingsNode();
if (appSettingsNode == null)
{
XmlNode root = m_AppConfig.DocumentElement;
if (root == null)
{
root = m_AppConfig.CreateNode(XmlNodeType.XmlDeclaration, "", "");
m_AppConfig.AppendChild(root);
}
root = m_AppConfig.SelectSingleNode("/configuration");
if (root == null)
{
root = m_AppConfig.CreateNode(XmlNodeType.Element, "configuration", "");
}
appSettingsNode = m_AppConfig.CreateNode(XmlNodeType.Element, "appSettings", "");
root.AppendChild(appSettingsNode);
m_AppConfig.AppendChild(root);
}
return appSettingsNode;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLite
{
public class SQLiteUserProfilesData: IProfilesData
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteConnection m_connection;
private string m_connectionString;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteUserProfilesData()
{
}
public SQLiteUserProfilesData(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string connectionString)
{
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
m_connectionString = connectionString;
m_log.Info("[PROFILES_DATA]: Sqlite - connecting: "+m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Migration m = new Migration(m_connection, Assembly, "UserProfiles");
m.Update();
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
#region IProfilesData implementation
public OSDArray GetClassifiedRecords(UUID creatorId)
{
OSDArray data = new OSDArray();
string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = :Id";
IDataReader reader = null;
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", creatorId);
reader = cmd.ExecuteReader();
}
while (reader.Read())
{
OSDMap n = new OSDMap();
UUID Id = UUID.Zero;
string Name = null;
try
{
UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id);
Name = Convert.ToString(reader["name"]);
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": UserAccount exception {0}", e.Message);
}
n.Add("classifieduuid", OSD.FromUUID(Id));
n.Add("name", OSD.FromString(Name));
data.Add(n);
}
reader.Close();
return data;
}
public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result)
{
string query = string.Empty;
query += "INSERT OR REPLACE INTO classifieds (";
query += "`classifieduuid`,";
query += "`creatoruuid`,";
query += "`creationdate`,";
query += "`expirationdate`,";
query += "`category`,";
query += "`name`,";
query += "`description`,";
query += "`parceluuid`,";
query += "`parentestate`,";
query += "`snapshotuuid`,";
query += "`simname`,";
query += "`posglobal`,";
query += "`parcelname`,";
query += "`classifiedflags`,";
query += "`priceforlisting`) ";
query += "VALUES (";
query += ":ClassifiedId,";
query += ":CreatorId,";
query += ":CreatedDate,";
query += ":ExpirationDate,";
query += ":Category,";
query += ":Name,";
query += ":Description,";
query += ":ParcelId,";
query += ":ParentEstate,";
query += ":SnapshotId,";
query += ":SimName,";
query += ":GlobalPos,";
query += ":ParcelName,";
query += ":Flags,";
query += ":ListingPrice ) ";
if(string.IsNullOrEmpty(ad.ParcelName))
ad.ParcelName = "Unknown";
if(ad.ParcelId == null)
ad.ParcelId = UUID.Zero;
if(string.IsNullOrEmpty(ad.Description))
ad.Description = "No Description";
DateTime epoch = new DateTime(1970, 1, 1);
DateTime now = DateTime.Now;
TimeSpan epochnow = now - epoch;
TimeSpan duration;
DateTime expiration;
TimeSpan epochexp;
if(ad.Flags == 2)
{
duration = new TimeSpan(7,0,0,0);
expiration = now.Add(duration);
epochexp = expiration - epoch;
}
else
{
duration = new TimeSpan(365,0,0,0);
expiration = now.Add(duration);
epochexp = expiration - epoch;
}
ad.CreationDate = (int)epochnow.TotalSeconds;
ad.ExpirationDate = (int)epochexp.TotalSeconds;
try {
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ClassifiedId", ad.ClassifiedId.ToString());
cmd.Parameters.AddWithValue(":CreatorId", ad.CreatorId.ToString());
cmd.Parameters.AddWithValue(":CreatedDate", ad.CreationDate.ToString());
cmd.Parameters.AddWithValue(":ExpirationDate", ad.ExpirationDate.ToString());
cmd.Parameters.AddWithValue(":Category", ad.Category.ToString());
cmd.Parameters.AddWithValue(":Name", ad.Name.ToString());
cmd.Parameters.AddWithValue(":Description", ad.Description.ToString());
cmd.Parameters.AddWithValue(":ParcelId", ad.ParcelId.ToString());
cmd.Parameters.AddWithValue(":ParentEstate", ad.ParentEstate.ToString());
cmd.Parameters.AddWithValue(":SnapshotId", ad.SnapshotId.ToString ());
cmd.Parameters.AddWithValue(":SimName", ad.SimName.ToString());
cmd.Parameters.AddWithValue(":GlobalPos", ad.GlobalPos.ToString());
cmd.Parameters.AddWithValue(":ParcelName", ad.ParcelName.ToString());
cmd.Parameters.AddWithValue(":Flags", ad.Flags.ToString());
cmd.Parameters.AddWithValue(":ListingPrice", ad.Price.ToString ());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": ClassifiedesUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool DeleteClassifiedRecord(UUID recordId)
{
string query = string.Empty;
query += "DELETE FROM classifieds WHERE ";
query += "classifieduuid = :ClasifiedId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ClassifiedId", recordId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": DeleteClassifiedRecord exception {0}", e.Message);
return false;
}
return true;
}
public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM classifieds WHERE ";
query += "classifieduuid = :AdId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":AdId", ad.ClassifiedId.ToString());
using (reader = cmd.ExecuteReader())
{
if(reader.Read ())
{
ad.CreatorId = new UUID(reader["creatoruuid"].ToString());
ad.ParcelId = new UUID(reader["parceluuid"].ToString ());
ad.SnapshotId = new UUID(reader["snapshotuuid"].ToString ());
ad.CreationDate = Convert.ToInt32(reader["creationdate"]);
ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]);
ad.ParentEstate = Convert.ToInt32(reader["parentestate"]);
ad.Flags = (byte) Convert.ToUInt32(reader["classifiedflags"]);
ad.Category = Convert.ToInt32(reader["category"]);
ad.Price = Convert.ToInt16(reader["priceforlisting"]);
ad.Name = reader["name"].ToString();
ad.Description = reader["description"].ToString();
ad.SimName = reader["simname"].ToString();
ad.GlobalPos = reader["posglobal"].ToString();
ad.ParcelName = reader["parcelname"].ToString();
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return true;
}
public OSDArray GetAvatarPicks(UUID avatarId)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT `pickuuid`,`name` FROM userpicks WHERE ";
query += "creatoruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader())
{
while (reader.Read())
{
OSDMap record = new OSDMap();
record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"]));
record.Add("name",OSD.FromString((string)reader["name"]));
data.Add(record);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarPicks exception {0}", e.Message);
}
return data;
}
public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId)
{
IDataReader reader = null;
string query = string.Empty;
UserProfilePick pick = new UserProfilePick();
query += "SELECT * FROM userpicks WHERE ";
query += "creatoruuid = :CreatorId AND ";
query += "pickuuid = :PickId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":CreatorId", avatarId.ToString());
cmd.Parameters.AddWithValue(":PickId", pickId.ToString());
using (reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string description = (string)reader["description"];
if (string.IsNullOrEmpty(description))
description = "No description given.";
UUID.TryParse((string)reader["pickuuid"], out pick.PickId);
UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId);
UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId);
UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId);
pick.GlobalPos = (string)reader["posglobal"];
bool.TryParse((string)reader["toppick"].ToString(), out pick.TopPick);
bool.TryParse((string)reader["enabled"].ToString(), out pick.Enabled);
pick.Name = (string)reader["name"];
pick.Desc = description;
pick.ParcelName = (string)reader["user"];
pick.OriginalName = (string)reader["originalname"];
pick.SimName = (string)reader["simname"];
pick.SortOrder = (int)reader["sortorder"];
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return pick;
}
public bool UpdatePicksRecord(UserProfilePick pick)
{
string query = string.Empty;
query += "INSERT OR REPLACE INTO userpicks (";
query += "pickuuid, ";
query += "creatoruuid, ";
query += "toppick, ";
query += "parceluuid, ";
query += "name, ";
query += "description, ";
query += "snapshotuuid, ";
query += "user, ";
query += "originalname, ";
query += "simname, ";
query += "posglobal, ";
query += "sortorder, ";
query += "enabled ) ";
query += "VALUES (";
query += ":PickId,";
query += ":CreatorId,";
query += ":TopPick,";
query += ":ParcelId,";
query += ":Name,";
query += ":Desc,";
query += ":SnapshotId,";
query += ":User,";
query += ":Original,";
query += ":SimName,";
query += ":GlobalPos,";
query += ":SortOrder,";
query += ":Enabled) ";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
int top_pick;
int.TryParse(pick.TopPick.ToString(), out top_pick);
int enabled;
int.TryParse(pick.Enabled.ToString(), out enabled);
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":PickId", pick.PickId.ToString());
cmd.Parameters.AddWithValue(":CreatorId", pick.CreatorId.ToString());
cmd.Parameters.AddWithValue(":TopPick", top_pick);
cmd.Parameters.AddWithValue(":ParcelId", pick.ParcelId.ToString());
cmd.Parameters.AddWithValue(":Name", pick.Name.ToString());
cmd.Parameters.AddWithValue(":Desc", pick.Desc.ToString());
cmd.Parameters.AddWithValue(":SnapshotId", pick.SnapshotId.ToString());
cmd.Parameters.AddWithValue(":User", pick.ParcelName.ToString());
cmd.Parameters.AddWithValue(":Original", pick.OriginalName.ToString());
cmd.Parameters.AddWithValue(":SimName",pick.SimName.ToString());
cmd.Parameters.AddWithValue(":GlobalPos", pick.GlobalPos);
cmd.Parameters.AddWithValue(":SortOrder", pick.SortOrder.ToString ());
cmd.Parameters.AddWithValue(":Enabled", enabled);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false;
}
return true;
}
public bool DeletePicksRecord(UUID pickId)
{
string query = string.Empty;
query += "DELETE FROM userpicks WHERE ";
query += "pickuuid = :PickId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":PickId", pickId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": DeleteUserPickRecord exception {0}", e.Message);
return false;
}
return true;
}
public bool GetAvatarNotes(ref UserProfileNotes notes)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT `notes` FROM usernotes WHERE ";
query += "useruuid = :Id AND ";
query += "targetuuid = :TargetId";
OSDArray data = new OSDArray();
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", notes.UserId.ToString());
cmd.Parameters.AddWithValue(":TargetId", notes.TargetId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
while (reader.Read())
{
notes.Notes = OSD.FromString((string)reader["notes"]);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
}
return true;
}
public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result)
{
string query = string.Empty;
bool remove;
if(string.IsNullOrEmpty(note.Notes))
{
remove = true;
query += "DELETE FROM usernotes WHERE ";
query += "useruuid=:UserId AND ";
query += "targetuuid=:TargetId";
}
else
{
remove = false;
query += "INSERT OR REPLACE INTO usernotes VALUES ( ";
query += ":UserId,";
query += ":TargetId,";
query += ":Notes )";
}
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
if(!remove)
cmd.Parameters.AddWithValue(":Notes", note.Notes);
cmd.Parameters.AddWithValue(":TargetId", note.TargetId.ToString ());
cmd.Parameters.AddWithValue(":UserId", note.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false;
}
return true;
}
public bool GetAvatarProperties(ref UserProfileProperties props, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM userprofile WHERE ";
query += "useruuid = :Id";
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
try
{
reader = cmd.ExecuteReader();
}
catch(Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarProperties exception {0}", e.Message);
result = e.Message;
return false;
}
if(reader != null && reader.Read())
{
props.WebUrl = (string)reader["profileURL"];
UUID.TryParse((string)reader["profileImage"], out props.ImageId);
props.AboutText = (string)reader["profileAboutText"];
UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId);
props.FirstLifeText = (string)reader["profileFirstText"];
UUID.TryParse((string)reader["profilePartner"], out props.PartnerId);
props.WantToMask = (int)reader["profileWantToMask"];
props.WantToText = (string)reader["profileWantToText"];
props.SkillsMask = (int)reader["profileSkillsMask"];
props.SkillsText = (string)reader["profileSkillsText"];
props.Language = (string)reader["profileLanguages"];
}
else
{
props.WebUrl = string.Empty;
props.ImageId = UUID.Zero;
props.AboutText = string.Empty;
props.FirstLifeImageId = UUID.Zero;
props.FirstLifeText = string.Empty;
props.PartnerId = UUID.Zero;
props.WantToMask = 0;
props.WantToText = string.Empty;
props.SkillsMask = 0;
props.SkillsText = string.Empty;
props.Language = string.Empty;
props.PublishProfile = false;
props.PublishMature = false;
query = "INSERT INTO userprofile (";
query += "useruuid, ";
query += "profilePartner, ";
query += "profileAllowPublish, ";
query += "profileMaturePublish, ";
query += "profileURL, ";
query += "profileWantToMask, ";
query += "profileWantToText, ";
query += "profileSkillsMask, ";
query += "profileSkillsText, ";
query += "profileLanguages, ";
query += "profileImage, ";
query += "profileAboutText, ";
query += "profileFirstImage, ";
query += "profileFirstText) VALUES (";
query += ":userId, ";
query += ":profilePartner, ";
query += ":profileAllowPublish, ";
query += ":profileMaturePublish, ";
query += ":profileURL, ";
query += ":profileWantToMask, ";
query += ":profileWantToText, ";
query += ":profileSkillsMask, ";
query += ":profileSkillsText, ";
query += ":profileLanguages, ";
query += ":profileImage, ";
query += ":profileAboutText, ";
query += ":profileFirstImage, ";
query += ":profileFirstText)";
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.CommandText = query;
put.Parameters.AddWithValue(":userId", props.UserId.ToString());
put.Parameters.AddWithValue(":profilePartner", props.PartnerId.ToString());
put.Parameters.AddWithValue(":profileAllowPublish", props.PublishProfile);
put.Parameters.AddWithValue(":profileMaturePublish", props.PublishMature);
put.Parameters.AddWithValue(":profileURL", props.WebUrl);
put.Parameters.AddWithValue(":profileWantToMask", props.WantToMask);
put.Parameters.AddWithValue(":profileWantToText", props.WantToText);
put.Parameters.AddWithValue(":profileSkillsMask", props.SkillsMask);
put.Parameters.AddWithValue(":profileSkillsText", props.SkillsText);
put.Parameters.AddWithValue(":profileLanguages", props.Language);
put.Parameters.AddWithValue(":profileImage", props.ImageId.ToString());
put.Parameters.AddWithValue(":profileAboutText", props.AboutText);
put.Parameters.AddWithValue(":profileFirstImage", props.FirstLifeImageId.ToString());
put.Parameters.AddWithValue(":profileFirstText", props.FirstLifeText);
put.ExecuteNonQuery();
}
}
}
return true;
}
public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result)
{
string query = string.Empty;
query += "UPDATE userprofile SET ";
query += "profileURL=:profileURL, ";
query += "profileImage=:image, ";
query += "profileAboutText=:abouttext,";
query += "profileFirstImage=:firstlifeimage,";
query += "profileFirstText=:firstlifetext ";
query += "WHERE useruuid=:uuid";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":profileURL", props.WebUrl);
cmd.Parameters.AddWithValue(":image", props.ImageId.ToString());
cmd.Parameters.AddWithValue(":abouttext", props.AboutText);
cmd.Parameters.AddWithValue(":firstlifeimage", props.FirstLifeImageId.ToString());
cmd.Parameters.AddWithValue(":firstlifetext", props.FirstLifeText);
cmd.Parameters.AddWithValue(":uuid", props.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentPropertiesUpdate exception {0}", e.Message);
return false;
}
return true;
}
public bool UpdateAvatarInterests(UserProfileProperties up, ref string result)
{
string query = string.Empty;
query += "UPDATE userprofile SET ";
query += "profileWantToMask=:WantMask, ";
query += "profileWantToText=:WantText,";
query += "profileSkillsMask=:SkillsMask,";
query += "profileSkillsText=:SkillsText, ";
query += "profileLanguages=:Languages ";
query += "WHERE useruuid=:uuid";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":WantMask", up.WantToMask);
cmd.Parameters.AddWithValue(":WantText", up.WantToText);
cmd.Parameters.AddWithValue(":SkillsMask", up.SkillsMask);
cmd.Parameters.AddWithValue(":SkillsText", up.SkillsText);
cmd.Parameters.AddWithValue(":Languages", up.Language);
cmd.Parameters.AddWithValue(":uuid", up.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool UpdateUserPreferences(ref UserPreferences pref, ref string result)
{
string query = string.Empty;
query += "UPDATE usersettings SET ";
query += "imviaemail=:ImViaEmail, ";
query += "visible=:Visible, ";
query += "email=:EMail ";
query += "WHERE useruuid=:uuid";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ImViaEmail", pref.IMViaEmail);
cmd.Parameters.AddWithValue(":Visible", pref.Visible);
cmd.Parameters.AddWithValue(":EMail", pref.EMail);
cmd.Parameters.AddWithValue(":uuid", pref.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool GetUserPreferences(ref UserPreferences pref, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT imviaemail,visible,email FROM ";
query += "usersettings WHERE ";
query += "useruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail);
bool.TryParse((string)reader["visible"], out pref.Visible);
pref.EMail = (string)reader["email"];
}
else
{
query = "INSERT INTO usersettings VALUES ";
query += "(:Id,'false','false', :Email)";
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.Parameters.AddWithValue(":Id", pref.UserId.ToString());
put.Parameters.AddWithValue(":Email", pref.EMail);
put.ExecuteNonQuery();
}
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": Get preferences exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool GetUserAppData(ref UserAppData props, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM `userdata` WHERE ";
query += "UserId = :Id AND ";
query += "TagId = :TagId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
cmd.Parameters.AddWithValue (":TagId", props.TagId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
props.DataKey = (string)reader["DataKey"];
props.DataVal = (string)reader["DataVal"];
}
else
{
query += "INSERT INTO userdata VALUES ( ";
query += ":UserId,";
query += ":TagId,";
query += ":DataKey,";
query += ":DataVal) ";
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.Parameters.AddWithValue(":Id", props.UserId.ToString());
put.Parameters.AddWithValue(":TagId", props.TagId.ToString());
put.Parameters.AddWithValue(":DataKey", props.DataKey.ToString());
put.Parameters.AddWithValue(":DataVal", props.DataVal.ToString());
put.ExecuteNonQuery();
}
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": Requst application data exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool SetUserAppData(UserAppData props, ref string result)
{
string query = string.Empty;
query += "UPDATE userdata SET ";
query += "TagId = :TagId, ";
query += "DataKey = :DataKey, ";
query += "DataVal = :DataVal WHERE ";
query += "UserId = :UserId AND ";
query += "TagId = :TagId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":UserId", props.UserId.ToString());
cmd.Parameters.AddWithValue(":TagId", props.TagId.ToString ());
cmd.Parameters.AddWithValue(":DataKey", props.DataKey.ToString ());
cmd.Parameters.AddWithValue(":DataVal", props.DataKey.ToString ());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": SetUserData exception {0}", e.Message);
return false;
}
return true;
}
public OSDArray GetUserImageAssets(UUID avatarId)
{
IDataReader reader = null;
OSDArray data = new OSDArray();
string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = :Id";
// Get classified image assets
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
while(reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString()));
}
}
}
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString ()));
}
}
}
query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = :Id";
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
data.Add(new OSDString((string)reader["profileImage"].ToString ()));
data.Add(new OSDString((string)reader["profileFirstImage"].ToString ()));
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
}
return data;
}
#endregion
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace BerkeleyDB {
/// <summary>
/// A class representing configuration parameters for <see cref="Database"/>
/// </summary>
public class DatabaseConfig {
/// <summary>
/// The Berkeley DB environment within which to create a database. If
/// null, the database will be created stand-alone; that is, it is not
/// part of any Berkeley DB environment.
/// </summary>
/// <remarks>
/// The database access methods automatically make calls to the other
/// subsystems in Berkeley DB, based on the enclosing environment. For
/// example, if the environment has been configured to use locking, the
/// access methods will automatically acquire the correct locks when
/// reading and writing pages of the database.
/// </remarks>
public DatabaseEnvironment Env;
/// <summary>
/// The cache priority for pages referenced by the database.
/// </summary>
/// <remarks>
/// The priority of a page biases the replacement algorithm to be more
/// or less likely to discard a page when space is needed in the buffer
/// pool. The bias is temporary, and pages will eventually be discarded
/// if they are not referenced again. This priority is only advisory,
/// and does not guarantee pages will be treated in a specific way.
/// </remarks>
public CachePriority Priority;
/// <summary>
/// The size of the shared memory buffer pool -- that is, the cache.
/// </summary>
/// <remarks>
/// <para>
/// The cache should be the size of the normal working data set of the
/// application, with some small amount of additional memory for unusual
/// situations. (Note: the working set is not the same as the number of
/// pages accessed simultaneously, and is usually much larger.)
/// </para>
/// <para>
/// The default cache size is 256KB, and may not be specified as less
/// than 20KB. Any cache size less than 500MB is automatically increased
/// by 25% to account for buffer pool overhead; cache sizes larger than
/// 500MB are used as specified. The maximum size of a single cache is
/// 4GB on 32-bit systems and 10TB on 64-bit systems. (All sizes are in
/// powers-of-two, that is, 256KB is 2^18 not 256,000.) For information
/// on tuning the Berkeley DB cache size, see Selecting a cache size in
/// the Programmer's Reference Guide.
/// </para>
/// </remarks>
public CacheInfo CacheSize;
/// <summary>
/// The byte order for integers in the stored database metadata. The
/// host byte order of the machine where the Berkeley DB library was
/// compiled is the default value.
/// </summary>
/// <remarks>
/// <para>
/// The access methods provide no guarantees about the byte ordering of
/// the application data stored in the database, and applications are
/// responsible for maintaining any necessary ordering.
/// </para>
/// <para>
/// If creating additional databases in a single physical file, this
/// parameter will be ignored and the byte order of the existing
/// databases will be used.
/// </para>
/// </remarks>
public ByteOrder ByteOrder = ByteOrder.MACHINE;
internal bool pagesizeIsSet;
private uint pgsz;
/// <summary>
/// The size of the pages used to hold items in the database, in bytes.
/// </summary>
/// <remarks>
/// <para>
/// The minimum page size is 512 bytes, the maximum page size is 64K
/// bytes, and the page size must be a power-of-two. If the page size is
/// not explicitly set, one is selected based on the underlying
/// filesystem I/O block size. The automatically selected size has a
/// lower limit of 512 bytes and an upper limit of 16K bytes.
/// </para>
/// <para>
/// For information on tuning the Berkeley DB page size, see Selecting a
/// page size in the Programmer's Reference Guide.
/// </para>
/// <para>
/// If creating additional databases in a single physical file, this
/// parameter will be ignored and the page size of the existing
/// databases will be used.
/// </para>
/// </remarks>
public uint PageSize {
get { return pgsz; }
set {
pagesizeIsSet = true;
pgsz = value;
}
}
internal bool encryptionIsSet;
private String encryptPwd;
private EncryptionAlgorithm encryptAlg;
/// <summary>
/// Set the password and algorithm used by the Berkeley DB library to
/// perform encryption and decryption.
/// </summary>
/// <param name="password">
/// The password used to perform encryption and decryption.
/// </param>
/// <param name="alg">
/// The algorithm used to perform encryption and decryption.
/// </param>
public void SetEncryption(String password, EncryptionAlgorithm alg) {
encryptionIsSet = true;
encryptPwd = password;
encryptAlg = alg;
}
/// <summary>
/// The password used to perform encryption and decryption.
/// </summary>
public string EncryptionPassword { get { return encryptPwd; } }
/// <summary>
/// The algorithm used to perform encryption and decryption.
/// </summary>
public EncryptionAlgorithm EncryptAlgorithm {
get { return encryptAlg; }
}
/// <summary>
/// The prefix string that appears before error messages issued by
/// Berkeley DB.
/// </summary>
public String ErrorPrefix;
/// <summary>
/// The mechanism for reporting error messages to the application.
/// </summary>
/// <remarks>
/// <para>
/// In some cases, when an error occurs, Berkeley DB will call
/// ErrorFeedback with additional error information. It is up to the
/// delegate function to display the error message in an appropriate
/// manner.
/// </para>
/// <para>
/// This error-logging enhancement does not slow performance or
/// significantly increase application size, and may be run during
/// normal operation as well as during application debugging.
/// </para>
/// <para>
/// For databases opened inside of Berkeley DB environments, setting
/// ErrorFeedback affects the entire environment and is equivalent to
/// setting <see cref="DatabaseEnvironment.ErrorFeedback"/>.
/// </para>
/// </remarks>
public ErrorFeedbackDelegate ErrorFeedback;
/// <summary>
///
/// </summary>
public DatabaseFeedbackDelegate Feedback;
/// <summary>
/// If true, do checksum verification of pages read into the cache from
/// the backing filestore.
/// </summary>
/// <remarks>
/// <para>
/// Berkeley DB uses the SHA1 Secure Hash Algorithm if encryption is
/// configured and a general hash algorithm if it is not.
/// </para>
/// <para>
/// If the database already exists, this setting will be ignored.
/// </para>
/// </remarks>
public bool DoChecksum;
/// <summary>
/// If true, Berkeley DB will not write log records for this database.
/// </summary>
/// <remarks>
/// If Berkeley DB does not write log records, updates of this database
/// will exhibit the ACI (atomicity, consistency, and isolation)
/// properties, but not D (durability); that is, database integrity will
/// be maintained, but if the application or system fails, integrity
/// will not persist. The database file must be verified and/or restored
/// from backup after a failure. In order to ensure integrity after
/// application shut down, the database must be synced when closed, or
/// all database changes must be flushed from the database environment
/// cache using either
/// <see cref="DatabaseEnvironment.Checkpoint"/> or
/// <see cref="DatabaseEnvironment.SyncMemPool"/>. All database objects
/// for a single physical file must set NonDurableTxns, including
/// database objects for different databases in a physical file.
/// </remarks>
public bool NonDurableTxns;
internal uint flags {
get {
uint ret = 0;
ret |= DoChecksum ? Internal.DbConstants.DB_CHKSUM : 0;
ret |= encryptionIsSet ? Internal.DbConstants.DB_ENCRYPT : 0;
ret |= NonDurableTxns ? Internal.DbConstants.DB_TXN_NOT_DURABLE : 0;
return ret;
}
}
/// <summary>
/// Enclose the open call within a transaction. If the call succeeds,
/// the open operation will be recoverable and all subsequent database
/// modification operations based on this handle will be transactionally
/// protected. If the call fails, no database will have been created.
/// </summary>
public bool AutoCommit;
/// <summary>
/// Cause the database object to be free-threaded; that is, concurrently
/// usable by multiple threads in the address space.
/// </summary>
public bool FreeThreaded;
/// <summary>
/// Do not map this database into process memory.
/// </summary>
public bool NoMMap;
/// <summary>
/// Open the database for reading only. Any attempt to modify items in
/// the database will fail, regardless of the actual permissions of any
/// underlying files.
/// </summary>
public bool ReadOnly;
/// <summary>
/// Support transactional read operations with degree 1 isolation.
/// </summary>
/// <remarks>
/// Read operations on the database may request the return of modified
/// but not yet committed data. This flag must be specified on all
/// database objects used to perform dirty reads or database updates,
/// otherwise requests for dirty reads may not be honored and the read
/// may block.
/// </remarks>
public bool ReadUncommitted;
/// <summary>
/// Physically truncate the underlying file, discarding all previous databases it might have held.
/// </summary>
/// <remarks>
/// <para>
/// Underlying filesystem primitives are used to implement this flag.
/// For this reason, it is applicable only to the file and cannot be
/// used to discard databases within a file.
/// </para>
/// <para>
/// This setting cannot be lock or transaction-protected, and it is an
/// error to specify it in a locking or transaction-protected
/// environment.
/// </para>
/// </remarks>
public bool Truncate;
/// <summary>
/// Open the database with support for multiversion concurrency control.
/// </summary>
/// <remarks>
/// This will cause updates to the database to follow a copy-on-write
/// protocol, which is required to support snapshot isolation. This
/// settting requires that the database be transactionally protected
/// during its open and is not supported by the queue format.
/// </remarks>
public bool UseMVCC;
internal uint openFlags {
get {
uint ret = 0;
ret |= AutoCommit ? Internal.DbConstants.DB_AUTO_COMMIT : 0;
ret |= FreeThreaded ? Internal.DbConstants.DB_THREAD : 0;
ret |= NoMMap ? Internal.DbConstants.DB_NOMMAP : 0;
ret |= ReadOnly ? Internal.DbConstants.DB_RDONLY : 0;
ret |= ReadUncommitted ? Internal.DbConstants.DB_READ_UNCOMMITTED : 0;
ret |= Truncate ? Internal.DbConstants.DB_TRUNCATE : 0;
ret |= UseMVCC ? Internal.DbConstants.DB_MULTIVERSION : 0;
return ret;
}
}
/// <summary>
/// Instantiate a new DatabaseConfig object
/// </summary>
public DatabaseConfig() {
Env = null;
Priority = CachePriority.DEFAULT;
pagesizeIsSet = false;
encryptionIsSet = false;
ErrorPrefix = null;
Feedback = null;
DoChecksum = false;
NonDurableTxns = false;
AutoCommit = false;
FreeThreaded = false;
NoMMap = false;
ReadOnly = false;
ReadUncommitted = false;
Truncate = false;
UseMVCC = false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Xml.Xsl.Qil;
namespace System.Xml.Xsl.Xslt
{
using ContextInfo = XsltInput.ContextInfo;
using XPathQilFactory = System.Xml.Xsl.XPath.XPathQilFactory;
// Set of classes that represent XSLT AST
// XSLT AST is a tree of nodes that represent content of xsl template.
// All nodes are subclasses of QilNode. This was done to keep NodeCtor and Text ctors
// the sames nodes thay will be in resulting QilExpression tree.
// So we have: ElementCtor, AttributeCtor, QilTextCtor, CommentCtor, PICtor, NamespaceDecl, List.
// Plus couple subclasses of XslNode that represent different xslt instructions
// including artifitial: Sort, ExNamespaceDecl, UseAttributeSets
internal enum XslNodeType
{
Unknown = 0,
ApplyImports,
ApplyTemplates,
Attribute,
AttributeSet,
CallTemplate,
Choose,
Comment,
Copy,
CopyOf,
Element,
Error,
ForEach,
If,
Key,
List,
LiteralAttribute,
LiteralElement,
Message,
Nop,
Number,
Otherwise,
Param,
PI,
Sort,
Template,
Text,
UseAttributeSet,
ValueOf,
ValueOfDoe,
Variable,
WithParam,
}
internal class NsDecl
{
public readonly NsDecl Prev;
public readonly string Prefix; // Empty string denotes the default namespace, null - extension or excluded namespace
public readonly string NsUri; // null means "#all" -- all namespace defined above this one are excluded.
public NsDecl(NsDecl prev, string prefix, string nsUri)
{
Debug.Assert(nsUri != null || Prefix == null);
this.Prev = prev;
this.Prefix = prefix;
this.NsUri = nsUri;
}
}
internal class XslNode
{
public readonly XslNodeType NodeType;
public ISourceLineInfo SourceLine;
public NsDecl Namespaces;
public readonly QilName Name; // name or mode
public readonly object Arg; // select or test or terminate or stylesheet;-)
public readonly XslVersion XslVersion;
public XslFlags Flags;
private List<XslNode> _content;
public XslNode(XslNodeType nodeType, QilName name, object arg, XslVersion xslVer)
{
this.NodeType = nodeType;
this.Name = name;
this.Arg = arg;
this.XslVersion = xslVer;
}
public XslNode(XslNodeType nodeType)
{
this.NodeType = nodeType;
this.XslVersion = XslVersion.Current;
}
public string Select { get { return (string)Arg; } }
public bool ForwardsCompatible { get { return XslVersion == XslVersion.ForwardsCompatible; } }
// -------------------------------- Content Management --------------------------------
private static readonly IList<XslNode> s_emptyList = new List<XslNode>().AsReadOnly();
public IList<XslNode> Content
{
get { return _content ?? s_emptyList; }
}
public void SetContent(List<XslNode> content)
{
_content = content;
}
public void AddContent(XslNode node)
{
Debug.Assert(node != null);
if (_content == null)
{
_content = new List<XslNode>();
}
_content.Add(node);
}
public void InsertContent(IEnumerable<XslNode> collection)
{
if (_content == null)
{
_content = new List<XslNode>(collection);
}
else
{
_content.InsertRange(0, collection);
}
}
internal string TraceName
{
get
{
#if DEBUG
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string nodeTypeName;
switch (NodeType)
{
case XslNodeType.AttributeSet: nodeTypeName = "attribute-set"; break;
case XslNodeType.Template: nodeTypeName = "template"; break;
case XslNodeType.Param: nodeTypeName = "param"; break;
case XslNodeType.Variable: nodeTypeName = "variable"; break;
case XslNodeType.WithParam: nodeTypeName = "with-param"; break;
default: nodeTypeName = NodeType.ToString(); break;
}
sb.Append(nodeTypeName);
if (Name != null)
{
sb.Append(' ');
sb.Append(Name.QualifiedName);
}
ISourceLineInfo lineInfo = SourceLine;
if (lineInfo == null && NodeType == XslNodeType.AttributeSet)
{
lineInfo = Content[0].SourceLine;
Debug.Assert(lineInfo != null);
}
if (lineInfo != null)
{
string fileName = SourceLineInfo.GetFileName(lineInfo.Uri);
int idx = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1;
sb.Append(" (");
sb.Append(fileName, idx, fileName.Length - idx);
sb.Append(':');
sb.Append(lineInfo.Start.Line);
sb.Append(')');
}
return sb.ToString();
#else
return null;
#endif
}
}
}
internal abstract class ProtoTemplate : XslNode
{
public QilFunction Function; // Compiled body
public ProtoTemplate(XslNodeType nt, QilName name, XslVersion xslVer) : base(nt, name, null, xslVer) { }
public abstract string GetDebugName();
}
internal enum CycleCheck
{
NotStarted = 0,
Processing = 1,
Completed = 2,
}
internal class AttributeSet : ProtoTemplate
{
public CycleCheck CycleCheck; // Used to detect circular references
public AttributeSet(QilName name, XslVersion xslVer) : base(XslNodeType.AttributeSet, name, xslVer) { }
public override string GetDebugName()
{
StringBuilder dbgName = new StringBuilder();
dbgName.Append("<xsl:attribute-set name=\"");
dbgName.Append(Name.QualifiedName);
dbgName.Append("\">");
return dbgName.ToString();
}
public new void AddContent(XslNode node)
{
Debug.Assert(node != null && node.NodeType == XslNodeType.List);
base.AddContent(node);
}
public void MergeContent(AttributeSet other)
{
InsertContent(other.Content);
}
}
internal class Template : ProtoTemplate
{
public readonly string Match;
public readonly QilName Mode;
public readonly double Priority;
public int ImportPrecedence;
public int OrderNumber;
public Template(QilName name, string match, QilName mode, double priority, XslVersion xslVer)
: base(XslNodeType.Template, name, xslVer)
{
this.Match = match;
this.Mode = mode;
this.Priority = priority;
}
public override string GetDebugName()
{
StringBuilder dbgName = new StringBuilder();
dbgName.Append("<xsl:template");
if (Match != null)
{
dbgName.Append(" match=\"");
dbgName.Append(Match);
dbgName.Append('"');
}
if (Name != null)
{
dbgName.Append(" name=\"");
dbgName.Append(Name.QualifiedName);
dbgName.Append('"');
}
if (!double.IsNaN(Priority))
{
dbgName.Append(" priority=\"");
dbgName.Append(Priority.ToString(CultureInfo.InvariantCulture));
dbgName.Append('"');
}
if (Mode.LocalName.Length != 0)
{
dbgName.Append(" mode=\"");
dbgName.Append(Mode.QualifiedName);
dbgName.Append('"');
}
dbgName.Append('>');
return dbgName.ToString();
}
}
internal class VarPar : XslNode
{
public XslFlags DefValueFlags;
public QilNode Value; // Contains value for WithParams and global VarPars
public VarPar(XslNodeType nt, QilName name, string select, XslVersion xslVer) : base(nt, name, select, xslVer) { }
}
internal class Sort : XslNode
{
public readonly string Lang;
public readonly string DataType;
public readonly string Order;
public readonly string CaseOrder;
public Sort(string select, string lang, string dataType, string order, string caseOrder, XslVersion xslVer)
: base(XslNodeType.Sort, null, select, xslVer)
{
this.Lang = lang;
this.DataType = dataType;
this.Order = order;
this.CaseOrder = caseOrder;
}
}
internal class Keys : KeyedCollection<QilName, List<Key>>
{
protected override QilName GetKeyForItem(List<Key> list)
{
Debug.Assert(list != null && list.Count > 0);
return list[0].Name;
}
}
internal class Key : XslNode
{
public readonly string Match;
public readonly string Use;
public QilFunction Function;
public Key(QilName name, string match, string use, XslVersion xslVer)
: base(XslNodeType.Key, name, null, xslVer)
{
// match and use can be null in case of incorrect stylesheet
Debug.Assert(name != null);
this.Match = match;
this.Use = use;
}
public string GetDebugName()
{
StringBuilder dbgName = new StringBuilder();
dbgName.Append("<xsl:key name=\"");
dbgName.Append(Name.QualifiedName);
dbgName.Append('"');
if (Match != null)
{
dbgName.Append(" match=\"");
dbgName.Append(Match);
dbgName.Append('"');
}
if (Use != null)
{
dbgName.Append(" use=\"");
dbgName.Append(Use);
dbgName.Append('"');
}
dbgName.Append('>');
return dbgName.ToString();
}
}
internal enum NumberLevel
{
Single,
Multiple,
Any,
}
internal class Number : XslNode
{
public readonly NumberLevel Level;
public readonly string Count;
public readonly string From;
public readonly string Value;
public readonly string Format;
public readonly string Lang;
public readonly string LetterValue;
public readonly string GroupingSeparator;
public readonly string GroupingSize;
public Number(NumberLevel level, string count, string from, string value,
string format, string lang, string letterValue, string groupingSeparator, string groupingSize,
XslVersion xslVer) : base(XslNodeType.Number, null, null, xslVer)
{
this.Level = level;
this.Count = count;
this.From = from;
this.Value = value;
this.Format = format;
this.Lang = lang;
this.LetterValue = letterValue;
this.GroupingSeparator = groupingSeparator;
this.GroupingSize = groupingSize;
}
}
internal class NodeCtor : XslNode
{
public readonly string NameAvt;
public readonly string NsAvt;
public NodeCtor(XslNodeType nt, string nameAvt, string nsAvt, XslVersion xslVer)
: base(nt, null, null, xslVer)
{
this.NameAvt = nameAvt;
this.NsAvt = nsAvt;
}
}
internal class Text : XslNode
{
public readonly SerializationHints Hints;
public Text(string data, SerializationHints hints, XslVersion xslVer)
: base(XslNodeType.Text, null, data, xslVer)
{
this.Hints = hints;
}
}
internal class XslNodeEx : XslNode
{
public readonly ISourceLineInfo ElemNameLi;
public readonly ISourceLineInfo EndTagLi;
public XslNodeEx(XslNodeType t, QilName name, object arg, ContextInfo ctxInfo, XslVersion xslVer)
: base(t, name, arg, xslVer)
{
ElemNameLi = ctxInfo.elemNameLi;
EndTagLi = ctxInfo.endTagLi;
}
public XslNodeEx(XslNodeType t, QilName name, object arg, XslVersion xslVer) : base(t, name, arg, xslVer)
{
}
}
internal static class AstFactory
{
public static XslNode XslNode(XslNodeType nodeType, QilName name, string arg, XslVersion xslVer)
{
return new XslNode(nodeType, name, arg, xslVer);
}
public static XslNode ApplyImports(QilName mode, Stylesheet sheet, XslVersion xslVer)
{
return new XslNode(XslNodeType.ApplyImports, mode, sheet, xslVer);
}
public static XslNodeEx ApplyTemplates(QilName mode, string select, ContextInfo ctxInfo, XslVersion xslVer)
{
return new XslNodeEx(XslNodeType.ApplyTemplates, mode, select, ctxInfo, xslVer);
}
// Special node for start apply-templates
public static XslNodeEx ApplyTemplates(QilName mode)
{
return new XslNodeEx(XslNodeType.ApplyTemplates, mode, /*select:*/null, XslVersion.Current);
}
public static NodeCtor Attribute(string nameAvt, string nsAvt, XslVersion xslVer)
{
return new NodeCtor(XslNodeType.Attribute, nameAvt, nsAvt, xslVer);
}
public static AttributeSet AttributeSet(QilName name)
{
return new AttributeSet(name, XslVersion.Current);
}
public static XslNodeEx CallTemplate(QilName name, ContextInfo ctxInfo)
{
return new XslNodeEx(XslNodeType.CallTemplate, name, null, ctxInfo, XslVersion.Current);
}
public static XslNode Choose()
{
return new XslNode(XslNodeType.Choose);
}
public static XslNode Comment()
{
return new XslNode(XslNodeType.Comment);
}
public static XslNode Copy()
{
return new XslNode(XslNodeType.Copy);
}
public static XslNode CopyOf(string select, XslVersion xslVer)
{
return new XslNode(XslNodeType.CopyOf, null, select, xslVer);
}
public static NodeCtor Element(string nameAvt, string nsAvt, XslVersion xslVer)
{
return new NodeCtor(XslNodeType.Element, nameAvt, nsAvt, xslVer);
}
public static XslNode Error(string message)
{
return new XslNode(XslNodeType.Error, null, message, XslVersion.Current);
}
public static XslNodeEx ForEach(string select, ContextInfo ctxInfo, XslVersion xslVer)
{
return new XslNodeEx(XslNodeType.ForEach, null, select, ctxInfo, xslVer);
}
public static XslNode If(string test, XslVersion xslVer)
{
return new XslNode(XslNodeType.If, null, test, xslVer);
}
public static Key Key(QilName name, string match, string use, XslVersion xslVer)
{
return new Key(name, match, use, xslVer);
}
public static XslNode List()
{
return new XslNode(XslNodeType.List);
}
public static XslNode LiteralAttribute(QilName name, string value, XslVersion xslVer)
{
return new XslNode(XslNodeType.LiteralAttribute, name, value, xslVer);
}
public static XslNode LiteralElement(QilName name)
{
return new XslNode(XslNodeType.LiteralElement, name, null, XslVersion.Current);
}
public static XslNode Message(bool term)
{
return new XslNode(XslNodeType.Message, null, term, XslVersion.Current);
}
public static XslNode Nop()
{
return new XslNode(XslNodeType.Nop);
}
public static Number Number(NumberLevel level, string count, string from, string value,
string format, string lang, string letterValue, string groupingSeparator, string groupingSize,
XslVersion xslVer)
{
return new Number(level, count, from, value, format, lang, letterValue, groupingSeparator, groupingSize, xslVer);
}
public static XslNode Otherwise()
{
return new XslNode(XslNodeType.Otherwise);
}
public static XslNode PI(string name, XslVersion xslVer)
{
return new XslNode(XslNodeType.PI, null, name, xslVer);
}
public static Sort Sort(string select, string lang, string dataType, string order, string caseOrder, XslVersion xslVer)
{
return new Sort(select, lang, dataType, order, caseOrder, xslVer);
}
public static Template Template(QilName name, string match, QilName mode, double priority, XslVersion xslVer)
{
return new Template(name, match, mode, priority, xslVer);
}
public static XslNode Text(string data)
{
return new Text(data, SerializationHints.None, XslVersion.Current);
}
public static XslNode Text(string data, SerializationHints hints)
{
return new Text(data, hints, XslVersion.Current);
}
public static XslNode UseAttributeSet(QilName name)
{
return new XslNode(XslNodeType.UseAttributeSet, name, null, XslVersion.Current);
}
public static VarPar VarPar(XslNodeType nt, QilName name, string select, XslVersion xslVer)
{
return new VarPar(nt, name, select, xslVer);
}
public static VarPar WithParam(QilName name)
{
return VarPar(XslNodeType.WithParam, name, /*select*/null, XslVersion.Current);
}
private static QilFactory s_f = new QilFactory();
public static QilName QName(string local, string uri, string prefix)
{
return s_f.LiteralQName(local, uri, prefix);
}
public static QilName QName(string local)
{
return s_f.LiteralQName(local);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class PathUtilsTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
[TestMethod, Priority(0)]
public void TestMakeUri() {
Assert.AreEqual(@"C:\a\b\c\", PathUtils.MakeUri(@"C:\a\b\c", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a\b\c", PathUtils.MakeUri(@"C:\a\b\c", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c\", PathUtils.MakeUri(@"\\a\b\c", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c", PathUtils.MakeUri(@"\\a\b\c", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"ftp://me@a.net:123/b/c/", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", true, UriKind.Absolute).AbsoluteUri);
Assert.AreEqual(@"ftp://me@a.net:123/b/c", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.Absolute).AbsoluteUri);
Assert.AreEqual(@"C:\a b c\d e f\g\", PathUtils.MakeUri(@"C:\a b c\d e f\g", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a b c\d e f\g", PathUtils.MakeUri(@"C:\a b c\d e f\g", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a\b\c\", PathUtils.MakeUri(@"C:\a\b\c\d\..", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"C:\a\b\c\e", PathUtils.MakeUri(@"C:\a\b\c\d\..\e", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c\", PathUtils.MakeUri(@"\\a\b\c\d\..", true, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"\\a\b\c\e", PathUtils.MakeUri(@"\\a\b\c\d\..\e", false, UriKind.Absolute).LocalPath);
Assert.AreEqual(@"ftp://me@a.net:123/b/c/", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c/d/..", true, UriKind.Absolute).AbsoluteUri);
Assert.AreEqual(@"ftp://me@a.net:123/b/c/e", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c/d/../e", false, UriKind.Absolute).AbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@"a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@"\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@".\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsFalse(PathUtils.MakeUri(@"..\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", false, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", true, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", false, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", true, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsFalse(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.RelativeOrAbsolute).IsFile);
Assert.IsFalse(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", true, UriKind.RelativeOrAbsolute).IsFile);
Assert.AreEqual(@"..\a\b\c\", PathUtils.MakeUri(@"..\a\b\c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"..\a\b\c", PathUtils.MakeUri(@"..\a\b\c", false, UriKind.Relative).ToString());
Assert.AreEqual(@"..\a b c\", PathUtils.MakeUri(@"..\a b c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"..\a b c", PathUtils.MakeUri(@"..\a b c", false, UriKind.Relative).ToString());
Assert.AreEqual(@"../a/b/c\", PathUtils.MakeUri(@"../a/b/c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"../a/b/c", PathUtils.MakeUri(@"../a/b/c", false, UriKind.Relative).ToString());
Assert.AreEqual(@"../a b c\", PathUtils.MakeUri(@"../a b c", true, UriKind.Relative).ToString());
Assert.AreEqual(@"../a b c", PathUtils.MakeUri(@"../a b c", false, UriKind.Relative).ToString());
}
private static void AssertIsNotSameDirectory(string first, string second) {
Assert.IsFalse(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsFalse(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
}
private static void AssertIsSameDirectory(string first, string second) {
Assert.IsTrue(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsTrue(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second));
}
private static void AssertIsNotSamePath(string first, string second) {
Assert.IsFalse(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsFalse(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
}
private static void AssertIsSamePath(string first, string second) {
Assert.IsTrue(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
first = first.Replace("\\", "/");
second = second.Replace("\\", "/");
Assert.IsTrue(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second));
}
[TestMethod, Priority(0)]
public void TestIsSamePath() {
// These paths should all look like files. Separators are added to the end
// to test the directory cases. Paths ending in "." or ".." are always directories,
// and will fail the tests here.
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c",
@"a\b\.\c", @"a\b\c",
@"a\b\d\..\c", @"a\b\c",
@"a\b\c", @"a\..\a\b\..\b\c\..\c"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\Share\", @"ftp://me@ftp.home.net/" }) {
string first, second;
first = root + testCase.Item1;
second = root + testCase.Item2;
AssertIsSamePath(first, second);
AssertIsNotSamePath(first + "\\", second);
AssertIsNotSamePath(first, second + "\\");
AssertIsSamePath(first + "\\", second + "\\");
if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
// Files are case-insensitive
AssertIsSamePath(first.ToLowerInvariant(), second.ToUpperInvariant());
} else {
// FTP is case-sensitive
AssertIsNotSamePath(first.ToLowerInvariant(), second.ToUpperInvariant());
}
AssertIsSameDirectory(first, second);
AssertIsSameDirectory(first + "\\", second);
AssertIsSameDirectory(first, second + "\\");
AssertIsSameDirectory(first + "\\", second + "\\");
if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
// Files are case-insensitive
AssertIsSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
} else {
// FTP is case-sensitive
AssertIsNotSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
}
}
}
// The first part always resolves to a directory, regardless of whether there
// is a separator at the end.
foreach (var testCase in Pairs(
@"a\b\c\..", @"a\b",
@"a\b\c\..\..", @"a"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\Share\", @"ftp://me@example.com/" }) {
string first, second;
first = root + testCase.Item1;
second = root + testCase.Item2;
AssertIsNotSamePath(first, second);
AssertIsNotSamePath(first + "\\", second);
AssertIsSamePath(first, second + "\\");
AssertIsSamePath(first + "\\", second + "\\");
AssertIsNotSamePath(first.ToLowerInvariant(), second.ToUpperInvariant());
AssertIsSameDirectory(first, second);
AssertIsSameDirectory(first + "\\", second);
AssertIsSameDirectory(first, second + "\\");
AssertIsSameDirectory(first + "\\", second + "\\");
if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
// Files are case-insensitive
AssertIsSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
} else {
// FTP is case-sensitive
AssertIsNotSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant());
}
}
}
}
[TestMethod, Priority(0)]
public void TestCreateFriendlyDirectoryPath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\", @"..\..",
@"C:\a\b", @"C:\a", @"..",
@"C:\a\b", @"C:\a\b", @".",
@"C:\a\b", @"C:\a\b\c", @"c",
@"C:\a\b", @"D:\a\b", @"D:\a\b",
@"C:\a\b", @"C:\", @"..\..",
@"\\pc\share\a\b", @"\\pc\share\", @"..\..",
@"\\pc\share\a\b", @"\\pc\share\a", @"..",
@"\\pc\share\a\b", @"\\pc\share\a\b", @".",
@"\\pc\share\a\b", @"\\pc\share\a\b\c", @"c",
@"\\pc\share\a\b", @"\\pc\othershare\a\b", @"..\..\..\othershare\a\b",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/", @"../..",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a", @"..",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b", @".",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/c", @"c",
@"ftp://me@example.com/a/b", @"ftp://me@another.example.com/a/b", @"ftp://me@another.example.com/a/b"
)) {
var expected = testCase.Item3;
var actual = PathUtils.CreateFriendlyDirectoryPath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(0)]
public void TestCreateFriendlyFilePath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\file.exe", @"..\..\file.exe",
@"C:\a\b", @"C:\a\file.exe", @"..\file.exe",
@"C:\a\b", @"C:\a\b\file.exe", @"file.exe",
@"C:\a\b", @"C:\a\b\c\file.exe", @"c\file.exe",
@"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe",
@"\\pc\share\a\b", @"\\pc\share\file.exe", @"..\..\file.exe",
@"\\pc\share\a\b", @"\\pc\share\a\file.exe", @"..\file.exe",
@"\\pc\share\a\b", @"\\pc\share\a\b\file.exe", @"file.exe",
@"\\pc\share\a\b", @"\\pc\share\a\b\c\file.exe", @"c\file.exe",
@"\\pc\share\a\b", @"\\pc\othershare\a\b\file.exe", @"..\..\..\othershare\a\b\file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/file.exe", @"../../file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/file.exe", @"../file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/file.exe", @"file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/c/file.exe", @"c/file.exe",
@"ftp://me@example.com/a/b", @"ftp://me@another.example.com/a/b/file.exe", @"ftp://me@another.example.com/a/b/file.exe"
)) {
var expected = testCase.Item3;
var actual = PathUtils.CreateFriendlyFilePath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(0)]
public void TestGetRelativeDirectoryPath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\", @"..\..\",
@"C:\a\b", @"C:\a", @"..\",
@"C:\a\b\c", @"C:\a", @"..\..\",
@"C:\a\b", @"C:\a\b", @"",
@"C:\a\b", @"C:\a\b\c", @"c\",
@"C:\a\b", @"D:\a\b", @"D:\a\b\",
@"C:\a\b", @"C:\d\e", @"..\..\d\e\",
@"\\root\share\path", @"\\Root\Share", @"..\",
@"\\root\share\path", @"\\Root\share\Path\subpath", @"subpath\",
@"\\root\share\path\subpath", @"\\Root\share\Path\othersubpath", @"..\othersubpath\",
@"\\root\share\path", @"\\root\othershare\path", @"..\..\othershare\path\",
@"\\root\share\path", @"\\root\share\otherpath\", @"..\otherpath\",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/", @"../../",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/Share", @"../../Share/",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/path/subpath", @"subpath/",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/Path/subpath", @"../Path/subpath/",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/path/othersubpath", @"../othersubpath/",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/Path/othersubpath", @"../../Path/othersubpath/",
@"ftp://me@example.com/path", @"ftp://me@example.com/otherpath/", @"../otherpath/",
@"C:\a\b\c\d", @"C:\.dottedname", @"..\..\..\..\.dottedname\",
@"C:\a\b\c\d", @"C:\..dottedname", @"..\..\..\..\..dottedname\",
@"C:\a\b\c\d", @"C:\a\.dottedname", @"..\..\..\.dottedname\",
@"C:\a\b\c\d", @"C:\a\..dottedname", @"..\..\..\..dottedname\",
"C:\\a\\b\\", @"C:\a\b", @"",
@"C:\a\b", "C:\\a\\b\\", @""
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetRelativeDirectoryPath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual, string.Format("From {0} to {1}", testCase.Item1, testCase.Item2));
}
}
[TestMethod, Priority(0)]
public void TestGetRelativeFilePath() {
foreach (var testCase in Triples(
@"C:\a\b", @"C:\file.exe", @"..\..\file.exe",
@"C:\a\b", @"C:\a\file.exe", @"..\file.exe",
@"C:\a\b\c", @"C:\a\file.exe", @"..\..\file.exe",
@"C:\a\b", @"C:\A\B\file.exe", @"file.exe",
@"C:\a\b", @"C:\a\B\C\file.exe", @"C\file.exe",
@"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe",
@"C:\a\b", @"C:\d\e\file.exe", @"..\..\d\e\file.exe",
@"\\root\share\path", @"\\Root\Share\file.exe", @"..\file.exe",
@"\\root\share\path", @"\\Root\Share\Path\file.exe", @"file.exe",
@"\\root\share\path", @"\\Root\share\Path\subpath\file.exe", @"subpath\file.exe",
@"\\root\share\path\subpath", @"\\Root\share\Path\othersubpath\file.exe", @"..\othersubpath\file.exe",
@"\\root\share\path", @"\\root\othershare\path\file.exe", @"..\..\othershare\path\file.exe",
@"\\root\share\path", @"\\root\share\otherpath\file.exe", @"..\otherpath\file.exe",
@"\\root\share\", @"\\otherroot\share\file.exe", @"\\otherroot\share\file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/file.exe", @"../../file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/Share/file.exe", @"../../Share/file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/path/subpath/file.exe", @"subpath/file.exe",
@"ftp://me@example.com/share/path", @"ftp://me@example.com/share/Path/subpath/file.exe", @"../Path/subpath/file.exe",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/path/othersubpath/file.exe", @"../othersubpath/file.exe",
@"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/Path/othersubpath/file.exe", @"../../Path/othersubpath/file.exe",
@"ftp://me@example.com/path", @"ftp://me@example.com/otherpath/file.exe", @"../otherpath/file.exe",
@"C:\a\b", "C:\\a\\b\\", @"",
// This is the expected behavior for GetRelativeFilePath
// because the 'b' in the second part is assumed to be a file
// and hence may be different to the directory 'b' in the first
// part.
// GetRelativeDirectoryPath returns an empty string, because it
// assumes that both paths are directories.
"C:\\a\\b\\", @"C:\a\b", @"..\b",
// Ensure end-separators are retained when the target is a
// directory rather than a file.
"C:\\a\\", "C:\\a\\b\\", "b\\",
"C:\\a", "C:\\a\\b\\", "b\\"
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetRelativeFilePath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual, string.Format("From {0} to {1}", testCase.Item1, testCase.Item2));
}
}
[TestMethod, Priority(0)]
public void TestGetAbsoluteDirectoryPath() {
foreach (var testCase in Triples(
@"C:\a\b", @"\", @"C:\",
@"C:\a\b", @"..\", @"C:\a\",
@"C:\a\b", @"", @"C:\a\b\",
@"C:\a\b", @".", @"C:\a\b\",
@"C:\a\b", @"c", @"C:\a\b\c\",
@"C:\a\b", @"D:\a\b", @"D:\a\b\",
@"C:\a\b", @"\d\e", @"C:\d\e\",
@"C:\a\b\c\d", @"..\..\..\..", @"C:\",
@"\\root\share\path", @"..", @"\\root\share\",
@"\\root\share\path", @"subpath", @"\\root\share\path\subpath\",
@"\\root\share\path", @"..\otherpath\", @"\\root\share\otherpath\",
@"ftp://me@example.com/path", @"..", @"ftp://me@example.com/",
@"ftp://me@example.com/path", @"subpath", @"ftp://me@example.com/path/subpath/",
@"ftp://me@example.com/path", @"../otherpath/", @"ftp://me@example.com/otherpath/"
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetAbsoluteDirectoryPath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(0)]
public void TestGetAbsoluteFilePath() {
foreach (var testCase in Triples(
@"C:\a\b", @"\file.exe", @"C:\file.exe",
@"C:\a\b", @"..\file.exe", @"C:\a\file.exe",
@"C:\a\b", @"file.exe", @"C:\a\b\file.exe",
@"C:\a\b", @"c\file.exe", @"C:\a\b\c\file.exe",
@"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe",
@"C:\a\b", @"\d\e\file.exe", @"C:\d\e\file.exe",
@"C:\a\b\c\d\", @"..\..\..\..\", @"C:\",
@"\\root\share\path", @"..\file.exe", @"\\root\share\file.exe",
@"\\root\share\path", @"file.exe", @"\\root\share\path\file.exe",
@"\\root\share\path", @"subpath\file.exe", @"\\root\share\path\subpath\file.exe",
@"\\root\share\path", @"..\otherpath\file.exe", @"\\root\share\otherpath\file.exe",
@"ftp://me@example.com/path", @"../file.exe", @"ftp://me@example.com/file.exe",
@"ftp://me@example.com/path", @"file.exe", @"ftp://me@example.com/path/file.exe",
@"ftp://me@example.com/path", @"subpath/file.exe", @"ftp://me@example.com/path/subpath/file.exe",
@"ftp://me@example.com/path", @"../otherpath/file.exe", @"ftp://me@example.com/otherpath/file.exe"
)) {
var expected = testCase.Item3;
var actual = PathUtils.GetAbsoluteFilePath(testCase.Item1, testCase.Item2);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(0)]
public void TestNormalizeDirectoryPath() {
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c\",
@"a\b\.\c", @"a\b\c\",
@"a\b\d\..\c", @"a\b\c\",
@"a\b\\c", @"a\b\c\"
)) {
foreach (var root in new[] { "", @".\", @"..\", @"\" }) {
var expected = (root == @".\" ? "" : root) + testCase.Item2;
var actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1);
Assert.AreEqual(expected, actual);
}
}
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c\",
@"a\b\.\c", @"a\b\c\",
@"a\b\d\..\c", @"a\b\c\",
@"a\..\..\b", @"b\"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\share\", @"ftp://me@example.com/" }) {
var expected = root + testCase.Item2;
var actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1);
if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
expected = expected.Replace('\\', '/');
}
Assert.AreEqual(expected, actual);
actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1 + @"\");
Assert.AreEqual(expected, actual);
}
}
}
[TestMethod, Priority(0)]
public void TestNormalizePath() {
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c",
@"a\b\.\c", @"a\b\c",
@"a\b\d\..\c", @"a\b\c",
@"a\b\\c", @"a\b\c"
)) {
foreach (var root in new[] { "", @".\", @"..\", @"\" }) {
var expected = (root == @".\" ? "" : root) + testCase.Item2;
var actual = PathUtils.NormalizePath(root + testCase.Item1);
Assert.AreEqual(expected, actual);
expected += @"\";
actual = PathUtils.NormalizePath(root + testCase.Item1 + @"\");
Assert.AreEqual(expected, actual);
}
}
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\c",
@"a\b\.\c", @"a\b\c",
@"a\b\d\..\c", @"a\b\c",
@"a\..\..\b", @"b"
)) {
foreach (var root in new[] { @"C:\", @"\\pc\share\", @"ftp://me@example.com/" }) {
var expected = root + testCase.Item2;
var actual = PathUtils.NormalizePath(root + testCase.Item1);
if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
expected = expected.Replace('\\', '/');
}
Assert.AreEqual(expected, actual);
expected += @"\";
actual = PathUtils.NormalizePath(root + testCase.Item1 + @"\");
if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) {
expected = expected.Replace('\\', '/');
}
Assert.AreEqual(expected, actual);
}
}
}
[TestMethod, Priority(0)]
public void TestTrimEndSeparator() {
// TrimEndSeparator uses System.IO.Path.(Alt)DirectorySeparatorChar
// Here we assume these are '\\' and '/'
foreach (var testCase in Pairs(
@"no separator", @"no separator",
@"one slash/", @"one slash",
@"two slashes//", @"two slashes/",
@"one backslash\", @"one backslash",
@"two backslashes\\", @"two backslashes\",
@"mixed/\", @"mixed/",
@"mixed\/", @"mixed\",
@"/leading", @"/leading",
@"\leading", @"\leading",
@"wit/hin", @"wit/hin",
@"wit\hin", @"wit\hin",
@"C:\a\", @"C:\a",
@"C:\", @"C:\",
@"ftp://a/", @"ftp://a",
@"ftp://", @"ftp://"
)) {
var expected = testCase.Item2;
var actual = PathUtils.TrimEndSeparator(testCase.Item1);
Assert.AreEqual(expected, actual);
}
}
[TestMethod, Priority(0)]
public void TestIsSubpathOf() {
// Positive tests
foreach (var testCase in Pairs(
@"C:\a\b", @"C:\A\B",
@"C:\a\b\", @"C:\A\B", // IsSubpathOf has a special case for this
@"C:\a\b", @"C:\A\B\C",
@"C:\a\b\", @"C:\a\b\c", // IsSubpathOf has a quick path for this
@"C:\a\b\", @"C:\A\B\C", // Quick path should not be taken
@"C:", @"C:\a\b\",
@"C:\a\b", @"C:\A\X\..\B\C"
)) {
Assert.IsTrue(PathUtils.IsSubpathOf(testCase.Item1, testCase.Item2), string.Format("{0} should be subpath of {1}", testCase.Item2, testCase.Item1));
}
// Negative tests
foreach (var testCase in Pairs(
@"C:\a\b\c", @"C:\A\B",
@"C:\a\bcd", @"c:\a\b\cd", // Quick path should not be taken
@"C:\a\bcd", @"C:\A\B\CD", // Quick path should not be taken
@"C:\a\b", @"D:\A\B\C",
@"C:\a\b\c", @"C:\B\A\C\D",
@"C:\a\b\", @"C:\a\b\..\x\c" // Quick path should not be taken
)) {
Assert.IsFalse(PathUtils.IsSubpathOf(testCase.Item1, testCase.Item2), string.Format("{0} should not be subpath of {1}", testCase.Item2, testCase.Item1));
}
}
[TestMethod, Priority(0)]
public void TestGetLastDirectoryName() {
foreach (var testCase in Pairs(
@"a\b\c", "b",
@"a\b\", "b",
@"a\b\c\", "c",
@"a\b\.\c", "b",
@"a\b\.\.\.\.\.\.\c", "b"
)) {
foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) {
var path = scheme + testCase.Item1;
Assert.AreEqual(testCase.Item2, PathUtils.GetLastDirectoryName(path), "Path: " + path);
if (path.IndexOf('.') >= 0) {
// Path.GetFileName will always fail on these, so don't
// even bother testing.
continue;
}
string ioPathResult;
try {
ioPathResult = Path.GetFileName(PathUtils.TrimEndSeparator(Path.GetDirectoryName(path)));
} catch (ArgumentException) {
continue;
}
Assert.AreEqual(
PathUtils.GetLastDirectoryName(path),
ioPathResult ?? string.Empty,
"Did not match Path.GetFileName(...) result for " + path
);
}
}
}
[TestMethod, Priority(0)]
public void TestGetParentOfDirectory() {
foreach (var testCase in Pairs(
@"a\b\c", @"a\b\",
@"a\b\", @"a\",
@"a\b\c\", @"a\b\"
)) {
foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) {
var path = scheme + testCase.Item1;
var expected = scheme + testCase.Item2;
Assert.AreEqual(expected, PathUtils.GetParent(path), "Path: " + path);
if (scheme.Contains("://")) {
// Path.GetFileName will always fail on these, so don't
// even bother testing.
continue;
}
string ioPathResult;
try {
ioPathResult = Path.GetDirectoryName(PathUtils.TrimEndSeparator(path)) + Path.DirectorySeparatorChar;
} catch (ArgumentException) {
continue;
}
Assert.AreEqual(
PathUtils.GetParent(path),
ioPathResult ?? string.Empty,
"Did not match Path.GetDirectoryName(...) result for " + path
);
}
}
}
[TestMethod, Priority(0)]
public void TestGetFileOrDirectoryName() {
foreach (var testCase in Pairs(
@"a\b\c", @"c",
@"a\b\", @"b",
@"a\b\c\", @"c",
@"a", @"a",
@"a\", @"a"
)) {
foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) {
var path = scheme + testCase.Item1;
var expected = testCase.Item2;
Assert.AreEqual(expected, PathUtils.GetFileOrDirectoryName(path), "Path: " + path);
if (scheme.Contains("://")) {
// Path.GetFileName will always fail on these, so don't
// even bother testing.
continue;
}
string ioPathResult;
try {
ioPathResult = PathUtils.GetFileOrDirectoryName(path);
} catch (ArgumentException) {
continue;
}
Assert.AreEqual(
PathUtils.GetFileOrDirectoryName(path),
ioPathResult ?? string.Empty,
"Did not match Path.GetDirectoryName(...) result for " + path
);
}
}
}
[TestMethod, Priority(0)]
public void TestEnumerateDirectories() {
// Use "Windows", as we won't be able to enumerate everything in
// here, but we should still not crash.
var windows = Environment.GetEnvironmentVariable("SYSTEMROOT");
var dirs = PathUtils.EnumerateDirectories(windows).ToList();
Assert.AreNotEqual(0, dirs.Count);
// Expect all paths to be rooted
AssertUtil.ContainsExactly(dirs.Where(d => !Path.IsPathRooted(d)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(dirs.Where(d => !PathUtils.IsSubpathOf(windows, d)));
dirs = PathUtils.EnumerateDirectories(windows, recurse: false, fullPaths: false).ToList();
Assert.AreNotEqual(0, dirs.Count);
// Expect all paths to be relative
AssertUtil.ContainsExactly(dirs.Where(d => Path.IsPathRooted(d)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(dirs.Where(d => !Directory.Exists(Path.Combine(windows, d))));
}
[TestMethod, Priority(0)]
public void TestEnumerateFiles() {
// Use "Windows", as we won't be able to enumerate everything in
// here, but we should still not crash.
var windows = Environment.GetEnvironmentVariable("SYSTEMROOT");
var files = PathUtils.EnumerateFiles(windows).ToList();
Assert.AreNotEqual(0, files.Count);
// Expect all paths to be rooted
AssertUtil.ContainsExactly(files.Where(f => !Path.IsPathRooted(f)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(files.Where(f => !PathUtils.IsSubpathOf(windows, f)));
// Expect multiple extensions
Assert.AreNotEqual(1, files.Select(f => Path.GetExtension(f)).ToSet().Count);
files = PathUtils.EnumerateFiles(windows, recurse: false, fullPaths: false).ToList();
Assert.AreNotEqual(0, files.Count);
// Expect all paths to be relative
AssertUtil.ContainsExactly(files.Where(f => Path.IsPathRooted(f)));
// Expect all paths to be only filenames
AssertUtil.ContainsExactly(files.Where(f => f.IndexOfAny(new[] { '\\', '/' }) >= 0));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(files.Where(f => !File.Exists(Path.Combine(windows, f))));
files = PathUtils.EnumerateFiles(windows, "*.exe", recurse: false, fullPaths: false).ToList();
Assert.AreNotEqual(0, files.Count);
// Expect all paths to be relative
AssertUtil.ContainsExactly(files.Where(f => Path.IsPathRooted(f)));
// Expect all paths to be within Windows
AssertUtil.ContainsExactly(files.Where(f => !File.Exists(Path.Combine(windows, f))));
// Expect only one extension
AssertUtil.ContainsExactly(files.Select(f => Path.GetExtension(f).ToLowerInvariant()).ToSet(), ".exe");
}
[TestMethod, Priority(0)]
public void TestFindFile() {
var root = TestData.GetPath("TestData");
// File is too deep - should not find
Assert.IsNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 0));
// Find file with BFS
Assert.IsNotNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 1));
// Find file with correct firstCheck
Assert.IsNotNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 1, firstCheck: new[] { "FindFile" }));
// Find file with incorrect firstCheck
Assert.IsNotNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 1, firstCheck: new[] { "FindFileX" }));
// File is too deep
Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 0));
Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 1));
Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 2));
Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 3));
// File is found
Assert.IsNotNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 4));
}
private IEnumerable<Tuple<string, string>> Pairs(params string[] items) {
using (var e = items.Cast<string>().GetEnumerator()) {
while (e.MoveNext()) {
var first = e.Current;
if (!e.MoveNext()) {
yield break;
}
var second = e.Current;
yield return new Tuple<string, string>(first, second);
}
}
}
private IEnumerable<Tuple<string, string, string>> Triples(params string[] items) {
using (var e = items.Cast<string>().GetEnumerator()) {
while (e.MoveNext()) {
var first = e.Current;
if (!e.MoveNext()) {
yield break;
}
var second = e.Current;
if (!e.MoveNext()) {
yield break;
}
var third = e.Current;
yield return new Tuple<string, string, string>(first, second, third);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using InAudioSystem.ExtensionMethods;
using InAudioSystem.Internal;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace InAudioSystem.InAudioEditor
{
public class TreeDrawer<T> where T : Object, InITreeNode<T>
{
public TreeDrawer(EditorWindow window)
{
Window = window;
EditorApplication.update += Update;
}
public T SelectedNode
{
get { return selectedNode; }
set { selectedNode = value; }
}
public Vector2 ScrollPosition;
public delegate void OnContextDelegate(T node);
public OnContextDelegate OnContext;
public delegate bool OnNodeDrawDelegate(T node, bool isSelected, out bool clicked);
public OnNodeDrawDelegate OnNodeDraw;
public delegate void OnDropDelegate(T node, Object[] objects);
public OnDropDelegate OnDrop;
public delegate bool CanDropObjectsDelegate(T node, Object[] objects);
public CanDropObjectsDelegate CanDropObjects;
public delegate bool CanPlaceHereDelegate(T newParent, T toPlace);
public CanPlaceHereDelegate CanPlaceHere = (P, N) => true;
public delegate void AssignNewParentDelegate(T newParent, T node, int index = -1);
public AssignNewParentDelegate AssignNewParent = (p, n, i) =>
{
n._getParent = p;
if (i == -1)
{
p._getChildren.Insert(0, n);
}
else
{
p._getChildren.Insert(i, n);
}
};
public delegate void DeattachFromParentDelegate(T node);
public DeattachFromParentDelegate DeattachFromParent = node => node._getParent._getChildren.Remove(node);
public bool DrawTree(T treeRoot, Rect area)
{
dirty = false;
if (SelectedNode == null)
selectedNode = treeRoot;
if (SelectedNode == null)
return false;
KeyboardControl();
int startIndent = EditorGUI.indentLevel;
ScrollPosition = EditorGUILayout.BeginScrollView(ScrollPosition, false, true);
if (treeRoot == null || OnNodeDraw == null)
return true;
if (selectedNode.EditorSettings.IsFiltered)
selectedNode = treeRoot;
if (triggerFilter)
{
FilterNodes(treeRoot, filterFunc);
triggerFilter = false;
}
toDrawArea.Clear();
DrawTree(treeRoot, EditorGUI.indentLevel);
if (DragAndDrop.objectReferences.FirstOrDefault() as T != null && EditorWindow.focusedWindow == Window)
{
dirty = true;
}
if (EditorWindow.focusedWindow == Window)
{
foreach (var drawArea in toDrawArea)
{
var fullArea = drawArea.Big;
var smallArea = drawArea.Small;
if (DragAndDrop.objectReferences.FirstOrDefault() as T != null)
{
if (smallArea.Contains(Event.current.mousePosition))
{
GUIDrawRect(smallArea, EditorResources.Instance.GetBackground().GetPixel(0, 0) * 0.7f);
break;
}
else if (fullArea.Contains(Event.current.mousePosition))
{
DrawAround(area, smallArea, fullArea);
break;
}
}
else if (CanDropObjects(drawArea.Node, DragAndDrop.objectReferences) && fullArea.Contains(Event.current.mousePosition))
{
DrawAround(area, smallArea, fullArea);
break;
}
}
}
if (Event.current.type == EventType.DragExited)
{
dirty = true;
Window.Repaint();
}
EditorGUILayout.EndScrollView();
EditorGUI.indentLevel = startIndent;
return dirty;
}
private void DrawAround(Rect treeArea, Rect smallArea, Rect nodeArea)
{
Rect top = smallArea;
top.y += 4;
top.height = 3;
GUIDrawRect(top, EditorResources.Instance.GetBackground().GetPixel(0, 0) * 0.7f);
var bottom = top;
bottom.y -= nodeArea.height;
GUIDrawRect(bottom, EditorResources.Instance.GetBackground().GetPixel(0, 0) * 0.7f);
Rect left = bottom;
left.width = 3;
left.height = nodeArea.height;
left.x += 2 + ScrollPosition.x;
var right = left;
right.x += treeArea.width - 20 + ScrollPosition.x;
GUIDrawRect(left, EditorResources.Instance.GetBackground().GetPixel(0, 0) * 0.7f);
GUIDrawRect(right, EditorResources.Instance.GetBackground().GetPixel(0, 0) * 0.7f);
}
public void Filter(Func<T, bool> filter)
{
filterFunc = filter;
triggerFilter = true;
}
public void FocusOnSelectedNode()
{
focusOnSelectedNode = true;
}
private bool genericCanPlaceHere(T p, T n)
{
if (p == null || n == null || p == n || n.IsRoot || TreeWalker.IsParentOf(n, p))
{
return false;
}
var actualparent = GetPotentialParent(p);
if (TreeWalker.IsParentOf(n, actualparent))
return false;
if ((!p.IsFolder && !p.IsRoot) && n.IsFolder)
{
return false;
}
if (!CanPlaceHere(actualparent, n))
{
return false;
}
return true;
}
private T GetPotentialParent(T p)
{
if (p._getChildren.Any() && p.EditorSettings.IsFoldedOut)
{
return p;
}
else
{
return p._getParent;
}
}
private void genericPlaceHere(T p, T n)
{
InUndoHelper.DoInGroup(() =>
{
InUndoHelper.RecordObjects("Location", p, p._getParent, n, n._getParent);
DeattachFromParent(n);
if (p._getChildren.Any() && p.EditorSettings.IsFoldedOut)
{
AssignNewParent(p, n, 0);
}
else if (n._getParent == p._getParent)
{
var index = p._getParent._getChildren.IndexOf(p);
AssignNewParent(p._getParent, n, index + 1);
}
else
{
if (!p.IsRoot)
{
int newIndex = p._getParent._getChildren.IndexOf(p) + 1;
AssignNewParent(p._getParent, n, newIndex);
}
else
{
int newIndex = p._getChildren.IndexOf(p) + 1;
AssignNewParent(p, n, newIndex);
}
}
});
}
public static void GUIDrawRect(Rect position, Color color)
{
if (_staticRectStyle == null)
{
_staticRectStyle = new GUIStyle();
}
EditorResources.Instance.GenericColor.SetPixel(0, 0, color);
EditorResources.Instance.GenericColor.Apply();
_staticRectStyle.normal.background = EditorResources.Instance.GenericColor;
GUI.Box(position, GUIContent.none, _staticRectStyle);
}
//Draw all nodes recursively
void DrawTree(T node, int indentLevel)
{
if (node != null)
{
if (node.EditorSettings.IsFiltered)
return;
EditorGUI.indentLevel = indentLevel + 1;
bool clicked;
//Draw node
node.EditorSettings.IsFoldedOut = OnNodeDraw(node, node == selectedNode, out clicked);
Rect area = GUILayoutUtility.GetLastRect();
Rect drawArea = area;
drawArea.y += area.height - 5;
drawArea.height = 10;
toDrawArea.Add(new DrawArea(node, area, drawArea));
if (node == selectedNode && focusOnSelectedNode && Event.current.type == EventType.Repaint)
{
ScrollPosition.y = area.y - 50;
dirty = true;
focusOnSelectedNode = false;
}
if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform)
{
if (Event.current.Contains(drawArea) && DragAndDrop.objectReferences.Length > 0)
{
if (genericCanPlaceHere(node, DragAndDrop.objectReferences[0] as T))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Link;
}
}
else if (Event.current.Contains(area) && CanDropObjects(node, DragAndDrop.objectReferences))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Link;
}
}
if (Event.current.type == EventType.DragPerform)
{
requriesUpdate = true;
updateTime = Time.time;
if (Event.current.Contains(drawArea))
{
if (genericCanPlaceHere(node, DragAndDrop.objectReferences[0] as T))
{
genericPlaceHere(node, DragAndDrop.objectReferences[0] as T);
}
Event.current.UseEvent();
}
else if (Event.current.Contains(area) && CanDropObjects(node, DragAndDrop.objectReferences))
{
OnDrop(node, DragAndDrop.objectReferences);
}
}
if (area.Contains(Event.current.mousePosition))
{
if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData(node._ID.ToString(), new Object[] { node });
Event.current.UseEvent();
}
if (Event.current.type == EventType.MouseDrag)
{
var genericData = DragAndDrop.GetGenericData(node._ID.ToString()) as Object[];
if (genericData != null)
{
var data = genericData.FirstOrDefault() as T;
if (data != null && data == node)
{
DragAndDrop.objectReferences = new Object[] { node };
DragAndDrop.StartDrag("Dragging Node Element");
Event.current.UseEvent();
}
}
}
}
if (clicked)
{
selectedNode = node;
GUIUtility.keyboardControl = 0;
Event.current.UseEvent();
}
if (Event.current.MouseUpWithin(area, 1))
{
OnContext(node);
SelectedNode = node;
}
EditorGUI.indentLevel = indentLevel - 1;
if (Event.current.type == EventType.Layout)
NodeWorker.RemoveNullChildren(node);
if (node.EditorSettings.IsFoldedOut)
{
for (int i = 0; i < node._getChildren.Count; ++i)
{
T child = node._getChildren[i];
DrawTree(child, indentLevel + 1);
}
}
}
}
private void KeyboardControl()
{
#region keyboard control
if (GUIUtility.keyboardControl != 0)
return;
if (Event.current.IsKeyDown(KeyCode.LeftArrow))
{
selectedNode.EditorSettings.IsFoldedOut = false;
FocusOnSelectedNode();
Event.current.UseEvent();
}
if (Event.current.IsKeyDown(KeyCode.RightArrow))
{
selectedNode.EditorSettings.IsFoldedOut = true;
FocusOnSelectedNode();
Event.current.UseEvent();
}
if (Event.current.IsKeyDown(KeyCode.UpArrow))
{
selectedNode = TreeWalker.FindPreviousUnfoldedNode(selectedNode, arg => !arg.EditorSettings.IsFiltered);
FocusOnSelectedNode();
Event.current.UseEvent();
}
if (Event.current.IsKeyDown(KeyCode.DownArrow))
{
selectedNode = TreeWalker.FindNextNode(SelectedNode, arg => !arg.EditorSettings.IsFiltered);
FocusOnSelectedNode();
Event.current.UseEvent();
}
if (Event.current.IsKeyDown(KeyCode.Home))
{
ScrollPosition = new Vector2();
}
if (Event.current.IsKeyDown(KeyCode.End))
{
ScrollPosition = new Vector2(0, 100000);
}
// if (hasPressedDown && (_area.y + ScrollPosition.y + _area.height - selectedArea.height * 2 < selectedArea.y + selectedArea.height))
// {
// ScrollPosition.y += selectedArea.height;
// }
// if (hasPressedUp && (_area.y + ScrollPosition.y + selectedArea.height > selectedArea.y))
// {
// ScrollPosition.y -= selectedArea.height;
// }
#endregion
}
//FilterBy: true if node contains search
private bool FilterNodes(T node, Func<T, bool> filter)
{
if (node == null)
return false;
node.EditorSettings.IsFiltered = false;
if (node._getChildren.Count > 0)
{
bool allChildrenFilted = true;
foreach (var child in node._getChildren)
{
bool filtered = FilterNodes(child, filter);
if (!filtered)
{
allChildrenFilted = false;
}
}
node.EditorSettings.IsFiltered = allChildrenFilted; //If all children are filtered, this node also becomes filtered unless its name is not filtered
if (node.EditorSettings.IsFiltered)
node.EditorSettings.IsFiltered = filter(node);
return node.EditorSettings.IsFiltered;
}
else
{
node.EditorSettings.IsFiltered = filter(node);
return node.EditorSettings.IsFiltered;
}
}
//Workaround to force redraw
private void Update()
{
if (requriesUpdate && Window != null && updateTime + 0.5f > Time.time)
{
Window.Repaint();
requriesUpdate = false;
}
}
private bool dirty;
private static GUIStyle _staticRectStyle;
private EditorWindow Window;
private bool requriesUpdate = false;
private float updateTime = 0;
private T selectedNode;
private T draggingNode;
private Rect selectedArea;
private bool triggerFilter = false;
private Func<T, bool> filterFunc;
private bool canDropObjects;
private Vector2 clickPos;
private List<DrawArea> toDrawArea = new List<DrawArea>();
private bool focusOnSelectedNode;
private struct DrawArea
{
public Rect Big;
public Rect Small;
public T Node;
public DrawArea(T node, Rect big, Rect small)
{
this.Node = node;
Big = big;
Small = small;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 Leaderboard.Web.Areas.HelpPage.ModelDescriptions;
using Leaderboard.Web.Areas.HelpPage.Models;
namespace Leaderboard.Web.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;
}
if (complexTypeDescription != null)
{
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 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);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{
/// <summary>
/// The possible states that an agent can be in when its being transferred between regions.
/// </summary>
/// <remarks>
/// This is a state machine.
///
/// [Entry] => Preparing
/// Preparing => { Transferring || Cancelling || CleaningUp || Aborting || [Exit] }
/// Transferring => { ReceivedAtDestination || Cancelling || CleaningUp || Aborting }
/// Cancelling => CleaningUp || Aborting
/// ReceivedAtDestination => CleaningUp || Aborting
/// CleaningUp => [Exit]
/// Aborting => [Exit]
///
/// In other words, agents normally travel throwing Preparing => Transferring => ReceivedAtDestination => CleaningUp
/// However, any state can transition to CleaningUp if the teleport has failed.
/// </remarks>
enum AgentTransferState
{
Preparing, // The agent is being prepared for transfer
Transferring, // The agent is in the process of being transferred to a destination
ReceivedAtDestination, // The destination has notified us that the agent has been successfully received
CleaningUp, // The agent is being changed to child/removed after a transfer
Cancelling, // The user has cancelled the teleport but we have yet to act upon this.
Aborting // The transfer is aborting. Unlike Cancelling, no compensating actions should be performed
}
/// <summary>
/// Records the state of entities when they are in transfer within or between regions (cross or teleport).
/// </summary>
public class EntityTransferStateMachine
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[ENTITY TRANSFER STATE MACHINE]";
/// <summary>
/// If true then on a teleport, the source region waits for a callback from the destination region. If
/// a callback fails to arrive within a set time then the user is pulled back into the source region.
/// </summary>
public bool EnableWaitForAgentArrivedAtDestination { get; set; }
private EntityTransferModule m_mod;
private Dictionary<UUID, AgentTransferState> m_agentsInTransit = new Dictionary<UUID, AgentTransferState>();
public EntityTransferStateMachine(EntityTransferModule module)
{
m_mod = module;
}
/// <summary>
/// Set that an agent is in transit.
/// </summary>
/// <param name='id'>The ID of the agent being teleported</param>
/// <returns>true if the agent was not already in transit, false if it was</returns>
internal bool SetInTransit(UUID id)
{
m_log.DebugFormat("{0} SetInTransit. agent={1}, newState=Preparing", LogHeader, id);
lock (m_agentsInTransit)
{
if (!m_agentsInTransit.ContainsKey(id))
{
m_agentsInTransit[id] = AgentTransferState.Preparing;
return true;
}
}
return false;
}
/// <summary>
/// Updates the state of an agent that is already in transit.
/// </summary>
/// <param name='id'></param>
/// <param name='newState'></param>
/// <returns></returns>
/// <exception cref='Exception'>Illegal transitions will throw an Exception</exception>
internal bool UpdateInTransit(UUID id, AgentTransferState newState)
{
m_log.DebugFormat("{0} UpdateInTransit. agent={1}, newState={2}", LogHeader, id, newState);
bool transitionOkay = false;
// We don't want to throw an exception on cancel since this can come it at any time.
bool failIfNotOkay = true;
// Should be a failure message if failure is not okay.
string failureMessage = null;
AgentTransferState? oldState = null;
lock (m_agentsInTransit)
{
// Illegal to try and update an agent that's not actually in transit.
if (!m_agentsInTransit.ContainsKey(id))
{
if (newState != AgentTransferState.Cancelling && newState != AgentTransferState.Aborting)
failureMessage = string.Format(
"Agent with ID {0} is not registered as in transit in {1}",
id, m_mod.Scene.RegionInfo.RegionName);
else
failIfNotOkay = false;
}
else
{
oldState = m_agentsInTransit[id];
if (newState == AgentTransferState.Aborting)
{
transitionOkay = true;
}
else if (newState == AgentTransferState.CleaningUp && oldState != AgentTransferState.CleaningUp)
{
transitionOkay = true;
}
else if (newState == AgentTransferState.Transferring && oldState == AgentTransferState.Preparing)
{
transitionOkay = true;
}
else if (newState == AgentTransferState.ReceivedAtDestination && oldState == AgentTransferState.Transferring)
{
transitionOkay = true;
}
else
{
if (newState == AgentTransferState.Cancelling
&& (oldState == AgentTransferState.Preparing || oldState == AgentTransferState.Transferring))
{
transitionOkay = true;
}
else
{
failIfNotOkay = false;
}
}
if (!transitionOkay)
failureMessage
= string.Format(
"Agent with ID {0} is not allowed to move from old transit state {1} to new state {2} in {3}",
id, oldState, newState, m_mod.Scene.RegionInfo.RegionName);
}
if (transitionOkay)
{
m_agentsInTransit[id] = newState;
// m_log.DebugFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Changed agent with id {0} from state {1} to {2} in {3}",
// id, oldState, newState, m_mod.Scene.Name);
}
else if (failIfNotOkay)
{
m_log.DebugFormat("{0} UpdateInTransit. Throwing transition failure = {1}", LogHeader, failureMessage);
throw new Exception(failureMessage);
}
// else
// {
// if (oldState != null)
// m_log.DebugFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Ignored change of agent with id {0} from state {1} to {2} in {3}",
// id, oldState, newState, m_mod.Scene.Name);
// else
// m_log.DebugFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Ignored change of agent with id {0} to state {1} in {2} since agent not in transit",
// id, newState, m_mod.Scene.Name);
// }
}
return transitionOkay;
}
/// <summary>
/// Gets the current agent transfer state.
/// </summary>
/// <returns>Null if the agent is not in transit</returns>
/// <param name='id'>
/// Identifier.
/// </param>
internal AgentTransferState? GetAgentTransferState(UUID id)
{
lock (m_agentsInTransit)
{
if (!m_agentsInTransit.ContainsKey(id))
return null;
else
return m_agentsInTransit[id];
}
}
/// <summary>
/// Removes an agent from the transit state machine.
/// </summary>
/// <param name='id'></param>
/// <returns>true if the agent was flagged as being teleported when this method was called, false otherwise</returns>
internal bool ResetFromTransit(UUID id)
{
lock (m_agentsInTransit)
{
if (m_agentsInTransit.ContainsKey(id))
{
AgentTransferState state = m_agentsInTransit[id];
if (state == AgentTransferState.Transferring || state == AgentTransferState.ReceivedAtDestination)
{
// FIXME: For now, we allow exit from any state since a thrown exception in teleport is now guranteed
// to be handled properly - ResetFromTransit() could be invoked at any step along the process
m_log.WarnFormat(
"[ENTITY TRANSFER STATE MACHINE]: Agent with ID {0} should not exit directly from state {1}, should go to {2} state first in {3}",
id, state, AgentTransferState.CleaningUp, m_mod.Scene.RegionInfo.RegionName);
// throw new Exception(
// "Agent with ID {0} cannot exit directly from state {1}, it must go to {2} state first",
// state, AgentTransferState.CleaningUp);
}
m_agentsInTransit.Remove(id);
m_log.DebugFormat(
"[ENTITY TRANSFER STATE MACHINE]: Agent {0} cleared from transit in {1}",
id, m_mod.Scene.RegionInfo.RegionName);
return true;
}
}
m_log.WarnFormat(
"[ENTITY TRANSFER STATE MACHINE]: Agent {0} requested to clear from transit in {1} but was already cleared",
id, m_mod.Scene.RegionInfo.RegionName);
return false;
}
internal bool WaitForAgentArrivedAtDestination(UUID id)
{
if (!m_mod.WaitForAgentArrivedAtDestination)
return true;
lock (m_agentsInTransit)
{
AgentTransferState? currentState = GetAgentTransferState(id);
if (currentState == null)
throw new Exception(
string.Format(
"Asked to wait for destination callback for agent with ID {0} in {1} but agent is not in transit",
id, m_mod.Scene.RegionInfo.RegionName));
if (currentState != AgentTransferState.Transferring && currentState != AgentTransferState.ReceivedAtDestination)
throw new Exception(
string.Format(
"Asked to wait for destination callback for agent with ID {0} in {1} but agent is in state {2}",
id, m_mod.Scene.RegionInfo.RegionName, currentState));
}
int count = 400;
// There should be no race condition here since no other code should be removing the agent transfer or
// changing the state to another other than Transferring => ReceivedAtDestination.
while (count-- > 0)
{
lock (m_agentsInTransit)
{
if (m_agentsInTransit[id] == AgentTransferState.ReceivedAtDestination)
break;
}
// m_log.Debug(" >>> Waiting... " + count);
Thread.Sleep(100);
}
return count > 0;
}
internal void SetAgentArrivedAtDestination(UUID id)
{
lock (m_agentsInTransit)
{
if (!m_agentsInTransit.ContainsKey(id))
{
m_log.WarnFormat(
"[ENTITY TRANSFER STATE MACHINE]: Region {0} received notification of arrival in destination of agent {1} but no teleport request is active",
m_mod.Scene.RegionInfo.RegionName, id);
return;
}
AgentTransferState currentState = m_agentsInTransit[id];
if (currentState == AgentTransferState.ReceivedAtDestination)
{
// An anomoly but don't make this an outright failure - destination region could be overzealous in sending notification.
m_log.WarnFormat(
"[ENTITY TRANSFER STATE MACHINE]: Region {0} received notification of arrival in destination of agent {1} but notification has already previously been received",
m_mod.Scene.RegionInfo.RegionName, id);
}
else if (currentState != AgentTransferState.Transferring)
{
m_log.ErrorFormat(
"[ENTITY TRANSFER STATE MACHINE]: Region {0} received notification of arrival in destination of agent {1} but agent is in state {2}",
m_mod.Scene.RegionInfo.RegionName, id, currentState);
return;
}
m_agentsInTransit[id] = AgentTransferState.ReceivedAtDestination;
}
}
}
}
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
// ReSharper disable ConditionIsAlwaysTrueOrFalse (we're allowing nulls to be passed to the writer where the underlying class doesn't).
// ReSharper disable HeuristicUnreachableCode
namespace osu.Game.IO.Legacy
{
/// <summary> SerializationWriter. Extends BinaryWriter to add additional data types,
/// handle null strings and simplify use with ISerializable. </summary>
public class SerializationWriter : BinaryWriter
{
public SerializationWriter(Stream s)
: base(s, Encoding.UTF8)
{
}
/// <summary> Static method to initialise the writer with a suitable MemoryStream. </summary>
public static SerializationWriter GetWriter()
{
MemoryStream ms = new MemoryStream(1024);
return new SerializationWriter(ms);
}
/// <summary> Writes a string to the buffer. Overrides the base implementation so it can cope with nulls </summary>
public override void Write(string str)
{
if (str == null)
{
Write((byte)ObjType.nullType);
}
else
{
Write((byte)ObjType.stringType);
base.Write(str);
}
}
/// <summary> Writes a byte array to the buffer. Overrides the base implementation to
/// send the length of the array which is needed when it is retrieved </summary>
public override void Write(byte[] b)
{
if (b == null)
{
Write(-1);
}
else
{
int len = b.Length;
Write(len);
if (len > 0) base.Write(b);
}
}
/// <summary> Writes a char array to the buffer. Overrides the base implementation to
/// sends the length of the array which is needed when it is read. </summary>
public override void Write(char[] c)
{
if (c == null)
{
Write(-1);
}
else
{
int len = c.Length;
Write(len);
if (len > 0) base.Write(c);
}
}
/// <summary>
/// Writes DateTime to the buffer.
/// </summary>
/// <param name="dt"></param>
public void Write(DateTime dt)
{
Write(dt.ToUniversalTime().Ticks);
}
/// <summary> Writes a generic ICollection (such as an IList(T)) to the buffer.</summary>
public void Write<T>(List<T> c) where T : ILegacySerializable
{
if (c == null)
{
Write(-1);
}
else
{
int count = c.Count;
Write(count);
for (int i = 0; i < count; i++)
c[i].WriteToStream(this);
}
}
/// <summary> Writes a generic IDictionary to the buffer. </summary>
public void Write<T, U>(IDictionary<T, U> d)
{
if (d == null)
{
Write(-1);
}
else
{
Write(d.Count);
foreach (KeyValuePair<T, U> kvp in d)
{
WriteObject(kvp.Key);
WriteObject(kvp.Value);
}
}
}
/// <summary> Writes an arbitrary object to the buffer. Useful where we have something of type "object"
/// and don't know how to treat it. This works out the best method to use to write to the buffer. </summary>
public void WriteObject(object obj)
{
if (obj == null)
{
Write((byte)ObjType.nullType);
}
else
{
switch (obj.GetType().Name)
{
case "Boolean":
Write((byte)ObjType.boolType);
Write((bool)obj);
break;
case "Byte":
Write((byte)ObjType.byteType);
Write((byte)obj);
break;
case "UInt16":
Write((byte)ObjType.uint16Type);
Write((ushort)obj);
break;
case "UInt32":
Write((byte)ObjType.uint32Type);
Write((uint)obj);
break;
case "UInt64":
Write((byte)ObjType.uint64Type);
Write((ulong)obj);
break;
case "SByte":
Write((byte)ObjType.sbyteType);
Write((sbyte)obj);
break;
case "Int16":
Write((byte)ObjType.int16Type);
Write((short)obj);
break;
case "Int32":
Write((byte)ObjType.int32Type);
Write((int)obj);
break;
case "Int64":
Write((byte)ObjType.int64Type);
Write((long)obj);
break;
case "Char":
Write((byte)ObjType.charType);
base.Write((char)obj);
break;
case "String":
Write((byte)ObjType.stringType);
base.Write((string)obj);
break;
case "Single":
Write((byte)ObjType.singleType);
Write((float)obj);
break;
case "Double":
Write((byte)ObjType.doubleType);
Write((double)obj);
break;
case "Decimal":
Write((byte)ObjType.decimalType);
Write((decimal)obj);
break;
case "DateTime":
Write((byte)ObjType.dateTimeType);
Write((DateTime)obj);
break;
case "Byte[]":
Write((byte)ObjType.byteArrayType);
base.Write((byte[])obj);
break;
case "Char[]":
Write((byte)ObjType.charArrayType);
base.Write((char[])obj);
break;
default:
Write((byte)ObjType.otherType);
BinaryFormatter b = new BinaryFormatter
{
// AssemblyFormat = FormatterAssemblyStyle.Simple,
TypeFormat = FormatterTypeStyle.TypesWhenNeeded
};
b.Serialize(BaseStream, obj);
break;
} // switch
} // if obj==null
} // WriteObject
/// <summary> Adds the SerializationWriter buffer to the SerializationInfo at the end of GetObjectData(). </summary>
public void AddToInfo(SerializationInfo info)
{
byte[] b = ((MemoryStream)BaseStream).ToArray();
info.AddValue("X", b, typeof(byte[]));
}
public void WriteRawBytes(byte[] b)
{
base.Write(b);
}
public void WriteByteArray(byte[] b)
{
if (b == null)
{
Write(-1);
}
else
{
int len = b.Length;
Write(len);
if (len > 0) base.Write(b);
}
}
public void WriteUtf8(string str)
{
WriteRawBytes(Encoding.UTF8.GetBytes(str));
}
}
}
| |
// 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.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using ControlzEx;
using ControlzEx.Theming;
using MahApps.Metro.Automation.Peers;
using MahApps.Metro.ValueBoxes;
namespace MahApps.Metro.Controls
{
/// <summary>
/// A sliding panel control that is hosted in a <see cref="MetroWindow"/> via a <see cref="FlyoutsControl"/>.
/// </summary>
[TemplatePart(Name = "PART_Root", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_Header", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_Content", Type = typeof(FrameworkElement))]
public class Flyout : HeaderedContentControl
{
public static readonly RoutedEvent IsOpenChangedEvent =
EventManager.RegisterRoutedEvent(nameof(IsOpenChanged),
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(Flyout));
/// <summary>
/// An event that is raised when <see cref="IsOpen"/> property changes.
/// </summary>
public event RoutedEventHandler IsOpenChanged
{
add => this.AddHandler(IsOpenChangedEvent, value);
remove => this.RemoveHandler(IsOpenChangedEvent, value);
}
public static readonly RoutedEvent OpeningFinishedEvent =
EventManager.RegisterRoutedEvent(nameof(OpeningFinished),
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(Flyout));
/// <summary>
/// An event that is raised when the opening animation has finished.
/// </summary>
public event RoutedEventHandler OpeningFinished
{
add => this.AddHandler(OpeningFinishedEvent, value);
remove => this.RemoveHandler(OpeningFinishedEvent, value);
}
public static readonly RoutedEvent ClosingFinishedEvent =
EventManager.RegisterRoutedEvent(nameof(ClosingFinished),
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(Flyout));
/// <summary>
/// An event that is raised when the closing animation has finished.
/// </summary>
public event RoutedEventHandler ClosingFinished
{
add => this.AddHandler(ClosingFinishedEvent, value);
remove => this.RemoveHandler(ClosingFinishedEvent, value);
}
public static readonly DependencyProperty PositionProperty =
DependencyProperty.Register(nameof(Position),
typeof(Position),
typeof(Flyout),
new PropertyMetadata(Position.Left, OnPositionPropertyChanged));
private static void OnPositionPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var flyout = (Flyout)dependencyObject;
var wasOpen = flyout.IsOpen;
if (wasOpen && flyout.AnimateOnPositionChange)
{
flyout.ApplyAnimation((Position)e.NewValue, flyout.AnimateOpacity);
VisualStateManager.GoToState(flyout, "Hide", true);
}
else
{
flyout.ApplyAnimation((Position)e.NewValue, flyout.AnimateOpacity, false);
}
if (wasOpen && flyout.AnimateOnPositionChange)
{
flyout.ApplyAnimation((Position)e.NewValue, flyout.AnimateOpacity);
VisualStateManager.GoToState(flyout, "Show", true);
}
}
/// <summary>
/// Gets or sets the position of this <see cref="Flyout"/> inside the <see cref="FlyoutsControl"/>.
/// </summary>
public Position Position
{
get => (Position)this.GetValue(PositionProperty);
set => this.SetValue(PositionProperty, value);
}
public static readonly DependencyProperty IsPinnedProperty
= DependencyProperty.Register(nameof(IsPinned),
typeof(bool),
typeof(Flyout),
new PropertyMetadata(BooleanBoxes.TrueBox));
/// <summary>
/// Gets or sets whether this <see cref="Flyout"/> stays open when the user clicks somewhere outside of it.
/// </summary>
public bool IsPinned
{
get => (bool)this.GetValue(IsPinnedProperty);
set => this.SetValue(IsPinnedProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty IsOpenProperty
= DependencyProperty.Register(nameof(IsOpen),
typeof(bool),
typeof(Flyout),
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsOpenPropertyChanged));
private static void OnIsOpenPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var flyout = (Flyout)dependencyObject;
Action openedChangedAction = () =>
{
if (e.NewValue != e.OldValue)
{
if (flyout.AreAnimationsEnabled)
{
if ((bool)e.NewValue)
{
if (flyout.hideStoryboard != null)
{
// don't let the storyboard end it's completed event
// otherwise it could be hidden on start
flyout.hideStoryboard.Completed -= flyout.HideStoryboardCompleted;
}
flyout.Visibility = Visibility.Visible;
flyout.ApplyAnimation(flyout.Position, flyout.AnimateOpacity);
flyout.TryFocusElement();
if (flyout.showStoryboard != null)
{
flyout.showStoryboard.Completed += flyout.ShowStoryboardCompleted;
}
else
{
flyout.Shown();
}
if (flyout.IsAutoCloseEnabled)
{
flyout.StartAutoCloseTimer();
}
}
else
{
if (flyout.showStoryboard != null)
{
flyout.showStoryboard.Completed -= flyout.ShowStoryboardCompleted;
}
flyout.StopAutoCloseTimer();
flyout.SetValue(IsShownPropertyKey, BooleanBoxes.FalseBox);
if (flyout.hideStoryboard != null)
{
flyout.hideStoryboard.Completed += flyout.HideStoryboardCompleted;
}
else
{
flyout.Hide();
}
}
VisualStateManager.GoToState(flyout, (bool)e.NewValue == false ? "Hide" : "Show", true);
}
else
{
if ((bool)e.NewValue)
{
flyout.Visibility = Visibility.Visible;
flyout.TryFocusElement();
flyout.Shown();
if (flyout.IsAutoCloseEnabled)
{
flyout.StartAutoCloseTimer();
}
}
else
{
flyout.StopAutoCloseTimer();
flyout.SetValue(IsShownPropertyKey, BooleanBoxes.FalseBox);
flyout.Hide();
}
VisualStateManager.GoToState(flyout, (bool)e.NewValue == false ? "HideDirect" : "ShowDirect", true);
}
}
flyout.RaiseEvent(new RoutedEventArgs(IsOpenChangedEvent));
};
flyout.Dispatcher.BeginInvoke(DispatcherPriority.Background, openedChangedAction);
}
/// <summary>
/// Gets or sets whether this <see cref="Flyout"/> should be visible or not.
/// </summary>
public bool IsOpen
{
get => (bool)this.GetValue(IsOpenProperty);
set => this.SetValue(IsOpenProperty, BooleanBoxes.Box(value));
}
/// <summary>Identifies the <see cref="IsShown"/> dependency property.</summary>
private static readonly DependencyPropertyKey IsShownPropertyKey
= DependencyProperty.RegisterReadOnly(nameof(IsShown),
typeof(bool),
typeof(Flyout),
new PropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>Identifies the <see cref="IsShown"/> dependency property.</summary>
public static readonly DependencyProperty IsShownProperty = IsShownPropertyKey.DependencyProperty;
/// <summary>
/// Gets whether the <see cref="Flyout"/> is completely shown (after <see cref="IsOpen"/> was set to true).
/// </summary>
public bool IsShown
{
get => (bool)this.GetValue(IsShownProperty);
protected set => this.SetValue(IsShownPropertyKey, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty AnimateOnPositionChangeProperty
= DependencyProperty.Register(nameof(AnimateOnPositionChange),
typeof(bool),
typeof(Flyout),
new PropertyMetadata(BooleanBoxes.TrueBox));
/// <summary>
/// Gets or sets whether this <see cref="Flyout"/> uses the open/close animation when changing the <see cref="Position"/> property (default is true).
/// </summary>
public bool AnimateOnPositionChange
{
get => (bool)this.GetValue(AnimateOnPositionChangeProperty);
set => this.SetValue(AnimateOnPositionChangeProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty AnimateOpacityProperty
= DependencyProperty.Register(nameof(AnimateOpacity),
typeof(bool),
typeof(Flyout),
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, (d, args) => (d as Flyout)?.UpdateOpacityChange()));
/// <summary>
/// Gets or sets whether this <see cref="Flyout"/> animates the opacity when opening/closing the <see cref="Flyout"/>.
/// </summary>
public bool AnimateOpacity
{
get => (bool)this.GetValue(AnimateOpacityProperty);
set => this.SetValue(AnimateOpacityProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty IsModalProperty
= DependencyProperty.Register(nameof(IsModal),
typeof(bool),
typeof(Flyout),
new PropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>
/// Gets or sets whether this <see cref="Flyout"/> is modal.
/// </summary>
public bool IsModal
{
get => (bool)this.GetValue(IsModalProperty);
set => this.SetValue(IsModalProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty CloseCommandProperty
= DependencyProperty.RegisterAttached(nameof(CloseCommand),
typeof(ICommand),
typeof(Flyout),
new UIPropertyMetadata(null));
/// <summary>
/// Gets or sets a <see cref="ICommand"/> which will be executed if the close button was clicked.
/// </summary>
/// <remarks>
/// The <see cref="ICommand"/> won't be executed when <see cref="IsOpen"/> property will be set to false/true.
/// </remarks>
public ICommand? CloseCommand
{
get => (ICommand?)this.GetValue(CloseCommandProperty);
set => this.SetValue(CloseCommandProperty, value);
}
public static readonly DependencyProperty CloseCommandParameterProperty
= DependencyProperty.Register(nameof(CloseCommandParameter),
typeof(object),
typeof(Flyout),
new PropertyMetadata(null));
/// <summary>
/// Gets or sets the parameter for the <see cref="CloseCommand"/>.
/// </summary>
public object? CloseCommandParameter
{
get => this.GetValue(CloseCommandParameterProperty);
set => this.SetValue(CloseCommandParameterProperty, value);
}
public static readonly DependencyProperty ThemeProperty
= DependencyProperty.Register(nameof(Theme),
typeof(FlyoutTheme),
typeof(Flyout),
new FrameworkPropertyMetadata(FlyoutTheme.Dark, (d, args) => (d as Flyout)?.UpdateFlyoutTheme()));
/// <summary>
/// Gets or sets the theme for the <see cref="Flyout"/>.
/// </summary>
public FlyoutTheme Theme
{
get => (FlyoutTheme)this.GetValue(ThemeProperty);
set => this.SetValue(ThemeProperty, value);
}
public static readonly DependencyProperty ExternalCloseButtonProperty
= DependencyProperty.Register(nameof(ExternalCloseButton),
typeof(MouseButton),
typeof(Flyout),
new PropertyMetadata(MouseButton.Left));
/// <summary>
/// Gets or sets the mouse button that closes the <see cref="Flyout"/> when the user clicks somewhere outside of it.
/// </summary>
public MouseButton ExternalCloseButton
{
get => (MouseButton)this.GetValue(ExternalCloseButtonProperty);
set => this.SetValue(ExternalCloseButtonProperty, value);
}
public static readonly DependencyProperty CloseButtonVisibilityProperty
= DependencyProperty.Register(nameof(CloseButtonVisibility),
typeof(Visibility),
typeof(Flyout),
new FrameworkPropertyMetadata(Visibility.Visible));
/// <summary>
/// Gets or sets the visibility of the close button for this <see cref="Flyout"/>.
/// </summary>
public Visibility CloseButtonVisibility
{
get => (Visibility)this.GetValue(CloseButtonVisibilityProperty);
set => this.SetValue(CloseButtonVisibilityProperty, value);
}
public static readonly DependencyProperty CloseButtonIsCancelProperty
= DependencyProperty.Register(nameof(CloseButtonIsCancel),
typeof(bool),
typeof(Flyout),
new PropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>
/// Gets or sets a value that indicates whether the close button is a Cancel button. A user can activate the Cancel button by pressing the ESC key.
/// </summary>
public bool CloseButtonIsCancel
{
get => (bool)this.GetValue(CloseButtonIsCancelProperty);
set => this.SetValue(CloseButtonIsCancelProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty TitleVisibilityProperty
= DependencyProperty.Register(nameof(TitleVisibility),
typeof(Visibility),
typeof(Flyout),
new FrameworkPropertyMetadata(Visibility.Visible));
/// <summary>
/// Gets or sets the visibility of the title.
/// </summary>
public Visibility TitleVisibility
{
get => (Visibility)this.GetValue(TitleVisibilityProperty);
set => this.SetValue(TitleVisibilityProperty, value);
}
public static readonly DependencyProperty AreAnimationsEnabledProperty
= DependencyProperty.Register(nameof(AreAnimationsEnabled),
typeof(bool),
typeof(Flyout),
new PropertyMetadata(BooleanBoxes.TrueBox));
/// <summary>
/// Gets or sets a value that indicates whether the <see cref="Flyout"/> uses animations for open/close.
/// </summary>
public bool AreAnimationsEnabled
{
get => (bool)this.GetValue(AreAnimationsEnabledProperty);
set => this.SetValue(AreAnimationsEnabledProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty FocusedElementProperty
= DependencyProperty.Register(nameof(FocusedElement),
typeof(FrameworkElement),
typeof(Flyout),
new UIPropertyMetadata(null));
/// <summary>
/// Gets or sets the focused element.
/// </summary>
public FrameworkElement? FocusedElement
{
get => (FrameworkElement?)this.GetValue(FocusedElementProperty);
set => this.SetValue(FocusedElementProperty, value);
}
public static readonly DependencyProperty AllowFocusElementProperty
= DependencyProperty.Register(nameof(AllowFocusElement),
typeof(bool),
typeof(Flyout),
new PropertyMetadata(BooleanBoxes.TrueBox));
/// <summary>
/// Gets or sets a value indicating whether the <see cref="Flyout"/> should try focus an element.
/// </summary>
public bool AllowFocusElement
{
get => (bool)this.GetValue(AllowFocusElementProperty);
set => this.SetValue(AllowFocusElementProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty IsAutoCloseEnabledProperty
= DependencyProperty.Register(nameof(IsAutoCloseEnabled),
typeof(bool),
typeof(Flyout),
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, OnIsAutoCloseEnabledPropertyChanged));
private static void OnIsAutoCloseEnabledPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var flyout = (Flyout)dependencyObject;
Action autoCloseEnabledChangedAction = () =>
{
if (e.NewValue != e.OldValue)
{
if ((bool)e.NewValue)
{
if (flyout.IsOpen)
{
flyout.StartAutoCloseTimer();
}
}
else
{
flyout.StopAutoCloseTimer();
}
}
};
flyout.Dispatcher.BeginInvoke(DispatcherPriority.Background, autoCloseEnabledChangedAction);
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="Flyout"/> should auto close after the <see cref="AutoCloseInterval"/> has passed.
/// </summary>
public bool IsAutoCloseEnabled
{
get => (bool)this.GetValue(IsAutoCloseEnabledProperty);
set => this.SetValue(IsAutoCloseEnabledProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty AutoCloseIntervalProperty
= DependencyProperty.Register(nameof(AutoCloseInterval),
typeof(long),
typeof(Flyout),
new FrameworkPropertyMetadata(5000L, AutoCloseIntervalChanged));
private static void AutoCloseIntervalChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var flyout = (Flyout)dependencyObject;
Action autoCloseIntervalChangedAction = () =>
{
if (e.NewValue != e.OldValue)
{
flyout.InitializeAutoCloseTimer();
if (flyout.IsAutoCloseEnabled && flyout.IsOpen)
{
flyout.StartAutoCloseTimer();
}
}
};
flyout.Dispatcher.BeginInvoke(DispatcherPriority.Background, autoCloseIntervalChangedAction);
}
/// <summary>
/// Gets or sets the time in milliseconds when the <see cref="Flyout"/> should auto close.
/// </summary>
public long AutoCloseInterval
{
get => (long)this.GetValue(AutoCloseIntervalProperty);
set => this.SetValue(AutoCloseIntervalProperty, value);
}
/// <summary>Identifies the <see cref="Owner"/> dependency property.</summary>
private static readonly DependencyPropertyKey OwnerPropertyKey =
DependencyProperty.RegisterReadOnly(nameof(Owner),
typeof(FlyoutsControl),
typeof(Flyout),
new PropertyMetadata(null));
/// <summary>Identifies the <see cref="Owner"/> dependency property.</summary>
public static readonly DependencyProperty OwnerProperty = OwnerPropertyKey.DependencyProperty;
public FlyoutsControl? Owner
{
get => (FlyoutsControl?)this.GetValue(OwnerProperty);
protected set => this.SetValue(OwnerPropertyKey, value);
}
private DispatcherTimer? autoCloseTimer;
private FrameworkElement? flyoutRoot;
private Storyboard? showStoryboard;
private Storyboard? hideStoryboard;
private SplineDoubleKeyFrame? hideFrame;
private SplineDoubleKeyFrame? hideFrameY;
private SplineDoubleKeyFrame? showFrame;
private SplineDoubleKeyFrame? showFrameY;
private SplineDoubleKeyFrame? fadeOutFrame;
private FrameworkElement? flyoutHeader;
private FrameworkElement? flyoutContent;
private MetroWindow? parentWindow;
private MetroWindow? ParentWindow => this.parentWindow ??= this.TryFindParent<MetroWindow>();
/// <summary>
/// <see cref="IsOpen"/> property changed notifier used in <see cref="FlyoutsControl"/>.
/// </summary>
internal PropertyChangeNotifier? IsOpenPropertyChangeNotifier { get; set; }
/// <summary>
/// <see cref="Theme"/> property changed notifier used in <see cref="FlyoutsControl"/>.
/// </summary>
internal PropertyChangeNotifier? ThemePropertyChangeNotifier { get; set; }
static Flyout()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Flyout), new FrameworkPropertyMetadata(typeof(Flyout)));
}
public Flyout()
{
this.Loaded += (sender, args) => this.UpdateFlyoutTheme();
this.InitializeAutoCloseTimer();
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new FlyoutAutomationPeer(this);
}
private void InitializeAutoCloseTimer()
{
this.StopAutoCloseTimer();
this.autoCloseTimer = new DispatcherTimer();
this.autoCloseTimer.Tick += this.AutoCloseTimerCallback;
this.autoCloseTimer.Interval = TimeSpan.FromMilliseconds(this.AutoCloseInterval);
}
private void StartAutoCloseTimer()
{
// in case it is already running
this.StopAutoCloseTimer();
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
this.autoCloseTimer?.Start();
}
}
private void StopAutoCloseTimer()
{
if (this.autoCloseTimer != null && this.autoCloseTimer.IsEnabled)
{
this.autoCloseTimer.Stop();
}
}
private void AutoCloseTimerCallback(object? sender, EventArgs e)
{
this.StopAutoCloseTimer();
// if the flyout is open and auto close is still enabled then close the flyout
if (this.IsOpen && this.IsAutoCloseEnabled)
{
this.SetCurrentValue(IsOpenProperty, BooleanBoxes.FalseBox);
}
}
private void UpdateFlyoutTheme()
{
if (this.IsLoaded == false)
{
return;
}
var flyoutsControl = this.Owner ?? this.TryFindParent<FlyoutsControl>();
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
this.SetCurrentValue(VisibilityProperty, flyoutsControl != null ? Visibility.Collapsed : Visibility.Visible);
}
var window = this.ParentWindow;
if (window != null)
{
var windowTheme = DetectTheme(this);
if (windowTheme != null)
{
this.ChangeFlyoutTheme(windowTheme);
}
// we must certain to get the right foreground for window commands and buttons
if (flyoutsControl != null && this.IsOpen)
{
flyoutsControl.HandleFlyoutStatusChange(this, window);
}
}
}
private static ControlzEx.Theming.Theme? DetectTheme(Flyout? flyout)
{
if (flyout is null)
{
return null;
}
// first look for owner
var window = flyout.ParentWindow;
var theme = window != null ? ThemeManager.Current.DetectTheme(window) : null;
if (theme != null)
{
return theme;
}
// second try, look for main window and then for current application
if (Application.Current != null)
{
theme = Application.Current.MainWindow is null
? ThemeManager.Current.DetectTheme(Application.Current)
: ThemeManager.Current.DetectTheme(Application.Current.MainWindow);
if (theme != null)
{
return theme;
}
}
return null;
}
internal void ChangeFlyoutTheme(ControlzEx.Theming.Theme windowTheme)
{
if (windowTheme == ThemeManager.Current.DetectTheme(this.Resources))
{
return;
}
switch (this.Theme)
{
case FlyoutTheme.Adapt:
ThemeManager.Current.ApplyThemeResourcesFromTheme(this.Resources, windowTheme);
break;
case FlyoutTheme.Inverse:
var inverseTheme = ThemeManager.Current.GetInverseTheme(windowTheme);
if (inverseTheme is null)
{
throw new InvalidOperationException("The inverse Flyout theme only works if the window theme abides the naming convention. " +
"See ThemeManager.GetInverseAppTheme for more infos");
}
ThemeManager.Current.ApplyThemeResourcesFromTheme(this.Resources, inverseTheme);
break;
case FlyoutTheme.Dark:
var darkTheme = windowTheme.BaseColorScheme == ThemeManager.BaseColorDark ? windowTheme : ThemeManager.Current.GetInverseTheme(windowTheme);
if (darkTheme is null)
{
throw new InvalidOperationException("The Dark Flyout theme only works if the window theme abides the naming convention. " +
"See ThemeManager.GetInverseAppTheme for more infos");
}
ThemeManager.Current.ApplyThemeResourcesFromTheme(this.Resources, darkTheme);
break;
case FlyoutTheme.Light:
var lightTheme = windowTheme.BaseColorScheme == ThemeManager.BaseColorLight ? windowTheme : ThemeManager.Current.GetInverseTheme(windowTheme);
if (lightTheme is null)
{
throw new InvalidOperationException("The Light Flyout theme only works if the window theme abides the naming convention. " +
"See ThemeManager.GetInverseAppTheme for more infos");
}
ThemeManager.Current.ApplyThemeResourcesFromTheme(this.Resources, lightTheme);
break;
}
}
private void UpdateOpacityChange()
{
if (this.flyoutRoot is null || this.fadeOutFrame is null || System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
return;
}
if (!this.AnimateOpacity)
{
this.fadeOutFrame.Value = 1;
this.flyoutRoot.Opacity = 1;
}
else
{
this.fadeOutFrame.Value = 0;
if (!this.IsOpen)
{
this.flyoutRoot.Opacity = 0;
}
}
}
private void HideStoryboardCompleted(object? sender, EventArgs e)
{
if (this.hideStoryboard is not null)
{
this.hideStoryboard.Completed -= this.HideStoryboardCompleted;
}
this.Hide();
}
private void Hide()
{
// hide the flyout, we should get better performance and prevent showing the flyout on any resizing events
this.Visibility = Visibility.Hidden;
this.RaiseEvent(new RoutedEventArgs(ClosingFinishedEvent));
}
private void ShowStoryboardCompleted(object? sender, EventArgs e)
{
if (this.showStoryboard is not null)
{
this.showStoryboard.Completed -= this.ShowStoryboardCompleted;
}
this.Shown();
}
private void Shown()
{
this.SetValue(IsShownPropertyKey, BooleanBoxes.TrueBox);
this.RaiseEvent(new RoutedEventArgs(OpeningFinishedEvent));
}
private void TryFocusElement()
{
if (this.AllowFocusElement)
{
// first focus itself
this.Focus();
if (this.FocusedElement != null)
{
this.FocusedElement.Focus();
}
else if (this.flyoutContent is null || !this.flyoutContent.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)))
{
this.flyoutHeader?.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
}
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var flyoutsControl = ItemsControl.ItemsControlFromItemContainer(this) as FlyoutsControl ?? this.TryFindParent<FlyoutsControl>();
this.SetValue(OwnerPropertyKey, flyoutsControl);
this.flyoutRoot = this.GetTemplateChild("PART_Root") as FrameworkElement;
if (this.flyoutRoot is null)
{
return;
}
this.flyoutHeader = this.GetTemplateChild("PART_Header") as FrameworkElement;
this.flyoutHeader?.ApplyTemplate();
this.flyoutContent = this.GetTemplateChild("PART_Content") as FrameworkElement;
if (this.flyoutHeader is IMetroThumb thumb)
{
thumb.PreviewMouseLeftButtonUp -= this.HeaderThumbOnPreviewMouseLeftButtonUp;
thumb.DragDelta -= this.HeaderThumbMoveOnDragDelta;
thumb.MouseDoubleClick -= this.HeaderThumbChangeWindowStateOnMouseDoubleClick;
thumb.MouseRightButtonUp -= this.HeaderThumbSystemMenuOnMouseRightButtonUp;
thumb.PreviewMouseLeftButtonUp += this.HeaderThumbOnPreviewMouseLeftButtonUp;
thumb.DragDelta += this.HeaderThumbMoveOnDragDelta;
thumb.MouseDoubleClick += this.HeaderThumbChangeWindowStateOnMouseDoubleClick;
thumb.MouseRightButtonUp += this.HeaderThumbSystemMenuOnMouseRightButtonUp;
}
#pragma warning disable WPF0130 // Add [TemplatePart] to the type.
this.showStoryboard = this.GetTemplateChild("ShowStoryboard") as Storyboard;
this.hideStoryboard = this.GetTemplateChild("HideStoryboard") as Storyboard;
this.hideFrame = this.GetTemplateChild("hideFrame") as SplineDoubleKeyFrame;
this.hideFrameY = this.GetTemplateChild("hideFrameY") as SplineDoubleKeyFrame;
this.showFrame = this.GetTemplateChild("showFrame") as SplineDoubleKeyFrame;
this.showFrameY = this.GetTemplateChild("showFrameY") as SplineDoubleKeyFrame;
this.fadeOutFrame = this.GetTemplateChild("fadeOutFrame") as SplineDoubleKeyFrame;
#pragma warning restore WPF0130 // Add [TemplatePart] to the type.
if (this.hideFrame is null || this.showFrame is null || this.hideFrameY is null || this.showFrameY is null || this.fadeOutFrame is null)
{
return;
}
this.ApplyAnimation(this.Position, this.AnimateOpacity);
}
internal void CleanUp()
{
if (this.flyoutHeader is IMetroThumb thumb)
{
thumb.PreviewMouseLeftButtonUp -= this.HeaderThumbOnPreviewMouseLeftButtonUp;
thumb.DragDelta -= this.HeaderThumbMoveOnDragDelta;
thumb.MouseDoubleClick -= this.HeaderThumbChangeWindowStateOnMouseDoubleClick;
thumb.MouseRightButtonUp -= this.HeaderThumbSystemMenuOnMouseRightButtonUp;
}
this.parentWindow = null;
}
private void HeaderThumbOnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var window = this.ParentWindow;
if (window != null && this.Position != Position.Bottom)
{
MetroWindow.DoWindowTitleThumbOnPreviewMouseLeftButtonUp(window, e);
}
}
private void HeaderThumbMoveOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs)
{
var window = this.ParentWindow;
if (window != null && this.Position != Position.Bottom)
{
MetroWindow.DoWindowTitleThumbMoveOnDragDelta(sender as IMetroThumb, window, dragDeltaEventArgs);
}
}
private void HeaderThumbChangeWindowStateOnMouseDoubleClick(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var window = this.ParentWindow;
if (window != null && this.Position != Position.Bottom && Mouse.GetPosition((IInputElement)sender).Y <= window.TitleBarHeight && window.TitleBarHeight > 0)
{
MetroWindow.DoWindowTitleThumbChangeWindowStateOnMouseDoubleClick(window, mouseButtonEventArgs);
}
}
private void HeaderThumbSystemMenuOnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
var window = this.ParentWindow;
if (window != null && this.Position != Position.Bottom && Mouse.GetPosition((IInputElement)sender).Y <= window.TitleBarHeight && window.TitleBarHeight > 0)
{
MetroWindow.DoWindowTitleThumbSystemMenuOnMouseRightButtonUp(window, e);
}
}
internal void ApplyAnimation(Position position, bool animateOpacity, bool resetShowFrame = true)
{
if (this.flyoutRoot is null || this.hideFrame is null || this.showFrame is null || this.hideFrameY is null || this.showFrameY is null || this.fadeOutFrame is null)
{
return;
}
if (this.Position == Position.Left || this.Position == Position.Right)
{
this.showFrame.Value = 0;
}
if (this.Position == Position.Top || this.Position == Position.Bottom)
{
this.showFrameY.Value = 0;
}
if (!animateOpacity)
{
this.fadeOutFrame.Value = 1;
this.flyoutRoot.Opacity = 1;
}
else
{
this.fadeOutFrame.Value = 0;
if (!this.IsOpen)
{
this.flyoutRoot.Opacity = 0;
}
}
switch (position)
{
default:
this.HorizontalAlignment = this.Margin.Right <= 0 ? this.HorizontalContentAlignment != HorizontalAlignment.Stretch ? HorizontalAlignment.Left : this.HorizontalContentAlignment : HorizontalAlignment.Stretch;
this.VerticalAlignment = VerticalAlignment.Stretch;
this.hideFrame.Value = -this.flyoutRoot.ActualWidth - this.Margin.Left;
if (resetShowFrame)
{
this.flyoutRoot.RenderTransform = new TranslateTransform(-this.flyoutRoot.ActualWidth, 0);
}
break;
case Position.Right:
this.HorizontalAlignment = this.Margin.Left <= 0 ? this.HorizontalContentAlignment != HorizontalAlignment.Stretch ? HorizontalAlignment.Right : this.HorizontalContentAlignment : HorizontalAlignment.Stretch;
this.VerticalAlignment = VerticalAlignment.Stretch;
this.hideFrame.Value = this.flyoutRoot.ActualWidth + this.Margin.Right;
if (resetShowFrame)
{
this.flyoutRoot.RenderTransform = new TranslateTransform(this.flyoutRoot.ActualWidth, 0);
}
break;
case Position.Top:
this.HorizontalAlignment = HorizontalAlignment.Stretch;
this.VerticalAlignment = this.Margin.Bottom <= 0 ? this.VerticalContentAlignment != VerticalAlignment.Stretch ? VerticalAlignment.Top : this.VerticalContentAlignment : VerticalAlignment.Stretch;
this.hideFrameY.Value = -this.flyoutRoot.ActualHeight - 1 - this.Margin.Top;
if (resetShowFrame)
{
this.flyoutRoot.RenderTransform = new TranslateTransform(0, -this.flyoutRoot.ActualHeight - 1);
}
break;
case Position.Bottom:
this.HorizontalAlignment = HorizontalAlignment.Stretch;
this.VerticalAlignment = this.Margin.Top <= 0 ? this.VerticalContentAlignment != VerticalAlignment.Stretch ? VerticalAlignment.Bottom : this.VerticalContentAlignment : VerticalAlignment.Stretch;
this.hideFrameY.Value = this.flyoutRoot.ActualHeight + this.Margin.Bottom;
if (resetShowFrame)
{
this.flyoutRoot.RenderTransform = new TranslateTransform(0, this.flyoutRoot.ActualHeight);
}
break;
}
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
if (!this.IsOpen)
{
return; // no changes for invisible flyouts, ApplyAnimation is called now in visible changed event
}
if (!sizeInfo.WidthChanged && !sizeInfo.HeightChanged)
{
return;
}
if (this.flyoutRoot is null || this.hideFrame is null || this.showFrame is null || this.hideFrameY is null || this.showFrameY is null)
{
return; // don't bother checking IsOpen and calling ApplyAnimation
}
if (this.Position == Position.Left || this.Position == Position.Right)
{
this.showFrame.Value = 0;
}
if (this.Position == Position.Top || this.Position == Position.Bottom)
{
this.showFrameY.Value = 0;
}
switch (this.Position)
{
default:
this.hideFrame.Value = -this.flyoutRoot.ActualWidth - this.Margin.Left;
break;
case Position.Right:
this.hideFrame.Value = this.flyoutRoot.ActualWidth + this.Margin.Right;
break;
case Position.Top:
this.hideFrameY.Value = -this.flyoutRoot.ActualHeight - 1 - this.Margin.Top;
break;
case Position.Bottom:
this.hideFrameY.Value = this.flyoutRoot.ActualHeight + this.Margin.Bottom;
break;
}
}
}
}
| |
using System;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using UIKit;
namespace Airbnb.Lottie
{
// @interface LOTAnimationTransitionController : NSObject <UIViewControllerAnimatedTransitioning>
[BaseType(typeof(NSObject))]
interface LOTAnimationTransitionController : IUIViewControllerAnimatedTransitioning
{
// -(instancetype _Nonnull)initWithAnimationNamed:(NSString * _Nonnull)animation fromLayerNamed:(NSString * _Nullable)fromLayer toLayerNamed:(NSString * _Nullable)toLayer applyAnimationTransform:(BOOL)applyAnimationTransform;
[Export("initWithAnimationNamed:fromLayerNamed:toLayerNamed:applyAnimationTransform:")]
IntPtr Constructor(string animation, [NullAllowed] string fromLayer, [NullAllowed] string toLayer, bool applyAnimationTransform);
// -(instancetype _Nonnull)initWithAnimationNamed:(NSString * _Nonnull)animation fromLayerNamed:(NSString * _Nullable)fromLayer toLayerNamed:(NSString * _Nullable)toLayer applyAnimationTransform:(BOOL)applyAnimationTransform inBundle:(NSBundle * _Nonnull)bundle;
[Export("initWithAnimationNamed:fromLayerNamed:toLayerNamed:applyAnimationTransform:inBundle:")]
IntPtr Constructor(string animation, [NullAllowed] string fromLayer, [NullAllowed] string toLayer, bool applyAnimationTransform, NSBundle bundle);
}
// @interface LOTAnimatedControl : UIControl
[BaseType(typeof(UIControl))]
interface LOTAnimatedControl
{
// -(void)setLayerName:(NSString * _Nonnull)layerName forState:(UIControlState)state;
[Export("setLayerName:forState:")]
void SetLayerName(string layerName, UIControlState state);
// @property (readonly, nonatomic) LOTAnimationView * _Nonnull animationView;
[Export("animationView")]
LOTAnimationView AnimationView { get; }
// @property (nonatomic) LOTComposition * _Nullable animationComp;
[NullAllowed, Export("animationComp", ArgumentSemantic.Assign)]
LOTComposition AnimationComp { get; set; }
}
// @interface LOTAnimatedSwitch : LOTAnimatedControl
[BaseType(typeof(LOTAnimatedControl))]
interface LOTAnimatedSwitch
{
// +(instancetype _Nonnull)switchNamed:(NSString * _Nonnull)toggleName;
[Static]
[Export("switchNamed:")]
LOTAnimatedSwitch SwitchNamed(string toggleName);
// +(instancetype _Nonnull)switchNamed:(NSString * _Nonnull)toggleName inBundle:(NSBundle * _Nonnull)bundle;
[Static]
[Export("switchNamed:inBundle:")]
LOTAnimatedSwitch SwitchNamed(string toggleName, NSBundle bundle);
// @property (getter = isOn, nonatomic) BOOL on;
[Export("on")]
bool On { [Bind("isOn")] get; set; }
// @property (nonatomic) BOOL interactiveGesture;
[Export("interactiveGesture")]
bool InteractiveGesture { get; set; }
// -(void)setOn:(BOOL)on animated:(BOOL)animated;
[Export("setOn:animated:")]
void SetOn(bool on, bool animated);
// -(void)setProgressRangeForOnState:(CGFloat)fromProgress toProgress:(CGFloat)toProgress;
[Export("setProgressRangeForOnState:toProgress:")]
void SetProgressRangeForOnState(nfloat fromProgress, nfloat toProgress);
// -(void)setProgressRangeForOffState:(CGFloat)fromProgress toProgress:(CGFloat)toProgress;
[Export("setProgressRangeForOffState:toProgress:")]
void SetProgressRangeForOffState(nfloat fromProgress, nfloat toProgress);
}
// @interface LOTCacheProvider : NSObject
[BaseType(typeof(NSObject))]
interface LOTCacheProvider
{
// +(id<LOTImageCache>)imageCache;
// +(void)setImageCache:(id<LOTImageCache>)cache;
[Static]
[Export("imageCache")]
LOTImageCache ImageCache { get; set; }
}
// @protocol LOTImageCache <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface LOTImageCache
{
// @required -(UIImage *)imageForKey:(NSString *)key;
[Abstract]
[Export("imageForKey:")]
UIImage ImageForKey(string key);
// @required -(void)setImage:(UIImage *)image forKey:(NSString *)key;
[Abstract]
[Export("setImage:forKey:")]
void SetImage(UIImage image, string key);
}
// @interface LOTComposition : NSObject
[BaseType(typeof(NSObject))]
interface LOTComposition
{
// +(instancetype _Nullable)animationNamed:(NSString * _Nonnull)animationName;
[Static]
[Export("animationNamed:")]
[return: NullAllowed]
LOTComposition AnimationNamed(string animationName);
// +(instancetype _Nullable)animationNamed:(NSString * _Nonnull)animationName inBundle:(NSBundle * _Nonnull)bundle;
[Static]
[Export("animationNamed:inBundle:")]
[return: NullAllowed]
LOTComposition AnimationNamed(string animationName, NSBundle bundle);
// +(instancetype _Nullable)animationWithFilePath:(NSString * _Nonnull)filePath;
[Static]
[Export("animationWithFilePath:")]
[return: NullAllowed]
LOTComposition AnimationWithFilePath(string filePath);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nonnull)animationJSON;
[Static]
[Export("animationFromJSON:")]
LOTComposition AnimationFromJSON(NSDictionary animationJSON);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nullable)animationJSON inBundle:(NSBundle * _Nullable)bundle;
[Static]
[Export("animationFromJSON:inBundle:")]
LOTComposition AnimationFromJSON([NullAllowed] NSDictionary animationJSON, [NullAllowed] NSBundle bundle);
// -(instancetype _Nonnull)initWithJSON:(NSDictionary * _Nullable)jsonDictionary withAssetBundle:(NSBundle * _Nullable)bundle;
[Export("initWithJSON:withAssetBundle:")]
IntPtr Constructor([NullAllowed] NSDictionary jsonDictionary, [NullAllowed] NSBundle bundle);
// @property (readonly, nonatomic) CGRect compBounds;
[Export("compBounds")]
CGRect CompBounds { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable startFrame;
[NullAllowed, Export("startFrame")]
NSNumber StartFrame { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable endFrame;
[NullAllowed, Export("endFrame")]
NSNumber EndFrame { get; }
// @property (readonly, nonatomic) NSNumber * _Nullable framerate;
[NullAllowed, Export("framerate")]
NSNumber Framerate { get; }
// @property (readonly, nonatomic) NSTimeInterval timeDuration;
[Export("timeDuration")]
double TimeDuration { get; }
// @property (readonly, nonatomic) LOTLayerGroup * _Nullable layerGroup;
//[NullAllowed, Export("layerGroup")]
//LOTLayerGroup LayerGroup { get; }
//// @property (readonly, nonatomic) LOTAssetGroup * _Nullable assetGroup;
//[NullAllowed, Export("assetGroup")]
//LOTAssetGroup AssetGroup { get; }
// @property (readwrite, nonatomic) NSString * _Nullable rootDirectory;
[NullAllowed, Export("rootDirectory")]
string RootDirectory { get; set; }
// @property (readonly, nonatomic) NSBundle * _Nullable assetBundle;
[NullAllowed, Export("assetBundle")]
NSBundle AssetBundle { get; }
// @property (copy, nonatomic) NSString * _Nullable cacheKey;
[NullAllowed, Export("cacheKey")]
string CacheKey { get; set; }
}
// @interface LOTKeypath : NSObject
[BaseType(typeof(NSObject))]
interface LOTKeypath
{
// +(LOTKeypath * _Nonnull)keypathWithString:(NSString * _Nonnull)keypath;
[Static]
[Export("keypathWithString:")]
LOTKeypath KeypathWithString(string keypath);
// +(LOTKeypath * _Nonnull)keypathWithKeys:(NSString * _Nonnull)firstKey, ... __attribute__((sentinel(0, 1)));
[Static, Internal]
[Export("keypathWithKeys:", IsVariadic = true)]
LOTKeypath KeypathWithKeys(string firstKey, IntPtr varArgs);
// @property (readonly, nonatomic) NSString * _Nonnull absoluteKeypath;
[Export("absoluteKeypath")]
string AbsoluteKeypath { get; }
// @property (readonly, nonatomic) NSString * _Nonnull currentKey;
[Export("currentKey")]
string CurrentKey { get; }
// @property (readonly, nonatomic) NSString * _Nonnull currentKeyPath;
[Export("currentKeyPath")]
string CurrentKeyPath { get; }
// @property (readonly, nonatomic) NSDictionary * _Nonnull searchResults;
[Export("searchResults")]
NSDictionary SearchResults { get; }
// @property (readonly, nonatomic) BOOL hasFuzzyWildcard;
[Export("hasFuzzyWildcard")]
bool HasFuzzyWildcard { get; }
// @property (readonly, nonatomic) BOOL hasWildcard;
[Export("hasWildcard")]
bool HasWildcard { get; }
// @property (readonly, nonatomic) BOOL endOfKeypath;
[Export("endOfKeypath")]
bool EndOfKeypath { get; }
// -(BOOL)pushKey:(NSString * _Nonnull)key;
[Export("pushKey:")]
bool PushKey(string key);
// -(void)popKey;
[Export("popKey")]
void PopKey();
// -(void)popToRootKey;
[Export("popToRootKey")]
void PopToRootKey();
// -(void)addSearchResultForCurrentPath:(id _Nonnull)result;
[Export("addSearchResultForCurrentPath:")]
void AddSearchResultForCurrentPath(NSObject result);
}
// @protocol LOTValueDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface LOTValueDelegate
{
}
// @protocol LOTColorValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTColorValueDelegate
{
// @required -(CGColorRef)colorForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startColor:(CGColorRef)startColor endColor:(CGColorRef)endColor currentColor:(CGColorRef)interpolatedColor;
[Abstract]
[Export("colorForFrame:startKeyframe:endKeyframe:interpolatedProgress:startColor:endColor:currentColor:")]
unsafe CGColor StartKeyframe(nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, CGColor startColor, CGColor endColor, CGColor interpolatedColor);
}
// @protocol LOTNumberValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTNumberValueDelegate
{
// @required -(CGFloat)floatValueForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startValue:(CGFloat)startValue endValue:(CGFloat)endValue currentValue:(CGFloat)interpolatedValue;
[Abstract]
[Export("floatValueForFrame:startKeyframe:endKeyframe:interpolatedProgress:startValue:endValue:currentValue:")]
nfloat StartKeyframe(nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, nfloat startValue, nfloat endValue, nfloat interpolatedValue);
}
// @protocol LOTPointValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTPointValueDelegate
{
// @required -(CGPoint)pointForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint currentPoint:(CGPoint)interpolatedPoint;
[Abstract]
[Export("pointForFrame:startKeyframe:endKeyframe:interpolatedProgress:startPoint:endPoint:currentPoint:")]
CGPoint StartKeyframe(nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, CGPoint startPoint, CGPoint endPoint, CGPoint interpolatedPoint);
}
// @protocol LOTSizeValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTSizeValueDelegate
{
// @required -(CGSize)sizeForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress startSize:(CGSize)startSize endSize:(CGSize)endSize currentSize:(CGSize)interpolatedSize;
[Abstract]
[Export("sizeForFrame:startKeyframe:endKeyframe:interpolatedProgress:startSize:endSize:currentSize:")]
CGSize StartKeyframe(nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress, CGSize startSize, CGSize endSize, CGSize interpolatedSize);
}
// @protocol LOTPathValueDelegate <LOTValueDelegate>
[Protocol, Model]
[BaseType(typeof(LOTValueDelegate))]
interface LOTPathValueDelegate
{
// @required -(CGPathRef)pathForFrame:(CGFloat)currentFrame startKeyframe:(CGFloat)startKeyframe endKeyframe:(CGFloat)endKeyframe interpolatedProgress:(CGFloat)interpolatedProgress;
[Abstract]
[Export("pathForFrame:startKeyframe:endKeyframe:interpolatedProgress:")]
unsafe CGPath StartKeyframe(nfloat currentFrame, nfloat startKeyframe, nfloat endKeyframe, nfloat interpolatedProgress);
}
// typedef void (^LOTAnimationCompletionBlock)(BOOL);
delegate void LOTAnimationCompletionBlock(bool animationFinished);
// @interface LOTAnimationView : UIView
[BaseType(typeof(UIView))]
interface LOTAnimationView
{
// +(instancetype _Nonnull)animationNamed:(NSString * _Nonnull)animationName;
[Static]
[Export("animationNamed:")]
LOTAnimationView AnimationNamed(string animationName);
// +(instancetype _Nonnull)animationNamed:(NSString * _Nonnull)animationName inBundle:(NSBundle * _Nonnull)bundle;
[Static]
[Export("animationNamed:inBundle:")]
LOTAnimationView AnimationNamed(string animationName, NSBundle bundle);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nonnull)animationJSON;
[Static]
[Export("animationFromJSON:")]
LOTAnimationView AnimationFromJSON(NSDictionary animationJSON);
// +(instancetype _Nonnull)animationWithFilePath:(NSString * _Nonnull)filePath;
[Static]
[Export("animationWithFilePath:")]
LOTAnimationView AnimationWithFilePath(string filePath);
// +(instancetype _Nonnull)animationFromJSON:(NSDictionary * _Nullable)animationJSON inBundle:(NSBundle * _Nullable)bundle;
[Static]
[Export("animationFromJSON:inBundle:")]
LOTAnimationView AnimationFromJSON([NullAllowed] NSDictionary animationJSON, [NullAllowed] NSBundle bundle);
// -(instancetype _Nonnull)initWithModel:(LOTComposition * _Nullable)model inBundle:(NSBundle * _Nullable)bundle;
[Export("initWithModel:inBundle:")]
IntPtr Constructor([NullAllowed] LOTComposition model, [NullAllowed] NSBundle bundle);
// -(instancetype _Nonnull)initWithContentsOfURL:(NSURL * _Nonnull)url;
[Export("initWithContentsOfURL:")]
IntPtr Constructor(NSUrl url);
// -(void)setAnimationNamed:(NSString * _Nonnull)animationName;
[Export("setAnimationNamed:")]
void SetAnimationNamed(string animationName);
// @property (readonly, nonatomic) BOOL isAnimationPlaying;
[Export("isAnimationPlaying")]
bool IsAnimationPlaying { get; }
// @property (assign, nonatomic) BOOL loopAnimation;
[Export("loopAnimation")]
bool LoopAnimation { get; set; }
// @property (assign, nonatomic) BOOL autoReverseAnimation;
[Export("autoReverseAnimation")]
bool AutoReverseAnimation { get; set; }
// @property (assign, nonatomic) CGFloat animationProgress;
[Export("animationProgress")]
nfloat AnimationProgress { get; set; }
// @property (assign, nonatomic) CGFloat animationSpeed;
[Export("animationSpeed")]
nfloat AnimationSpeed { get; set; }
// @property (readonly, nonatomic) CGFloat animationDuration;
[Export("animationDuration")]
nfloat AnimationDuration { get; }
// @property (assign, nonatomic) BOOL cacheEnable;
[Export("cacheEnable")]
bool CacheEnable { get; set; }
// @property (assign, nonatomic) BOOL shouldRasterizeWhenIdle;
[Export("shouldRasterizeWhenIdle")]
bool ShouldRasterizeWhenIdle { get; set; }
// @property (copy, nonatomic) LOTAnimationCompletionBlock _Nullable completionBlock;
[NullAllowed, Export("completionBlock", ArgumentSemantic.Copy)]
LOTAnimationCompletionBlock CompletionBlock { get; set; }
// @property (nonatomic, strong) LOTComposition * _Nullable sceneModel;
[NullAllowed, Export("sceneModel", ArgumentSemantic.Strong)]
LOTComposition SceneModel { get; set; }
// -(void)playToProgress:(CGFloat)toProgress withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export("playToProgress:withCompletion:")]
void PlayToProgress(nfloat toProgress, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playFromProgress:(CGFloat)fromStartProgress toProgress:(CGFloat)toEndProgress withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export("playFromProgress:toProgress:withCompletion:")]
void PlayFromProgress(nfloat fromStartProgress, nfloat toEndProgress, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playToFrame:(NSNumber * _Nonnull)toFrame withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export("playToFrame:withCompletion:")]
void PlayToFrame(NSNumber toFrame, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playFromFrame:(NSNumber * _Nonnull)fromStartFrame toFrame:(NSNumber * _Nonnull)toEndFrame withCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export("playFromFrame:toFrame:withCompletion:")]
void PlayFromFrame(NSNumber fromStartFrame, NSNumber toEndFrame, [NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)playWithCompletion:(LOTAnimationCompletionBlock _Nullable)completion;
[Export("playWithCompletion:")]
void PlayWithCompletion([NullAllowed] LOTAnimationCompletionBlock completion);
// -(void)play;
[Export("play")]
void Play();
// -(void)pause;
[Export("pause")]
void Pause();
// -(void)stop;
[Export("stop")]
void Stop();
// -(void)setProgressWithFrame:(NSNumber * _Nonnull)currentFrame;
[Export("setProgressWithFrame:")]
void SetProgressWithFrame(NSNumber currentFrame);
// -(void)forceDrawingUpdate;
[Export("forceDrawingUpdate")]
void ForceDrawingUpdate();
// -(void)logHierarchyKeypaths;
[Export("logHierarchyKeypaths")]
void LogHierarchyKeypaths();
// -(void)setValueDelegate:(id<LOTValueDelegate> _Nonnull)delegates forKeypath:(LOTKeypath * _Nonnull)keypath;
[Export("setValueDelegate:forKeypath:")]
void SetValueDelegate(NSObject delegates, LOTKeypath keypath);
// -(NSArray * _Nullable)keysForKeyPath:(LOTKeypath * _Nonnull)keypath;
[Export("keysForKeyPath:")]
[return: NullAllowed]
LOTKeypath[] KeysForKeyPath(LOTKeypath keypath);
// -(CGPoint)convertPoint:(CGPoint)point toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export("convertPoint:toKeypathLayer:")]
CGPoint ConvertPointToKeypath(CGPoint point, LOTKeypath keypath);
// -(CGRect)convertRect:(CGRect)rect toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export("convertRect:toKeypathLayer:")]
CGRect ConvertRectToKeypath(CGRect rect, LOTKeypath keypath);
// -(CGPoint)convertPoint:(CGPoint)point fromKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export("convertPoint:fromKeypathLayer:")]
CGPoint ConvertPointFromKeypath(CGPoint point, LOTKeypath keypath);
// -(CGRect)convertRect:(CGRect)rect fromKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export("convertRect:fromKeypathLayer:")]
CGRect ConvertRectFromKeypath(CGRect rect, LOTKeypath keypath);
// -(void)addSubview:(UIView * _Nonnull)view toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export("addSubview:toKeypathLayer:")]
void AddSubview(UIView view, LOTKeypath keypath);
// -(void)maskSubview:(UIView * _Nonnull)view toKeypathLayer:(LOTKeypath * _Nonnull)keypath;
[Export("maskSubview:toKeypathLayer:")]
void MaskSubview(UIView view, LOTKeypath keypath);
// -(void)setValue:(id _Nonnull)value forKeypath:(NSString * _Nonnull)keypath atFrame:(NSNumber * _Nullable)frame __attribute__((deprecated("")));
[Export("setValue:forKeypath:atFrame:")]
void SetValue(NSObject value, string keypath, [NullAllowed] NSNumber frame);
// -(void)addSubview:(UIView * _Nonnull)view toLayerNamed:(NSString * _Nonnull)layer applyTransform:(BOOL)applyTransform __attribute__((deprecated("")));
[Export("addSubview:toLayerNamed:applyTransform:")]
void AddSubview(UIView view, string layer, bool applyTransform);
// -(CGRect)convertRect:(CGRect)rect toLayerNamed:(NSString * _Nullable)layerName __attribute__((deprecated("")));
[Export("convertRect:toLayerNamed:")]
CGRect ConvertRect(CGRect rect, [NullAllowed] string layerName);
}
// @interface LOTAnimationCache : NSObject
[BaseType(typeof(NSObject))]
interface LOTAnimationCache
{
// +(instancetype _Nonnull)sharedCache;
[Static]
[Export("sharedCache")]
LOTAnimationCache SharedCache();
// -(void)addAnimation:(LOTComposition * _Nonnull)animation forKey:(NSString * _Nonnull)key;
[Export("addAnimation:forKey:")]
void AddAnimation(LOTComposition animation, string key);
// -(LOTComposition * _Nullable)animationForKey:(NSString * _Nonnull)key;
[Export("animationForKey:")]
[return: NullAllowed]
LOTComposition AnimationForKey(string key);
// -(void)removeAnimationForKey:(NSString * _Nonnull)key;
[Export("removeAnimationForKey:")]
void RemoveAnimationForKey(string key);
// -(void)clearCache;
[Export("clearCache")]
void ClearCache();
// -(void)disableCaching;
[Export("disableCaching")]
void DisableCaching();
}
// typedef CGColorRef _Nonnull (^LOTColorValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGColorRef _Nullable, CGColorRef _Nullable, CGColorRef _Nullable);
unsafe delegate IntPtr LOTColorValueCallbackBlock(nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, [NullAllowed] CGColor startColor, [NullAllowed] CGColor endColor, [NullAllowed] CGColor interpolatedColor);
// typedef CGFloat (^LOTNumberValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGFloat, CGFloat, CGFloat);
delegate nfloat LOTNumberValueCallbackBlock(nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, nfloat startValue, nfloat endValue, nfloat interpolatedValue);
// typedef CGPoint (^LOTPointValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGPoint, CGPoint, CGPoint);
delegate CGPoint LOTPointValueCallbackBlock(nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, CGPoint startPoint, CGPoint endPoint, CGPoint interpolatedPoint);
// typedef CGSize (^LOTSizeValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat, CGSize, CGSize, CGSize);
delegate CGSize LOTSizeValueCallbackBlock(nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress, CGSize startSize, CGSize endSize, CGSize interpolatedSize);
// typedef CGPathRef _Nonnull (^LOTPathValueCallbackBlock)(CGFloat, CGFloat, CGFloat, CGFloat);
unsafe delegate CGPath LOTPathValueCallbackBlock(nfloat currentFrame, nfloat startKeyFrame, nfloat endKeyFrame, nfloat interpolatedProgress);
// @interface LOTColorBlockCallback : NSObject <LOTColorValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTColorBlockCallback : LOTColorValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTColorValueCallbackBlock _Nonnull)block;
[Static]
[Export("withBlock:")]
LOTColorBlockCallback WithBlock(LOTColorValueCallbackBlock block);
// @property (copy, nonatomic) LOTColorValueCallbackBlock _Nonnull callback;
[Export("callback", ArgumentSemantic.Copy)]
LOTColorValueCallbackBlock Callback { get; set; }
}
// @interface LOTNumberBlockCallback : NSObject <LOTNumberValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTNumberBlockCallback : LOTNumberValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTNumberValueCallbackBlock _Nonnull)block;
[Static]
[Export("withBlock:")]
LOTNumberBlockCallback WithBlock(LOTNumberValueCallbackBlock block);
// @property (copy, nonatomic) LOTNumberValueCallbackBlock _Nonnull callback;
[Export("callback", ArgumentSemantic.Copy)]
LOTNumberValueCallbackBlock Callback { get; set; }
}
// @interface LOTPointBlockCallback : NSObject <LOTPointValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTPointBlockCallback : LOTPointValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTPointValueCallbackBlock _Nonnull)block;
[Static]
[Export("withBlock:")]
LOTPointBlockCallback WithBlock(LOTPointValueCallbackBlock block);
// @property (copy, nonatomic) LOTPointValueCallbackBlock _Nonnull callback;
[Export("callback", ArgumentSemantic.Copy)]
LOTPointValueCallbackBlock Callback { get; set; }
}
// @interface LOTSizeBlockCallback : NSObject <LOTSizeValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTSizeBlockCallback : LOTSizeValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTSizeValueCallbackBlock _Nonnull)block;
[Static]
[Export("withBlock:")]
LOTSizeBlockCallback WithBlock(LOTSizeValueCallbackBlock block);
// @property (copy, nonatomic) LOTSizeValueCallbackBlock _Nonnull callback;
[Export("callback", ArgumentSemantic.Copy)]
LOTSizeValueCallbackBlock Callback { get; set; }
}
// @interface LOTPathBlockCallback : NSObject <LOTPathValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTPathBlockCallback : LOTPathValueDelegate
{
// +(instancetype _Nonnull)withBlock:(LOTPathValueCallbackBlock _Nonnull)block;
[Static]
[Export("withBlock:")]
LOTPathBlockCallback WithBlock(LOTPathValueCallbackBlock block);
// @property (copy, nonatomic) LOTPathValueCallbackBlock _Nonnull callback;
[Export("callback", ArgumentSemantic.Copy)]
LOTPathValueCallbackBlock Callback { get; set; }
}
// @interface LOTPointInterpolatorCallback : NSObject <LOTPointValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTPointInterpolatorCallback : LOTPointValueDelegate
{
// +(instancetype _Nonnull)withFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint;
[Static]
[Export("withFromPoint:toPoint:")]
LOTPointInterpolatorCallback WithFromPoint(CGPoint fromPoint, CGPoint toPoint);
// @property (nonatomic) CGPoint fromPoint;
[Export("fromPoint", ArgumentSemantic.Assign)]
CGPoint FromPoint { get; set; }
// @property (nonatomic) CGPoint toPoint;
[Export("toPoint", ArgumentSemantic.Assign)]
CGPoint ToPoint { get; set; }
// @property (assign, nonatomic) CGFloat currentProgress;
[Export("currentProgress")]
nfloat CurrentProgress { get; set; }
}
// @interface LOTSizeInterpolatorCallback : NSObject <LOTSizeValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTSizeInterpolatorCallback : LOTSizeValueDelegate
{
// +(instancetype _Nonnull)withFromSize:(CGSize)fromSize toSize:(CGSize)toSize;
[Static]
[Export("withFromSize:toSize:")]
LOTSizeInterpolatorCallback WithFromSize(CGSize fromSize, CGSize toSize);
// @property (nonatomic) CGSize fromSize;
[Export("fromSize", ArgumentSemantic.Assign)]
CGSize FromSize { get; set; }
// @property (nonatomic) CGSize toSize;
[Export("toSize", ArgumentSemantic.Assign)]
CGSize ToSize { get; set; }
// @property (assign, nonatomic) CGFloat currentProgress;
[Export("currentProgress")]
nfloat CurrentProgress { get; set; }
}
// @interface LOTFloatInterpolatorCallback : NSObject <LOTNumberValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTFloatInterpolatorCallback : LOTNumberValueDelegate
{
// +(instancetype _Nonnull)withFromFloat:(CGFloat)fromFloat toFloat:(CGFloat)toFloat;
[Static]
[Export("withFromFloat:toFloat:")]
LOTFloatInterpolatorCallback WithFromFloat(nfloat fromFloat, nfloat toFloat);
// @property (nonatomic) CGFloat fromFloat;
[Export("fromFloat")]
nfloat FromFloat { get; set; }
// @property (nonatomic) CGFloat toFloat;
[Export("toFloat")]
nfloat ToFloat { get; set; }
// @property (assign, nonatomic) CGFloat currentProgress;
[Export("currentProgress")]
nfloat CurrentProgress { get; set; }
}
// @interface LOTColorValueCallback : NSObject <LOTColorValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTColorValueCallback : LOTColorValueDelegate
{
// +(instancetype _Nonnull)withCGColor:(CGColorRef _Nonnull)color;
[Static]
[Export("withCGColor:")]
unsafe LOTColorValueCallback WithCGColor(CGColor color);
// @property (nonatomic) CGColorRef _Nonnull colorValue;
[Export("colorValue", ArgumentSemantic.Assign)]
unsafe CGColor ColorValue { get; set; }
}
// @interface LOTNumberValueCallback : NSObject <LOTNumberValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTNumberValueCallback : LOTNumberValueDelegate
{
// +(instancetype _Nonnull)withFloatValue:(CGFloat)numberValue;
[Static]
[Export("withFloatValue:")]
LOTNumberValueCallback WithFloatValue(nfloat numberValue);
// @property (assign, nonatomic) CGFloat numberValue;
[Export("numberValue")]
nfloat NumberValue { get; set; }
}
// @interface LOTPointValueCallback : NSObject <LOTPointValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTPointValueCallback : LOTPointValueDelegate
{
// +(instancetype _Nonnull)withPointValue:(CGPoint)pointValue;
[Static]
[Export("withPointValue:")]
LOTPointValueCallback WithPointValue(CGPoint pointValue);
// @property (assign, nonatomic) CGPoint pointValue;
[Export("pointValue", ArgumentSemantic.Assign)]
CGPoint PointValue { get; set; }
}
// @interface LOTSizeValueCallback : NSObject <LOTSizeValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTSizeValueCallback : LOTSizeValueDelegate
{
// +(instancetype _Nonnull)withPointValue:(CGSize)sizeValue;
[Static]
[Export("withPointValue:")]
LOTSizeValueCallback WithPointValue(CGSize sizeValue);
// @property (assign, nonatomic) CGSize sizeValue;
[Export("sizeValue", ArgumentSemantic.Assign)]
CGSize SizeValue { get; set; }
}
// @interface LOTPathValueCallback : NSObject <LOTPathValueDelegate>
[BaseType(typeof(NSObject))]
interface LOTPathValueCallback : LOTPathValueDelegate
{
// +(instancetype _Nonnull)withCGPath:(CGPathRef _Nonnull)path;
[Static]
[Export("withCGPath:")]
unsafe LOTPathValueCallback WithCGPath(CGPath path);
// @property (nonatomic) CGPathRef _Nonnull pathValue;
[Export("pathValue", ArgumentSemantic.Assign)]
unsafe CGPath PathValue { get; set; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorMaterializerImpl.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Akka.Actor;
using Akka.Dispatch;
using Akka.Event;
using Akka.Pattern;
using Akka.Streams.Implementation.Fusing;
using Akka.Util;
using Akka.Util.Internal;
namespace Akka.Streams.Implementation
{
/// <summary>
/// ExtendedActorMaterializer used by subtypes which materializer using GraphInterpreterShell
/// </summary>
public abstract class ExtendedActorMaterializer : ActorMaterializer
{
public abstract TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable, Func<GraphInterpreterShell, IActorRef> subFlowFuser);
public override IActorRef ActorOf(MaterializationContext context, Props props)
{
var dispatcher = props.Deploy.Dispatcher == Deploy.NoDispatcherGiven
? EffectiveSettings(context.EffectiveAttributes).Dispatcher
: props.Dispatcher;
return ActorOf(props, context.StageName, dispatcher);
}
protected IActorRef ActorOf(Props props, string name, string dispatcher)
{
if (Supervisor is LocalActorRef)
{
var aref = (LocalActorRef)Supervisor;
return ((ActorCell)aref.Underlying).AttachChild(props.WithDispatcher(dispatcher), isSystemService: false, name: name);
}
if (Supervisor is RepointableActorRef)
{
var aref = (RepointableActorRef)Supervisor;
if (aref.IsStarted)
return ((ActorCell)aref.Underlying).AttachChild(props.WithDispatcher(dispatcher), isSystemService: false, name: name);
var timeout = aref.Underlying.System.Settings.CreationTimeout;
var f = Supervisor.Ask<IActorRef>(new StreamSupervisor.Materialize(props.WithDispatcher(dispatcher), name), timeout);
return f.Result;
}
throw new IllegalStateException($"Stream supervisor must be a local actor, was [{Supervisor.GetType()}]");
}
}
public sealed class ActorMaterializerImpl : ExtendedActorMaterializer
{
#region Materializer session implementation
private sealed class ActorMaterializerSession : MaterializerSession
{
private static readonly MethodInfo ProcessorForMethod =
typeof(ActorMaterializerSession).GetMethod("ProcessorFor",
BindingFlags.NonPublic | BindingFlags.Instance);
private readonly ActorMaterializerImpl _materializer;
private readonly Func<GraphInterpreterShell, IActorRef> _subflowFuser;
private readonly string _flowName;
private int _nextId;
public ActorMaterializerSession(ActorMaterializerImpl materializer, IModule topLevel, Attributes initialAttributes, Func<GraphInterpreterShell, IActorRef> subflowFuser)
: base(topLevel, initialAttributes)
{
_materializer = materializer;
_subflowFuser = subflowFuser;
_flowName = _materializer.CreateFlowName();
}
protected override object MaterializeAtomic(AtomicModule atomic, Attributes effectiveAttributes,
IDictionary<IModule, object> materializedValues)
{
if(IsDebug)
Console.WriteLine($"materializing {atomic}");
if (atomic is ISinkModule)
{
var sink = (ISinkModule) atomic;
object materialized;
var subscriber = sink.Create(CreateMaterializationContext(effectiveAttributes), out materialized);
AssignPort(sink.Shape.Inlets.First(), subscriber);
materializedValues.Add(atomic, materialized);
}
else if (atomic is ISourceModule)
{
var source = (ISourceModule) atomic;
object materialized;
var publisher = source.Create(CreateMaterializationContext(effectiveAttributes), out materialized);
AssignPort(source.Shape.Outlets.First(), publisher);
materializedValues.Add(atomic, materialized);
}
else if (atomic is IProcessorModule)
{
var stage = atomic as IProcessorModule;
var t = stage.CreateProcessor();
var processor = t.Item1;
var materialized = t.Item2;
AssignPort(stage.In, UntypedSubscriber.FromTyped(processor));
AssignPort(stage.Out, UntypedPublisher.FromTyped(processor));
materializedValues.Add(atomic, materialized);
}
//else if (atomic is TlsModule)
//{
//})
else if (atomic is GraphModule)
{
var graph = (GraphModule) atomic;
MaterializeGraph(graph, effectiveAttributes, materializedValues);
}
else if (atomic is GraphStageModule)
{
var stage = (GraphStageModule) atomic;
var graph =
new GraphModule(
GraphAssembly.Create(stage.Shape.Inlets, stage.Shape.Outlets, new[] {stage.Stage}),
stage.Shape, stage.Attributes, new IModule[] {stage});
MaterializeGraph(graph, effectiveAttributes, materializedValues);
}
return NotUsed.Instance;
}
private string StageName(Attributes attr) => $"{_flowName}-{_nextId++}-{attr.GetNameOrDefault()}";
private MaterializationContext CreateMaterializationContext(Attributes effectiveAttributes)
=> new MaterializationContext(_materializer, effectiveAttributes, StageName(effectiveAttributes));
private void MaterializeGraph(GraphModule graph, Attributes effectiveAttributes, IDictionary<IModule, object> materializedValues)
{
var calculatedSettings = _materializer.EffectiveSettings(effectiveAttributes);
var t = graph.Assembly.Materialize(effectiveAttributes, graph.MaterializedValueIds, materializedValues, RegisterSource);
var connections = t.Item1;
var logics = t.Item2;
var shell = new GraphInterpreterShell(graph.Assembly, connections, logics, graph.Shape, calculatedSettings, _materializer);
var impl = _subflowFuser != null && !effectiveAttributes.Contains(Attributes.AsyncBoundary.Instance)
? _subflowFuser(shell)
: _materializer.ActorOf(ActorGraphInterpreter.Props(shell), StageName(effectiveAttributes), calculatedSettings.Dispatcher);
var i = 0;
var inletsEnumerator = graph.Shape.Inlets.GetEnumerator();
while (inletsEnumerator.MoveNext())
{
var inlet = inletsEnumerator.Current;
var elementType = inlet.GetType().GetGenericArguments().First();
var subscriber = typeof(ActorGraphInterpreter.BoundarySubscriber<>).Instantiate(elementType, impl, shell, i);
AssignPort(inlet, UntypedSubscriber.FromTyped(subscriber));
i++;
}
i = 0;
var outletsEnumerator = graph.Shape.Outlets.GetEnumerator();
while (outletsEnumerator.MoveNext())
{
var outlet = outletsEnumerator.Current;
var elementType = outlet.GetType().GetGenericArguments().First();
var publisher = typeof(ActorGraphInterpreter.BoundaryPublisher<>).Instantiate(elementType, impl, shell, i);
var message = new ActorGraphInterpreter.ExposedPublisher(shell, i, (IActorPublisher)publisher);
impl.Tell(message);
AssignPort(outletsEnumerator.Current, (IUntypedPublisher) publisher);
i++;
}
}
}
#endregion
private readonly ActorSystem _system;
private readonly ActorMaterializerSettings _settings;
private readonly Dispatchers _dispatchers;
private readonly IActorRef _supervisor;
private readonly AtomicBoolean _haveShutDown;
private readonly EnumerableActorName _flowNames;
private ILoggingAdapter _logger;
public ActorMaterializerImpl(ActorSystem system, ActorMaterializerSettings settings, Dispatchers dispatchers, IActorRef supervisor, AtomicBoolean haveShutDown, EnumerableActorName flowNames)
{
_system = system;
_settings = settings;
_dispatchers = dispatchers;
_supervisor = supervisor;
_haveShutDown = haveShutDown;
_flowNames = flowNames;
_executionContext = new Lazy<MessageDispatcher>(() => _dispatchers.Lookup(_settings.Dispatcher == Deploy.NoDispatcherGiven
? Dispatchers.DefaultDispatcherId
: _settings.Dispatcher));
if (_settings.IsFuzzingMode && !_system.Settings.Config.HasPath("akka.stream.secret-test-fuzzing-warning-disable"))
Logger.Warning("Fuzzing mode is enabled on this system. If you see this warning on your production system then set 'akka.materializer.debug.fuzzing-mode' to off.");
}
public override bool IsShutdown => _haveShutDown.Value;
public override ActorMaterializerSettings Settings => _settings;
public override ActorSystem System => _system;
public override IActorRef Supervisor => _supervisor;
public override ILoggingAdapter Logger => _logger ?? (_logger = GetLogger());
public override IMaterializer WithNamePrefix(string name)
=> new ActorMaterializerImpl(_system, _settings, _dispatchers, _supervisor, _haveShutDown, _flowNames.Copy(name));
private string CreateFlowName() => _flowNames.Next();
private Attributes InitialAttributes =>
Attributes.CreateInputBuffer(_settings.InitialInputBufferSize, _settings.MaxInputBufferSize)
.And(ActorAttributes.CreateDispatcher(_settings.Dispatcher))
.And(ActorAttributes.CreateSupervisionStrategy(_settings.SupervisionDecider));
public override ActorMaterializerSettings EffectiveSettings(Attributes attributes)
{
return attributes.AttributeList.Aggregate(Settings, (settings, attribute) =>
{
if (attribute is Attributes.InputBuffer)
{
var inputBuffer = (Attributes.InputBuffer)attribute;
return settings.WithInputBuffer(inputBuffer.Initial, inputBuffer.Max);
}
if (attribute is ActorAttributes.Dispatcher)
return settings.WithDispatcher(((ActorAttributes.Dispatcher)attribute).Name);
if (attribute is ActorAttributes.SupervisionStrategy)
return settings.WithSupervisionStrategy(((ActorAttributes.SupervisionStrategy)attribute).Decider);
return settings;
});
}
public override ICancelable ScheduleOnce(TimeSpan delay, Action action)
=> _system.Scheduler.Advanced.ScheduleOnceCancelable(delay, action);
public override ICancelable ScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action)
=> _system.Scheduler.Advanced.ScheduleRepeatedlyCancelable(initialDelay, interval, action);
public override TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable) => Materialize(runnable, null);
public override TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable, Func<GraphInterpreterShell, IActorRef> subFlowFuser)
{
var runnableGraph = _settings.IsAutoFusing
? Fusing.Fusing.Aggressive(runnable)
: runnable;
if (_haveShutDown.Value)
throw new IllegalStateException("Attempted to call Materialize() after the ActorMaterializer has been shut down.");
if (StreamLayout.IsDebug)
StreamLayout.Validate(runnableGraph.Module);
var session = new ActorMaterializerSession(this, runnableGraph.Module, InitialAttributes, subFlowFuser);
var matVal = session.Materialize();
return (TMat) matVal;
}
private readonly Lazy<MessageDispatcher> _executionContext;
public override MessageDispatcher ExecutionContext => _executionContext.Value;
public override void Shutdown()
{
if (_haveShutDown.CompareAndSet(false, true))
Supervisor.Tell(PoisonPill.Instance);
}
private ILoggingAdapter GetLogger() => _system.Log;
}
public class SubFusingActorMaterializerImpl : IMaterializer
{
private readonly ExtendedActorMaterializer _delegateMaterializer;
private readonly Func<GraphInterpreterShell, IActorRef> _registerShell;
public SubFusingActorMaterializerImpl(ExtendedActorMaterializer delegateMaterializer, Func<GraphInterpreterShell, IActorRef> registerShell)
{
_delegateMaterializer = delegateMaterializer;
_registerShell = registerShell;
}
public IMaterializer WithNamePrefix(string namePrefix)
=> new SubFusingActorMaterializerImpl((ActorMaterializerImpl) _delegateMaterializer.WithNamePrefix(namePrefix), _registerShell);
public TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable)
=> _delegateMaterializer.Materialize(runnable, _registerShell);
public ICancelable ScheduleOnce(TimeSpan delay, Action action)
=> _delegateMaterializer.ScheduleOnce(delay, action);
public ICancelable ScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action)
=> _delegateMaterializer.ScheduleRepeatedly(initialDelay, interval, action);
public MessageDispatcher ExecutionContext => _delegateMaterializer.ExecutionContext;
}
public class FlowNameCounter : ExtensionIdProvider<FlowNameCounter>, IExtension
{
public static FlowNameCounter Instance(ActorSystem system)
=> system.WithExtension<FlowNameCounter, FlowNameCounter>();
public readonly AtomicCounterLong Counter = new AtomicCounterLong(0);
public override FlowNameCounter CreateExtension(ExtendedActorSystem system) => new FlowNameCounter();
}
public class StreamSupervisor : ActorBase
{
#region Messages
public sealed class Materialize : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
public readonly Props Props;
public readonly string Name;
public Materialize(Props props, string name)
{
Props = props;
Name = name;
}
}
public sealed class GetChildren
{
public static readonly GetChildren Instance = new GetChildren();
private GetChildren() { }
}
public sealed class StopChildren
{
public static readonly StopChildren Instance = new StopChildren();
private StopChildren() { }
}
public sealed class StoppedChildren
{
public static readonly StoppedChildren Instance = new StoppedChildren();
private StoppedChildren() { }
}
public sealed class PrintDebugDump
{
public static readonly PrintDebugDump Instance = new PrintDebugDump();
private PrintDebugDump() { }
}
public sealed class Children
{
public readonly IImmutableSet<IActorRef> Refs;
public Children(IImmutableSet<IActorRef> refs)
{
Refs = refs;
}
}
#endregion
public static Props Props(ActorMaterializerSettings settings, AtomicBoolean haveShutdown)
=> Actor.Props.Create(() => new StreamSupervisor(settings, haveShutdown)).WithDeploy(Deploy.Local);
public static string NextName() => ActorName.Next();
private static readonly EnumerableActorName ActorName = new EnumerableActorNameImpl("StreamSupervisor", new AtomicCounterLong(0L));
public readonly ActorMaterializerSettings Settings;
public readonly AtomicBoolean HaveShutdown;
public StreamSupervisor(ActorMaterializerSettings settings, AtomicBoolean haveShutdown)
{
Settings = settings;
HaveShutdown = haveShutdown;
}
protected override SupervisorStrategy SupervisorStrategy() => Actor.SupervisorStrategy.StoppingStrategy;
protected override bool Receive(object message)
{
if (message is Materialize)
{
var materialize = (Materialize) message;
Sender.Tell(Context.ActorOf(materialize.Props, materialize.Name));
}
else if (message is GetChildren)
Sender.Tell(new Children(Context.GetChildren().ToImmutableHashSet()));
else if (message is StopChildren)
{
foreach (var child in Context.GetChildren())
Context.Stop(child);
Sender.Tell(StoppedChildren.Instance);
}
else
return false;
return true;
}
protected override void PostStop() => HaveShutdown.Value = true;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyInteger
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// IntModel operations.
/// </summary>
public partial interface IIntModel
{
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetOverflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetUnderflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<long?>> GetOverflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<long?>> GetUnderflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMax32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMax64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMin32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMin64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<System.DateTime?>> GetUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutUnixTimeDateWithHttpMessagesAsync(System.DateTime intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<System.DateTime?>> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<System.DateTime?>> GetNullUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Runtime.Serialization;
using System.Threading;
namespace System
{
public unsafe struct RuntimeTypeHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeTypeHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeTypeHandle(type);
}
// Returns type for interop with EE. The type is guaranteed to be non-null.
internal RuntimeType GetTypeChecked()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsInstanceOfType(RuntimeType type, object? o);
internal static Type GetTypeHelper(Type typeStart, Type[]? genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
if (genericArgs != null)
{
type = type.MakeGenericType(genericArgs);
}
if (cModifiers > 0)
{
int* arModifiers = (int*)pModifiers.ToPointer();
for (int i = 0; i < cModifiers; i++)
{
if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ELEMENT_TYPE_PTR)
type = type.MakePointerType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ELEMENT_TYPE_BYREF)
type = type.MakeByRefType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ELEMENT_TYPE_SZARRAY)
type = type.MakeArrayType();
else
type = type.MakeArrayType(Marshal.ReadInt32((IntPtr)arModifiers, ++i * sizeof(int)));
}
}
return type;
}
public static bool operator ==(RuntimeTypeHandle left, object? right) => left.Equals(right);
public static bool operator ==(object? left, RuntimeTypeHandle right) => right.Equals(left);
public static bool operator !=(RuntimeTypeHandle left, object? right) => !left.Equals(right);
public static bool operator !=(object? left, RuntimeTypeHandle right) => !right.Equals(left);
// This is the RuntimeType for the type
internal RuntimeType m_type;
public override int GetHashCode()
{
return m_type != null ? m_type.GetHashCode() : 0;
}
public override bool Equals(object? obj)
{
if (!(obj is RuntimeTypeHandle))
return false;
RuntimeTypeHandle handle = (RuntimeTypeHandle)obj;
return handle.m_type == m_type;
}
public bool Equals(RuntimeTypeHandle handle)
{
return handle.m_type == m_type;
}
public IntPtr Value => m_type != null ? m_type.m_handle : IntPtr.Zero;
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle);
internal RuntimeTypeHandle(RuntimeType type)
{
m_type = type;
}
internal static bool IsTypeDefinition(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
if (!((corElemType >= CorElementType.ELEMENT_TYPE_VOID && corElemType < CorElementType.ELEMENT_TYPE_PTR) ||
corElemType == CorElementType.ELEMENT_TYPE_VALUETYPE ||
corElemType == CorElementType.ELEMENT_TYPE_CLASS ||
corElemType == CorElementType.ELEMENT_TYPE_TYPEDBYREF ||
corElemType == CorElementType.ELEMENT_TYPE_I ||
corElemType == CorElementType.ELEMENT_TYPE_U ||
corElemType == CorElementType.ELEMENT_TYPE_OBJECT))
return false;
if (HasInstantiation(type) && !IsGenericTypeDefinition(type))
return false;
return true;
}
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType >= CorElementType.ELEMENT_TYPE_BOOLEAN && corElemType <= CorElementType.ELEMENT_TYPE_R8) ||
corElemType == CorElementType.ELEMENT_TYPE_I ||
corElemType == CorElementType.ELEMENT_TYPE_U;
}
internal static bool IsByRef(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_BYREF;
}
internal static bool IsPointer(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_PTR;
}
internal static bool IsArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_ARRAY || corElemType == CorElementType.ELEMENT_TYPE_SZARRAY;
}
internal static bool IsSZArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_SZARRAY;
}
internal static bool HasElementType(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return corElemType == CorElementType.ELEMENT_TYPE_ARRAY || corElemType == CorElementType.ELEMENT_TYPE_SZARRAY // IsArray
|| (corElemType == CorElementType.ELEMENT_TYPE_PTR) // IsPointer
|| (corElemType == CorElementType.ELEMENT_TYPE_BYREF); // IsByRef
}
internal static IntPtr[]? CopyRuntimeTypeHandles(RuntimeTypeHandle[]? inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].Value;
}
length = outHandles.Length;
return outHandles;
}
internal static IntPtr[]? CopyRuntimeTypeHandles(Type[]? inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].GetTypeHandleInternal().Value;
}
length = outHandles.Length;
return outHandles;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool hasNoDefaultCtor);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo? ctor);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object Allocate(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
internal RuntimeType GetRuntimeType()
{
return m_type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern CorElementType GetCorElementType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeAssembly GetAssembly(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeModule GetModule(RuntimeType type);
public ModuleHandle GetModuleHandle()
{
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetBaseType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern TypeAttributes GetAttributes(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetElementType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetArrayRank(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
// This is managed wrapper for MethodTable::IntroducedMethodIterator
internal struct IntroducedMethodEnumerator
{
private bool _firstCall;
private RuntimeMethodHandleInternal _handle;
internal IntroducedMethodEnumerator(RuntimeType type)
{
_handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
_firstCall = true;
}
public bool MoveNext()
{
if (_firstCall)
{
_firstCall = false;
}
else if (_handle.Value != IntPtr.Zero)
{
RuntimeTypeHandle.GetNextIntroducedMethod(ref _handle);
}
return !(_handle.Value == IntPtr.Zero);
}
public RuntimeMethodHandleInternal Current => _handle;
// Glue to make this work nicely with C# foreach statement
public IntroducedMethodEnumerator GetEnumerator()
{
return this;
}
}
internal static IntroducedMethodEnumerator GetIntroducedMethods(RuntimeType type)
{
return new IntroducedMethodEnumerator(type);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool GetFields(RuntimeType type, IntPtr* result, int* count);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern Type[]? GetInterfaces(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetConstraints(QCallTypeHandle handle, ObjectHandleOnStack types);
internal Type[] GetConstraints()
{
Type[]? types = null;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
GetConstraints(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref types));
return types!;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern IntPtr GetGCHandle(QCallTypeHandle handle, GCHandleType type);
internal IntPtr GetGCHandle(GCHandleType type)
{
RuntimeTypeHandle nativeHandle = GetNativeHandle();
return GetGCHandle(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), type);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetNumVirtuals(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void VerifyInterfaceIsImplemented(QCallTypeHandle handle, QCallTypeHandle interfaceHandle);
internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
{
RuntimeTypeHandle nativeHandle = GetNativeHandle();
RuntimeTypeHandle nativeInterfaceHandle = interfaceHandle.GetNativeHandle();
VerifyInterfaceIsImplemented(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetQCallTypeHandleOnStack(ref nativeInterfaceHandle));
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern RuntimeMethodHandleInternal GetInterfaceMethodImplementation(QCallTypeHandle handle, QCallTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle);
internal RuntimeMethodHandleInternal GetInterfaceMethodImplementation(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle)
{
RuntimeTypeHandle nativeHandle = GetNativeHandle();
RuntimeTypeHandle nativeInterfaceHandle = interfaceHandle.GetNativeHandle();
return GetInterfaceMethodImplementation(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetQCallTypeHandleOnStack(ref nativeInterfaceHandle), interfaceMethodHandle);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsComObject(RuntimeType type, bool isGenericCOM);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsInterface(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsByRefLike(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsVisible(QCallTypeHandle typeHandle);
internal static bool IsVisible(RuntimeType type)
{
return _IsVisible(JitHelpers.GetQCallTypeHandleOnStack(ref type));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsValueType(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ConstructName(QCallTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString);
internal string ConstructName(TypeNameFormatFlags formatFlags)
{
string? name = null;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
ConstructName(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), formatFlags, JitHelpers.GetStringHandleOnStack(ref name));
return name!;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void* _GetUtf8Name(RuntimeType type);
internal static MdUtf8String GetUtf8Name(RuntimeType type)
{
return new MdUtf8String(_GetUtf8Name(type));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool CanCastTo(RuntimeType type, RuntimeType target);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetDeclaringType(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetDefaultConstructor(QCallTypeHandle handle, ObjectHandleOnStack method);
internal IRuntimeMethodInfo? GetDefaultConstructor()
{
IRuntimeMethodInfo? ctor = null;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
GetDefaultConstructor(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref ctor));
return ctor;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetTypeByName(string name, bool throwOnError, bool ignoreCase, StackCrawlMarkHandle stackMark,
ObjectHandleOnStack assemblyLoadContext,
bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive);
// Wrapper function to reduce the need for ifdefs.
internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, bool loadTypeFromPartialName)
{
return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext!, loadTypeFromPartialName);
}
internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark,
AssemblyLoadContext assemblyLoadContext,
bool loadTypeFromPartialName)
{
if (string.IsNullOrEmpty(name))
{
if (throwOnError)
throw new TypeLoadException(SR.Arg_TypeLoadNullStr);
return null;
}
RuntimeType? type = null;
object? keepAlive = null;
AssemblyLoadContext assemblyLoadContextStack = assemblyLoadContext;
GetTypeByName(name, throwOnError, ignoreCase,
JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
JitHelpers.GetObjectHandleOnStack(ref assemblyLoadContextStack),
loadTypeFromPartialName, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetTypeByNameUsingCARules(string name, QCallModule scope, ObjectHandleOnStack type);
internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException(null, nameof(name));
RuntimeType type = null!;
GetTypeByNameUsingCARules(name, JitHelpers.GetQCallModuleOnStack(ref scope), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void GetInstantiation(QCallTypeHandle type, ObjectHandleOnStack types, Interop.BOOL fAsRuntimeTypeArray);
internal RuntimeType[] GetInstantiationInternal()
{
RuntimeType[] types = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
GetInstantiation(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref types), Interop.BOOL.TRUE);
return types;
}
internal Type[] GetInstantiationPublic()
{
Type[] types = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
GetInstantiation(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref types), Interop.BOOL.FALSE);
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void Instantiate(QCallTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
internal RuntimeType Instantiate(Type[]? inst)
{
// defensive copy to be sure array is not mutated from the outside during processing
int instCount;
IntPtr[]? instHandles = CopyRuntimeTypeHandles(inst, out instCount);
fixed (IntPtr* pInst = instHandles)
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
Instantiate(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), pInst, instCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(inst);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakeArray(QCallTypeHandle handle, int rank, ObjectHandleOnStack type);
internal RuntimeType MakeArray(int rank)
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakeArray(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), rank, JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakeSZArray(QCallTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeSZArray()
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakeSZArray(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakeByRef(QCallTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeByRef()
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakeByRef(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void MakePointer(QCallTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakePointer()
{
RuntimeType type = null!;
RuntimeTypeHandle nativeHandle = GetNativeHandle();
MakePointer(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern Interop.BOOL IsCollectible(QCallTypeHandle handle);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool HasInstantiation(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetGenericTypeDefinition(QCallTypeHandle type, ObjectHandleOnStack retType);
internal static RuntimeType GetGenericTypeDefinition(RuntimeType type)
{
RuntimeType retType = type;
if (HasInstantiation(retType) && !IsGenericTypeDefinition(retType))
{
RuntimeTypeHandle nativeHandle = retType.GetTypeHandleInternal();
GetGenericTypeDefinition(JitHelpers.GetQCallTypeHandleOnStack(ref nativeHandle), JitHelpers.GetObjectHandleOnStack(ref retType));
}
return retType;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsGenericTypeDefinition(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsGenericVariable(RuntimeType type);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetGenericVariableIndex(RuntimeType type);
internal int GetGenericVariableIndex()
{
RuntimeType type = GetTypeChecked();
if (!IsGenericVariable(type))
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
return GetGenericVariableIndex(type);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool ContainsGenericVariables(RuntimeType handle);
internal bool ContainsGenericVariables()
{
return ContainsGenericVariables(GetTypeChecked());
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType);
internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[]? typeContext, RuntimeType[]? methodContext, RuntimeType toType)
{
int typeContextLength;
int methodContextLength;
IntPtr[]? typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
IntPtr[]? methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
{
bool result = SatisfiesConstraints(paramType, pTypeContextHandles, typeContextLength, pMethodContextHandles, methodContextLength, toType);
GC.KeepAlive(typeContext);
GC.KeepAlive(methodContext);
return result;
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IntPtr _GetMetadataImport(RuntimeType type);
internal static MetadataImport GetMetadataImport(RuntimeType type)
{
return new MetadataImport(_GetMetadataImport(type), type);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
#if FEATURE_TYPEEQUIVALENCE
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsEquivalentTo(RuntimeType rtType1, RuntimeType rtType2);
#endif // FEATURE_TYPEEQUIVALENCE
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an IRuntimeMethodInfo, and ensure that the IRuntimeMethodInfo is preserved
// across the lifetime of the RuntimeMethodHandleInternal instance
// 3. When another object is used to keep the RuntimeMethodHandleInternal alive. See delegates, CreateInstance cache, Signature structure
// When in doubt, do not use.
internal struct RuntimeMethodHandleInternal
{
internal static RuntimeMethodHandleInternal EmptyHandle => new RuntimeMethodHandleInternal();
internal bool IsNullHandle()
{
return m_handle == IntPtr.Zero;
}
internal IntPtr Value => m_handle;
internal RuntimeMethodHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal class RuntimeMethodInfoStub : IRuntimeMethodInfo
{
public RuntimeMethodInfoStub(RuntimeMethodHandleInternal methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = methodHandleValue;
}
public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = new RuntimeMethodHandleInternal(methodHandleValue);
}
private object m_keepalive;
// These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo
#pragma warning disable CA1823, 414
private object m_a = null!;
private object m_b = null!;
private object m_c = null!;
private object m_d = null!;
private object m_e = null!;
private object m_f = null!;
private object m_g = null!;
#pragma warning restore CA1823, 414
public RuntimeMethodHandleInternal m_value;
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => m_value;
}
internal interface IRuntimeMethodInfo
{
RuntimeMethodHandleInternal Value
{
get;
}
}
public unsafe struct RuntimeMethodHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method)
{
if (method == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return method;
}
private IRuntimeMethodInfo m_value;
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
{
m_value = method;
}
internal IRuntimeMethodInfo GetMethodInfo()
{
return m_value;
}
// Used by EE
private static IntPtr GetValueInternal(RuntimeMethodHandle rmh)
{
return rmh.Value;
}
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public IntPtr Value => m_value != null ? m_value.Value.Value : IntPtr.Zero;
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object? obj)
{
if (!(obj is RuntimeMethodHandle))
return false;
RuntimeMethodHandle handle = (RuntimeMethodHandle)obj;
return handle.Value == Value;
}
public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right) => left.Equals(right);
public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right) => !left.Equals(right);
public bool Equals(RuntimeMethodHandle handle)
{
return handle.Value == Value;
}
internal bool IsNullHandle()
{
return m_value == null;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle);
public IntPtr GetFunctionPointer()
{
IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value!).Value);
GC.KeepAlive(m_value);
return ptr;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern Interop.BOOL GetIsCollectible(RuntimeMethodHandleInternal handle);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern Interop.BOOL IsCAVisibleFromDecoratedType(
QCallTypeHandle attrTypeHandle,
RuntimeMethodHandleInternal attrCtor,
QCallTypeHandle sourceTypeHandle,
QCallModule sourceModule);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IRuntimeMethodInfo? _GetCurrentMethod(ref StackCrawlMark stackMark);
internal static IRuntimeMethodInfo? GetCurrentMethod(ref StackCrawlMark stackMark)
{
return _GetCurrentMethod(ref stackMark);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method)
{
MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value);
GC.KeepAlive(method);
return retVal;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ConstructInstantiation(RuntimeMethodHandleInternal method, TypeNameFormatFlags format, StringHandleOnStack retString);
internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
{
string? name = null;
IRuntimeMethodInfo methodInfo = EnsureNonNullMethodInfo(method);
ConstructInstantiation(methodInfo.Value, format, JitHelpers.GetStringHandleOnStack(ref name));
GC.KeepAlive(methodInfo);
return name!;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method);
internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method)
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value);
GC.KeepAlive(method);
return type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetSlot(RuntimeMethodHandleInternal method);
internal static int GetSlot(IRuntimeMethodInfo method)
{
Debug.Assert(method != null);
int slot = RuntimeMethodHandle.GetSlot(method.Value);
GC.KeepAlive(method);
return slot;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetMethodDef(IRuntimeMethodInfo method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern string GetName(RuntimeMethodHandleInternal method);
internal static string GetName(IRuntimeMethodInfo method)
{
string name = RuntimeMethodHandle.GetName(method.Value);
GC.KeepAlive(method);
return name;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void* _GetUtf8Name(RuntimeMethodHandleInternal method);
internal static MdUtf8String GetUtf8Name(RuntimeMethodHandleInternal method)
{
return new MdUtf8String(_GetUtf8Name(method));
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object InvokeMethod(object? target, object[]? arguments, Signature sig, bool constructor, bool wrapExceptions);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, Interop.BOOL fAsRuntimeTypeArray);
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
{
RuntimeType[] types = null!;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), Interop.BOOL.TRUE);
GC.KeepAlive(method);
return types;
}
internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
{
RuntimeType[] types = null!;
GetMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref types), Interop.BOOL.TRUE);
return types;
}
internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
{
RuntimeType[] types = null!;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), Interop.BOOL.FALSE);
GC.KeepAlive(method);
return types;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool HasMethodInstantiation(RuntimeMethodHandleInternal method);
internal static bool HasMethodInstantiation(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[]? methodInstantiation);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetTypicalMethodDefinition(RuntimeMethodHandleInternal method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
{
if (!IsTypicalMethodDefinition(method))
{
GetTypicalMethodDefinition(method.Value, JitHelpers.GetObjectHandleOnStack(ref method));
GC.KeepAlive(method);
}
return method;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetGenericParameterCount(RuntimeMethodHandleInternal method);
internal static int GetGenericParameterCount(IRuntimeMethodInfo method) => GetGenericParameterCount(method.Value);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void StripMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
{
IRuntimeMethodInfo strippedMethod = method;
StripMethodInstantiation(method.Value, JitHelpers.GetObjectHandleOnStack(ref strippedMethod));
GC.KeepAlive(method);
return strippedMethod;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsDynamicMethod(RuntimeMethodHandleInternal method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void Destroy(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern Resolver GetResolver(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodBody? GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsConstructor(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method);
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an RtFieldInfo, and ensure that the RtFieldInfo is preserved
// across the lifetime of the RuntimeFieldHandleInternal instance
// 3. When another object is used to keep the RuntimeFieldHandleInternal alive.
// When in doubt, do not use.
internal struct RuntimeFieldHandleInternal
{
internal bool IsNullHandle()
{
return m_handle == IntPtr.Zero;
}
internal IntPtr Value => m_handle;
internal RuntimeFieldHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal interface IRuntimeFieldInfo
{
RuntimeFieldHandleInternal Value
{
get;
}
}
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
#pragma warning disable 414
private object m_keepalive = null!;
private object m_c = null!;
private object m_d = null!;
private int m_b;
private object m_e = null!;
private RuntimeFieldHandleInternal m_fieldHandle;
#pragma warning restore 414
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value => m_fieldHandle;
}
public unsafe struct RuntimeFieldHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeFieldHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
IRuntimeFieldInfo field = m_ptr;
if (field == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeFieldHandle(field);
}
private IRuntimeFieldInfo m_ptr;
internal RuntimeFieldHandle(IRuntimeFieldInfo fieldInfo)
{
m_ptr = fieldInfo;
}
internal IRuntimeFieldInfo GetRuntimeFieldInfo()
{
return m_ptr;
}
public IntPtr Value => m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero;
internal bool IsNullHandle()
{
return m_ptr == null;
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object? obj)
{
if (!(obj is RuntimeFieldHandle))
return false;
RuntimeFieldHandle handle = (RuntimeFieldHandle)obj;
return handle.Value == Value;
}
public bool Equals(RuntimeFieldHandle handle)
{
return handle.Value == Value;
}
public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right) => left.Equals(right);
public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right) => !left.Equals(right);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern string GetName(RtFieldInfo field);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void* _GetUtf8Name(RuntimeFieldHandleInternal field);
internal static MdUtf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new MdUtf8String(_GetUtf8Name(field)); }
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field)
{
RuntimeType type = GetApproxDeclaringType(field.Value);
GC.KeepAlive(field);
return type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RtFieldInfo field);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object? GetValue(RtFieldInfo field, object? instance, RuntimeType fieldType, RuntimeType? declaringType, ref bool domainInitialized);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object? GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType? contextType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetValue(RtFieldInfo field, object? obj, object? value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType? declaringType, ref bool domainInitialized);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, object? value, RuntimeType? contextType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field);
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
public unsafe struct ModuleHandle
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
#region Public Static Members
public static readonly ModuleHandle EmptyHandle = GetEmptyMH();
#endregion
private static ModuleHandle GetEmptyMH()
{
return new ModuleHandle();
}
#region Private Data Members
private RuntimeModule m_ptr;
#endregion
#region Constructor
internal ModuleHandle(RuntimeModule module)
{
m_ptr = module;
}
#endregion
#region Internal FCalls
internal RuntimeModule GetRuntimeModule()
{
return m_ptr;
}
public override int GetHashCode()
{
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
public override bool Equals(object? obj)
{
if (!(obj is ModuleHandle))
return false;
ModuleHandle handle = (ModuleHandle)obj;
return handle.m_ptr == m_ptr;
}
public bool Equals(ModuleHandle handle)
{
return handle.m_ptr == m_ptr;
}
public static bool operator ==(ModuleHandle left, ModuleHandle right) => left.Equals(right);
public static bool operator !=(ModuleHandle left, ModuleHandle right) => !left.Equals(right);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDynamicMethod(System.Reflection.Emit.DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeModule module);
private static void ValidateModulePointer(RuntimeModule module)
{
// Make sure we have a valid Module to resolve against.
if (module == null)
throw new InvalidOperationException(SR.InvalidOperation_NullModuleHandle);
}
// SQL-CLR LKG9 Compiler dependency
public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); }
public RuntimeTypeHandle ResolveTypeHandle(int typeToken)
{
return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null));
}
public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
throw new ArgumentOutOfRangeException(nameof(typeToken),
SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module)));
int typeInstCount, methodInstCount;
IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
RuntimeType type = null!;
ResolveType(JitHelpers.GetQCallModuleOnStack(ref module), typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ResolveType(QCallModule module,
int typeToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack type);
// SQL-CLR LKG9 Compiler dependency
public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); }
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
}
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
int typeInstCount, methodInstCount;
IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount);
IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return retVal;
}
internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[]? typeInstantiationContext, int typeInstCount, IntPtr[]? methodInstantiationContext, int methodInstCount)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
throw new ArgumentOutOfRangeException(nameof(methodToken),
SR.Format(SR.Argument_InvalidToken, methodToken, new ModuleHandle(module)));
fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext)
{
return ResolveMethod(JitHelpers.GetQCallModuleOnStack(ref module), methodToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount);
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern RuntimeMethodHandleInternal ResolveMethod(QCallModule module,
int methodToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount);
// SQL-CLR LKG9 Compiler dependency
public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{ return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
throw new ArgumentOutOfRangeException(nameof(fieldToken),
SR.Format(SR.Argument_InvalidToken, fieldToken, new ModuleHandle(module)));
// defensive copy to be sure array is not mutated from the outside during processing
int typeInstCount, methodInstCount;
IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
IRuntimeFieldInfo field = null!;
ResolveField(JitHelpers.GetQCallModuleOnStack(ref module), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref field));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return field;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void ResolveField(QCallModule module,
int fieldToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack retField);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern Interop.BOOL _ContainsPropertyMatchingHash(QCallModule module, int propertyToken, uint hash);
internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash)
{
return _ContainsPropertyMatchingHash(JitHelpers.GetQCallModuleOnStack(ref module), propertyToken, hash) != Interop.BOOL.FALSE;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void GetModuleType(QCallModule handle, ObjectHandleOnStack type);
internal static RuntimeType GetModuleType(RuntimeModule module)
{
RuntimeType type = null!;
GetModuleType(JitHelpers.GetQCallModuleOnStack(ref module), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetPEKind(QCallModule handle, int* peKind, int* machine);
// making this internal, used by Module.GetPEKind
internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
int lKind, lMachine;
GetPEKind(JitHelpers.GetQCallModuleOnStack(ref module), &lKind, &lMachine);
peKind = (PortableExecutableKinds)lKind;
machine = (ImageFileMachine)lMachine;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int GetMDStreamVersion(RuntimeModule module);
public int MDStreamVersion => GetMDStreamVersion(GetRuntimeModule().GetNativeHandle());
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern IntPtr _GetMetadataImport(RuntimeModule module);
internal static MetadataImport GetMetadataImport(RuntimeModule module)
{
return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
}
#endregion
}
internal unsafe class Signature
{
#region Definitions
internal enum MdSigCallingConvention : byte
{
Generics = 0x10,
HasThis = 0x20,
ExplicitThis = 0x40,
CallConvMask = 0x0F,
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmgd = 0x09,
GenericInst = 0x0A,
Max = 0x0B,
}
#endregion
#region FCalls
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo? methodHandle, RuntimeType? declaringType);
#endregion
#region Private Data Members
//
// Keep the layout in sync with SignatureNative in the VM
//
internal RuntimeType[] m_arguments = null!;
internal RuntimeType m_declaringType = null!; // seems not used
internal RuntimeType m_returnTypeORfieldType = null!;
internal object? m_keepalive;
internal void* m_sig;
internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
internal int m_nSizeOfArgStack;
internal int m_csig;
internal RuntimeMethodHandleInternal m_pMethod;
#endregion
#region Constructors
public Signature(
IRuntimeMethodInfo method,
RuntimeType[] arguments,
RuntimeType returnType,
CallingConventions callingConvention)
{
m_pMethod = method.Value;
m_arguments = arguments;
m_returnTypeORfieldType = returnType;
m_managedCallingConventionAndArgIteratorFlags = (byte)callingConvention;
GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null);
}
public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
{
GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType);
}
public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
{
GetSignature(null, 0, fieldHandle.Value, null, declaringType);
GC.KeepAlive(fieldHandle);
}
public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType)
{
GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
}
#endregion
#region Internal Members
internal CallingConventions CallingConvention => (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags;
internal RuntimeType[] Arguments => m_arguments;
internal RuntimeType ReturnType => m_returnTypeORfieldType;
internal RuntimeType FieldType => m_returnTypeORfieldType;
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool CompareSig(Signature sig1, Signature sig2);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern Type[] GetCustomModifiers(int position, bool required);
#endregion
}
internal abstract class Resolver
{
internal struct CORINFO_EH_CLAUSE
{
internal int Flags;
internal int TryOffset;
internal int TryLength;
internal int HandlerOffset;
internal int HandlerLength;
internal int ClassTokenOrFilterOffset;
}
// ILHeader info
internal abstract RuntimeType? GetJitContext(out int securityControlFlags);
internal abstract byte[] GetCodeInfo(out int stackSize, out int initLocals, out int EHCount);
internal abstract byte[] GetLocalsSignature();
internal abstract unsafe void GetEHInfo(int EHNumber, void* exception);
internal abstract byte[]? GetRawEHInfo();
// token resolution
internal abstract string? GetStringLiteral(int token);
internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle);
internal abstract byte[]? ResolveSignature(int token, int fromMethod);
//
internal abstract MethodInfo GetDynamicMethod();
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Media;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using EditorDefGuidList = Microsoft.VisualStudio.Editor.DefGuidList;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using NuGet.PackageManagement.VisualStudio;
namespace NuGetConsole.Implementation.Console
{
internal interface IPrivateWpfConsole : IWpfConsole
{
SnapshotPoint? InputLineStart { get; }
InputHistory InputHistory { get; }
void BeginInputLine();
SnapshotSpan? EndInputLine(bool isEcho);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Maintainability",
"CA1506:AvoidExcessiveClassCoupling",
Justification = "We don't have resources to refactor this class.")]
internal class WpfConsole : ObjectWithFactory<WpfConsoleService>, IDisposable
{
private readonly IPrivateConsoleStatus _consoleStatus;
private IVsTextBuffer _bufferAdapter;
private int _consoleWidth = -1;
private IContentType _contentType;
private int _currentHistoryInputIndex;
private IPrivateConsoleDispatcher _dispatcher;
private IList<string> _historyInputs;
private IHost _host;
private InputHistory _inputHistory;
private SnapshotPoint? _inputLineStart;
private PrivateMarshaler _marshaler;
private uint _pdwCookieForStatusBar;
private IReadOnlyRegion _readOnlyRegionBegin;
private IReadOnlyRegion _readOnlyRegionBody;
private IVsTextView _view;
private IVsStatusbar _vsStatusBar;
private IWpfTextView _wpfTextView;
private bool _startedWritingOutput;
private List<Tuple<string, Color?, Color?>> _outputCache = new List<Tuple<string, Color?, Color?>>();
public WpfConsole(
WpfConsoleService factory,
IServiceProvider sp,
IPrivateConsoleStatus consoleStatus,
string contentTypeName,
string hostName)
: base(factory)
{
UtilityMethods.ThrowIfArgumentNull(sp);
_consoleStatus = consoleStatus;
ServiceProvider = sp;
ContentTypeName = contentTypeName;
HostName = hostName;
}
private IServiceProvider ServiceProvider { get; set; }
public string ContentTypeName { get; private set; }
public string HostName { get; private set; }
public IPrivateConsoleDispatcher Dispatcher
{
get
{
if (_dispatcher == null)
{
_dispatcher = new ConsoleDispatcher(Marshaler);
}
return _dispatcher;
}
}
public IVsUIShell VsUIShell
{
get { return ServiceProvider.GetService<IVsUIShell>(typeof(SVsUIShell)); }
}
private IVsStatusbar VsStatusBar
{
get
{
if (_vsStatusBar == null)
{
_vsStatusBar = ServiceProvider.GetService<IVsStatusbar>(typeof(SVsStatusbar));
}
return _vsStatusBar;
}
}
private IOleServiceProvider OleServiceProvider
{
get { return ServiceProvider.GetService<IOleServiceProvider>(typeof(IOleServiceProvider)); }
}
private IContentType ContentType
{
get
{
if (_contentType == null)
{
_contentType = Factory.ContentTypeRegistryService.GetContentType(this.ContentTypeName);
if (_contentType == null)
{
_contentType = Factory.ContentTypeRegistryService.AddContentType(
this.ContentTypeName, new string[] { "text" });
}
}
return _contentType;
}
}
private IVsTextBuffer VsTextBuffer
{
get
{
if (_bufferAdapter == null)
{
// make sure we only create text editor after StartWritingOutput() is called.
Debug.Assert(_startedWritingOutput);
_bufferAdapter = Factory.VsEditorAdaptersFactoryService.CreateVsTextBufferAdapter(
OleServiceProvider, ContentType);
_bufferAdapter.InitializeContent(string.Empty, 0);
}
return _bufferAdapter;
}
}
public IWpfTextView WpfTextView
{
get
{
if (_wpfTextView == null)
{
// make sure we only create text editor after StartWritingOutput() is called.
Debug.Assert(_startedWritingOutput);
_wpfTextView = Factory.VsEditorAdaptersFactoryService.GetWpfTextView(VsTextView);
}
return _wpfTextView;
}
}
private IWpfTextViewHost WpfTextViewHost
{
get
{
var userData = VsTextView as IVsUserData;
object data;
Guid guidIWpfTextViewHost = EditorDefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidIWpfTextViewHost, out data);
var wpfTextViewHost = data as IWpfTextViewHost;
return wpfTextViewHost;
}
}
/// <summary>
/// Get current input line start point (updated to current WpfTextView's text snapshot).
/// </summary>
public SnapshotPoint? InputLineStart
{
get
{
if (_inputLineStart != null)
{
ITextSnapshot snapshot = WpfTextView.TextSnapshot;
if (_inputLineStart.Value.Snapshot != snapshot)
{
_inputLineStart = _inputLineStart.Value.TranslateTo(snapshot, PointTrackingMode.Negative);
}
}
return _inputLineStart;
}
}
public SnapshotSpan InputLineExtent
{
get { return GetInputLineExtent(); }
}
/// <summary>
/// Get the snapshot extent from InputLineStart to END. Normally this console expects
/// one line only on InputLine. However in some cases multiple lines could appear, e.g.
/// when a DTE event handler writes to the console. This scenario is not fully supported,
/// but it is better to clean up nicely with ESC/ArrowUp/Return.
/// </summary>
public SnapshotSpan AllInputExtent
{
get
{
SnapshotPoint start = InputLineStart.Value;
return new SnapshotSpan(start, start.Snapshot.GetEnd());
}
}
public string InputLineText
{
get { return InputLineExtent.GetText(); }
}
private PrivateMarshaler Marshaler
{
get
{
if (_marshaler == null)
{
_marshaler = new PrivateMarshaler(this);
}
return _marshaler;
}
}
public IWpfConsole MarshaledConsole
{
get { return this.Marshaler; }
}
public IHost Host
{
get { return _host; }
set
{
if (_host != null)
{
throw new InvalidOperationException();
}
_host = value;
}
}
public int ConsoleWidth
{
get
{
if (_consoleWidth < 0)
{
ITextViewMargin leftMargin = WpfTextViewHost.GetTextViewMargin(PredefinedMarginNames.Left);
ITextViewMargin rightMargin = WpfTextViewHost.GetTextViewMargin(PredefinedMarginNames.Right);
double marginSize = 0.0;
if (leftMargin != null && leftMargin.Enabled)
{
marginSize += leftMargin.MarginSize;
}
if (rightMargin != null && rightMargin.Enabled)
{
marginSize += rightMargin.MarginSize;
}
var n = (int)((WpfTextView.ViewportWidth - marginSize) / WpfTextView.FormattedLineSource.ColumnWidth);
_consoleWidth = Math.Max(80, n); // Larger of 80 or n
}
return _consoleWidth;
}
}
private InputHistory InputHistory
{
get
{
if (_inputHistory == null)
{
_inputHistory = new InputHistory();
}
return _inputHistory;
}
}
public IVsTextView VsTextView
{
get
{
if (_view == null)
{
var textViewRoleSet = Factory.TextEditorFactoryService.CreateTextViewRoleSet(
PredefinedTextViewRoles.Interactive,
PredefinedTextViewRoles.Editable,
PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Zoomable);
_view = Factory.VsEditorAdaptersFactoryService.CreateVsTextViewAdapter(OleServiceProvider, textViewRoleSet);
_view.Initialize(
VsTextBuffer as IVsTextLines,
IntPtr.Zero,
(uint)(TextViewInitFlags.VIF_HSCROLL | TextViewInitFlags.VIF_VSCROLL) |
(uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
null);
// Set font and color
var propCategoryContainer = _view as IVsTextEditorPropertyCategoryContainer;
if (propCategoryContainer != null)
{
IVsTextEditorPropertyContainer propContainer;
Guid guidPropCategory = EditorDefGuidList.guidEditPropCategoryViewMasterSettings;
int hr = propCategoryContainer.GetPropertyCategory(ref guidPropCategory, out propContainer);
if (hr == 0)
{
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGeneral_FontCategory,
GuidList.guidPackageManagerConsoleFontAndColorCategory);
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGeneral_ColorCategory,
GuidList.guidPackageManagerConsoleFontAndColorCategory);
}
}
// add myself as IConsole
WpfTextView.TextBuffer.Properties.AddProperty(typeof(IConsole), this);
// Initial mark readonly region. Must call Start() to start accepting inputs.
SetReadOnlyRegionType(ReadOnlyRegionType.All);
// Set some EditorOptions: -DragDropEditing, +WordWrap
IEditorOptions editorOptions = Factory.EditorOptionsFactoryService.GetOptions(WpfTextView);
editorOptions.SetOptionValue(DefaultTextViewOptions.DragDropEditingId, false);
editorOptions.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.WordWrap);
// Reset console width when needed
WpfTextView.ViewportWidthChanged += (sender, e) => ResetConsoleWidth();
WpfTextView.ZoomLevelChanged += (sender, e) => ResetConsoleWidth();
// Create my Command Filter
new WpfConsoleKeyProcessor(this);
}
return _view;
}
}
public object Content
{
get { return WpfTextViewHost.HostControl; }
}
#region IDisposable Members
void IDisposable.Dispose()
{
try
{
Dispose(true);
}
finally
{
GC.SuppressFinalize(this);
}
}
#endregion
public event EventHandler<EventArgs<Tuple<SnapshotSpan, Color?, Color?>>> NewColorSpan;
public event EventHandler ConsoleCleared;
private void SetReadOnlyRegionType(ReadOnlyRegionType value)
{
if (!_startedWritingOutput)
{
return;
}
ITextBuffer buffer = WpfTextView.TextBuffer;
ITextSnapshot snapshot = buffer.CurrentSnapshot;
using (IReadOnlyRegionEdit edit = buffer.CreateReadOnlyRegionEdit())
{
edit.ClearReadOnlyRegion(ref _readOnlyRegionBegin);
edit.ClearReadOnlyRegion(ref _readOnlyRegionBody);
switch (value)
{
case ReadOnlyRegionType.BeginAndBody:
if (snapshot.Length > 0)
{
_readOnlyRegionBegin = edit.CreateReadOnlyRegion(new Span(0, 0),
SpanTrackingMode.EdgeExclusive,
EdgeInsertionMode.Deny);
_readOnlyRegionBody = edit.CreateReadOnlyRegion(new Span(0, snapshot.Length));
}
break;
case ReadOnlyRegionType.All:
_readOnlyRegionBody = edit.CreateReadOnlyRegion(new Span(0, snapshot.Length),
SpanTrackingMode.EdgeExclusive,
EdgeInsertionMode.Deny);
break;
}
edit.Apply();
}
}
public SnapshotSpan GetInputLineExtent(int start = 0, int length = -1)
{
SnapshotPoint beginPoint = InputLineStart.Value + start;
return length >= 0
? new SnapshotSpan(beginPoint, length)
: new SnapshotSpan(beginPoint, beginPoint.GetContainingLine().End);
}
public void BeginInputLine()
{
if (!_startedWritingOutput)
{
return;
}
if (_inputLineStart == null)
{
SetReadOnlyRegionType(ReadOnlyRegionType.BeginAndBody);
_inputLineStart = WpfTextView.TextSnapshot.GetEnd();
}
}
public SnapshotSpan? EndInputLine(bool isEcho = false)
{
if (!_startedWritingOutput)
{
return null;
}
// Reset history navigation upon end of a command line
ResetNavigateHistory();
if (_inputLineStart != null)
{
SnapshotSpan inputSpan = InputLineExtent;
_inputLineStart = null;
SetReadOnlyRegionType(ReadOnlyRegionType.All);
if (!isEcho)
{
Dispatcher.PostInputLine(new InputLine(inputSpan));
}
return inputSpan;
}
return null;
}
private void ResetConsoleWidth()
{
_consoleWidth = -1;
}
public void Write(string text)
{
if (!_startedWritingOutput)
{
_outputCache.Add(Tuple.Create<string, Color?, Color?>(text, null, null));
return;
}
if (_inputLineStart == null) // If not in input mode, need unlock to enable output
{
SetReadOnlyRegionType(ReadOnlyRegionType.None);
}
// Append text to editor buffer
ITextBuffer textBuffer = WpfTextView.TextBuffer;
textBuffer.Insert(textBuffer.CurrentSnapshot.Length, text);
// Ensure caret visible (scroll)
WpfTextView.Caret.EnsureVisible();
if (_inputLineStart == null) // If not in input mode, need lock again
{
SetReadOnlyRegionType(ReadOnlyRegionType.All);
}
}
public void WriteLine(string text)
{
// If append \n only, text becomes 1 line when copied to notepad.
Write(text + Environment.NewLine);
}
public void WriteBackspace()
{
if (_inputLineStart == null) // If not in input mode, need unlock to enable output
{
SetReadOnlyRegionType(ReadOnlyRegionType.None);
}
// Delete last character from input buffer.
ITextBuffer textBuffer = WpfTextView.TextBuffer;
if (textBuffer.CurrentSnapshot.Length > 0)
{
textBuffer.Delete(new Span(textBuffer.CurrentSnapshot.Length - 1, 1));
}
// Ensure caret visible (scroll)
WpfTextView.Caret.EnsureVisible();
if (_inputLineStart == null) // If not in input mode, need lock again
{
SetReadOnlyRegionType(ReadOnlyRegionType.All);
}
}
public void Write(string text, Color? foreground, Color? background)
{
if (!_startedWritingOutput)
{
_outputCache.Add(Tuple.Create(text, foreground, background));
return;
}
int begin = WpfTextView.TextSnapshot.Length;
Write(text);
int end = WpfTextView.TextSnapshot.Length;
if (foreground != null || background != null)
{
var span = new SnapshotSpan(WpfTextView.TextSnapshot, begin, end - begin);
NewColorSpan.Raise(this, Tuple.Create(span, foreground, background));
}
}
public void StartWritingOutput()
{
_startedWritingOutput = true;
FlushOutput();
}
private void FlushOutput()
{
foreach (var tuple in _outputCache)
{
Write(tuple.Item1, tuple.Item2, tuple.Item3);
}
_outputCache.Clear();
_outputCache = null;
}
private void ResetNavigateHistory()
{
_historyInputs = null;
_currentHistoryInputIndex = -1;
}
public void NavigateHistory(int offset)
{
if (_historyInputs == null)
{
_historyInputs = InputHistory.History;
if (_historyInputs == null)
{
_historyInputs = new string[] { };
}
_currentHistoryInputIndex = _historyInputs.Count;
}
int index = _currentHistoryInputIndex + offset;
if (index >= -1 && index <= _historyInputs.Count)
{
_currentHistoryInputIndex = index;
string input = (index >= 0 && index < _historyInputs.Count)
? _historyInputs[_currentHistoryInputIndex]
: string.Empty;
// Replace all text after InputLineStart with new text
WpfTextView.TextBuffer.Replace(AllInputExtent, input);
WpfTextView.Caret.EnsureVisible();
}
}
private void WriteProgress(string operation, int percentComplete)
{
if (operation == null)
{
throw new ArgumentNullException("operation");
}
if (percentComplete < 0)
{
percentComplete = 0;
}
if (percentComplete > 100)
{
percentComplete = 100;
}
if (percentComplete == 100)
{
HideProgress();
}
else
{
VsStatusBar.Progress(
ref _pdwCookieForStatusBar,
1 /* in progress */,
operation,
(uint)percentComplete,
(uint)100);
}
}
private void HideProgress()
{
VsStatusBar.Progress(
ref _pdwCookieForStatusBar,
0 /* completed */,
String.Empty,
(uint)100,
(uint)100);
}
public void SetExecutionMode(bool isExecuting)
{
_consoleStatus.SetBusyState(isExecuting);
if (!isExecuting)
{
HideProgress();
VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */);
}
}
public void Clear()
{
if (!_startedWritingOutput)
{
_outputCache.Clear();
return;
}
SetReadOnlyRegionType(ReadOnlyRegionType.None);
ITextBuffer textBuffer = WpfTextView.TextBuffer;
textBuffer.Delete(new Span(0, textBuffer.CurrentSnapshot.Length));
// Dispose existing incompleted input line
_inputLineStart = null;
// Raise event
ConsoleCleared.Raise(this);
}
public void ClearConsole()
{
if (_inputLineStart != null)
{
Dispatcher.ClearConsole();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Usage",
"CA2213:DisposableFieldsShouldBeDisposed",
MessageId = "_marshaler",
Justification = "The Dispose() method on _marshaler is called when the tool window is closed."),
System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We don't want to crash VS when it exits.")]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_bufferAdapter != null)
{
var docData = _bufferAdapter as IVsPersistDocData;
if (docData != null)
{
try
{
docData.Close();
}
catch (Exception exception)
{
ExceptionHelper.WriteToActivityLog(exception);
}
_bufferAdapter = null;
}
}
var disposable = _dispatcher as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
~WpfConsole()
{
Dispose(false);
}
#region Nested type: PrivateMarshaler
private class PrivateMarshaler : Marshaler<WpfConsole>, IPrivateWpfConsole
{
public PrivateMarshaler(WpfConsole impl)
: base(impl)
{
}
#region IPrivateWpfConsole Members
public SnapshotPoint? InputLineStart
{
get { return Invoke(() => _impl.InputLineStart); }
}
public void BeginInputLine()
{
Invoke(() => _impl.BeginInputLine());
}
public SnapshotSpan? EndInputLine(bool isEcho)
{
return Invoke(() => _impl.EndInputLine(isEcho));
}
public InputHistory InputHistory
{
get { return Invoke(() => _impl.InputHistory); }
}
#endregion
#region IWpfConsole Members
public IHost Host
{
get { return Invoke(() => _impl.Host); }
set { Invoke(() => { _impl.Host = value; }); }
}
public IConsoleDispatcher Dispatcher
{
get { return Invoke(() => _impl.Dispatcher); }
}
public int ConsoleWidth
{
get { return Invoke(() => _impl.ConsoleWidth); }
}
public void Write(string text)
{
Invoke(() => _impl.Write(text));
}
public void WriteLine(string text)
{
Invoke(() => _impl.WriteLine(text));
}
public void WriteBackspace()
{
Invoke(_impl.WriteBackspace);
}
public void Write(string text, Color? foreground, Color? background)
{
Invoke(() => _impl.Write(text, foreground, background));
}
public void Clear()
{
Invoke(_impl.Clear);
}
public void SetExecutionMode(bool isExecuting)
{
Invoke(() => _impl.SetExecutionMode(isExecuting));
}
public object Content
{
get { return Invoke(() => _impl.Content); }
}
public void WriteProgress(string operation, int percentComplete)
{
Invoke(() => _impl.WriteProgress(operation, percentComplete));
}
public object VsTextView
{
get { return Invoke(() => _impl.VsTextView); }
}
public bool ShowDisclaimerHeader
{
get { return true; }
}
public void StartWritingOutput()
{
Invoke(_impl.StartWritingOutput);
}
#endregion
public void Dispose()
{
_impl.Dispose(disposing: true);
}
}
#endregion
#region Nested type: ReadOnlyRegionType
private enum ReadOnlyRegionType
{
/// <summary>
/// No ReadOnly region. The whole text buffer allows edit.
/// </summary>
None,
/// <summary>
/// Begin and body are ReadOnly. Only allows edit at the end.
/// </summary>
BeginAndBody,
/// <summary>
/// The whole text buffer is ReadOnly. Does not allow any edit.
/// </summary>
All
};
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeX509ChainHandle : System.Runtime.InteropServices.SafeHandle
{
internal SafeX509ChainHandle() : base(default(System.IntPtr), default(bool)) { }
protected override bool ReleaseHandle() { return default(bool); }
}
}
namespace System.Security.Cryptography.X509Certificates
{
public static partial class ECDsaCertificateExtensions
{
public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.ECDsa); }
public static System.Security.Cryptography.ECDsa GetECDsaPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.ECDsa); }
}
[System.FlagsAttribute]
public enum OpenFlags
{
IncludeArchived = 8,
MaxAllowed = 2,
OpenExistingOnly = 4,
ReadOnly = 0,
ReadWrite = 1,
}
public sealed partial class PublicKey
{
public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { }
public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { return default(System.Security.Cryptography.AsnEncodedData); } }
public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { return default(System.Security.Cryptography.AsnEncodedData); } }
public System.Security.Cryptography.Oid Oid { get { return default(System.Security.Cryptography.Oid); } }
}
public static partial class RSACertificateExtensions
{
public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.RSA); }
public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.RSA); }
}
public enum StoreLocation
{
CurrentUser = 1,
LocalMachine = 2,
}
public enum StoreName
{
AddressBook = 1,
AuthRoot = 2,
CertificateAuthority = 3,
Disallowed = 4,
My = 5,
Root = 6,
TrustedPeople = 7,
TrustedPublisher = 8,
}
public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData
{
public X500DistinguishedName(byte[] encodedDistinguishedName) { }
public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { }
public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { }
public X500DistinguishedName(string distinguishedName) { }
public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { }
public string Name { get { return default(string); } }
public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { return default(string); }
public override string Format(bool multiLine) { return default(string); }
}
[System.FlagsAttribute]
public enum X500DistinguishedNameFlags
{
DoNotUsePlusSign = 32,
DoNotUseQuotes = 64,
ForceUTF8Encoding = 16384,
None = 0,
Reversed = 1,
UseCommas = 128,
UseNewLines = 256,
UseSemicolons = 16,
UseT61Encoding = 8192,
UseUTF8Encoding = 4096,
}
public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509BasicConstraintsExtension() { }
public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { }
public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { }
public bool CertificateAuthority { get { return default(bool); } }
public bool HasPathLengthConstraint { get { return default(bool); } }
public int PathLengthConstraint { get { return default(int); } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public partial class X509Certificate : System.IDisposable
{
public X509Certificate() { }
public X509Certificate(byte[] data) { }
public X509Certificate(byte[] rawData, string password) { }
public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
[System.Security.SecurityCriticalAttribute]
public X509Certificate(System.IntPtr handle) { }
public X509Certificate(string fileName) { }
public X509Certificate(string fileName, string password) { }
public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public System.IntPtr Handle {[System.Security.SecurityCriticalAttribute]get { return default(System.IntPtr); } }
public string Issuer { get { return default(string); } }
public string Subject { get { return default(string); } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public override bool Equals(object obj) { return default(bool); }
public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { return default(bool); }
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { return default(byte[]); }
public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { return default(byte[]); }
public virtual byte[] GetCertHash() { return default(byte[]); }
public virtual string GetFormat() { return default(string); }
public override int GetHashCode() { return default(int); }
public virtual string GetKeyAlgorithm() { return default(string); }
public virtual byte[] GetKeyAlgorithmParameters() { return default(byte[]); }
public virtual string GetKeyAlgorithmParametersString() { return default(string); }
public virtual byte[] GetPublicKey() { return default(byte[]); }
public virtual byte[] GetSerialNumber() { return default(byte[]); }
public override string ToString() { return default(string); }
public virtual string ToString(bool fVerbose) { return default(string); }
}
public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate
{
public X509Certificate2() { }
public X509Certificate2(byte[] rawData) { }
public X509Certificate2(byte[] rawData, string password) { }
public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public X509Certificate2(System.IntPtr handle) { }
public X509Certificate2(string fileName) { }
public X509Certificate2(string fileName, string password) { }
public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public bool Archived { get { return default(bool); } set { } }
public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { return default(System.Security.Cryptography.X509Certificates.X509ExtensionCollection); } }
public string FriendlyName { get { return default(string); } set { } }
public bool HasPrivateKey { get { return default(bool); } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { return default(System.Security.Cryptography.X509Certificates.X500DistinguishedName); } }
public System.DateTime NotAfter { get { return default(System.DateTime); } }
public System.DateTime NotBefore { get { return default(System.DateTime); } }
public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { return default(System.Security.Cryptography.X509Certificates.PublicKey); } }
public byte[] RawData { get { return default(byte[]); } }
public string SerialNumber { get { return default(string); } }
public System.Security.Cryptography.Oid SignatureAlgorithm { get { return default(System.Security.Cryptography.Oid); } }
public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { return default(System.Security.Cryptography.X509Certificates.X500DistinguishedName); } }
public string Thumbprint { get { return default(string); } }
public int Version { get { return default(int); } }
public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { return default(System.Security.Cryptography.X509Certificates.X509ContentType); }
public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { return default(System.Security.Cryptography.X509Certificates.X509ContentType); }
public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { return default(string); }
public override string ToString() { return default(string); }
public override string ToString(bool verbose) { return default(string); }
}
public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection
{
public X509Certificate2Collection() { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } set { } }
public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(int); }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(bool); }
public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { return default(byte[]); }
public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { return default(byte[]); }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); }
public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator); }
public void Import(byte[] rawData) { }
public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public void Import(string fileName) { }
public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { }
public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { }
public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { }
}
public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator
{
internal X509Certificate2Enumerator() { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public bool MoveNext() { return default(bool); }
public void Reset() { }
bool System.Collections.IEnumerator.MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
public partial class X509CertificateCollection
{
public X509CertificateCollection() { }
public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { }
public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { }
public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate); } set { } }
public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(int); }
public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { }
public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { }
public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(bool); }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { }
public System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator); }
public override int GetHashCode() { return default(int); }
public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(int); }
public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { }
public partial class X509CertificateEnumerator : System.Collections.IEnumerator
{
public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { }
public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public bool MoveNext() { return default(bool); }
public void Reset() { }
bool System.Collections.IEnumerator.MoveNext() { return default(bool); }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class X509Chain : System.IDisposable
{
public X509Chain() { }
public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElementCollection); } }
public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { return default(System.Security.Cryptography.X509Certificates.X509ChainPolicy); } set { } }
public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatus[]); } }
public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { return default(Microsoft.Win32.SafeHandles.SafeX509ChainHandle); } }
public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(bool); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
}
public partial class X509ChainElement
{
internal X509ChainElement() { }
public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } }
public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatus[]); } }
public string Information { get { return default(string); } }
}
public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal X509ChainElementCollection() { }
public int Count { get { return default(int); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElement); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { }
public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator
{
internal X509ChainElementEnumerator() { }
public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElement); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public bool MoveNext() { return default(bool); }
public void Reset() { }
}
public sealed partial class X509ChainPolicy
{
public X509ChainPolicy() { }
public System.Security.Cryptography.OidCollection ApplicationPolicy { get { return default(System.Security.Cryptography.OidCollection); } }
public System.Security.Cryptography.OidCollection CertificatePolicy { get { return default(System.Security.Cryptography.OidCollection); } }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } }
public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { return default(System.Security.Cryptography.X509Certificates.X509RevocationFlag); } set { } }
public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { return default(System.Security.Cryptography.X509Certificates.X509RevocationMode); } set { } }
public System.TimeSpan UrlRetrievalTimeout { get { return default(System.TimeSpan); } set { } }
public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { return default(System.Security.Cryptography.X509Certificates.X509VerificationFlags); } set { } }
public System.DateTime VerificationTime { get { return default(System.DateTime); } set { } }
public void Reset() { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct X509ChainStatus
{
public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatusFlags); } set { } }
public string StatusInformation { get { return default(string); } set { } }
}
[System.FlagsAttribute]
public enum X509ChainStatusFlags
{
CtlNotSignatureValid = 262144,
CtlNotTimeValid = 131072,
CtlNotValidForUsage = 524288,
Cyclic = 128,
HasExcludedNameConstraint = 32768,
HasNotDefinedNameConstraint = 8192,
HasNotPermittedNameConstraint = 16384,
HasNotSupportedNameConstraint = 4096,
InvalidBasicConstraints = 1024,
InvalidExtension = 256,
InvalidNameConstraints = 2048,
InvalidPolicyConstraints = 512,
NoError = 0,
NoIssuanceChainPolicy = 33554432,
NotSignatureValid = 8,
NotTimeNested = 2,
NotTimeValid = 1,
NotValidForUsage = 16,
OfflineRevocation = 16777216,
PartialChain = 65536,
RevocationStatusUnknown = 64,
Revoked = 4,
UntrustedRoot = 32,
}
public enum X509ContentType
{
Authenticode = 6,
Cert = 1,
Pfx = 3,
Pkcs12 = 3,
Pkcs7 = 5,
SerializedCert = 2,
SerializedStore = 4,
Unknown = 0,
}
public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509EnhancedKeyUsageExtension() { }
public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { }
public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { }
public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { return default(System.Security.Cryptography.OidCollection); } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public partial class X509Extension : System.Security.Cryptography.AsnEncodedData
{
protected X509Extension() { }
public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { }
public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { }
public X509Extension(string oid, byte[] rawData, bool critical) { }
public bool Critical { get { return default(bool); } set { } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
public X509ExtensionCollection() { }
public int Count { get { return default(int); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } }
public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { return default(int); }
public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { }
public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator
{
internal X509ExtensionEnumerator() { }
public System.Security.Cryptography.X509Certificates.X509Extension Current { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public bool MoveNext() { return default(bool); }
public void Reset() { }
}
public enum X509FindType
{
FindByApplicationPolicy = 10,
FindByCertificatePolicy = 11,
FindByExtension = 12,
FindByIssuerDistinguishedName = 4,
FindByIssuerName = 3,
FindByKeyUsage = 13,
FindBySerialNumber = 5,
FindBySubjectDistinguishedName = 2,
FindBySubjectKeyIdentifier = 14,
FindBySubjectName = 1,
FindByTemplateName = 9,
FindByThumbprint = 0,
FindByTimeExpired = 8,
FindByTimeNotYetValid = 7,
FindByTimeValid = 6,
}
[System.FlagsAttribute]
public enum X509KeyStorageFlags
{
DefaultKeySet = 0,
Exportable = 4,
MachineKeySet = 2,
PersistKeySet = 16,
UserKeySet = 1,
UserProtected = 8,
}
public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509KeyUsageExtension() { }
public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { }
public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { }
public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { return default(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags); } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
[System.FlagsAttribute]
public enum X509KeyUsageFlags
{
CrlSign = 2,
DataEncipherment = 16,
DecipherOnly = 32768,
DigitalSignature = 128,
EncipherOnly = 1,
KeyAgreement = 8,
KeyCertSign = 4,
KeyEncipherment = 32,
None = 0,
NonRepudiation = 64,
}
public enum X509NameType
{
DnsFromAlternativeName = 4,
DnsName = 3,
EmailName = 1,
SimpleName = 0,
UpnName = 2,
UrlName = 5,
}
public enum X509RevocationFlag
{
EndCertificateOnly = 0,
EntireChain = 1,
ExcludeRoot = 2,
}
public enum X509RevocationMode
{
NoCheck = 0,
Offline = 2,
Online = 1,
}
public sealed partial class X509Store : System.IDisposable
{
public X509Store() { }
public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } }
public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { return default(System.Security.Cryptography.X509Certificates.StoreLocation); } }
public string Name { get { return default(string); } }
public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
public void Dispose() { }
public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { }
public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
}
public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension
{
public X509SubjectKeyIdentifierExtension() { }
public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { }
public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { }
public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { }
public string SubjectKeyIdentifier { get { return default(string); } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public enum X509SubjectKeyIdentifierHashAlgorithm
{
CapiSha1 = 2,
Sha1 = 0,
ShortSha1 = 1,
}
[System.FlagsAttribute]
public enum X509VerificationFlags
{
AllFlags = 4095,
AllowUnknownCertificateAuthority = 16,
IgnoreCertificateAuthorityRevocationUnknown = 1024,
IgnoreCtlNotTimeValid = 2,
IgnoreCtlSignerRevocationUnknown = 512,
IgnoreEndRevocationUnknown = 256,
IgnoreInvalidBasicConstraints = 8,
IgnoreInvalidName = 64,
IgnoreInvalidPolicy = 128,
IgnoreNotTimeNested = 4,
IgnoreNotTimeValid = 1,
IgnoreRootRevocationUnknown = 2048,
IgnoreWrongUsage = 32,
NoFlag = 0,
}
}
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Fungus;
namespace Fungus
{
/// <summary>
/// Manager for main camera. Supports several types of camera transition including snap, pan & fade.
/// </summary>
public class CameraManager : MonoBehaviour
{
[Tooltip("Full screen texture used for screen fade effect.")]
[SerializeField] protected Texture2D screenFadeTexture;
[Tooltip("Icon to display when swipe pan mode is active.")]
[SerializeField] protected Texture2D swipePanIcon;
[Tooltip("Position of continue and swipe icons in normalized screen space coords. (0,0) = top left, (1,1) = bottom right")]
[SerializeField] protected Vector2 swipeIconPosition = new Vector2(1,0);
[Tooltip("Set the camera z coordinate to a fixed value every frame.")]
[SerializeField] protected bool setCameraZ = true;
[Tooltip("Fixed Z coordinate of main camera.")]
[SerializeField] protected float cameraZ = -10f;
[Tooltip("Camera to use when in swipe mode")]
[SerializeField] protected Camera swipeCamera;
protected float fadeAlpha = 0f;
// Swipe panning control
protected bool swipePanActive;
protected float swipeSpeedMultiplier = 1f;
protected View swipePanViewA;
protected View swipePanViewB;
protected Vector3 previousMousePos;
//Coroutine handles for panning and fading commands
protected LTDescr fadeTween, sizeTween, camPosTween, camRotTween;
protected class CameraView
{
public Vector3 cameraPos;
public Quaternion cameraRot;
public float cameraSize;
};
protected Dictionary<string, CameraView> storedViews = new Dictionary<string, CameraView>();
protected virtual void OnGUI()
{
if (swipePanActive)
{
// Draw the swipe panning icon
if (swipePanIcon)
{
float x = Screen.width * swipeIconPosition.x;
float y = Screen.height * swipeIconPosition.y;
float width = swipePanIcon.width;
float height = swipePanIcon.height;
x = Mathf.Max(x, 0);
y = Mathf.Max(y, 0);
x = Mathf.Min(x, Screen.width - width);
y = Mathf.Min(y, Screen.height - height);
Rect rect = new Rect(x, y, width, height);
GUI.DrawTexture(rect, swipePanIcon);
}
}
// Draw full screen fade texture
if (fadeAlpha > 0f &&
screenFadeTexture != null)
{
// 1 = scene fully visible
// 0 = scene fully obscured
GUI.color = new Color(1,1,1, fadeAlpha);
GUI.depth = -1000;
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), screenFadeTexture);
}
}
protected virtual void SetCameraZ(Camera camera)
{
if (!setCameraZ)
{
return;
}
if (camera == null)
{
Debug.LogWarning("Camera is null");
return;
}
camera.transform.position = new Vector3(camera.transform.position.x, camera.transform.position.y, cameraZ);
}
protected virtual void Update()
{
if (!swipePanActive)
{
return;
}
if (swipeCamera == null)
{
Debug.LogWarning("Camera is null");
return;
}
Vector3 delta = Vector3.zero;
if (Input.touchCount > 0)
{
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{
delta = Input.GetTouch(0).deltaPosition;
}
}
if (Input.GetMouseButtonDown(0))
{
previousMousePos = Input.mousePosition;
}
else if (Input.GetMouseButton(0))
{
delta = Input.mousePosition - previousMousePos;
previousMousePos = Input.mousePosition;
}
Vector3 cameraDelta = swipeCamera.ScreenToViewportPoint(delta);
cameraDelta.x *= -2f * swipeSpeedMultiplier;
cameraDelta.y *= -2f * swipeSpeedMultiplier;
cameraDelta.z = 0f;
Vector3 cameraPos = swipeCamera.transform.position;
cameraPos += cameraDelta;
swipeCamera.transform.position = CalcCameraPosition(cameraPos, swipePanViewA, swipePanViewB);
swipeCamera.orthographicSize = CalcCameraSize(cameraPos, swipePanViewA, swipePanViewB);
}
// Clamp camera position to region defined by the two views
protected virtual Vector3 CalcCameraPosition(Vector3 pos, View viewA, View viewB)
{
Vector3 safePos = pos;
// Clamp camera position to region defined by the two views
safePos.x = Mathf.Max(safePos.x, Mathf.Min(viewA.transform.position.x, viewB.transform.position.x));
safePos.x = Mathf.Min(safePos.x, Mathf.Max(viewA.transform.position.x, viewB.transform.position.x));
safePos.y = Mathf.Max(safePos.y, Mathf.Min(viewA.transform.position.y, viewB.transform.position.y));
safePos.y = Mathf.Min(safePos.y, Mathf.Max(viewA.transform.position.y, viewB.transform.position.y));
return safePos;
}
// Smoothly interpolate camera orthographic size based on relative position to two views
protected virtual float CalcCameraSize(Vector3 pos, View viewA, View viewB)
{
// Get ray and point in same space
Vector3 toViewB = viewB.transform.position - viewA.transform.position;
Vector3 localPos = pos - viewA.transform.position;
// Normalize
float distance = toViewB.magnitude;
toViewB /= distance;
localPos /= distance;
// Project point onto ray
float t = Vector3.Dot(toViewB, localPos);
t = Mathf.Clamp01(t); // Not really necessary but no harm
float cameraSize = Mathf.Lerp(viewA.ViewSize, viewB.ViewSize, t);
return cameraSize;
}
#region Public members
/// <summary>
/// Creates a flat colored texture.
/// </summary>
public static Texture2D CreateColorTexture(Color color, int width, int height)
{
Color[] pixels = new Color[width * height];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = color;
}
Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false);
texture.SetPixels(pixels);
texture.Apply();
return texture;
}
/// <summary>
/// Full screen texture used for screen fade effect.
/// </summary>
/// <value>The screen fade texture.</value>
public Texture2D ScreenFadeTexture { set { screenFadeTexture = value; } }
/// <summary>
/// Perform a fullscreen fade over a duration.
/// </summary>
public virtual void Fade(float targetAlpha, float fadeDuration, Action fadeAction, LeanTweenType leanTweenType = LeanTweenType.easeInOutQuad)
{
StopFadeTween();
if (Mathf.Approximately(fadeDuration, 0))
{
fadeAlpha = targetAlpha;
if (fadeAction != null) fadeAction();
}
else
{
fadeTween = LeanTween.value(fadeAlpha, targetAlpha, fadeDuration)
.setEase(leanTweenType)
.setOnUpdate((x) => fadeAlpha = x)
.setOnComplete(() =>
{
fadeAlpha = targetAlpha;
var tempFadeActin = fadeAction;
fadeAction = null;
if (tempFadeActin != null) tempFadeActin();
});
}
}
/// <summary>
/// Fade out, move camera to view and then fade back in.
/// </summary>
public virtual void FadeToView(Camera camera, View view, float fadeDuration, bool fadeOut, Action fadeAction,
LeanTweenType fadeType = LeanTweenType.easeInOutQuad, LeanTweenType sizeTweenType = LeanTweenType.easeInOutQuad,
LeanTweenType posTweenType = LeanTweenType.easeInOutQuad, LeanTweenType rotTweenType = LeanTweenType.easeInOutQuad)
{
swipePanActive = false;
fadeAlpha = 0f;
float outDuration;
float inDuration;
if (fadeOut)
{
outDuration = fadeDuration / 2f;
inDuration = fadeDuration / 2f;
}
else
{
outDuration = 0;
inDuration = fadeDuration;
}
// Fade out
Fade(1f, outDuration, delegate {
// Snap to new view
PanToPosition(camera, view.transform.position, view.transform.rotation, view.ViewSize, 0f, null, sizeTweenType, posTweenType, rotTweenType);
// Fade in
Fade(0f, inDuration, delegate {
if (fadeAction != null)
{
fadeAction();
}
}, fadeType);
}, fadeType);
}
/// <summary>
/// Stop all camera tweening.
/// </summary>
public virtual void Stop()
{
StopFadeTween();
StopPosTweens();
}
protected void StopFadeTween()
{
if (fadeTween != null)
{
LeanTween.cancel(fadeTween.id, true);
fadeTween = null;
}
}
protected void StopPosTweens()
{
if (sizeTween != null)
{
LeanTween.cancel(sizeTween.id, true);
sizeTween = null;
}
if (camPosTween != null)
{
LeanTween.cancel(camPosTween.id, true);
camPosTween = null;
}
if (camRotTween != null)
{
LeanTween.cancel(camRotTween.id, true);
camRotTween = null;
}
}
/// <summary>
/// Moves camera from current position to a target position over a period of time.
/// </summary>
public virtual void PanToPosition(Camera camera, Vector3 targetPosition, Quaternion targetRotation, float targetSize, float duration, Action arriveAction,
LeanTweenType sizeTweenType = LeanTweenType.easeInOutQuad, LeanTweenType posTweenType = LeanTweenType.easeInOutQuad, LeanTweenType rotTweenType = LeanTweenType.easeInOutQuad)
{
if (camera == null)
{
Debug.LogWarning("Camera is null");
return;
}
if(setCameraZ)
{
targetPosition.z = camera.transform.position.z;
}
// Stop any pan that is currently active
StopPosTweens();
swipePanActive = false;
if (Mathf.Approximately(duration, 0f))
{
// Move immediately
camera.orthographicSize = targetSize;
camera.transform.position = targetPosition;
camera.transform.rotation = targetRotation;
SetCameraZ(camera);
if (arriveAction != null)
{
arriveAction();
}
}
else
{
sizeTween = LeanTween.value(camera.orthographicSize, targetSize, duration)
.setEase(sizeTweenType)
.setOnUpdate(x => camera.orthographicSize = x)
.setOnComplete(() =>
{
camera.orthographicSize = targetSize;
if (arriveAction != null) arriveAction();
sizeTween = null;
});
camPosTween = LeanTween.move(camera.gameObject, targetPosition, duration)
.setEase(posTweenType)
.setOnComplete(() =>
{
camera.transform.position = targetPosition;
camPosTween = null;
});
camRotTween = LeanTween.rotate(camera.gameObject, targetRotation.eulerAngles, duration)
.setEase(rotTweenType)
.setOnComplete(() =>
{
camera.transform.rotation = targetRotation;
camRotTween = null;
});
}
}
/// <summary>
/// Activates swipe panning mode. The player can pan the camera within the area between viewA & viewB.
/// </summary>
public virtual void StartSwipePan(Camera camera, View viewA, View viewB, float duration, float speedMultiplier, Action arriveAction)
{
if (camera == null)
{
Debug.LogWarning("Camera is null");
return;
}
swipePanViewA = viewA;
swipePanViewB = viewB;
swipeSpeedMultiplier = speedMultiplier;
Vector3 cameraPos = camera.transform.position;
Vector3 targetPosition = CalcCameraPosition(cameraPos, swipePanViewA, swipePanViewB);
float targetSize = CalcCameraSize(cameraPos, swipePanViewA, swipePanViewB);
PanToPosition(camera, targetPosition, Quaternion.identity, targetSize, duration, delegate {
swipePanActive = true;
swipeCamera = camera;
if (arriveAction != null)
{
arriveAction();
}
});
}
/// <summary>
/// Deactivates swipe panning mode.
/// </summary>
public virtual void StopSwipePan()
{
swipePanActive = false;
swipePanViewA = null;
swipePanViewB = null;
swipeCamera = null;
}
#endregion
}
}
| |
// <copyright file="FirefoxProfile.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using Newtonsoft.Json;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium.Firefox
{
/// <summary>
/// Provides the ability to edit the preferences associated with a Firefox profile.
/// </summary>
public class FirefoxProfile
{
private const string UserPreferencesFileName = "user.js";
private string profileDir;
private string sourceProfileDir;
private bool deleteSource;
private bool deleteOnClean = true;
private Preferences profilePreferences;
private Dictionary<string, FirefoxExtension> extensions = new Dictionary<string, FirefoxExtension>();
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxProfile"/> class.
/// </summary>
public FirefoxProfile()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxProfile"/> class using a
/// specific profile directory.
/// </summary>
/// <param name="profileDirectory">The directory containing the profile.</param>
public FirefoxProfile(string profileDirectory)
: this(profileDirectory, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxProfile"/> class using a
/// specific profile directory.
/// </summary>
/// <param name="profileDirectory">The directory containing the profile.</param>
/// <param name="deleteSourceOnClean">Delete the source directory of the profile upon cleaning.</param>
public FirefoxProfile(string profileDirectory, bool deleteSourceOnClean)
{
this.sourceProfileDir = profileDirectory;
this.deleteSource = deleteSourceOnClean;
this.ReadDefaultPreferences();
this.profilePreferences.AppendPreferences(this.ReadExistingPreferences());
}
/// <summary>
/// Gets the directory containing the profile.
/// </summary>
public string ProfileDirectory
{
get { return this.profileDir; }
}
/// <summary>
/// Gets or sets a value indicating whether to delete this profile after use with
/// the <see cref="FirefoxDriver"/>.
/// </summary>
public bool DeleteAfterUse
{
get { return this.deleteOnClean; }
set { this.deleteOnClean = value; }
}
/// <summary>
/// Converts a base64-encoded string into a <see cref="FirefoxProfile"/>.
/// </summary>
/// <param name="base64">The base64-encoded string containing the profile contents.</param>
/// <returns>The constructed <see cref="FirefoxProfile"/>.</returns>
public static FirefoxProfile FromBase64String(string base64)
{
string destinationDirectory = FileUtilities.GenerateRandomTempDirectoryName("webdriver.{0}.duplicated");
byte[] zipContent = Convert.FromBase64String(base64);
using (MemoryStream zipStream = new MemoryStream(zipContent))
{
using (ZipArchive profileZipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read))
{
profileZipArchive.ExtractToDirectory(destinationDirectory);
}
}
return new FirefoxProfile(destinationDirectory, true);
}
/// <summary>
/// Adds a Firefox Extension to this profile
/// </summary>
/// <param name="extensionToInstall">The path to the new extension</param>
public void AddExtension(string extensionToInstall)
{
this.extensions.Add(Path.GetFileNameWithoutExtension(extensionToInstall), new FirefoxExtension(extensionToInstall));
}
/// <summary>
/// Sets a preference in the profile.
/// </summary>
/// <param name="name">The name of the preference to add.</param>
/// <param name="value">A <see cref="string"/> value to add to the profile.</param>
public void SetPreference(string name, string value)
{
this.profilePreferences.SetPreference(name, value);
}
/// <summary>
/// Sets a preference in the profile.
/// </summary>
/// <param name="name">The name of the preference to add.</param>
/// <param name="value">A <see cref="int"/> value to add to the profile.</param>
public void SetPreference(string name, int value)
{
this.profilePreferences.SetPreference(name, value);
}
/// <summary>
/// Sets a preference in the profile.
/// </summary>
/// <param name="name">The name of the preference to add.</param>
/// <param name="value">A <see cref="bool"/> value to add to the profile.</param>
public void SetPreference(string name, bool value)
{
this.profilePreferences.SetPreference(name, value);
}
/// <summary>
/// Writes this in-memory representation of a profile to disk.
/// </summary>
public void WriteToDisk()
{
this.profileDir = GenerateProfileDirectoryName();
if (!string.IsNullOrEmpty(this.sourceProfileDir))
{
FileUtilities.CopyDirectory(this.sourceProfileDir, this.profileDir);
}
else
{
Directory.CreateDirectory(this.profileDir);
}
this.InstallExtensions();
this.DeleteLockFiles();
this.DeleteExtensionsCache();
this.UpdateUserPreferences();
}
/// <summary>
/// Cleans this Firefox profile.
/// </summary>
/// <remarks>If this profile is a named profile that existed prior to
/// launching Firefox, the <see cref="Clean"/> method removes the WebDriver
/// Firefox extension. If the profile is an anonymous profile, the profile
/// is deleted.</remarks>
public void Clean()
{
if (this.deleteOnClean && !string.IsNullOrEmpty(this.profileDir) && Directory.Exists(this.profileDir))
{
FileUtilities.DeleteDirectory(this.profileDir);
}
if (this.deleteSource && !string.IsNullOrEmpty(this.sourceProfileDir) && Directory.Exists(this.sourceProfileDir))
{
FileUtilities.DeleteDirectory(this.sourceProfileDir);
}
}
/// <summary>
/// Converts the profile into a base64-encoded string.
/// </summary>
/// <returns>A base64-encoded string containing the contents of the profile.</returns>
public string ToBase64String()
{
string base64zip = string.Empty;
this.WriteToDisk();
using (MemoryStream profileMemoryStream = new MemoryStream())
{
using (ZipArchive profileZipArchive = new ZipArchive(profileMemoryStream, ZipArchiveMode.Create, true))
{
string[] files = Directory.GetFiles(this.profileDir, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
string fileNameInZip = file.Substring(this.profileDir.Length + 1).Replace(Path.DirectorySeparatorChar, '/');
profileZipArchive.CreateEntryFromFile(file, fileNameInZip);
}
}
base64zip = Convert.ToBase64String(profileMemoryStream.ToArray());
this.Clean();
}
return base64zip;
}
/// <summary>
/// Generates a random directory name for the profile.
/// </summary>
/// <returns>A random directory name for the profile.</returns>
private static string GenerateProfileDirectoryName()
{
return FileUtilities.GenerateRandomTempDirectoryName("anonymous.{0}.webdriver-profile");
}
/// <summary>
/// Deletes the lock files for a profile.
/// </summary>
private void DeleteLockFiles()
{
File.Delete(Path.Combine(this.profileDir, ".parentlock"));
File.Delete(Path.Combine(this.profileDir, "parent.lock"));
}
/// <summary>
/// Installs all extensions in the profile in the directory on disk.
/// </summary>
private void InstallExtensions()
{
foreach (string extensionKey in this.extensions.Keys)
{
this.extensions[extensionKey].Install(this.profileDir);
}
}
/// <summary>
/// Deletes the cache of extensions for this profile, if the cache exists.
/// </summary>
/// <remarks>If the extensions cache does not exist for this profile, the
/// <see cref="DeleteExtensionsCache"/> method performs no operations, but
/// succeeds.</remarks>
private void DeleteExtensionsCache()
{
DirectoryInfo ex = new DirectoryInfo(Path.Combine(this.profileDir, "extensions"));
string cacheFile = Path.Combine(ex.Parent.FullName, "extensions.cache");
if (File.Exists(cacheFile))
{
File.Delete(cacheFile);
}
}
/// <summary>
/// Writes the user preferences to the profile.
/// </summary>
private void UpdateUserPreferences()
{
string userPrefs = Path.Combine(this.profileDir, UserPreferencesFileName);
if (File.Exists(userPrefs))
{
try
{
File.Delete(userPrefs);
}
catch (Exception e)
{
throw new WebDriverException("Cannot delete existing user preferences", e);
}
}
string homePage = this.profilePreferences.GetPreference("browser.startup.homepage");
if (!string.IsNullOrEmpty(homePage))
{
this.profilePreferences.SetPreference("startup.homepage_welcome_url", string.Empty);
if (homePage != "about:blank")
{
this.profilePreferences.SetPreference("browser.startup.page", 1);
}
}
this.profilePreferences.WriteToFile(userPrefs);
}
private void ReadDefaultPreferences()
{
using (Stream defaultPrefsStream = ResourceUtilities.GetResourceStream("webdriver_prefs.json", "webdriver_prefs.json"))
{
using (StreamReader reader = new StreamReader(defaultPrefsStream))
{
string defaultPreferences = reader.ReadToEnd();
Dictionary<string, object> deserializedPreferences = JsonConvert.DeserializeObject<Dictionary<string, object>>(defaultPreferences, new ResponseValueJsonConverter());
Dictionary<string, object> immutableDefaultPreferences = deserializedPreferences["frozen"] as Dictionary<string, object>;
Dictionary<string, object> editableDefaultPreferences = deserializedPreferences["mutable"] as Dictionary<string, object>;
this.profilePreferences = new Preferences(immutableDefaultPreferences, editableDefaultPreferences);
}
}
}
/// <summary>
/// Reads the existing preferences from the profile.
/// </summary>
/// <returns>A <see cref="Dictionary{K, V}"/>containing key-value pairs representing the preferences.</returns>
/// <remarks>Assumes that we only really care about the preferences, not the comments</remarks>
private Dictionary<string, string> ReadExistingPreferences()
{
Dictionary<string, string> prefs = new Dictionary<string, string>();
try
{
if (!string.IsNullOrEmpty(this.sourceProfileDir))
{
string userPrefs = Path.Combine(this.sourceProfileDir, UserPreferencesFileName);
if (File.Exists(userPrefs))
{
string[] fileLines = File.ReadAllLines(userPrefs);
foreach (string line in fileLines)
{
if (line.StartsWith("user_pref(\"", StringComparison.OrdinalIgnoreCase))
{
string parsedLine = line.Substring("user_pref(\"".Length);
parsedLine = parsedLine.Substring(0, parsedLine.Length - ");".Length);
string[] parts = line.Split(new string[] { "," }, StringSplitOptions.None);
parts[0] = parts[0].Substring(0, parts[0].Length - 1);
prefs.Add(parts[0].Trim(), parts[1].Trim());
}
}
}
}
}
catch (IOException e)
{
throw new WebDriverException(string.Empty, e);
}
return prefs;
}
}
}
| |
/**
* Lexer.cs
* JSON lexer implementation based on a finite state machine.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#if !UNITY_WP8
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace OuyaSDK_LitJson
{
internal class FsmContext
{
public bool Return;
public int NextState;
public Lexer L;
public int StateStack;
}
internal class Lexer
{
#region Fields
private delegate bool StateHandler (FsmContext ctx);
private static int[] fsm_return_table;
private static StateHandler[] fsm_handler_table;
private bool allow_comments;
private bool allow_single_quoted_strings;
private bool end_of_input;
private FsmContext fsm_context;
private int input_buffer;
private int input_char;
private TextReader reader;
private int state;
private StringBuilder string_buffer;
private string string_value;
private int token;
private int unichar;
#endregion
#region Properties
public bool AllowComments {
get { return allow_comments; }
set { allow_comments = value; }
}
public bool AllowSingleQuotedStrings {
get { return allow_single_quoted_strings; }
set { allow_single_quoted_strings = value; }
}
public bool EndOfInput {
get { return end_of_input; }
}
public int Token {
get { return token; }
}
public string StringValue {
get { return string_value; }
}
#endregion
#region Constructors
static Lexer ()
{
PopulateFsmTables ();
}
public Lexer (TextReader reader)
{
allow_comments = true;
allow_single_quoted_strings = true;
input_buffer = 0;
string_buffer = new StringBuilder (128);
state = 1;
end_of_input = false;
this.reader = reader;
fsm_context = new FsmContext ();
fsm_context.L = this;
}
#endregion
#region Static Methods
private static int HexValue (int digit)
{
switch (digit) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return digit - '0';
}
}
private static void PopulateFsmTables ()
{
fsm_handler_table = new StateHandler[28] {
State1,
State2,
State3,
State4,
State5,
State6,
State7,
State8,
State9,
State10,
State11,
State12,
State13,
State14,
State15,
State16,
State17,
State18,
State19,
State20,
State21,
State22,
State23,
State24,
State25,
State26,
State27,
State28
};
fsm_return_table = new int[28] {
(int) ParserToken.Char,
0,
(int) ParserToken.Number,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
0,
(int) ParserToken.True,
0,
0,
0,
(int) ParserToken.False,
0,
0,
(int) ParserToken.Null,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
0,
0
};
}
private static char ProcessEscChar (int esc_char)
{
switch (esc_char) {
case '"':
case '\'':
case '\\':
case '/':
return Convert.ToChar (esc_char);
case 'n':
return '\n';
case 't':
return '\t';
case 'r':
return '\r';
case 'b':
return '\b';
case 'f':
return '\f';
default:
// Unreachable
return '?';
}
}
private static bool State1 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r')
continue;
if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '"':
ctx.NextState = 19;
ctx.Return = true;
return true;
case ',':
case ':':
case '[':
case ']':
case '{':
case '}':
ctx.NextState = 1;
ctx.Return = true;
return true;
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 2;
return true;
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
case 'f':
ctx.NextState = 12;
return true;
case 'n':
ctx.NextState = 16;
return true;
case 't':
ctx.NextState = 9;
return true;
case '\'':
if (! ctx.L.allow_single_quoted_strings)
return false;
ctx.L.input_char = '"';
ctx.NextState = 23;
ctx.Return = true;
return true;
case '/':
if (! ctx.L.allow_comments)
return false;
ctx.NextState = 25;
return true;
default:
return false;
}
}
return true;
}
private static bool State2 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '0':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 4;
return true;
default:
return false;
}
}
private static bool State3 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State4 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
private static bool State5 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 6;
return true;
}
return false;
}
private static bool State6 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State7 (FsmContext ctx)
{
ctx.L.GetChar ();
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
}
switch (ctx.L.input_char) {
case '+':
case '-':
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
ctx.NextState = 8;
return true;
default:
return false;
}
}
private static bool State8 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') {
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
return true;
}
private static bool State9 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'r':
ctx.NextState = 10;
return true;
default:
return false;
}
}
private static bool State10 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 11;
return true;
default:
return false;
}
}
private static bool State11 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State12 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'a':
ctx.NextState = 13;
return true;
default:
return false;
}
}
private static bool State13 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 14;
return true;
default:
return false;
}
}
private static bool State14 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 's':
ctx.NextState = 15;
return true;
default:
return false;
}
}
private static bool State15 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State16 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 17;
return true;
default:
return false;
}
}
private static bool State17 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 18;
return true;
default:
return false;
}
}
private static bool State18 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'l':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State19 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '"':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 20;
return true;
case '\\':
ctx.StateStack = 19;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State20 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '"':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State21 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 22;
return true;
case '"':
case '\'':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
ctx.L.string_buffer.Append (
ProcessEscChar (ctx.L.input_char));
ctx.NextState = ctx.StateStack;
return true;
default:
return false;
}
}
private static bool State22 (FsmContext ctx)
{
int counter = 0;
int mult = 4096;
ctx.L.unichar = 0;
while (ctx.L.GetChar ()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' ||
ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' ||
ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') {
ctx.L.unichar += HexValue (ctx.L.input_char) * mult;
counter++;
mult /= 16;
if (counter == 4) {
ctx.L.string_buffer.Append (
Convert.ToChar (ctx.L.unichar));
ctx.NextState = ctx.StateStack;
return true;
}
continue;
}
return false;
}
return true;
}
private static bool State23 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
switch (ctx.L.input_char) {
case '\'':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 24;
return true;
case '\\':
ctx.StateStack = 23;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append ((char) ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State24 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '\'':
ctx.L.input_char = '"';
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State25 (FsmContext ctx)
{
ctx.L.GetChar ();
switch (ctx.L.input_char) {
case '*':
ctx.NextState = 27;
return true;
case '/':
ctx.NextState = 26;
return true;
default:
return false;
}
}
private static bool State26 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '\n') {
ctx.NextState = 1;
return true;
}
}
return true;
}
private static bool State27 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*') {
ctx.NextState = 28;
return true;
}
}
return true;
}
private static bool State28 (FsmContext ctx)
{
while (ctx.L.GetChar ()) {
if (ctx.L.input_char == '*')
continue;
if (ctx.L.input_char == '/') {
ctx.NextState = 1;
return true;
}
ctx.NextState = 27;
return true;
}
return true;
}
#endregion
private bool GetChar ()
{
if ((input_char = NextChar ()) != -1)
return true;
end_of_input = true;
return false;
}
private int NextChar ()
{
if (input_buffer != 0) {
int tmp = input_buffer;
input_buffer = 0;
return tmp;
}
return reader.Read ();
}
public bool NextToken ()
{
StateHandler handler;
fsm_context.Return = false;
while (true) {
handler = fsm_handler_table[state - 1];
if (! handler (fsm_context))
throw new JsonException (input_char);
if (end_of_input)
return false;
if (fsm_context.Return) {
string_value = string_buffer.ToString ();
string_buffer.Remove (0, string_buffer.Length);
token = fsm_return_table[state - 1];
if (token == (int) ParserToken.Char)
token = input_char;
state = fsm_context.NextState;
return true;
}
state = fsm_context.NextState;
}
}
private void UngetChar ()
{
input_buffer = input_char;
}
}
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using Xunit;
namespace System.Reflection.Compatibility.UnitTests.MemberInfoTests
{
// MemberInfo.MemberType Property
// When overridden in a derived class, gets a MemberTypes value indicating
// the type of the member method, constructor, event, and so on.
public class ReflectionMemberInfoMemberType
{
// PosTest1: get accessor of public static property
[Fact]
public void PosTest1()
{
bool expectedValue = true;
bool actualValue = false;
MethodInfo methodInfo;
MemberInfo memberInfo;
methodInfo = typeof(TestClass1).GetProperty("InstanceCount").GetGetMethod();
memberInfo = methodInfo as MemberInfo;
actualValue = memberInfo.Name.Equals("get_InstanceCount");
Assert.Equal(expectedValue, actualValue);
}
// PosTest2: set accessor of public instance property
[Fact]
public void PosTest2()
{
bool expectedValue = true;
bool actualValue = false;
MethodInfo methodInfo;
MemberInfo memberInfo; methodInfo = typeof(TestClass1).GetProperty("Data1").GetSetMethod();
memberInfo = methodInfo as MemberInfo;
actualValue = memberInfo.Name.Equals("set_Data1");
Assert.Equal(expectedValue, actualValue);
}
// PosTest3: public static property
[Fact]
public void PosTest3()
{
bool expectedValue = true;
bool actualValue = false;
PropertyInfo propertyInfo;
MemberInfo memberInfo;
propertyInfo = typeof(TestClass1).GetProperty("InstanceCount");
memberInfo = propertyInfo as MemberInfo;
actualValue = memberInfo.Name.Equals("InstanceCount");
Assert.Equal(expectedValue, actualValue);
}
// PosTest4: public instance property
[Fact]
public void PosTest4()
{
bool expectedValue = true;
bool actualValue = false;
PropertyInfo propertyInfo;
MemberInfo memberInfo;
propertyInfo = typeof(TestClass1).GetProperty("Data1");
memberInfo = propertyInfo as MemberInfo;
actualValue = memberInfo.Name.Equals("Data1");
Assert.Equal(expectedValue, actualValue);
}
// PosTest5: public constructor
[Fact]
public void PosTest5()
{
bool expectedValue = true;
bool actualValue = false;
ConstructorInfo constructorInfo;
MemberInfo memberInfo;
Type[] parameterTypes = { typeof(int) };
constructorInfo = typeof(TestClass1).GetConstructor(parameterTypes);
memberInfo = constructorInfo as MemberInfo;
actualValue = memberInfo.Name.Equals(".ctor"); ;
Assert.Equal(expectedValue, actualValue);
}
// PosTest6: private instance field
[Fact]
public void PosTest6()
{
bool expectedValue = true;
bool actualValue = false;
Type testType;
FieldInfo fieldInfo;
MemberInfo memberInfo;
testType = typeof(TestClass1);
fieldInfo = testType.GetField("_data1", BindingFlags.NonPublic | BindingFlags.Instance);
memberInfo = fieldInfo as MemberInfo;
actualValue = memberInfo.Name.Equals("_data1");
Assert.Equal(expectedValue, actualValue);
}
// PosTest7: private static field
[Fact]
public void PosTest7()
{
bool expectedValue = true;
bool actualValue = false;
Type testType;
FieldInfo fieldInfo;
MemberInfo memberInfo;
testType = typeof(TestClass1);
fieldInfo = testType.GetField("s_count", BindingFlags.NonPublic | BindingFlags.Static);
memberInfo = fieldInfo as MemberInfo;
actualValue = memberInfo.Name.Equals("s_count"); ;
Assert.Equal(expectedValue, actualValue);
}
// PosTest8: private instance event
[Fact]
public void PosTest8()
{
bool expectedValue = true;
bool actualValue = false;
Type testType;
EventInfo eventInfo;
MemberInfo memberInfo;
testType = typeof(TestButton);
eventInfo = testType.GetEvent("Click");
memberInfo = eventInfo as MemberInfo;
actualValue = memberInfo.Name.Equals("Click"); ;
Assert.Equal(expectedValue, actualValue);
}
// PosTest9: nested type
[Fact]
public void PosTest9()
{
bool expectedValue = true;
bool actualValue = false;
Type testType;
Type nestedType;
testType = typeof(ReflectionMemberInfoMemberType);
nestedType = testType.GetNestedType("TestClass1", BindingFlags.NonPublic);
actualValue = nestedType.IsNested;
Assert.Equal(expectedValue, actualValue);
}
// PosTest10: unnested type
[Fact]
public void PosTest10()
{
bool expectedValue = true;
bool actualValue = false;
Type testType;
testType = typeof(ReflectionMemberInfoMemberType);
actualValue = testType.Name.Equals("ReflectionMemberInfoMemberType");
Assert.Equal(expectedValue, actualValue);
}
private class TestClass1
{
private static int s_count = 0;
//Defualt constructor
public TestClass1()
{
++s_count;
}
public TestClass1(int data1)
{
++s_count;
_data1 = data1;
}
public static int InstanceCount
{
get
{
return s_count;
}
}
public int Data1
{
get
{
return _data1;
}
set
{
_data1 = value;
}
}
private int _data1;
public void Do()
{
}
}
private class TestButton
{
public event EventHandler Click;
protected void OnClick(EventArgs e)
{
if (null != Click)
{
Click(this, e);
}
}
}
}
}
| |
#region Foreign-License
// .Net40 Kludge
#endregion
#if !CLR4
using System.Collections;
using System.Text;
using System.Collections.Generic;
namespace System
{
/// <summary>
/// ITuple
/// </summary>
internal interface ITuple
{
int GetHashCode(IEqualityComparer comparer);
string ToString(StringBuilder sb);
int Size { get; }
}
/// <summary>
/// Tuple
/// </summary>
#if !COREINTERNAL
public
#endif
static class Tuple
{
internal static int CombineHashCodes(int h1, int h2) { return (((h1 << 5) + h1) ^ h2); }
internal static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); }
internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); }
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); }
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); }
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); }
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); }
public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); }
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); }
public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); }
public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4); }
public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); }
public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); }
public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); }
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8)); }
}
#region Tuple<T1>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public Tuple(T1 item1) { _Item1 = item1; }
public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); }
public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); }
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = (other as Tuple<T1>);
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
return comparer.Compare(this._Item1, tuple._Item1);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1>);
if (tuple == null)
return false;
return comparer.Equals(_Item1, tuple._Item1);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(_Item1); }
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(this._Item1);
sb.Append(")");
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
int ITuple.Size
{
get { return 1; }
}
}
#endregion
#region Tuple<T1, T2>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
private readonly T2 _Item2;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public Tuple(T1 item1, T2 item2)
{
_Item1 = item1;
_Item2 = item2;
}
public override bool Equals(object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = (other as Tuple<T1, T2>);
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
int num = 0;
num = comparer.Compare(_Item1, tuple._Item1);
if (num != 0)
return num;
return comparer.Compare(_Item2, tuple._Item2);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1, T2>);
if (tuple == null)
return false;
return (comparer.Equals(_Item1, tuple._Item1) && comparer.Equals(_Item2, tuple._Item2));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(_Item1), comparer.GetHashCode(_Item2)); }
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(_Item1);
sb.Append(", ");
sb.Append(_Item2);
sb.Append(")");
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
public T2 Item2
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item2; }
}
int ITuple.Size
{
get { return 2; }
}
}
#endregion
#region Tuple<T1, T2, T3>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
private readonly T2 _Item2;
private readonly T3 _Item3;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public Tuple(T1 item1, T2 item2, T3 item3)
{
_Item1 = item1;
_Item2 = item2;
_Item3 = item3;
}
public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); }
public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); }
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = (other as Tuple<T1, T2, T3>);
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
int num = 0;
num = comparer.Compare(_Item1, tuple._Item1);
if (num != 0)
return num;
num = comparer.Compare(_Item2, tuple._Item2);
if (num != 0)
return num;
return comparer.Compare(_Item3, tuple._Item3);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1, T2, T3>);
if (tuple == null)
return false;
return ((comparer.Equals(_Item1, tuple._Item1) && comparer.Equals(_Item2, tuple._Item2)) && comparer.Equals(_Item3, tuple._Item3));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(_Item1), comparer.GetHashCode(_Item2), comparer.GetHashCode(_Item3)); }
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(_Item1);
sb.Append(", ");
sb.Append(_Item2);
sb.Append(", ");
sb.Append(_Item3);
sb.Append(")");
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
public T2 Item2
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item2; }
}
public T3 Item3
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item3; }
}
int ITuple.Size
{
get { return 3; }
}
}
#endregion
#region Tuple<T1, T2, T3, T4>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
private readonly T2 _Item2;
private readonly T3 _Item3;
private readonly T4 _Item4;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4)
{
_Item1 = item1;
_Item2 = item2;
_Item3 = item3;
_Item4 = item4;
}
public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); }
public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); }
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = (other as Tuple<T1, T2, T3, T4>);
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
int num = 0;
num = comparer.Compare(_Item1, tuple._Item1);
if (num != 0)
return num;
num = comparer.Compare(_Item2, tuple._Item2);
if (num != 0)
return num;
num = comparer.Compare(_Item3, tuple._Item3);
if (num != 0)
return num;
return comparer.Compare(_Item4, tuple._Item4);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1, T2, T3, T4>);
if (tuple == null)
return false;
return (((comparer.Equals(_Item1, tuple._Item1) && comparer.Equals(_Item2, tuple._Item2)) && comparer.Equals(_Item3, tuple._Item3)) && comparer.Equals(_Item4, tuple._Item4));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(_Item1), comparer.GetHashCode(_Item2), comparer.GetHashCode(_Item3), comparer.GetHashCode(_Item4)); }
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(_Item1);
sb.Append(", ");
sb.Append(_Item2);
sb.Append(", ");
sb.Append(_Item3);
sb.Append(", ");
sb.Append(_Item4);
sb.Append(")");
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
public T2 Item2
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item2; }
}
public T3 Item3
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item3; }
}
public T4 Item4
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item4; }
}
int ITuple.Size
{
get { return 4; }
}
}
#endregion
#region Tuple<T1, T2, T3, T4, T5>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
private readonly T2 _Item2;
private readonly T3 _Item3;
private readonly T4 _Item4;
private readonly T5 _Item5;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
_Item1 = item1;
_Item2 = item2;
_Item3 = item3;
_Item4 = item4;
_Item5 = item5;
}
public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); }
public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); }
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = (other as Tuple<T1, T2, T3, T4, T5>);
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
int num = 0;
num = comparer.Compare(_Item1, tuple._Item1);
if (num != 0)
return num;
num = comparer.Compare(_Item2, tuple._Item2);
if (num != 0)
return num;
num = comparer.Compare(_Item3, tuple._Item3);
if (num != 0)
return num;
num = comparer.Compare(_Item4, tuple._Item4);
if (num != 0)
return num;
return comparer.Compare(_Item5, tuple._Item5);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1, T2, T3, T4, T5>);
if (tuple == null)
return false;
return (((comparer.Equals(_Item1, tuple._Item1) && comparer.Equals(_Item2, tuple._Item2)) && (comparer.Equals(_Item3, tuple._Item3) && comparer.Equals(_Item4, tuple._Item4))) && comparer.Equals(_Item5, tuple._Item5));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(_Item1), comparer.GetHashCode(_Item2), comparer.GetHashCode(_Item3), comparer.GetHashCode(_Item4), comparer.GetHashCode(_Item5)); }
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(_Item1);
sb.Append(", ");
sb.Append(_Item2);
sb.Append(", ");
sb.Append(_Item3);
sb.Append(", ");
sb.Append(_Item4);
sb.Append(", ");
sb.Append(_Item5);
sb.Append(")");
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
public T2 Item2
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item2; }
}
public T3 Item3
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item3; }
}
public T4 Item4
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item4; }
}
public T5 Item5
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item5; }
}
int ITuple.Size
{
get { return 5; }
}
}
#endregion
#region Tuple<T1, T2, T3, T4, T5, T6>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
private readonly T2 _Item2;
private readonly T3 _Item3;
private readonly T4 _Item4;
private readonly T5 _Item5;
private readonly T6 _Item6;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
_Item1 = item1;
_Item2 = item2;
_Item3 = item3;
_Item4 = item4;
_Item5 = item5;
_Item6 = item6;
}
public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); }
public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); }
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = (other as Tuple<T1, T2, T3, T4, T5, T6>);
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
int num = 0;
num = comparer.Compare(_Item1, tuple._Item1);
if (num != 0)
return num;
num = comparer.Compare(_Item2, tuple._Item2);
if (num != 0)
return num;
num = comparer.Compare(_Item3, tuple._Item3);
if (num != 0)
return num;
num = comparer.Compare(_Item4, tuple._Item4);
if (num != 0)
return num;
num = comparer.Compare(_Item5, tuple._Item5);
if (num != 0)
return num;
return comparer.Compare(_Item6, tuple._Item6);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1, T2, T3, T4, T5, T6>);
if (tuple == null)
return false;
return ((((comparer.Equals(_Item1, tuple._Item1) && comparer.Equals(_Item2, tuple._Item2)) && (comparer.Equals(_Item3, tuple._Item3) && comparer.Equals(_Item4, tuple._Item4))) && comparer.Equals(_Item5, tuple._Item5)) && comparer.Equals(_Item6, tuple._Item6));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(_Item1), comparer.GetHashCode(_Item2), comparer.GetHashCode(_Item3), comparer.GetHashCode(_Item4), comparer.GetHashCode(_Item5), comparer.GetHashCode(_Item6)); }
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(_Item1);
sb.Append(", ");
sb.Append(_Item2);
sb.Append(", ");
sb.Append(_Item3);
sb.Append(", ");
sb.Append(_Item4);
sb.Append(", ");
sb.Append(_Item5);
sb.Append(", ");
sb.Append(_Item6);
sb.Append(")");
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
public T2 Item2
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item2; }
}
public T3 Item3
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item3; }
}
public T4 Item4
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item4; }
}
public T5 Item5
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item5; }
}
public T6 Item6
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item6; }
}
int ITuple.Size
{
get { return 6; }
}
}
#endregion
#region Tuple<T1, T2, T3, T4, T5, T6, T7>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
private readonly T2 _Item2;
private readonly T3 _Item3;
private readonly T4 _Item4;
private readonly T5 _Item5;
private readonly T6 _Item6;
private readonly T7 _Item7;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
_Item1 = item1;
_Item2 = item2;
_Item3 = item3;
_Item4 = item4;
_Item5 = item5;
_Item6 = item6;
_Item7 = item7;
}
public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); }
public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); }
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
int num = 0;
num = comparer.Compare(_Item1, tuple._Item1);
if (num != 0)
return num;
num = comparer.Compare(_Item2, tuple._Item2);
if (num != 0)
return num;
num = comparer.Compare(_Item3, tuple._Item3);
if (num != 0)
return num;
num = comparer.Compare(_Item4, tuple._Item4);
if (num != 0)
return num;
num = comparer.Compare(_Item5, tuple._Item5);
if (num != 0)
return num;
num = comparer.Compare(_Item6, tuple._Item6);
if (num != 0)
return num;
return comparer.Compare(_Item7, tuple._Item7);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1, T2, T3, T4, T5, T6, T7>);
if (tuple == null)
return false;
return ((((comparer.Equals(_Item1, tuple._Item1) && comparer.Equals(_Item2, tuple._Item2)) && (comparer.Equals(_Item3, tuple._Item3) && comparer.Equals(_Item4, tuple._Item4))) && (comparer.Equals(_Item5, tuple._Item5) && comparer.Equals(_Item6, tuple._Item6))) && comparer.Equals(_Item7, tuple._Item7));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(_Item1), comparer.GetHashCode(_Item2), comparer.GetHashCode(_Item3), comparer.GetHashCode(_Item4), comparer.GetHashCode(_Item5), comparer.GetHashCode(_Item6), comparer.GetHashCode(_Item7)); }
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(_Item1);
sb.Append(", ");
sb.Append(_Item2);
sb.Append(", ");
sb.Append(_Item3);
sb.Append(", ");
sb.Append(_Item4);
sb.Append(", ");
sb.Append(_Item5);
sb.Append(", ");
sb.Append(_Item6);
sb.Append(", ");
sb.Append(_Item7);
sb.Append(")");
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
public T2 Item2
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item2; }
}
public T3 Item3
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item3; }
}
public T4 Item4
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item4; }
}
public T5 Item5
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item5; }
}
public T6 Item6
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item6; }
}
public T7 Item7
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item7; }
}
int ITuple.Size
{
get { return 7; }
}
}
#endregion
#region Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
[Serializable]
#if !COREINTERNAL
public
#endif
class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
{
private readonly T1 _Item1;
private readonly T2 _Item2;
private readonly T3 _Item3;
private readonly T4 _Item4;
private readonly T5 _Item5;
private readonly T6 _Item6;
private readonly T7 _Item7;
private readonly TRest _Rest;
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
if (!(rest is ITuple))
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleLastArgumentNotATuple"));
_Item1 = item1;
_Item2 = item2;
_Item3 = item3;
_Item4 = item4;
_Item5 = item5;
_Item6 = item6;
_Item7 = item7;
_Rest = rest;
}
public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); }
public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); }
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null)
return 1;
var tuple = (other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>);
if (tuple == null)
throw new ArgumentException(EnvironmentEx2.GetResourceString("ArgumentException_TupleIncorrectType", new object[] { base.GetType().ToString() }), "other");
int num = 0;
num = comparer.Compare(_Item1, tuple._Item1);
if (num != 0)
return num;
num = comparer.Compare(_Item2, tuple._Item2);
if (num != 0)
return num;
num = comparer.Compare(_Item3, tuple._Item3);
if (num != 0)
return num;
num = comparer.Compare(_Item4, tuple._Item4);
if (num != 0)
return num;
num = comparer.Compare(_Item5, tuple._Item5);
if (num != 0)
return num;
num = comparer.Compare(_Item6, tuple._Item6);
if (num != 0)
return num;
num = comparer.Compare(_Item7, tuple._Item7);
if (num != 0)
return num;
return comparer.Compare(_Rest, tuple._Rest);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null)
return false;
var tuple = (other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>);
if (tuple == null)
return false;
return ((((comparer.Equals(_Item1, tuple._Item1) && comparer.Equals(_Item2, tuple._Item2)) && (comparer.Equals(_Item3, tuple._Item3) && comparer.Equals(_Item4, tuple._Item4))) && ((comparer.Equals(_Item5, tuple._Item5) && comparer.Equals(_Item6, tuple._Item6)) && comparer.Equals(_Item7, tuple._Item7))) && comparer.Equals(_Rest, tuple._Rest));
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
var rest = (ITuple)_Rest;
if (rest.Size >= 8)
return rest.GetHashCode(comparer);
switch ((8 - rest.Size))
{
case 1:
return Tuple.CombineHashCodes(comparer.GetHashCode(_Item7), rest.GetHashCode(comparer));
case 2:
return Tuple.CombineHashCodes(comparer.GetHashCode(_Item6), comparer.GetHashCode(_Item7), rest.GetHashCode(comparer));
case 3:
return Tuple.CombineHashCodes(comparer.GetHashCode(_Item5), comparer.GetHashCode(_Item6), comparer.GetHashCode(_Item7), rest.GetHashCode(comparer));
case 4:
return Tuple.CombineHashCodes(comparer.GetHashCode(_Item4), comparer.GetHashCode(_Item5), comparer.GetHashCode(_Item6), comparer.GetHashCode(_Item7), rest.GetHashCode(comparer));
case 5:
return Tuple.CombineHashCodes(comparer.GetHashCode(_Item3), comparer.GetHashCode(_Item4), comparer.GetHashCode(_Item5), comparer.GetHashCode(_Item6), comparer.GetHashCode(_Item7), rest.GetHashCode(comparer));
case 6:
return Tuple.CombineHashCodes(comparer.GetHashCode(_Item2), comparer.GetHashCode(_Item3), comparer.GetHashCode(_Item4), comparer.GetHashCode(_Item5), comparer.GetHashCode(_Item6), comparer.GetHashCode(_Item7), rest.GetHashCode(comparer));
case 7:
return Tuple.CombineHashCodes(comparer.GetHashCode(_Item1), comparer.GetHashCode(_Item2), comparer.GetHashCode(_Item3), comparer.GetHashCode(_Item4), comparer.GetHashCode(_Item5), comparer.GetHashCode(_Item6), comparer.GetHashCode(_Item7), rest.GetHashCode(comparer));
}
return -1;
}
int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); }
int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); }
string ITuple.ToString(StringBuilder sb)
{
sb.Append(_Item1);
sb.Append(", ");
sb.Append(_Item2);
sb.Append(", ");
sb.Append(_Item3);
sb.Append(", ");
sb.Append(_Item4);
sb.Append(", ");
sb.Append(_Item5);
sb.Append(", ");
sb.Append(_Item6);
sb.Append(", ");
sb.Append(_Item7);
sb.Append(", ");
return ((ITuple)_Rest).ToString(sb);
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
public T1 Item1
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item1; }
}
public T2 Item2
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item2; }
}
public T3 Item3
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item3; }
}
public T4 Item4
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item4; }
}
public T5 Item5
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item5; }
}
public T6 Item6
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item6; }
}
public T7 Item7
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Item7; }
}
public TRest Rest
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get { return _Rest; }
}
int ITuple.Size
{
get { return (7 + ((ITuple)_Rest).Size); }
}
}
#endregion
}
#endif
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Services
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Services;
using Apache.Ignite.Core.Services;
using NUnit.Framework;
/// <summary>
/// Tests <see cref="ServiceProxySerializer"/> functionality.
/// </summary>
public class ServiceProxyTest
{
/** */
private TestIgniteService _svc;
/** */
private readonly Marshaller _marsh = new Marshaller(new BinaryConfiguration
{
TypeConfigurations = new[]
{
new BinaryTypeConfiguration(typeof (TestBinarizableClass)),
new BinaryTypeConfiguration(typeof (CustomExceptionBinarizable))
}
});
/** */
protected readonly IBinary Binary;
/** */
private readonly PlatformMemoryManager _memory = new PlatformMemoryManager(1024);
/** */
protected bool KeepBinary;
/** */
protected bool SrvKeepBinary;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceProxyTest"/> class.
/// </summary>
public ServiceProxyTest()
{
Binary = new Binary(_marsh);
}
/// <summary>
/// Tests object class methods proxying.
/// </summary>
[Test]
public void TestObjectClassMethods()
{
var prx = GetProxy();
prx.IntProp = 12345;
Assert.AreEqual("12345", prx.ToString());
Assert.AreEqual("12345", _svc.ToString());
Assert.AreEqual(12345, prx.GetHashCode());
Assert.AreEqual(12345, _svc.GetHashCode());
}
/// <summary>
/// Tests properties proxying.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
public void TestProperties()
{
var prx = GetProxy();
prx.IntProp = 10;
Assert.AreEqual(10, prx.IntProp);
Assert.AreEqual(10, _svc.IntProp);
_svc.IntProp = 15;
Assert.AreEqual(15, prx.IntProp);
Assert.AreEqual(15, _svc.IntProp);
prx.ObjProp = "prop1";
Assert.AreEqual("prop1", prx.ObjProp);
Assert.AreEqual("prop1", _svc.ObjProp);
prx.ObjProp = null;
Assert.IsNull(prx.ObjProp);
Assert.IsNull(_svc.ObjProp);
prx.ObjProp = new TestClass {Prop = "prop2"};
var propVal = KeepBinary
? ((IBinaryObject) prx.ObjProp).Deserialize<TestClass>().Prop
: ((TestClass) prx.ObjProp).Prop;
Assert.AreEqual("prop2", propVal);
Assert.AreEqual("prop2", ((TestClass) _svc.ObjProp).Prop);
}
/// <summary>
/// Tests void methods proxying.
/// </summary>
[Test]
public void TestVoidMethods()
{
var prx = GetProxy();
prx.VoidMethod();
Assert.AreEqual("VoidMethod", prx.InvokeResult);
Assert.AreEqual("VoidMethod", _svc.InvokeResult);
prx.VoidMethod(10);
Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult);
prx.VoidMethod(10, "string", "arg");
Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult);
prx.VoidMethod(10, "string", "arg", "arg1", 2, 3, "arg4");
Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult);
}
/// <summary>
/// Tests object methods proxying.
/// </summary>
[Test]
public void TestObjectMethods()
{
var prx = GetProxy();
Assert.AreEqual("ObjectMethod", prx.ObjectMethod());
Assert.AreEqual("ObjectMethod987", prx.ObjectMethod(987));
Assert.AreEqual("ObjectMethod987str123TestClass", prx.ObjectMethod(987, "str123", new TestClass()));
Assert.AreEqual("ObjectMethod987str123TestClass34arg5arg6",
prx.ObjectMethod(987, "str123", new TestClass(), 3, 4, "arg5", "arg6"));
}
/// <summary>
/// Tests methods that exist in proxy interface, but do not exist in the actual service.
/// </summary>
[Test]
public void TestMissingMethods()
{
var prx = GetProxy();
var ex = Assert.Throws<InvalidOperationException>(() => prx.MissingMethod());
Assert.AreEqual("Failed to invoke proxy: there is no method 'MissingMethod'" +
" in type 'Apache.Ignite.Core.Tests.Services.ServiceProxyTest+TestIgniteService'" +
" with 0 arguments", ex.Message);
}
/// <summary>
/// Tests ambiguous methods handling (multiple methods with the same signature).
/// </summary>
[Test]
public void TestAmbiguousMethods()
{
var prx = GetProxy();
var ex = Assert.Throws<InvalidOperationException>(() => prx.AmbiguousMethod(1));
Assert.AreEqual("Failed to invoke proxy: there are 2 methods 'AmbiguousMethod' in type " +
"'Apache.Ignite.Core.Tests.Services.ServiceProxyTest+TestIgniteService' with (Int32) arguments, " +
"can't resolve ambiguity.", ex.Message);
}
/// <summary>
/// Tests the exception.
/// </summary>
[Test]
public void TestException()
{
var prx = GetProxy();
var err = Assert.Throws<ServiceInvocationException>(prx.ExceptionMethod);
if (KeepBinary)
{
Assert.IsNotNull(err.BinaryCause);
Assert.AreEqual("Expected exception", err.BinaryCause.Deserialize<Exception>().Message);
}
else
{
Assert.IsNotNull(err.InnerException);
Assert.AreEqual("Expected exception", err.InnerException.Message);
}
Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionMethod());
}
[Test]
public void TestBinarizableMarshallingException()
{
var prx = GetProxy();
var ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionBinarizableMethod(false, false));
if (KeepBinary)
{
Assert.AreEqual("Proxy method invocation failed with a binary error. " +
"Examine BinaryCause for details.", ex.Message);
Assert.IsNotNull(ex.BinaryCause);
Assert.IsNull(ex.InnerException);
}
else
{
Assert.AreEqual("Proxy method invocation failed with an exception. " +
"Examine InnerException for details.", ex.Message);
Assert.IsNull(ex.BinaryCause);
Assert.IsNotNull(ex.InnerException);
}
ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionBinarizableMethod(true, false));
Assert.IsTrue(ex.ToString().Contains(
"Call completed with error, but error serialization failed [errType=CustomExceptionBinarizable, " +
"serializationErrMsg=Expected exception in CustomExceptionBinarizable.WriteBinary]"));
ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionBinarizableMethod(true, true));
Assert.IsTrue(ex.ToString().Contains(
"Call completed with error, but error serialization failed [errType=CustomExceptionBinarizable, " +
"serializationErrMsg=Expected exception in CustomExceptionBinarizable.WriteBinary]"));
}
/// <summary>
/// Creates the proxy.
/// </summary>
protected ITestIgniteServiceProxyInterface GetProxy()
{
return GetProxy<ITestIgniteServiceProxyInterface>();
}
/// <summary>
/// Creates the proxy.
/// </summary>
private T GetProxy<T>()
{
_svc = new TestIgniteService(Binary);
var prx = ServiceProxyFactory<T>.CreateProxy(InvokeProxyMethod);
Assert.IsFalse(ReferenceEquals(_svc, prx));
return prx;
}
/// <summary>
/// Invokes the proxy.
/// </summary>
/// <param name="method">Method.</param>
/// <param name="args">Arguments.</param>
/// <returns>
/// Invocation result.
/// </returns>
private object InvokeProxyMethod(MethodBase method, object[] args)
{
using (var inStream = new PlatformMemoryStream(_memory.Allocate()))
using (var outStream = new PlatformMemoryStream(_memory.Allocate()))
{
// 1) Write to a stream
inStream.WriteBool(SrvKeepBinary); // WriteProxyMethod does not do this, but Java does
ServiceProxySerializer.WriteProxyMethod(_marsh.StartMarshal(inStream), method.Name,
method, args, Platform.DotNet);
inStream.SynchronizeOutput();
inStream.Seek(0, SeekOrigin.Begin);
// 2) call InvokeServiceMethod
string mthdName;
object[] mthdArgs;
ServiceProxySerializer.ReadProxyMethod(inStream, _marsh, out mthdName, out mthdArgs);
var result = ServiceProxyInvoker.InvokeServiceMethod(_svc, mthdName, mthdArgs);
ServiceProxySerializer.WriteInvocationResult(outStream, _marsh, result.Key, result.Value);
var writer = _marsh.StartMarshal(outStream);
writer.WriteString("unused"); // fake Java exception details
writer.WriteString("unused"); // fake Java exception details
outStream.SynchronizeOutput();
outStream.Seek(0, SeekOrigin.Begin);
return ServiceProxySerializer.ReadInvocationResult(outStream, _marsh, KeepBinary);
}
}
/// <summary>
/// Test service interface.
/// </summary>
public interface ITestIgniteServiceProperties
{
/** */
int IntProp { get; set; }
/** */
object ObjProp { get; set; }
/** */
string InvokeResult { get; }
}
/// <summary>
/// Test service interface to check ambiguity handling.
/// </summary>
public interface ITestIgniteServiceAmbiguity
{
/** */
int AmbiguousMethod(int arg);
}
/// <summary>
/// Test service interface.
/// </summary>
public interface ITestIgniteService : ITestIgniteServiceProperties
{
/** */
void VoidMethod();
/** */
void VoidMethod(int arg);
/** */
void VoidMethod(int arg, string arg1, object arg2 = null);
/** */
void VoidMethod(int arg, string arg1, object arg2 = null, params object[] args);
/** */
object ObjectMethod();
/** */
object ObjectMethod(int arg);
/** */
object ObjectMethod(int arg, string arg1, object arg2 = null);
/** */
object ObjectMethod(int arg, string arg1, object arg2 = null, params object[] args);
/** */
void ExceptionMethod();
/** */
void CustomExceptionMethod();
/** */
void CustomExceptionBinarizableMethod(bool throwOnWrite, bool throwOnRead);
/** */
TestBinarizableClass BinarizableArgMethod(int arg1, IBinaryObject arg2);
/** */
IBinaryObject BinarizableResultMethod(int arg1, TestBinarizableClass arg2);
/** */
IBinaryObject BinarizableArgAndResultMethod(int arg1, IBinaryObject arg2);
/** */
int AmbiguousMethod(int arg);
}
/// <summary>
/// Test service interface. Does not derive from actual interface, but has all the same method signatures.
/// </summary>
public interface ITestIgniteServiceProxyInterface
{
/** */
int IntProp { get; set; }
/** */
object ObjProp { get; set; }
/** */
string InvokeResult { get; }
/** */
void VoidMethod();
/** */
void VoidMethod(int arg);
/** */
void VoidMethod(int arg, string arg1, object arg2);
/** */
void VoidMethod(int arg, string arg1, object arg2, params object[] args);
/** */
object ObjectMethod();
/** */
object ObjectMethod(int arg);
/** */
object ObjectMethod(int arg, string arg1, object arg2);
/** */
object ObjectMethod(int arg, string arg1, object arg2, params object[] args);
/** */
void ExceptionMethod();
/** */
void CustomExceptionMethod();
/** */
void CustomExceptionBinarizableMethod(bool throwOnWrite, bool throwOnRead);
/** */
TestBinarizableClass BinarizableArgMethod(int arg1, IBinaryObject arg2);
/** */
IBinaryObject BinarizableResultMethod(int arg1, TestBinarizableClass arg2);
/** */
IBinaryObject BinarizableArgAndResultMethod(int arg1, IBinaryObject arg2);
/** */
void MissingMethod();
/** */
int AmbiguousMethod(int arg);
}
/// <summary>
/// Test service.
/// </summary>
[Serializable]
private class TestIgniteService : ITestIgniteService, ITestIgniteServiceAmbiguity
{
/** */
private readonly IBinary _binary;
/// <summary>
/// Initializes a new instance of the <see cref="TestIgniteService"/> class.
/// </summary>
/// <param name="binary">Binary.</param>
public TestIgniteService(IBinary binary)
{
_binary = binary;
}
/** <inheritdoc /> */
public int IntProp { get; set; }
/** <inheritdoc /> */
public object ObjProp { get; set; }
/** <inheritdoc /> */
public string InvokeResult { get; private set; }
/** <inheritdoc /> */
public void VoidMethod()
{
InvokeResult = "VoidMethod";
}
/** <inheritdoc /> */
public void VoidMethod(int arg)
{
InvokeResult = "VoidMethod" + arg;
}
/** <inheritdoc /> */
public void VoidMethod(int arg, string arg1, object arg2 = null)
{
InvokeResult = "VoidMethod" + arg + arg1 + arg2;
}
/** <inheritdoc /> */
public void VoidMethod(int arg, string arg1, object arg2 = null, params object[] args)
{
InvokeResult = "VoidMethod" + arg + arg1 + arg2 + string.Concat(args.Select(x => x.ToString()));
}
/** <inheritdoc /> */
public object ObjectMethod()
{
return "ObjectMethod";
}
/** <inheritdoc /> */
public object ObjectMethod(int arg)
{
return "ObjectMethod" + arg;
}
/** <inheritdoc /> */
public object ObjectMethod(int arg, string arg1, object arg2 = null)
{
return "ObjectMethod" + arg + arg1 + arg2;
}
/** <inheritdoc /> */
public object ObjectMethod(int arg, string arg1, object arg2 = null, params object[] args)
{
return "ObjectMethod" + arg + arg1 + arg2 + string.Concat(args.Select(x => x.ToString()));
}
/** <inheritdoc /> */
public void ExceptionMethod()
{
throw new ArithmeticException("Expected exception");
}
/** <inheritdoc /> */
public void CustomExceptionMethod()
{
throw new CustomException();
}
/** <inheritdoc /> */
public void CustomExceptionBinarizableMethod(bool throwOnWrite, bool throwOnRead)
{
throw new CustomExceptionBinarizable {ThrowOnRead = throwOnRead, ThrowOnWrite = throwOnWrite};
}
/** <inheritdoc /> */
public TestBinarizableClass BinarizableArgMethod(int arg1, IBinaryObject arg2)
{
return arg2.Deserialize<TestBinarizableClass>();
}
/** <inheritdoc /> */
public IBinaryObject BinarizableResultMethod(int arg1, TestBinarizableClass arg2)
{
return _binary.ToBinary<IBinaryObject>(arg2);
}
/** <inheritdoc /> */
public IBinaryObject BinarizableArgAndResultMethod(int arg1, IBinaryObject arg2)
{
return _binary.ToBinary<IBinaryObject>(arg2.Deserialize<TestBinarizableClass>());
}
/** <inheritdoc /> */
public override string ToString()
{
return IntProp.ToString();
}
/** <inheritdoc /> */
public override int GetHashCode()
{
// ReSharper disable once NonReadonlyMemberInGetHashCode
return IntProp.GetHashCode();
}
/** <inheritdoc /> */
int ITestIgniteService.AmbiguousMethod(int arg)
{
return arg;
}
/** <inheritdoc /> */
int ITestIgniteServiceAmbiguity.AmbiguousMethod(int arg)
{
return -arg;
}
}
/// <summary>
/// Test serializable class.
/// </summary>
[Serializable]
private class TestClass
{
/** */
public string Prop { get; set; }
/** <inheritdoc /> */
public override string ToString()
{
return "TestClass" + Prop;
}
}
/// <summary>
/// Custom non-serializable exception.
/// </summary>
private class CustomException : Exception, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
/// Custom non-serializable exception.
/// </summary>
private class CustomExceptionBinarizable : Exception, IBinarizable
{
/** */
public bool ThrowOnWrite { get; set; }
/** */
public bool ThrowOnRead { get; set; }
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteBoolean("ThrowOnRead", ThrowOnRead);
if (ThrowOnWrite)
throw new Exception("Expected exception in CustomExceptionBinarizable.WriteBinary");
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
ThrowOnRead = reader.ReadBoolean("ThrowOnRead");
if (ThrowOnRead)
throw new Exception("Expected exception in CustomExceptionBinarizable.ReadBinary");
}
}
/// <summary>
/// Binarizable object for method argument/result.
/// </summary>
public class TestBinarizableClass : IBinarizable
{
/** */
public string Prop { get; set; }
/** */
public bool ThrowOnWrite { get; set; }
/** */
public bool ThrowOnRead { get; set; }
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteString("Prop", Prop);
writer.WriteBoolean("ThrowOnRead", ThrowOnRead);
if (ThrowOnWrite)
throw new Exception("Expected exception in TestBinarizableClass.WriteBinary");
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
Prop = reader.ReadString("Prop");
ThrowOnRead = reader.ReadBoolean("ThrowOnRead");
if (ThrowOnRead)
throw new Exception("Expected exception in TestBinarizableClass.ReadBinary");
}
}
}
/// <summary>
/// Tests <see cref="ServiceProxySerializer"/> functionality with keepBinary mode enabled on client.
/// </summary>
public class ServiceProxyTestKeepBinaryClient : ServiceProxyTest
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceProxyTestKeepBinaryClient"/> class.
/// </summary>
public ServiceProxyTestKeepBinaryClient()
{
KeepBinary = true;
}
[Test]
public void TestBinarizableMethods()
{
var prx = GetProxy();
var obj = new TestBinarizableClass { Prop = "PropValue" };
var result = prx.BinarizableResultMethod(1, obj);
Assert.AreEqual(obj.Prop, result.Deserialize<TestBinarizableClass>().Prop);
}
}
/// <summary>
/// Tests <see cref="ServiceProxySerializer"/> functionality with keepBinary mode enabled on server.
/// </summary>
public class ServiceProxyTestKeepBinaryServer : ServiceProxyTest
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceProxyTestKeepBinaryServer"/> class.
/// </summary>
public ServiceProxyTestKeepBinaryServer()
{
SrvKeepBinary = true;
}
[Test]
public void TestBinarizableMethods()
{
var prx = GetProxy();
var obj = new TestBinarizableClass { Prop = "PropValue" };
var portObj = Binary.ToBinary<IBinaryObject>(obj);
var result = prx.BinarizableArgMethod(1, portObj);
Assert.AreEqual(obj.Prop, result.Prop);
}
}
/// <summary>
/// Tests <see cref="ServiceProxySerializer"/> functionality with keepBinary mode enabled on client and on server.
/// </summary>
public class ServiceProxyTestKeepBinaryClientServer : ServiceProxyTest
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceProxyTestKeepBinaryClientServer"/> class.
/// </summary>
public ServiceProxyTestKeepBinaryClientServer()
{
KeepBinary = true;
SrvKeepBinary = true;
}
[Test]
public void TestBinarizableMethods()
{
var prx = GetProxy();
var obj = new TestBinarizableClass { Prop = "PropValue" };
var portObj = Binary.ToBinary<IBinaryObject>(obj);
var result = prx.BinarizableArgAndResultMethod(1, portObj);
Assert.AreEqual(obj.Prop, result.Deserialize<TestBinarizableClass>().Prop);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AdventureWorks.UILogic.Models;
using AdventureWorks.UILogic.Services;
using AdventureWorks.UILogic.Tests.Mocks;
using AdventureWorks.UILogic.ViewModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AdventureWorks.UILogic.Tests.ViewModels
{
[TestClass]
public class CheckoutHubPageViewModelFixture
{
[TestMethod]
public void ExecuteGoNextCommand_Validates3ViewModels()
{
bool shippingValidationExecuted = false;
bool billingValidationExecuted = false;
bool paymentValidationExecuted = false;
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => { shippingValidationExecuted = true; return false; }
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => { billingValidationExecuted = true; return false; }
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => { paymentValidationExecuted = true; return false; }
};
var target = new CheckoutHubPageViewModel(new MockNavigationService(), null, null, new MockShoppingCartRepository(),
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.GoNextCommand.Execute();
Assert.IsTrue(shippingValidationExecuted);
Assert.IsTrue(billingValidationExecuted);
Assert.IsTrue(paymentValidationExecuted);
}
[TestMethod]
public void ExecuteGoNextCommand_ProcessesFormsAndNavigates_IfViewModelsAreValid()
{
bool shippingInfoProcessed = false;
bool billingInfoProcessed = false;
bool paymentInfoProcessed = false;
bool navigated = false;
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () =>
{
shippingInfoProcessed = true;
return Task.Delay(0);
}
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () =>
{
billingInfoProcessed = true;
return Task.Delay(0);
}
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = async () =>
{
paymentInfoProcessed = true;
await Task.Delay(0);
}
};
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () => Task.FromResult(new UserInfo()),
SignedInUser = new UserInfo() { UserName = "test" }
};
var orderRepository = new MockOrderRepository()
{
CreateBasicOrderAsyncDelegate = (a, b, c, d, e) => Task.FromResult(new Order() { Id = 1 })
};
var shoppingCartRepository = new MockShoppingCartRepository()
{
GetShoppingCartAsyncDelegate = () => Task.FromResult(new ShoppingCart(null))
};
var navigationService = new MockNavigationService()
{
NavigateDelegate = (a, b) => navigated = true
};
var target = new CheckoutHubPageViewModel(navigationService, accountService, orderRepository, shoppingCartRepository,
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.GoNextCommand.Execute();
Assert.IsTrue(shippingInfoProcessed);
Assert.IsTrue(billingInfoProcessed);
Assert.IsTrue(paymentInfoProcessed);
Assert.IsTrue(navigated);
}
[TestMethod]
public void ExecuteGoNextCommand_DoNothing_IfViewModelsAreInvalid()
{
bool formProcessStarted = false;
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () =>
{
// The process starts with a call to retrieve the logged user
formProcessStarted = true;
return Task.FromResult(new UserInfo());
}
};
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel();
var billingAddressPageViewModel = new MockBillingAddressPageViewModel();
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel();
var target = new CheckoutHubPageViewModel(new MockNavigationService(), accountService, null, null,
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
// ShippingAddress invalid only
shippingAddressPageViewModel.ValidateFormDelegate = () => false;
billingAddressPageViewModel.ValidateFormDelegate = () => true;
paymentMethodPageViewModel.ValidateFormDelegate = () => true;
target.GoNextCommand.Execute();
Assert.IsFalse(formProcessStarted);
// BillingAddress invalid only
shippingAddressPageViewModel.ValidateFormDelegate = () => true;
billingAddressPageViewModel.ValidateFormDelegate = () => false;
paymentMethodPageViewModel.ValidateFormDelegate = () => true;
Assert.IsFalse(formProcessStarted);
// PaymentMethod invalid only
shippingAddressPageViewModel.ValidateFormDelegate = () => true;
billingAddressPageViewModel.ValidateFormDelegate = () => true;
paymentMethodPageViewModel.ValidateFormDelegate = () => false;
Assert.IsFalse(formProcessStarted);
}
[TestMethod]
public void SettingUseShippingAddressToTrue_CopiesValuesFromShippingAddressToBilling()
{
var mockAddress = new Address()
{
FirstName = "TestFirstName",
MiddleInitial = "TestMiddleInitial",
LastName = "TestLastName",
StreetAddress = "TestStreetAddress",
OptionalAddress = "TestOptionalAddress",
City = "TestCity",
State = "TestState",
ZipCode = "123456",
Phone = "123456"
};
var compareAddressesFunc = new Func<Address, Address, bool>((Address a1, Address a2) =>
{
return a1.FirstName == a2.FirstName && a1.MiddleInitial == a2.MiddleInitial && a1.LastName == a2.LastName
&& a1.StreetAddress == a2.StreetAddress && a1.OptionalAddress == a2.OptionalAddress && a1.City == a2.City
&& a1.State == a2.State && a1.ZipCode == a2.ZipCode && a1.Phone == a2.Phone;
});
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () => Task.Delay(0),
Address = mockAddress
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => true
};
billingAddressPageViewModel.ProcessFormAsyncDelegate = () =>
{
// The Address have to be updated before the form is processed
Assert.IsTrue(compareAddressesFunc(shippingAddressPageViewModel.Address, billingAddressPageViewModel.Address));
return Task.Delay(0);
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = async () => await Task.Delay(0),
};
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () => Task.FromResult(new UserInfo()),
SignedInUser = new UserInfo()
};
var orderRepository = new MockOrderRepository()
{
CreateBasicOrderAsyncDelegate = (userId, shoppingCart, shippingAddress, billingAddress, paymentMethod) =>
{
// The Address information stored in the order must be the same
Assert.IsTrue(compareAddressesFunc(shippingAddress, billingAddress));
return Task.FromResult<Order>(new Order());
}
};
var shoppingCartRepository = new MockShoppingCartRepository()
{
GetShoppingCartAsyncDelegate = () => Task.FromResult(new ShoppingCart(null))
};
var navigationService = new MockNavigationService()
{
NavigateDelegate = (a, b) => true
};
var target = new CheckoutHubPageViewModel(navigationService, accountService, orderRepository, shoppingCartRepository,
shippingAddressPageViewModel, billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.UseSameAddressAsShipping = true;
target.GoNextCommand.Execute();
}
[TestMethod]
public void ProcessFormAsync_WithServerValidationError_ShowsMessage()
{
var shippingAddressPageViewModel = new MockShippingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () => Task.Delay(0),
Address = new Address()
};
var billingAddressPageViewModel = new MockBillingAddressPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = () => Task.Delay(0),
Address = new Address()
};
var paymentMethodPageViewModel = new MockPaymentMethodPageViewModel()
{
ValidateFormDelegate = () => true,
ProcessFormAsyncDelegate = async () => await Task.Delay(0),
PaymentMethod = new PaymentMethod()
};
var accountService = new MockAccountService()
{
VerifyUserAuthenticationAsyncDelegate = () => Task.FromResult(new UserInfo()),
SignedInUser = new UserInfo()
};
var shoppingCartRepository = new MockShoppingCartRepository()
{
GetShoppingCartAsyncDelegate =
() => Task.FromResult(new ShoppingCart(null))
};
var orderRepository = new MockOrderRepository()
{
CreateBasicOrderAsyncDelegate = (s, cart, arg3, arg4, arg5) =>
{
var result = new ModelValidationResult();
result.ModelState.Add("order.ShippingAddress.ZipCode", new List<string>{"Validation Message"});
throw new ModelValidationException(result);
}
};
var target = new CheckoutHubPageViewModel(new MockNavigationService(), accountService, orderRepository, shoppingCartRepository, shippingAddressPageViewModel,
billingAddressPageViewModel, paymentMethodPageViewModel, null, null);
target.GoNextCommand.Execute();
Assert.IsTrue(target.IsShippingAddressInvalid);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.DataLake.AnalyticsJob.Models;
namespace Microsoft.Azure.Management.DataLake.AnalyticsJob.Models
{
/// <summary>
/// The Data Lake Analytics U-SQL specific job properties.
/// </summary>
public partial class USqlProperties : JobProperties
{
private string _algebraFilePath;
/// <summary>
/// Optional. Gets or sets the U-SQL algebra file path after the job
/// has completed
/// </summary>
public string AlgebraFilePath
{
get { return this._algebraFilePath; }
set { this._algebraFilePath = value; }
}
private string _compileMode;
/// <summary>
/// Optional. Gets or sets the compile mode for the job.
/// </summary>
public string CompileMode
{
get { return this._compileMode; }
set { this._compileMode = value; }
}
private JobDataPath _debugData;
/// <summary>
/// Optional. Gets or sets the job specific debug data locations.
/// </summary>
public JobDataPath DebugData
{
get { return this._debugData; }
set { this._debugData = value; }
}
private IList<Diagnostics> _diagnostics;
/// <summary>
/// Optional. Gets or sets the diagnostics for the job.
/// </summary>
public IList<Diagnostics> Diagnostics
{
get { return this._diagnostics; }
set { this._diagnostics = value; }
}
private IList<JobResource> _resources;
/// <summary>
/// Optional. Gets or sets the list of resources that are required by
/// the job
/// </summary>
public IList<JobResource> Resources
{
get { return this._resources; }
set { this._resources = value; }
}
private System.Guid? _rootProcessNodeId;
/// <summary>
/// Optional. Gets or sets the ID used to identify the job manager
/// coordinating job execution.This value should not be set by the
/// user and will be ignored if it is.
/// </summary>
public System.Guid? RootProcessNodeId
{
get { return this._rootProcessNodeId; }
set { this._rootProcessNodeId = value; }
}
private JobStatistics _statistics;
/// <summary>
/// Optional. Gets or sets the job specific statistics.
/// </summary>
public JobStatistics Statistics
{
get { return this._statistics; }
set { this._statistics = value; }
}
private System.TimeSpan? _totalCompilationTime;
/// <summary>
/// Optional. Gets or sets the total time this job spent compiling.
/// This value should not be set by the user and will be ignored if it
/// is.
/// </summary>
public System.TimeSpan? TotalCompilationTime
{
get { return this._totalCompilationTime; }
set { this._totalCompilationTime = value; }
}
private System.TimeSpan? _totalPausedTime;
/// <summary>
/// Optional. Gets or sets the total time this job spent paused. This
/// value should not be set by the user and will be ignored if it is.
/// </summary>
public System.TimeSpan? TotalPausedTime
{
get { return this._totalPausedTime; }
set { this._totalPausedTime = value; }
}
private System.TimeSpan? _totalQueuedTime;
/// <summary>
/// Optional. Gets or sets the total time this job spent queued. This
/// value should not be set by the user and will be ignored if it is.
/// </summary>
public System.TimeSpan? TotalQueuedTime
{
get { return this._totalQueuedTime; }
set { this._totalQueuedTime = value; }
}
private System.TimeSpan? _totalRunningTime;
/// <summary>
/// Optional. Gets or sets the total time this job spent executing.
/// This value should not be set by the user and will be ignored if it
/// is.
/// </summary>
public System.TimeSpan? TotalRunningTime
{
get { return this._totalRunningTime; }
set { this._totalRunningTime = value; }
}
private int? _yarnApplicationId;
/// <summary>
/// Optional. Gets or sets the ID used to identify the yarn application
/// executing the job.This value should not be set by the user and
/// will be ignored if it is.
/// </summary>
public int? YarnApplicationId
{
get { return this._yarnApplicationId; }
set { this._yarnApplicationId = value; }
}
private long? _yarnApplicationTimeStamp;
/// <summary>
/// Optional. Gets or sets the timestamp (in ticks) for the yarn
/// application executing the job.This value should not be set by the
/// user and will be ignored if it is.
/// </summary>
public long? YarnApplicationTimeStamp
{
get { return this._yarnApplicationTimeStamp; }
set { this._yarnApplicationTimeStamp = value; }
}
/// <summary>
/// Initializes a new instance of the USqlProperties class.
/// </summary>
public USqlProperties()
{
this.Diagnostics = new LazyList<Diagnostics>();
this.Resources = new LazyList<JobResource>();
}
/// <summary>
/// Initializes a new instance of the USqlProperties class with
/// required arguments.
/// </summary>
public USqlProperties(string script)
: this()
{
if (script == null)
{
throw new ArgumentNullException("script");
}
this.Script = script;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.SiteRecovery;
using Microsoft.Azure.Management.SiteRecovery.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of Protection Container operations for the Site Recovery
/// extension.
/// </summary>
internal partial class ProtectionContainerOperations : IServiceOperations<SiteRecoveryManagementClient>, IProtectionContainerOperations
{
/// <summary>
/// Initializes a new instance of the ProtectionContainerOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProtectionContainerOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Discovers a protectable item.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Required. Protection container name.
/// </param>
/// <param name='input'>
/// Required. Discover Protectable Item Request.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> BeginDiscoverProtectableItemAsync(string fabricName, string protectionContainerName, DiscoverProtectableItemRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (fabricName == null)
{
throw new ArgumentNullException("fabricName");
}
if (protectionContainerName == null)
{
throw new ArgumentNullException("protectionContainerName");
}
if (input == null)
{
throw new ArgumentNullException("input");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("protectionContainerName", protectionContainerName);
tracingParameters.Add("input", input);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "BeginDiscoverProtectableItemAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationFabrics/";
url = url + Uri.EscapeDataString(fabricName);
url = url + "/replicationProtectionContainers/";
url = url + Uri.EscapeDataString(protectionContainerName);
url = url + "/discoverProtectableItem";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject discoverProtectableItemRequestValue = new JObject();
requestDoc = discoverProtectableItemRequestValue;
if (input.Properties != null)
{
JObject propertiesValue = new JObject();
discoverProtectableItemRequestValue["properties"] = propertiesValue;
if (input.Properties.FriendlyName != null)
{
propertiesValue["friendlyName"] = input.Properties.FriendlyName;
}
if (input.Properties.IpAddress != null)
{
propertiesValue["ipAddress"] = input.Properties.IpAddress;
}
if (input.Properties.OsType != null)
{
propertiesValue["osType"] = input.Properties.OsType;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
// Deserialize Response
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Location"))
{
result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Discovers a protectable item.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Required. Protection container name.
/// </param>
/// <param name='input'>
/// Required. Discover Protectable Item Request.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> DiscoverProtectableItemAsync(string fabricName, string protectionContainerName, DiscoverProtectableItemRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
SiteRecoveryManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("protectionContainerName", protectionContainerName);
tracingParameters.Add("input", input);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "DiscoverProtectableItemAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse response = await client.ProtectionContainer.BeginDiscoverProtectableItemAsync(fabricName, protectionContainerName, input, customRequestHeaders, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
DiscoverProtectableItemResponse result = await client.ProtectionContainer.GetDiscoverProtectableItemStatusAsync(response.Location, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.ProtectionContainer.GetDiscoverProtectableItemStatusAsync(response.Location, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get the protected container by Id.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric Name.
/// </param>
/// <param name='protectionContainerName'>
/// Required. Protection Container Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Protection Container object.
/// </returns>
public async Task<ProtectionContainerResponse> GetAsync(string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (fabricName == null)
{
throw new ArgumentNullException("fabricName");
}
if (protectionContainerName == null)
{
throw new ArgumentNullException("protectionContainerName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("protectionContainerName", protectionContainerName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationFabrics/";
url = url + Uri.EscapeDataString(fabricName);
url = url + "/replicationProtectionContainers/";
url = url + Uri.EscapeDataString(protectionContainerName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProtectionContainerResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProtectionContainerResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProtectionContainer protectionContainerInstance = new ProtectionContainer();
result.ProtectionContainer = protectionContainerInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ProtectionContainerProperties propertiesInstance = new ProtectionContainerProperties();
protectionContainerInstance.Properties = propertiesInstance;
JToken fabricFriendlyNameValue = propertiesValue["fabricFriendlyName"];
if (fabricFriendlyNameValue != null && fabricFriendlyNameValue.Type != JTokenType.Null)
{
string fabricFriendlyNameInstance = ((string)fabricFriendlyNameValue);
propertiesInstance.FabricFriendlyName = fabricFriendlyNameInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken fabricTypeValue = propertiesValue["fabricType"];
if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
{
string fabricTypeInstance = ((string)fabricTypeValue);
propertiesInstance.FabricType = fabricTypeInstance;
}
JToken protectedItemCountValue = propertiesValue["protectedItemCount"];
if (protectedItemCountValue != null && protectedItemCountValue.Type != JTokenType.Null)
{
int protectedItemCountInstance = ((int)protectedItemCountValue);
propertiesInstance.ProtectedItemCount = protectedItemCountInstance;
}
JToken pairingStatusValue = propertiesValue["pairingStatus"];
if (pairingStatusValue != null && pairingStatusValue.Type != JTokenType.Null)
{
string pairingStatusInstance = ((string)pairingStatusValue);
propertiesInstance.PairingStatus = pairingStatusInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken fabricSpecificDetailsValue = propertiesValue["fabricSpecificDetails"];
if (fabricSpecificDetailsValue != null && fabricSpecificDetailsValue.Type != JTokenType.Null)
{
string typeName = ((string)fabricSpecificDetailsValue["instanceType"]);
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
protectionContainerInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
protectionContainerInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
protectionContainerInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
protectionContainerInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
protectionContainerInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for operation which change status of protection
/// container.
/// </returns>
public async Task<DiscoverProtectableItemResponse> GetDiscoverProtectableItemStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetDiscoverProtectableItemStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DiscoverProtectableItemResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DiscoverProtectableItemResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProtectionContainer protectionContainerInstance = new ProtectionContainer();
result.ProtectionContainer = protectionContainerInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ProtectionContainerProperties propertiesInstance = new ProtectionContainerProperties();
protectionContainerInstance.Properties = propertiesInstance;
JToken fabricFriendlyNameValue = propertiesValue["fabricFriendlyName"];
if (fabricFriendlyNameValue != null && fabricFriendlyNameValue.Type != JTokenType.Null)
{
string fabricFriendlyNameInstance = ((string)fabricFriendlyNameValue);
propertiesInstance.FabricFriendlyName = fabricFriendlyNameInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken fabricTypeValue = propertiesValue["fabricType"];
if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
{
string fabricTypeInstance = ((string)fabricTypeValue);
propertiesInstance.FabricType = fabricTypeInstance;
}
JToken protectedItemCountValue = propertiesValue["protectedItemCount"];
if (protectedItemCountValue != null && protectedItemCountValue.Type != JTokenType.Null)
{
int protectedItemCountInstance = ((int)protectedItemCountValue);
propertiesInstance.ProtectedItemCount = protectedItemCountInstance;
}
JToken pairingStatusValue = propertiesValue["pairingStatus"];
if (pairingStatusValue != null && pairingStatusValue.Type != JTokenType.Null)
{
string pairingStatusInstance = ((string)pairingStatusValue);
propertiesInstance.PairingStatus = pairingStatusInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken fabricSpecificDetailsValue = propertiesValue["fabricSpecificDetails"];
if (fabricSpecificDetailsValue != null && fabricSpecificDetailsValue.Type != JTokenType.Null)
{
string typeName = ((string)fabricSpecificDetailsValue["instanceType"]);
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
protectionContainerInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
protectionContainerInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
protectionContainerInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
protectionContainerInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
protectionContainerInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken locationValue2 = responseDoc["Location"];
if (locationValue2 != null && locationValue2.Type != JTokenType.Null)
{
string locationInstance2 = ((string)locationValue2);
result.Location = locationInstance2;
}
JToken retryAfterValue = responseDoc["RetryAfter"];
if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null)
{
int retryAfterInstance = ((int)retryAfterValue);
result.RetryAfter = retryAfterInstance;
}
JToken asyncOperationValue = responseDoc["AsyncOperation"];
if (asyncOperationValue != null && asyncOperationValue.Type != JTokenType.Null)
{
string asyncOperationInstance = ((string)asyncOperationValue);
result.AsyncOperation = asyncOperationInstance;
}
JToken statusValue = responseDoc["Status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true));
result.Status = statusInstance;
}
JToken cultureValue = responseDoc["Culture"];
if (cultureValue != null && cultureValue.Type != JTokenType.Null)
{
string cultureInstance = ((string)cultureValue);
result.Culture = cultureInstance;
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Location"))
{
result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all ProtectionContainers for the given server.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric Unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list ProtectionContainers operation.
/// </returns>
public async Task<ProtectionContainerListResponse> ListAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (fabricName == null)
{
throw new ArgumentNullException("fabricName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationFabrics/";
url = url + Uri.EscapeDataString(fabricName);
url = url + "/replicationProtectionContainers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProtectionContainerListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProtectionContainerListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProtectionContainer protectionContainerInstance = new ProtectionContainer();
result.ProtectionContainers.Add(protectionContainerInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ProtectionContainerProperties propertiesInstance = new ProtectionContainerProperties();
protectionContainerInstance.Properties = propertiesInstance;
JToken fabricFriendlyNameValue = propertiesValue["fabricFriendlyName"];
if (fabricFriendlyNameValue != null && fabricFriendlyNameValue.Type != JTokenType.Null)
{
string fabricFriendlyNameInstance = ((string)fabricFriendlyNameValue);
propertiesInstance.FabricFriendlyName = fabricFriendlyNameInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken fabricTypeValue = propertiesValue["fabricType"];
if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
{
string fabricTypeInstance = ((string)fabricTypeValue);
propertiesInstance.FabricType = fabricTypeInstance;
}
JToken protectedItemCountValue = propertiesValue["protectedItemCount"];
if (protectedItemCountValue != null && protectedItemCountValue.Type != JTokenType.Null)
{
int protectedItemCountInstance = ((int)protectedItemCountValue);
propertiesInstance.ProtectedItemCount = protectedItemCountInstance;
}
JToken pairingStatusValue = propertiesValue["pairingStatus"];
if (pairingStatusValue != null && pairingStatusValue.Type != JTokenType.Null)
{
string pairingStatusInstance = ((string)pairingStatusValue);
propertiesInstance.PairingStatus = pairingStatusInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken fabricSpecificDetailsValue = propertiesValue["fabricSpecificDetails"];
if (fabricSpecificDetailsValue != null && fabricSpecificDetailsValue.Type != JTokenType.Null)
{
string typeName = ((string)fabricSpecificDetailsValue["instanceType"]);
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
protectionContainerInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
protectionContainerInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
protectionContainerInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
protectionContainerInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
protectionContainerInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all ProtectionContainers for the given vault.
/// </summary>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list ProtectionContainers operation.
/// </returns>
public async Task<ProtectionContainerListResponse> ListAllAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAllAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationProtectionContainers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProtectionContainerListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProtectionContainerListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProtectionContainer protectionContainerInstance = new ProtectionContainer();
result.ProtectionContainers.Add(protectionContainerInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ProtectionContainerProperties propertiesInstance = new ProtectionContainerProperties();
protectionContainerInstance.Properties = propertiesInstance;
JToken fabricFriendlyNameValue = propertiesValue["fabricFriendlyName"];
if (fabricFriendlyNameValue != null && fabricFriendlyNameValue.Type != JTokenType.Null)
{
string fabricFriendlyNameInstance = ((string)fabricFriendlyNameValue);
propertiesInstance.FabricFriendlyName = fabricFriendlyNameInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken fabricTypeValue = propertiesValue["fabricType"];
if (fabricTypeValue != null && fabricTypeValue.Type != JTokenType.Null)
{
string fabricTypeInstance = ((string)fabricTypeValue);
propertiesInstance.FabricType = fabricTypeInstance;
}
JToken protectedItemCountValue = propertiesValue["protectedItemCount"];
if (protectedItemCountValue != null && protectedItemCountValue.Type != JTokenType.Null)
{
int protectedItemCountInstance = ((int)protectedItemCountValue);
propertiesInstance.ProtectedItemCount = protectedItemCountInstance;
}
JToken pairingStatusValue = propertiesValue["pairingStatus"];
if (pairingStatusValue != null && pairingStatusValue.Type != JTokenType.Null)
{
string pairingStatusInstance = ((string)pairingStatusValue);
propertiesInstance.PairingStatus = pairingStatusInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken fabricSpecificDetailsValue = propertiesValue["fabricSpecificDetails"];
if (fabricSpecificDetailsValue != null && fabricSpecificDetailsValue.Type != JTokenType.Null)
{
string typeName = ((string)fabricSpecificDetailsValue["instanceType"]);
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
protectionContainerInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
protectionContainerInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
protectionContainerInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
protectionContainerInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
protectionContainerInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//
// Copyright (c) XSharp B.V. All Rights Reserved.
// Licensed under the Apache License, Version 2.0.
// See License.txt in the project root for license information.
//
namespace XSharp.Project
{
using Microsoft.VisualStudio.PlatformUI;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Shell;
using VSLangProj;
/// <summary>
/// Property page contents for the Candle Settings page.
/// </summary>
internal partial class XBuildPropertyPagePanel : XPropertyPagePanel
{
#region Constants
internal const string catSigning = "Code Signing";
internal const string catMisc = "Miscellaneous";
internal const string catWarnings = "Warnings";
internal const string catOutput = "\tOutput";
internal const string CatPreprocessor = "Preprocessor";
internal const string catXML = "XML Output";
internal const string captOutputPath = "Output Path";
internal const string descOutputPath = "Output Path (macros are allowed)";
internal const string captIntermediateOutputPath = "Intermediate Output Path";
internal const string descIntermediateOutputPath = "Intermediate Output Path (macros are allowed)";
internal const string captDocumentationFile = "Generate XML doc comments file";
internal const string descDocumentationFile = "Generate XML doc comments file";
internal const string captDocumentationFileName = "XML doc comments file name";
internal const string descDocumentationFileName = "XML doc comments file name";
internal const string captOptimize = "Optimize";
internal const string descOptimize = "Should compiler optimize output? (/optimize)";
internal const string captUseSharedCompilation = "Use Shared Compiler";
internal const string descUseSharedCompilation = "Should the shared compiler be used to compile the project? (Faster, but may hide some compiler errors) (/shared)";
internal const string captDisabledWarnings = "Suppress Specific Warnings";
internal const string descDisabledWarnings = "Specify a list of warnings to suppress (/nowarn)";
internal const string captWarningLevel = "Warning Level";
internal const string descWarningLevel = "Set the warning level to a value between 0 and 4 (/warn)";
internal const string captTreatWarningsAsErrors = "Warnings As Errors";
internal const string descTreatWarningsAsErrors = "Treat warnings as errors (/warnaserror)";
internal const string captSignAssembly = "Sign the output assembly";
internal const string descSignAssembly = "Sign the assembly (/keyfile)";
internal const string captDelaySign = "Delayed sign only";
internal const string descDelaySign = "Delayed signing (/delaysign)";
internal const string captAssemblyOriginatorKeyFile = "Code Signing KeyFile";
internal const string descAssemblyOriginatorKeyFile = "Choose a code signing key file (/keyfile)";
internal const string captRegisterForComInterop = "Register for COM Interop";
internal const string descRegisterForComInterop = "Register the output assembly for COM Interop (requires administrator rights)";
internal const string PPOCaption = "Generate preprocessor output";
internal const string PPODescription = "Save the output from the preprocessor to .ppo files (/ppo)";
internal const string CmdLineCaption = "Extra Command Line Options";
internal const string CmdLineDescription = "User-Defined Command Line options";
internal const string DefCaption = "Defines for the preprocessor";
internal const string DefDescription = "Defines for the preprocessor (/define)";
internal const string captPrefer32Bit = "\tPrefer 32 Bit";
internal const string descPrefer32Bit = "Prefer 32 bit when AnyCpu platform is selected. (/platform)";
internal const string SuppressRCWarningsCaption = "Suppress Resource Compiler warnings";
internal const string SuppressRCWarningsDescription = "Suppress warnings from the Native Resource Compiler about duplicate defines (RC4005)";
internal const string captPlatFormTarget= "Platform Target";
internal const string descPlatFormTarget = "Select the platform target when compiling this project. This should be AnyCPU, X86, x64,Arm or Itanium (/platform)";
internal const string defaultOutputPath = @"bin\$(Configuration)\";
internal const string defaultIntermediatePath = @"obj\$(Configuration)\";
internal const string descSpecificWarnings = "Specific Warnings To Treat As Errors";
#endregion
// =========================================================================================
// Constructors
// =========================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="XBuildEventsPropertyPagePanel"/> class.
/// </summary>
/// <param name="parentPropertyPage">The parent property page to which this is bound.</param>
public XBuildPropertyPagePanel(XPropertyPage parentPropertyPage)
: base(parentPropertyPage)
{
this.InitializeComponent();
this.chkPPO.Text = PPOCaption;
this.chkPPO.Tag = "PPO";
this.toolTip1.SetToolTip(this.chkPPO, PPODescription);
this.chkUseSharedCompilation.Text = captUseSharedCompilation;
this.chkUseSharedCompilation.Tag = XSharpProjectFileConstants.UseSharedCompilation;
this.toolTip1.SetToolTip(this.chkUseSharedCompilation, descUseSharedCompilation);
this.chkPrefer32Bit.Text = captPrefer32Bit;
this.chkPrefer32Bit.Tag = XSharpProjectFileConstants.Prefer32Bit;
this.toolTip1.SetToolTip(this.chkPrefer32Bit, descPrefer32Bit);
this.chkRegisterForComInterop.Text = captRegisterForComInterop;
this.chkRegisterForComInterop.Tag = XSharpProjectFileConstants.RegisterForComInterop;
this.toolTip1.SetToolTip(this.chkRegisterForComInterop, descRegisterForComInterop);
this.chkXMLDocumentationFile.Text = captDocumentationFile;
this.txtXMLDocumentationFile.Tag = XSharpProjectFileConstants.DocumentationFile;
this.toolTip1.SetToolTip(chkXMLDocumentationFile, descDocumentationFile);
this.toolTip1.SetToolTip(txtXMLDocumentationFile, descDocumentationFileName);
this.chkOptimize.Text =captOptimize;
this.chkOptimize.Tag = XSharpProjectFileConstants.Optimize;
this.toolTip1.SetToolTip(this.chkOptimize, descOptimize);
this.chkSignAssembly.Text = captSignAssembly;
this.chkSignAssembly.Tag = XSharpProjectFileConstants.SignAssembly;
this.toolTip1.SetToolTip(this.chkSignAssembly, descSignAssembly);
this.chkSuppressRCWarnings.Text = SuppressRCWarningsCaption;
this.chkSuppressRCWarnings.Tag = XSharpProjectFileConstants.SuppressRCWarnings;
this.toolTip1.SetToolTip(this.chkSuppressRCWarnings, SuppressRCWarningsDescription);
this.chkDelaySign.Text = captDelaySign;
this.chkDelaySign.Tag = XSharpProjectFileConstants.DelaySign;
this.toolTip1.SetToolTip(this.chkDelaySign, descDelaySign);
this.txtDefineConstants.Tag = XSharpProjectFileConstants.DefineConstants;
this.lblDefineConstants.Text = DefCaption;
this.toolTip1.SetToolTip(this.txtDefineConstants, DefDescription);
this.toolTip1.SetToolTip(this.lblDefineConstants, DefDescription);
this.txtCommandLineOption.Tag = XSharpProjectFileConstants.CommandLineOption;
this.lblCommandLineOption.Text = CmdLineCaption;
this.toolTip1.SetToolTip(txtCommandLineOption, CmdLineDescription);
this.toolTip1.SetToolTip(lblCommandLineOption, CmdLineDescription);
this.txtDisabledWarnings.Tag = XSharpProjectFileConstants.DisabledWarnings;
this.lblDisabledWarnings.Text = captDisabledWarnings;
this.toolTip1.SetToolTip(lblDisabledWarnings, descDisabledWarnings);
this.toolTip1.SetToolTip(txtDisabledWarnings, descDisabledWarnings);
this.txtOutputPath.Tag = XSharpProjectFileConstants.OutputPath;
this.lblOutputPath.Text = captOutputPath;
this.toolTip1.SetToolTip(txtOutputPath, descOutputPath);
this.toolTip1.SetToolTip(lblOutputPath, descOutputPath);
this.txtIntermediateOutputPath.Tag = XSharpProjectFileConstants.IntermediateOutputPath;
this.lblIntermediateOutputPath.Text = captIntermediateOutputPath;
this.toolTip1.SetToolTip(txtIntermediateOutputPath, descIntermediateOutputPath);
this.toolTip1.SetToolTip(lblIntermediateOutputPath, descIntermediateOutputPath);
this.txtAssemblyOriginatorKeyFile.Tag = XSharpProjectFileConstants.AssemblyOriginatorKeyFile;
this.lblAssemblyOriginatorKeyFile.Text = captAssemblyOriginatorKeyFile;
this.toolTip1.SetToolTip(txtAssemblyOriginatorKeyFile, descAssemblyOriginatorKeyFile);
this.toolTip1.SetToolTip(lblAssemblyOriginatorKeyFile, descAssemblyOriginatorKeyFile);
this.lblPlatformTarget.Text = captPlatFormTarget;
this.comboPlatformTarget.Tag = XSharpProjectFileConstants.PlatformTarget;
this.toolTip1.SetToolTip(lblPlatformTarget, descPlatFormTarget);
this.toolTip1.SetToolTip(comboPlatformTarget, descPlatFormTarget);
this.lblWarningLevel.Text = captWarningLevel;
this.cboWarningLevel.Tag = XSharpProjectFileConstants.WarningLevel;
this.toolTip1.SetToolTip(lblWarningLevel, descWarningLevel);
this.toolTip1.SetToolTip(cboWarningLevel, descWarningLevel);
this.rbWarningAll.Tag = XSharpProjectFileConstants.TreatWarningsAsErrors + "|True";
this.rbWarningNone.Tag = XSharpProjectFileConstants.TreatWarningsAsErrors + "|False";
this.rbWarningSpecific.Tag = XSharpProjectFileConstants.TreatWarningsAsErrors + "|False";
this.txtSpecificWarnings.Tag = XSharpProjectFileConstants.WarningsAsErrors;
this.toolTip1.SetToolTip(txtSpecificWarnings, descSpecificWarnings);
FillCombo(new PlatformConverter(), comboPlatformTarget);
// hook up the form to both editors
Color defaultBackground = SystemColors.ButtonFace;
Color defaultForeground = SystemColors.WindowText;
UpdateWindowColors(this, defaultBackground, defaultForeground);
}
/// <summary>
/// Adjust the color values. Adjusts the text color and text
/// area background color
/// </summary>
/// <param name="clrBackground">The desired color for the background of the text area</param>
/// <param name="clrForeground">The desired text color</param>
static void UpdateWindowColors(Control control, Color clrBackground, Color clrForeground)
{
// Update the window background
if (control is TextBox)
control.BackColor = Color.White;
else
control.BackColor = clrBackground;
control.ForeColor = clrForeground;
// Also update the label
foreach (Control child in control.Controls)
{
UpdateWindowColors(child, clrBackground, clrForeground);
}
}
private void btnOutputPathBrowse_Click(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
showMacroDialog(txtOutputPath, descOutputPath);
}
private void btnIntermediateOutputPath_Click(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
showMacroDialog(txtIntermediateOutputPath, descIntermediateOutputPath);
}
internal void Project_OnProjectPropertyChanged(object sender, ProjectPropertyChangedArgs e)
{
if (e.OldValue != e.NewValue)
{
if (string.Compare(e.PropertyName, XSharpProjectFileConstants.PlatformTarget, true) == 0)
{
chkPrefer32Bit.Enabled = e.NewValue.ToLower() == "anycpu";
}
}
}
private void chkXMLDocumentationFile_CheckedChanged(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
string documentationFile = "";
if (chkXMLDocumentationFile.Checked)
{
var asmName = this.ParentPropertyPage.GetProperty(XSharpProjectFileConstants.AssemblyName) ?? "NoName";
documentationFile = asmName + ".Xml";
}
this.ParentPropertyPage.SetProperty(XSharpProjectFileConstants.DocumentationFile, documentationFile);
this.txtXMLDocumentationFile.Text = documentationFile;
}
protected internal override void BindProperties()
{
base.BindProperties();
this.chkXMLDocumentationFile.Checked = !string.IsNullOrEmpty(ParentPropertyPage.GetProperty(XSharpProjectFileConstants.DocumentationFile));
var platform = ParentPropertyPage.GetProperty(XSharpProjectFileConstants.PlatformTarget) ?? "anycpu";
if (string.Compare(platform, "anycpu",true) == 0)
{
this.chkPrefer32Bit.Enabled = true;
}
else
{
this.chkPrefer32Bit.Enabled = false;
this.chkPrefer32Bit.Checked = false;
}
if (! string.IsNullOrEmpty(txtSpecificWarnings.Text))
{
rbWarningSpecific.Checked = true;
rbWarningAll.Checked = false;
rbWarningNone.Checked = false;
txtSpecificWarnings.Enabled = true;
}
else
{
var warn = ParentPropertyPage.GetProperty(XSharpProjectFileConstants.TreatWarningsAsErrors) ?? "false";
warn = warn.ToLower();
rbWarningSpecific.Checked = false;
rbWarningAll.Checked = warn == "true";
rbWarningNone.Checked = warn != "true";
txtSpecificWarnings.Enabled = false;
}
}
protected override void HandleControlValidated(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
base.HandleControlValidated(sender, e);
if (ParentPropertyPage.IsActive)
{
if (sender is RadioButton button && button.Checked)
{
// clear the specific warnings in the parent
var tag = (string)txtSpecificWarnings.Tag;
if (sender == rbWarningAll)
{
this.ParentPropertyPage.SetProperty(tag, " ");
}
else if (sender == rbWarningNone)
{
this.ParentPropertyPage.SetProperty(tag, " ");
}
else
{
this.ParentPropertyPage.SetProperty(tag, txtSpecificWarnings.Text);
}
}
}
}
private void btnKeyFile_Click(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
showMacroDialog(txtAssemblyOriginatorKeyFile, descAssemblyOriginatorKeyFile,
"Key Files (*.snk; *.pfx)|*.snk;*.pfx|All files (*.*)|*.*");
}
private void enableControls()
{
if (ParentPropertyPage.IsActive)
{
txtSpecificWarnings.Enabled = rbWarningSpecific.Checked;
}
}
private void rbWarningSpecific_CheckedChanged(object sender, EventArgs e)
{
enableControls();
}
private void rbWarningNone_CheckedChanged(object sender, EventArgs e)
{
enableControls();
}
private void rbWarningAll_CheckedChanged(object sender, EventArgs e)
{
enableControls();
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the ConAgendaGrupal class.
/// </summary>
[Serializable]
public partial class ConAgendaGrupalCollection : ActiveList<ConAgendaGrupal, ConAgendaGrupalCollection>
{
public ConAgendaGrupalCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConAgendaGrupalCollection</returns>
public ConAgendaGrupalCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConAgendaGrupal o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CON_AgendaGrupal table.
/// </summary>
[Serializable]
public partial class ConAgendaGrupal : ActiveRecord<ConAgendaGrupal>, IActiveRecord
{
#region .ctors and Default Settings
public ConAgendaGrupal()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConAgendaGrupal(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConAgendaGrupal(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConAgendaGrupal(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_AgendaGrupal", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdAgendaGrupal = new TableSchema.TableColumn(schema);
colvarIdAgendaGrupal.ColumnName = "idAgendaGrupal";
colvarIdAgendaGrupal.DataType = DbType.Int32;
colvarIdAgendaGrupal.MaxLength = 0;
colvarIdAgendaGrupal.AutoIncrement = true;
colvarIdAgendaGrupal.IsNullable = false;
colvarIdAgendaGrupal.IsPrimaryKey = true;
colvarIdAgendaGrupal.IsForeignKey = false;
colvarIdAgendaGrupal.IsReadOnly = false;
colvarIdAgendaGrupal.DefaultSetting = @"";
colvarIdAgendaGrupal.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdAgendaGrupal);
TableSchema.TableColumn colvarIdAgendaEstado = new TableSchema.TableColumn(schema);
colvarIdAgendaEstado.ColumnName = "idAgendaEstado";
colvarIdAgendaEstado.DataType = DbType.Int32;
colvarIdAgendaEstado.MaxLength = 0;
colvarIdAgendaEstado.AutoIncrement = false;
colvarIdAgendaEstado.IsNullable = false;
colvarIdAgendaEstado.IsPrimaryKey = false;
colvarIdAgendaEstado.IsForeignKey = true;
colvarIdAgendaEstado.IsReadOnly = false;
colvarIdAgendaEstado.DefaultSetting = @"((1))";
colvarIdAgendaEstado.ForeignKeyTableName = "CON_AgendaEstado";
schema.Columns.Add(colvarIdAgendaEstado);
TableSchema.TableColumn colvarIdMotivoInactivacion = new TableSchema.TableColumn(schema);
colvarIdMotivoInactivacion.ColumnName = "idMotivoInactivacion";
colvarIdMotivoInactivacion.DataType = DbType.Int32;
colvarIdMotivoInactivacion.MaxLength = 0;
colvarIdMotivoInactivacion.AutoIncrement = false;
colvarIdMotivoInactivacion.IsNullable = true;
colvarIdMotivoInactivacion.IsPrimaryKey = false;
colvarIdMotivoInactivacion.IsForeignKey = true;
colvarIdMotivoInactivacion.IsReadOnly = false;
colvarIdMotivoInactivacion.DefaultSetting = @"";
colvarIdMotivoInactivacion.ForeignKeyTableName = "CON_MotivoInactivacionAgenda";
schema.Columns.Add(colvarIdMotivoInactivacion);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = true;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"";
colvarIdEfector.ForeignKeyTableName = "Sys_Efector";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarIdTematica = new TableSchema.TableColumn(schema);
colvarIdTematica.ColumnName = "idTematica";
colvarIdTematica.DataType = DbType.Int32;
colvarIdTematica.MaxLength = 0;
colvarIdTematica.AutoIncrement = false;
colvarIdTematica.IsNullable = false;
colvarIdTematica.IsPrimaryKey = false;
colvarIdTematica.IsForeignKey = true;
colvarIdTematica.IsReadOnly = false;
colvarIdTematica.DefaultSetting = @"";
colvarIdTematica.ForeignKeyTableName = "CON_Tematica";
schema.Columns.Add(colvarIdTematica);
TableSchema.TableColumn colvarTematicaOtra = new TableSchema.TableColumn(schema);
colvarTematicaOtra.ColumnName = "tematicaOtra";
colvarTematicaOtra.DataType = DbType.AnsiString;
colvarTematicaOtra.MaxLength = 200;
colvarTematicaOtra.AutoIncrement = false;
colvarTematicaOtra.IsNullable = true;
colvarTematicaOtra.IsPrimaryKey = false;
colvarTematicaOtra.IsForeignKey = false;
colvarTematicaOtra.IsReadOnly = false;
colvarTematicaOtra.DefaultSetting = @"('')";
colvarTematicaOtra.ForeignKeyTableName = "";
schema.Columns.Add(colvarTematicaOtra);
TableSchema.TableColumn colvarIdTipoActividadGrupal = new TableSchema.TableColumn(schema);
colvarIdTipoActividadGrupal.ColumnName = "idTipoActividadGrupal";
colvarIdTipoActividadGrupal.DataType = DbType.Int32;
colvarIdTipoActividadGrupal.MaxLength = 0;
colvarIdTipoActividadGrupal.AutoIncrement = false;
colvarIdTipoActividadGrupal.IsNullable = false;
colvarIdTipoActividadGrupal.IsPrimaryKey = false;
colvarIdTipoActividadGrupal.IsForeignKey = true;
colvarIdTipoActividadGrupal.IsReadOnly = false;
colvarIdTipoActividadGrupal.DefaultSetting = @"";
colvarIdTipoActividadGrupal.ForeignKeyTableName = "CON_TipoActividadGrupal";
schema.Columns.Add(colvarIdTipoActividadGrupal);
TableSchema.TableColumn colvarTipoActividadGrupalOtro = new TableSchema.TableColumn(schema);
colvarTipoActividadGrupalOtro.ColumnName = "tipoActividadGrupalOtro";
colvarTipoActividadGrupalOtro.DataType = DbType.AnsiString;
colvarTipoActividadGrupalOtro.MaxLength = 200;
colvarTipoActividadGrupalOtro.AutoIncrement = false;
colvarTipoActividadGrupalOtro.IsNullable = true;
colvarTipoActividadGrupalOtro.IsPrimaryKey = false;
colvarTipoActividadGrupalOtro.IsForeignKey = false;
colvarTipoActividadGrupalOtro.IsReadOnly = false;
colvarTipoActividadGrupalOtro.DefaultSetting = @"('')";
colvarTipoActividadGrupalOtro.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoActividadGrupalOtro);
TableSchema.TableColumn colvarIdLugarActividadGrupal = new TableSchema.TableColumn(schema);
colvarIdLugarActividadGrupal.ColumnName = "idLugarActividadGrupal";
colvarIdLugarActividadGrupal.DataType = DbType.Int32;
colvarIdLugarActividadGrupal.MaxLength = 0;
colvarIdLugarActividadGrupal.AutoIncrement = false;
colvarIdLugarActividadGrupal.IsNullable = false;
colvarIdLugarActividadGrupal.IsPrimaryKey = false;
colvarIdLugarActividadGrupal.IsForeignKey = true;
colvarIdLugarActividadGrupal.IsReadOnly = false;
colvarIdLugarActividadGrupal.DefaultSetting = @"";
colvarIdLugarActividadGrupal.ForeignKeyTableName = "CON_LugarActividadGrupal";
schema.Columns.Add(colvarIdLugarActividadGrupal);
TableSchema.TableColumn colvarLugarActividadGrupalOtro = new TableSchema.TableColumn(schema);
colvarLugarActividadGrupalOtro.ColumnName = "lugarActividadGrupalOtro";
colvarLugarActividadGrupalOtro.DataType = DbType.AnsiString;
colvarLugarActividadGrupalOtro.MaxLength = 200;
colvarLugarActividadGrupalOtro.AutoIncrement = false;
colvarLugarActividadGrupalOtro.IsNullable = true;
colvarLugarActividadGrupalOtro.IsPrimaryKey = false;
colvarLugarActividadGrupalOtro.IsForeignKey = false;
colvarLugarActividadGrupalOtro.IsReadOnly = false;
colvarLugarActividadGrupalOtro.DefaultSetting = @"('')";
colvarLugarActividadGrupalOtro.ForeignKeyTableName = "";
schema.Columns.Add(colvarLugarActividadGrupalOtro);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarHoraInicio = new TableSchema.TableColumn(schema);
colvarHoraInicio.ColumnName = "horaInicio";
colvarHoraInicio.DataType = DbType.AnsiString;
colvarHoraInicio.MaxLength = 5;
colvarHoraInicio.AutoIncrement = false;
colvarHoraInicio.IsNullable = false;
colvarHoraInicio.IsPrimaryKey = false;
colvarHoraInicio.IsForeignKey = false;
colvarHoraInicio.IsReadOnly = false;
colvarHoraInicio.DefaultSetting = @"";
colvarHoraInicio.ForeignKeyTableName = "";
schema.Columns.Add(colvarHoraInicio);
TableSchema.TableColumn colvarHoraFin = new TableSchema.TableColumn(schema);
colvarHoraFin.ColumnName = "horaFin";
colvarHoraFin.DataType = DbType.AnsiString;
colvarHoraFin.MaxLength = 5;
colvarHoraFin.AutoIncrement = false;
colvarHoraFin.IsNullable = false;
colvarHoraFin.IsPrimaryKey = false;
colvarHoraFin.IsForeignKey = false;
colvarHoraFin.IsReadOnly = false;
colvarHoraFin.DefaultSetting = @"";
colvarHoraFin.ForeignKeyTableName = "";
schema.Columns.Add(colvarHoraFin);
TableSchema.TableColumn colvarCantidadAsistentes = new TableSchema.TableColumn(schema);
colvarCantidadAsistentes.ColumnName = "cantidadAsistentes";
colvarCantidadAsistentes.DataType = DbType.Int32;
colvarCantidadAsistentes.MaxLength = 0;
colvarCantidadAsistentes.AutoIncrement = false;
colvarCantidadAsistentes.IsNullable = true;
colvarCantidadAsistentes.IsPrimaryKey = false;
colvarCantidadAsistentes.IsForeignKey = false;
colvarCantidadAsistentes.IsReadOnly = false;
colvarCantidadAsistentes.DefaultSetting = @"((0))";
colvarCantidadAsistentes.ForeignKeyTableName = "";
schema.Columns.Add(colvarCantidadAsistentes);
TableSchema.TableColumn colvarOtrosOrganismos = new TableSchema.TableColumn(schema);
colvarOtrosOrganismos.ColumnName = "otrosOrganismos";
colvarOtrosOrganismos.DataType = DbType.AnsiString;
colvarOtrosOrganismos.MaxLength = 200;
colvarOtrosOrganismos.AutoIncrement = false;
colvarOtrosOrganismos.IsNullable = true;
colvarOtrosOrganismos.IsPrimaryKey = false;
colvarOtrosOrganismos.IsForeignKey = false;
colvarOtrosOrganismos.IsReadOnly = false;
colvarOtrosOrganismos.DefaultSetting = @"";
colvarOtrosOrganismos.ForeignKeyTableName = "";
schema.Columns.Add(colvarOtrosOrganismos);
TableSchema.TableColumn colvarIdConsultorio = new TableSchema.TableColumn(schema);
colvarIdConsultorio.ColumnName = "idConsultorio";
colvarIdConsultorio.DataType = DbType.Int32;
colvarIdConsultorio.MaxLength = 0;
colvarIdConsultorio.AutoIncrement = false;
colvarIdConsultorio.IsNullable = true;
colvarIdConsultorio.IsPrimaryKey = false;
colvarIdConsultorio.IsForeignKey = true;
colvarIdConsultorio.IsReadOnly = false;
colvarIdConsultorio.DefaultSetting = @"";
colvarIdConsultorio.ForeignKeyTableName = "CON_Consultorio";
schema.Columns.Add(colvarIdConsultorio);
TableSchema.TableColumn colvarResumenActividad = new TableSchema.TableColumn(schema);
colvarResumenActividad.ColumnName = "resumenActividad";
colvarResumenActividad.DataType = DbType.AnsiString;
colvarResumenActividad.MaxLength = 6000;
colvarResumenActividad.AutoIncrement = false;
colvarResumenActividad.IsNullable = true;
colvarResumenActividad.IsPrimaryKey = false;
colvarResumenActividad.IsForeignKey = false;
colvarResumenActividad.IsReadOnly = false;
colvarResumenActividad.DefaultSetting = @"";
colvarResumenActividad.ForeignKeyTableName = "";
schema.Columns.Add(colvarResumenActividad);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.AnsiString;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.AnsiString;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_AgendaGrupal",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdAgendaGrupal")]
[Bindable(true)]
public int IdAgendaGrupal
{
get { return GetColumnValue<int>(Columns.IdAgendaGrupal); }
set { SetColumnValue(Columns.IdAgendaGrupal, value); }
}
[XmlAttribute("IdAgendaEstado")]
[Bindable(true)]
public int IdAgendaEstado
{
get { return GetColumnValue<int>(Columns.IdAgendaEstado); }
set { SetColumnValue(Columns.IdAgendaEstado, value); }
}
[XmlAttribute("IdMotivoInactivacion")]
[Bindable(true)]
public int? IdMotivoInactivacion
{
get { return GetColumnValue<int?>(Columns.IdMotivoInactivacion); }
set { SetColumnValue(Columns.IdMotivoInactivacion, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("IdTematica")]
[Bindable(true)]
public int IdTematica
{
get { return GetColumnValue<int>(Columns.IdTematica); }
set { SetColumnValue(Columns.IdTematica, value); }
}
[XmlAttribute("TematicaOtra")]
[Bindable(true)]
public string TematicaOtra
{
get { return GetColumnValue<string>(Columns.TematicaOtra); }
set { SetColumnValue(Columns.TematicaOtra, value); }
}
[XmlAttribute("IdTipoActividadGrupal")]
[Bindable(true)]
public int IdTipoActividadGrupal
{
get { return GetColumnValue<int>(Columns.IdTipoActividadGrupal); }
set { SetColumnValue(Columns.IdTipoActividadGrupal, value); }
}
[XmlAttribute("TipoActividadGrupalOtro")]
[Bindable(true)]
public string TipoActividadGrupalOtro
{
get { return GetColumnValue<string>(Columns.TipoActividadGrupalOtro); }
set { SetColumnValue(Columns.TipoActividadGrupalOtro, value); }
}
[XmlAttribute("IdLugarActividadGrupal")]
[Bindable(true)]
public int IdLugarActividadGrupal
{
get { return GetColumnValue<int>(Columns.IdLugarActividadGrupal); }
set { SetColumnValue(Columns.IdLugarActividadGrupal, value); }
}
[XmlAttribute("LugarActividadGrupalOtro")]
[Bindable(true)]
public string LugarActividadGrupalOtro
{
get { return GetColumnValue<string>(Columns.LugarActividadGrupalOtro); }
set { SetColumnValue(Columns.LugarActividadGrupalOtro, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("HoraInicio")]
[Bindable(true)]
public string HoraInicio
{
get { return GetColumnValue<string>(Columns.HoraInicio); }
set { SetColumnValue(Columns.HoraInicio, value); }
}
[XmlAttribute("HoraFin")]
[Bindable(true)]
public string HoraFin
{
get { return GetColumnValue<string>(Columns.HoraFin); }
set { SetColumnValue(Columns.HoraFin, value); }
}
[XmlAttribute("CantidadAsistentes")]
[Bindable(true)]
public int? CantidadAsistentes
{
get { return GetColumnValue<int?>(Columns.CantidadAsistentes); }
set { SetColumnValue(Columns.CantidadAsistentes, value); }
}
[XmlAttribute("OtrosOrganismos")]
[Bindable(true)]
public string OtrosOrganismos
{
get { return GetColumnValue<string>(Columns.OtrosOrganismos); }
set { SetColumnValue(Columns.OtrosOrganismos, value); }
}
[XmlAttribute("IdConsultorio")]
[Bindable(true)]
public int? IdConsultorio
{
get { return GetColumnValue<int?>(Columns.IdConsultorio); }
set { SetColumnValue(Columns.IdConsultorio, value); }
}
[XmlAttribute("ResumenActividad")]
[Bindable(true)]
public string ResumenActividad
{
get { return GetColumnValue<string>(Columns.ResumenActividad); }
set { SetColumnValue(Columns.ResumenActividad, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.ConAgendaGrupalOrganismoCollection colConAgendaGrupalOrganismoRecords;
public DalSic.ConAgendaGrupalOrganismoCollection ConAgendaGrupalOrganismoRecords
{
get
{
if(colConAgendaGrupalOrganismoRecords == null)
{
colConAgendaGrupalOrganismoRecords = new DalSic.ConAgendaGrupalOrganismoCollection().Where(ConAgendaGrupalOrganismo.Columns.IdAgendaGrupal, IdAgendaGrupal).Load();
colConAgendaGrupalOrganismoRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalOrganismoRecords_ListChanged);
}
return colConAgendaGrupalOrganismoRecords;
}
set
{
colConAgendaGrupalOrganismoRecords = value;
colConAgendaGrupalOrganismoRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalOrganismoRecords_ListChanged);
}
}
void colConAgendaGrupalOrganismoRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colConAgendaGrupalOrganismoRecords[e.NewIndex].IdAgendaGrupal = IdAgendaGrupal;
}
}
private DalSic.ConAgendaGrupalProfesionalCollection colConAgendaGrupalProfesionalRecords;
public DalSic.ConAgendaGrupalProfesionalCollection ConAgendaGrupalProfesionalRecords
{
get
{
if(colConAgendaGrupalProfesionalRecords == null)
{
colConAgendaGrupalProfesionalRecords = new DalSic.ConAgendaGrupalProfesionalCollection().Where(ConAgendaGrupalProfesional.Columns.IdAgendaGrupal, IdAgendaGrupal).Load();
colConAgendaGrupalProfesionalRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalProfesionalRecords_ListChanged);
}
return colConAgendaGrupalProfesionalRecords;
}
set
{
colConAgendaGrupalProfesionalRecords = value;
colConAgendaGrupalProfesionalRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalProfesionalRecords_ListChanged);
}
}
void colConAgendaGrupalProfesionalRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colConAgendaGrupalProfesionalRecords[e.NewIndex].IdAgendaGrupal = IdAgendaGrupal;
}
}
private DalSic.ConAgendaGrupalPacienteCollection colConAgendaGrupalPacienteRecords;
public DalSic.ConAgendaGrupalPacienteCollection ConAgendaGrupalPacienteRecords
{
get
{
if(colConAgendaGrupalPacienteRecords == null)
{
colConAgendaGrupalPacienteRecords = new DalSic.ConAgendaGrupalPacienteCollection().Where(ConAgendaGrupalPaciente.Columns.IdAgendaGrupal, IdAgendaGrupal).Load();
colConAgendaGrupalPacienteRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalPacienteRecords_ListChanged);
}
return colConAgendaGrupalPacienteRecords;
}
set
{
colConAgendaGrupalPacienteRecords = value;
colConAgendaGrupalPacienteRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalPacienteRecords_ListChanged);
}
}
void colConAgendaGrupalPacienteRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colConAgendaGrupalPacienteRecords[e.NewIndex].IdAgendaGrupal = IdAgendaGrupal;
}
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a ConMotivoInactivacionAgenda ActiveRecord object related to this ConAgendaGrupal
///
/// </summary>
public DalSic.ConMotivoInactivacionAgenda ConMotivoInactivacionAgenda
{
get { return DalSic.ConMotivoInactivacionAgenda.FetchByID(this.IdMotivoInactivacion); }
set { SetColumnValue("idMotivoInactivacion", value.IdMotivoInactivacion); }
}
/// <summary>
/// Returns a SysEfector ActiveRecord object related to this ConAgendaGrupal
///
/// </summary>
public DalSic.SysEfector SysEfector
{
get { return DalSic.SysEfector.FetchByID(this.IdEfector); }
set { SetColumnValue("idEfector", value.IdEfector); }
}
/// <summary>
/// Returns a ConAgendaEstado ActiveRecord object related to this ConAgendaGrupal
///
/// </summary>
public DalSic.ConAgendaEstado ConAgendaEstado
{
get { return DalSic.ConAgendaEstado.FetchByID(this.IdAgendaEstado); }
set { SetColumnValue("idAgendaEstado", value.IdAgendaEstado); }
}
/// <summary>
/// Returns a ConConsultorio ActiveRecord object related to this ConAgendaGrupal
///
/// </summary>
public DalSic.ConConsultorio ConConsultorio
{
get { return DalSic.ConConsultorio.FetchByID(this.IdConsultorio); }
set { SetColumnValue("idConsultorio", value.IdConsultorio); }
}
/// <summary>
/// Returns a ConTematica ActiveRecord object related to this ConAgendaGrupal
///
/// </summary>
public DalSic.ConTematica ConTematica
{
get { return DalSic.ConTematica.FetchByID(this.IdTematica); }
set { SetColumnValue("idTematica", value.IdTematica); }
}
/// <summary>
/// Returns a ConTipoActividadGrupal ActiveRecord object related to this ConAgendaGrupal
///
/// </summary>
public DalSic.ConTipoActividadGrupal ConTipoActividadGrupal
{
get { return DalSic.ConTipoActividadGrupal.FetchByID(this.IdTipoActividadGrupal); }
set { SetColumnValue("idTipoActividadGrupal", value.IdTipoActividadGrupal); }
}
/// <summary>
/// Returns a ConLugarActividadGrupal ActiveRecord object related to this ConAgendaGrupal
///
/// </summary>
public DalSic.ConLugarActividadGrupal ConLugarActividadGrupal
{
get { return DalSic.ConLugarActividadGrupal.FetchByID(this.IdLugarActividadGrupal); }
set { SetColumnValue("idLugarActividadGrupal", value.IdLugarActividadGrupal); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdAgendaEstado,int? varIdMotivoInactivacion,int varIdEfector,int varIdTematica,string varTematicaOtra,int varIdTipoActividadGrupal,string varTipoActividadGrupalOtro,int varIdLugarActividadGrupal,string varLugarActividadGrupalOtro,DateTime varFecha,string varHoraInicio,string varHoraFin,int? varCantidadAsistentes,string varOtrosOrganismos,int? varIdConsultorio,string varResumenActividad,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
ConAgendaGrupal item = new ConAgendaGrupal();
item.IdAgendaEstado = varIdAgendaEstado;
item.IdMotivoInactivacion = varIdMotivoInactivacion;
item.IdEfector = varIdEfector;
item.IdTematica = varIdTematica;
item.TematicaOtra = varTematicaOtra;
item.IdTipoActividadGrupal = varIdTipoActividadGrupal;
item.TipoActividadGrupalOtro = varTipoActividadGrupalOtro;
item.IdLugarActividadGrupal = varIdLugarActividadGrupal;
item.LugarActividadGrupalOtro = varLugarActividadGrupalOtro;
item.Fecha = varFecha;
item.HoraInicio = varHoraInicio;
item.HoraFin = varHoraFin;
item.CantidadAsistentes = varCantidadAsistentes;
item.OtrosOrganismos = varOtrosOrganismos;
item.IdConsultorio = varIdConsultorio;
item.ResumenActividad = varResumenActividad;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdAgendaGrupal,int varIdAgendaEstado,int? varIdMotivoInactivacion,int varIdEfector,int varIdTematica,string varTematicaOtra,int varIdTipoActividadGrupal,string varTipoActividadGrupalOtro,int varIdLugarActividadGrupal,string varLugarActividadGrupalOtro,DateTime varFecha,string varHoraInicio,string varHoraFin,int? varCantidadAsistentes,string varOtrosOrganismos,int? varIdConsultorio,string varResumenActividad,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
ConAgendaGrupal item = new ConAgendaGrupal();
item.IdAgendaGrupal = varIdAgendaGrupal;
item.IdAgendaEstado = varIdAgendaEstado;
item.IdMotivoInactivacion = varIdMotivoInactivacion;
item.IdEfector = varIdEfector;
item.IdTematica = varIdTematica;
item.TematicaOtra = varTematicaOtra;
item.IdTipoActividadGrupal = varIdTipoActividadGrupal;
item.TipoActividadGrupalOtro = varTipoActividadGrupalOtro;
item.IdLugarActividadGrupal = varIdLugarActividadGrupal;
item.LugarActividadGrupalOtro = varLugarActividadGrupalOtro;
item.Fecha = varFecha;
item.HoraInicio = varHoraInicio;
item.HoraFin = varHoraFin;
item.CantidadAsistentes = varCantidadAsistentes;
item.OtrosOrganismos = varOtrosOrganismos;
item.IdConsultorio = varIdConsultorio;
item.ResumenActividad = varResumenActividad;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdAgendaGrupalColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdAgendaEstadoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdMotivoInactivacionColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn IdTematicaColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn TematicaOtraColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn IdTipoActividadGrupalColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn TipoActividadGrupalOtroColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn IdLugarActividadGrupalColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn LugarActividadGrupalOtroColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn HoraInicioColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn HoraFinColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn CantidadAsistentesColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn OtrosOrganismosColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn IdConsultorioColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn ResumenActividadColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[20]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdAgendaGrupal = @"idAgendaGrupal";
public static string IdAgendaEstado = @"idAgendaEstado";
public static string IdMotivoInactivacion = @"idMotivoInactivacion";
public static string IdEfector = @"idEfector";
public static string IdTematica = @"idTematica";
public static string TematicaOtra = @"tematicaOtra";
public static string IdTipoActividadGrupal = @"idTipoActividadGrupal";
public static string TipoActividadGrupalOtro = @"tipoActividadGrupalOtro";
public static string IdLugarActividadGrupal = @"idLugarActividadGrupal";
public static string LugarActividadGrupalOtro = @"lugarActividadGrupalOtro";
public static string Fecha = @"fecha";
public static string HoraInicio = @"horaInicio";
public static string HoraFin = @"horaFin";
public static string CantidadAsistentes = @"cantidadAsistentes";
public static string OtrosOrganismos = @"otrosOrganismos";
public static string IdConsultorio = @"idConsultorio";
public static string ResumenActividad = @"resumenActividad";
public static string CreatedBy = @"CreatedBy";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string ModifiedOn = @"ModifiedOn";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colConAgendaGrupalOrganismoRecords != null)
{
foreach (DalSic.ConAgendaGrupalOrganismo item in colConAgendaGrupalOrganismoRecords)
{
if (item.IdAgendaGrupal != IdAgendaGrupal)
{
item.IdAgendaGrupal = IdAgendaGrupal;
}
}
}
if (colConAgendaGrupalProfesionalRecords != null)
{
foreach (DalSic.ConAgendaGrupalProfesional item in colConAgendaGrupalProfesionalRecords)
{
if (item.IdAgendaGrupal != IdAgendaGrupal)
{
item.IdAgendaGrupal = IdAgendaGrupal;
}
}
}
if (colConAgendaGrupalPacienteRecords != null)
{
foreach (DalSic.ConAgendaGrupalPaciente item in colConAgendaGrupalPacienteRecords)
{
if (item.IdAgendaGrupal != IdAgendaGrupal)
{
item.IdAgendaGrupal = IdAgendaGrupal;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colConAgendaGrupalOrganismoRecords != null)
{
colConAgendaGrupalOrganismoRecords.SaveAll();
}
if (colConAgendaGrupalProfesionalRecords != null)
{
colConAgendaGrupalProfesionalRecords.SaveAll();
}
if (colConAgendaGrupalPacienteRecords != null)
{
colConAgendaGrupalPacienteRecords.SaveAll();
}
}
#endregion
}
}
| |
using De.Osthus.Ambeth.Cache.Rootcachevalue;
using De.Osthus.Ambeth.Merge.Model;
using De.Osthus.Ambeth.Metadata;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace De.Osthus.Ambeth.Bytecode.Visitor
{
public class RootCacheValueVisitor : ClassVisitor
{
private static readonly Type objType = typeof(Object);
private static readonly Type objRefArrayType = typeof(IObjRef[]);
protected readonly IEntityMetaData metaData;
public RootCacheValueVisitor(IClassVisitor cv, IEntityMetaData metaData)
: base(cv)
{
this.metaData = metaData;
}
public override void VisitEnd()
{
ImplementGetEntityType();
ImplementId();
ImplementVersion();
ImplementPrimitives();
ImplementRelations();
base.VisitEnd();
}
protected void ImplementGetEntityType()
{
MethodInstance template_m_getEntityType = new MethodInstance(null, typeof(RootCacheValue), typeof(Type), "getEntityType");
IMethodVisitor mv = VisitMethod(template_m_getEntityType);
mv.Push(metaData.EntityType);
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementId()
{
MethodInstance template_m_getId = new MethodInstance(null, typeof(RootCacheValue), typeof(Object), "get_Id");
MethodInstance template_m_setId = new MethodInstance(null, typeof(RootCacheValue), typeof(void), "set_Id", typeof(Object));
CacheMapEntryVisitor.ImplementNativeField(this, metaData.IdMember, template_m_getId, template_m_setId);
}
protected void ImplementVersion()
{
MethodInstance template_m_getVersion = new MethodInstance(null, typeof(RootCacheValue), typeof(Object), "get_Version");
MethodInstance template_m_setVersion = new MethodInstance(null, typeof(RootCacheValue), typeof(void), "set_Version", typeof(Object));
CacheMapEntryVisitor.ImplementNativeField(this, metaData.VersionMember, template_m_getVersion, template_m_setVersion);
}
protected void ImplementPrimitives()
{
Member[] primitiveMembers = metaData.PrimitiveMembers;
FieldInstance[] f_primitives = new FieldInstance[primitiveMembers.Length];
FieldInstance[] f_nullFlags = new FieldInstance[primitiveMembers.Length];
Type[] fieldType = new Type[primitiveMembers.Length];
for (int primitiveIndex = 0, size = primitiveMembers.Length; primitiveIndex < size; primitiveIndex++)
{
Member member = primitiveMembers[primitiveIndex];
Type realType = member.RealType;
Type nativeType = ImmutableTypeSet.GetUnwrappedType(realType);
bool isNullable = true;
if (nativeType == null)
{
nativeType = realType;
isNullable = false;
}
if (!nativeType.IsPrimitive)
{
nativeType = typeof(Object);
}
if (isNullable)
{
// field is a nullable numeric field. We need a flag field to handle true null case
FieldInstance f_nullFlag = ImplementField(new FieldInstance(FieldAttributes.Private, CacheMapEntryVisitor.GetFieldName(member) + "$isNull", typeof(bool)));
f_nullFlags[primitiveIndex] = f_nullFlag;
}
fieldType[primitiveIndex] = nativeType;
FieldInstance f_primitive = ImplementField(new FieldInstance(FieldAttributes.Private, CacheMapEntryVisitor.GetFieldName(member), nativeType));
f_primitives[primitiveIndex] = f_primitive;
}
ImplementGetPrimitive(primitiveMembers, f_primitives, f_nullFlags);
ImplementGetPrimitives(primitiveMembers, f_primitives, f_nullFlags);
ImplementSetPrimitives(primitiveMembers, f_primitives, f_nullFlags);
}
protected void ImplementGetPrimitive(Member[] primitiveMember, FieldInstance[] f_primitives, FieldInstance[] f_nullFlags)
{
MethodInstance template_m_getPrimitive = new MethodInstance(null, typeof(RootCacheValue), typeof(Object), "GetPrimitive", typeof(int));
IMethodVisitor mv = VisitMethod(template_m_getPrimitive);
if (f_primitives.Length > 0)
{
Label l_default = mv.NewLabel();
Label[] l_primitives = new Label[f_primitives.Length];
for (int primitiveIndex = 0, size = f_primitives.Length; primitiveIndex < size; primitiveIndex++)
{
l_primitives[primitiveIndex] = mv.NewLabel();
}
mv.LoadArg(0);
mv.Switch(0, l_primitives.Length - 1, l_default, l_primitives);
for (int primitiveIndex = 0, size = f_primitives.Length; primitiveIndex < size; primitiveIndex++)
{
FieldInstance f_primitive = f_primitives[primitiveIndex];
FieldInstance f_nullFlag = f_nullFlags[primitiveIndex];
mv.Mark(l_primitives[primitiveIndex]);
Label? l_fieldIsNull = null;
if (f_nullFlag != null)
{
l_fieldIsNull = mv.NewLabel();
// only do something if the field is non-null
mv.GetThisField(f_nullFlag);
mv.IfZCmp(CompareOperator.NE, l_fieldIsNull.Value);
}
mv.GetThisField(f_primitive);
mv.ValueOf(f_primitive.Type.Type);
mv.ReturnValue();
if (f_nullFlag != null)
{
mv.Mark(l_fieldIsNull.Value);
mv.PushNull();
}
mv.ReturnValue();
}
mv.Mark(l_default);
}
mv.ThrowException(typeof(ArgumentException), "Given relationIndex not known");
mv.PushNull();
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementGetPrimitives(Member[] primitiveMembers, FieldInstance[] f_primitives, FieldInstance[] f_nullFlags)
{
MethodInstance template_m_getPrimitives = new MethodInstance(null, typeof(RootCacheValue), typeof(Object[]), "GetPrimitives");
IMethodVisitor mv = VisitMethod(template_m_getPrimitives);
mv.Push(f_primitives.Length);
mv.NewArray(objType);
for (int primitiveIndex = 0, size = f_primitives.Length; primitiveIndex < size; primitiveIndex++)
{
FieldInstance f_primitive = f_primitives[primitiveIndex];
FieldInstance f_nullFlag = f_nullFlags[primitiveIndex];
Label? l_fieldIsNull = null;
if (f_nullFlag != null)
{
l_fieldIsNull = mv.NewLabel();
// only do something if the field is non-null
mv.GetThisField(f_nullFlag);
mv.IfZCmp(CompareOperator.NE, l_fieldIsNull.Value);
}
// duplicate array instance on stack
mv.Dup();
mv.Push(primitiveIndex);
mv.GetThisField(f_primitive);
mv.ValueOf(f_primitive.Type.Type);
mv.ArrayStore(objType);
if (f_nullFlag != null)
{
mv.Mark(l_fieldIsNull.Value);
}
}
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementSetPrimitives(Member[] primitiveMembers, FieldInstance[] f_primitives, FieldInstance[] f_nullFlags)
{
MethodInstance template_m_setPrimitives = new MethodInstance(null, typeof(RootCacheValue), typeof(void), "SetPrimitives", typeof(Object[]));
IMethodVisitor mv = VisitMethod(template_m_setPrimitives);
LocalVariableInfo loc_item = mv.NewLocal(objType);
for (int primitiveIndex = 0, size = f_primitives.Length; primitiveIndex < size; primitiveIndex++)
{
FieldInstance f_primitive = f_primitives[primitiveIndex];
FieldInstance f_nullFlag = f_nullFlags[primitiveIndex];
Member member = primitiveMembers[primitiveIndex];
Type originalType = member.RealType;
Script script_loadArrayValue = new Script(delegate(IMethodVisitor mg)
{
mg.LoadArg(0);
mg.Push(primitiveIndex);
mg.ArrayLoad(objType);
});
Label l_finish = mv.NewLabel();
if (f_nullFlag == null)
{
if (!originalType.IsValueType)
{
mv.PutThisField(f_primitive, script_loadArrayValue);
continue;
}
script_loadArrayValue(mv);
mv.StoreLocal(loc_item);
mv.LoadLocal(loc_item);
mv.IfNull(l_finish);
mv.PutThisField(f_primitive, new Script(delegate(IMethodVisitor mg)
{
mg.LoadLocal(loc_item);
mg.Unbox(f_primitive.Type.Type);
}));
mv.Mark(l_finish);
continue;
}
Label l_itemIsNull = mv.NewLabel();
script_loadArrayValue(mv);
mv.StoreLocal(loc_item);
mv.LoadLocal(loc_item);
mv.IfNull(l_itemIsNull);
mv.PutThisField(f_primitive, delegate(IMethodVisitor mg)
{
mg.LoadLocal(loc_item);
mg.Unbox(f_primitive.Type.Type);
});
if (f_nullFlag != null)
{
// field is a nullable numeric value in the entity, but a native numeric value in our RCV
mv.PutThisField(f_nullFlag, delegate(IMethodVisitor mg)
{
mg.Push(false);
});
}
mv.GoTo(l_finish);
mv.Mark(l_itemIsNull);
if (f_nullFlag != null)
{
// field is a nullable numeric value in the entity, but a native numeric value in our RCV
mv.PutThisField(f_nullFlag, delegate(IMethodVisitor mg)
{
mg.Push(true);
});
}
else
{
mv.PutThisField(f_primitive, delegate(IMethodVisitor mg)
{
mg.PushNullOrZero(f_primitive.Type.Type);
});
}
mv.Mark(l_finish);
}
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementRelations()
{
RelationMember[] relationMembers = metaData.RelationMembers;
FieldInstance[] f_relations = new FieldInstance[relationMembers.Length];
for (int relationIndex = 0, size = relationMembers.Length; relationIndex < size; relationIndex++)
{
RelationMember member = relationMembers[relationIndex];
FieldInstance f_relation = ImplementField(new FieldInstance(FieldAttributes.Private, CacheMapEntryVisitor.GetFieldName(member), typeof(IObjRef[])));
f_relations[relationIndex] = f_relation;
}
ImplementGetRelations(relationMembers, f_relations);
ImplementSetRelations(relationMembers, f_relations);
ImplementGetRelation(relationMembers, f_relations);
ImplementSetRelation(relationMembers, f_relations);
}
protected void ImplementGetRelation(RelationMember[] relationMembers, FieldInstance[] f_relations)
{
MethodInstance template_m_getRelation = new MethodInstance(null, typeof(RootCacheValue), typeof(IObjRef[]), "GetRelation", typeof(int));
IMethodVisitor mv = VisitMethod(template_m_getRelation);
if (f_relations.Length > 0)
{
Label l_default = mv.NewLabel();
Label[] l_relations = new Label[f_relations.Length];
for (int relationIndex = 0, size = l_relations.Length; relationIndex < size; relationIndex++)
{
l_relations[relationIndex] = mv.NewLabel();
}
mv.LoadArg(0);
mv.Switch(0, l_relations.Length - 1, l_default, l_relations);
for (int relationIndex = 0, size = f_relations.Length; relationIndex < size; relationIndex++)
{
FieldInstance f_relation = f_relations[relationIndex];
mv.Mark(l_relations[relationIndex]);
mv.GetThisField(f_relation);
mv.ReturnValue();
}
mv.Mark(l_default);
}
mv.ThrowException(typeof(ArgumentException), "Given relationIndex not known");
mv.PushNull();
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementSetRelation(RelationMember[] relationMembers, FieldInstance[] f_relations)
{
MethodInstance template_m_setRelation = new MethodInstance(null, typeof(RootCacheValue), typeof(void), "SetRelation", typeof(int), typeof(IObjRef[]));
IMethodVisitor mv = VisitMethod(template_m_setRelation);
Label l_finish = mv.NewLabel();
for (int relationIndex = 0, size = f_relations.Length; relationIndex < size; relationIndex++)
{
FieldInstance f_relation = f_relations[relationIndex];
Label l_notEqual = mv.NewLabel();
mv.LoadArg(0);
mv.Push(relationIndex);
mv.IfCmp(typeof(int), CompareOperator.NE, l_notEqual);
mv.PutThisField(f_relation, delegate(IMethodVisitor mg)
{
mg.LoadArg(1);
});
mv.GoTo(l_finish);
mv.Mark(l_notEqual);
}
mv.ThrowException(typeof(ArgumentException), "Given relationIndex not known");
mv.Mark(l_finish);
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementSetRelations(RelationMember[] relationMembers, FieldInstance[] fields)
{
MethodInstance template_m_setRelations = new MethodInstance(null, typeof(RootCacheValue), typeof(void), "SetRelations", typeof(IObjRef[][]));
IMethodVisitor mv = VisitMethod(template_m_setRelations);
for (int relationIndex = 0, size = fields.Length; relationIndex < size; relationIndex++)
{
FieldInstance f_relation = fields[relationIndex];
int f_relationIndex = relationIndex;
mv.PutThisField(f_relation, delegate(IMethodVisitor mg)
{
mg.LoadArg(0);
mg.Push(f_relationIndex);
mg.ArrayLoad(objRefArrayType);
});
}
mv.ReturnValue();
mv.EndMethod();
}
protected void ImplementGetRelations(RelationMember[] relationMembers, FieldInstance[] f_relations)
{
MethodInstance template_m_getRelations = new MethodInstance(null, typeof(RootCacheValue), typeof(IObjRef[][]), "GetRelations");
IMethodVisitor mv = VisitMethod(template_m_getRelations);
mv.Push(f_relations.Length);
mv.NewArray(objRefArrayType);
for (int relationIndex = 0, size = f_relations.Length; relationIndex < size; relationIndex++)
{
FieldInstance f_primitive = f_relations[relationIndex];
// duplicate array instance on stack
mv.Dup();
mv.Push(relationIndex);
mv.GetThisField(f_primitive);
mv.ArrayStore(objRefArrayType);
}
mv.ReturnValue();
mv.EndMethod();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Elasticsearch.Net.Serialization;
using Nest.Resolvers;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;
namespace Nest
{
public class NestSerializer : INestSerializer
{
private readonly IConnectionSettingsValues _settings;
private readonly JsonSerializerSettings _serializationSettings;
public NestSerializer(IConnectionSettingsValues settings)
{
this._settings = settings;
this._serializationSettings = this.CreateSettings();
}
public virtual byte[] Serialize(object data, SerializationFormatting formatting = SerializationFormatting.Indented)
{
var format = formatting == SerializationFormatting.None ? Formatting.None : Formatting.Indented;
var serialized = JsonConvert.SerializeObject(data, format, this._serializationSettings);
return serialized.Utf8Bytes();
}
/// <summary>
/// Deserialize an object
/// </summary>
/// <typeparam name="T">The type you want to deserialize too</typeparam>
/// <param name="response">If the type you want is a Nest Response you have to pass a response object</param>
/// <param name="stream">The stream to deserialize off</param>
/// <param name="deserializationState">Optional deserialization state</param>
public virtual T Deserialize<T>(IElasticsearchResponse response, Stream stream, object deserializationState = null)
{
var settings = this._serializationSettings;
var customConverter = deserializationState as Func<IElasticsearchResponse, Stream, T>;
if (customConverter != null)
{
var t = customConverter(response, stream);
return t;
}
var state = deserializationState as JsonConverter;
if (state != null)
settings = this.CreateSettings(state);
return _Deserialize<T>(response, stream, settings);
}
/// <summary>
/// Deserialize to type T bypassing checks for custom deserialization state and or BaseResponse return types.
/// </summary>
public T DeserializeInternal<T>(Stream stream)
{
var serializer = JsonSerializer.Create(this._serializationSettings);
var jsonTextReader = new JsonTextReader(new StreamReader(stream));
var t = (T) serializer.Deserialize(jsonTextReader, typeof (T));
return t;
}
protected internal T _Deserialize<T>(IElasticsearchResponse response, Stream stream, JsonSerializerSettings settings = null)
{
settings = settings ?? _serializationSettings;
var serializer = JsonSerializer.Create(settings);
var jsonTextReader = new JsonTextReader(new StreamReader(stream));
var t = (T) serializer.Deserialize(jsonTextReader, typeof (T));
var r = t as BaseResponse;
if (r != null)
{
r.ConnectionStatus = response;
}
return t;
}
public virtual Task<T> DeserializeAsync<T>(IElasticsearchResponse response, Stream stream, object deserializationState = null)
{
//TODO sadly json .net async does not read the stream async so
//figure out wheter reading the stream async on our own might be beneficial
//over memory possible memory usage
var tcs = new TaskCompletionSource<T>();
var r = this.Deserialize<T>(response, stream, deserializationState);
tcs.SetResult(r);
return tcs.Task;
}
internal JsonSerializerSettings CreateSettings(JsonConverter piggyBackJsonConverter = null)
{
var piggyBackState = new JsonConverterPiggyBackState { ActualJsonConverter = piggyBackJsonConverter };
var settings = new JsonSerializerSettings()
{
ContractResolver = new ElasticContractResolver(this._settings) { PiggyBackState = piggyBackState },
DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Ignore
};
if (_settings.ModifyJsonSerializerSettings != null)
_settings.ModifyJsonSerializerSettings(settings);
return settings;
}
public string SerializeBulkDescriptor(BulkDescriptor bulkDescriptor)
{
bulkDescriptor.ThrowIfNull("bulkDescriptor");
bulkDescriptor._Operations.ThrowIfEmpty("Bulk descriptor does not define any operations");
var sb = new StringBuilder();
var inferrer = new ElasticInferrer(this._settings);
foreach (var operation in bulkDescriptor._Operations)
{
var command = operation._Operation;
var index = operation._Index
?? inferrer.IndexName(bulkDescriptor._Index)
?? inferrer.IndexName(operation._ClrType);
var typeName = operation._Type
?? inferrer.TypeName(bulkDescriptor._Type)
?? inferrer.TypeName(operation._ClrType);
var id = operation.GetIdForObject(inferrer);
operation._Index = index;
operation._Type = typeName;
operation._Id = id;
var opJson = this.Serialize(operation, SerializationFormatting.None).Utf8String();
var action = "{{ \"{0}\" : {1} }}\n".F(command, opJson);
sb.Append(action);
if (command == "index" || command == "create")
{
var jsonCommand = this.Serialize(operation._Object, SerializationFormatting.None).Utf8String();
sb.Append(jsonCommand + "\n");
}
else if (command == "update")
{
var jsonCommand = this.Serialize(operation.GetBody(), SerializationFormatting.None).Utf8String();
sb.Append(jsonCommand + "\n");
}
}
var json = sb.ToString();
return json;
}
/// <summary>
/// _msearch needs a specialized json format in the body
/// </summary>
public string SerializeMultiSearch(MultiSearchDescriptor multiSearchDescriptor)
{
var sb = new StringBuilder();
var inferrer = new ElasticInferrer(this._settings);
foreach (var operation in multiSearchDescriptor._Operations.Values)
{
var indices = inferrer.IndexNames(operation._Indices);
if (operation._AllIndices.GetValueOrDefault(false))
indices = "_all";
var index = indices
?? inferrer.IndexName(multiSearchDescriptor._Index)
?? inferrer.IndexName(operation._ClrType);
var types = inferrer.TypeNames(operation._Types);
var typeName = types
?? inferrer.TypeName(multiSearchDescriptor._Type)
?? inferrer.TypeName(operation._ClrType);
if (operation._AllTypes.GetValueOrDefault(false))
typeName = null; //force empty typename so we'll query all types.
var op = new
{
index = index,
type = typeName,
search_type = this.GetSearchType(operation, multiSearchDescriptor),
preference = operation._Preference,
routing = operation._Routing
};
var opJson = this.Serialize(op, SerializationFormatting.None).Utf8String();
var action = "{0}\n".F(opJson);
sb.Append(action);
var searchJson = this.Serialize(operation, SerializationFormatting.None).Utf8String();
sb.Append(searchJson + "\n");
}
var json = sb.ToString();
return json;
}
protected string GetSearchType(SearchDescriptorBase descriptor, MultiSearchDescriptor multiSearchDescriptor)
{
if (descriptor._SearchType != null)
{
switch (descriptor._SearchType.Value)
{
case SearchTypeOptions.Count:
return "count";
case SearchTypeOptions.DfsQueryThenFetch:
return "dfs_query_then_fetch";
case SearchTypeOptions.DfsQueryAndFetch:
return "dfs_query_and_fetch";
case SearchTypeOptions.QueryThenFetch:
return "query_then_fetch";
case SearchTypeOptions.QueryAndFetch:
return "query_and_fetch";
case SearchTypeOptions.Scan:
return "scan";
}
}
return multiSearchDescriptor._QueryString.GetQueryStringValue<string>("search_type");
}
}
}
| |
using FluentNHibernate.Mapping;
using NUnit.Framework;
namespace FluentNHibernate.Testing.DomainModel.Mapping
{
[TestFixture]
public class AccessStrategyManyToOnePartTester
{
[Test]
public void AccessAsProperty_SetsAccessStrategyToProperty()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.Property();
})
.Element("class/bag").HasAttribute("access", "property");
}
[Test]
public void AccessAsField_SetsAccessStrategyToField()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.Field();
})
.Element("class/bag").HasAttribute("access", "field");
}
[Test]
public void AccessAsCamelCaseField_SetsAccessStrategyToField_and_SetsNamingStrategyToCamelCase()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.CamelCaseField();
})
.Element("class/bag").HasAttribute("access", "field.camelcase");
}
[Test]
public void AccessAsCamelCaseFieldWithUnderscorePrefix_SetsAccessStrategyToField_and_SetsNamingStrategyToCamelCaseUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.CamelCaseField(Prefix.Underscore);
})
.Element("class/bag").HasAttribute("access", "field.camelcase-underscore");
}
[Test]
public void AccessAsLowerCaseField_SetsAccessStrategyToField_and_SetsNamingStrategyToLowerCase()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.LowerCaseField();
})
.Element("class/bag").HasAttribute("access", "field.lowercase");
}
[Test]
public void AccessAsLowerCaseFieldWithUnderscorePrefix_SetsAccessStrategyToField_and_SetsNamingStrategyToLowerCaseUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.LowerCaseField(Prefix.Underscore);
})
.Element("class/bag").HasAttribute("access", "field.lowercase-underscore");
}
[Test]
public void AccessAsPascalCaseFieldWithUnderscorePrefix_SetsAccessStrategyToField_and_SetsNamingStrategyToPascalCaseUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.PascalCaseField(Prefix.Underscore);
})
.Element("class/bag").HasAttribute("access", "field.pascalcase-underscore");
}
[Test]
public void AccessAsPascalCaseFieldWithMPrefix_SetsAccessStrategyToField_and_SetsNamingStrategyToLowerCaseM()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.PascalCaseField(Prefix.m);
})
.Element("class/bag").HasAttribute("access", "field.pascalcase-m");
}
[Test]
public void AccessAsPascalCaseFieldWithMUnderscorePrefix_SetsAccessStrategyToField_and_SetsNamingStrategyToLowerCaseMUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.PascalCaseField(Prefix.mUnderscore);
})
.Element("class/bag").HasAttribute("access", "field.pascalcase-m-underscore");
}
[Test]
public void AccessAsReadOnlyPropertyThroughCamelCaseField_SetsAccessStrategyToNoSetter_and_SetsNamingStrategyToCamelCase()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.ReadOnlyPropertyThroughCamelCaseField();
})
.Element("class/bag").HasAttribute("access", "nosetter.camelcase");
}
[Test]
public void AccessAsReadOnlyPropertyThroughCamelCaseFieldWithUnderscorePrefix_SetsAccessStrategyToNoSetter_and_SetsNamingStrategyToCamelCaseUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore);
})
.Element("class/bag").HasAttribute("access", "nosetter.camelcase-underscore");
}
[Test]
public void AccessAsReadOnlyPropertyThroughLowerCaseField_SetsAccessStrategyToNoSetter_and_SetsNamingStrategyToLowerCase()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.ReadOnlyPropertyThroughLowerCaseField();
})
.Element("class/bag").HasAttribute("access", "nosetter.lowercase");
}
[Test]
public void AccessAsReadOnlyPropertyThroughLowerCaseFieldWithUnderscorePrefix_SetsAccessStrategyToNoSetter_and_SetsNamingStrategyToLowerCaseUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.ReadOnlyPropertyThroughLowerCaseField(Prefix.Underscore);
})
.Element("class/bag").HasAttribute("access", "nosetter.lowercase-underscore");
}
[Test]
public void AccessAsReadOnlyPropertyThroughPascalCaseFieldWithUnderscorePrefix_SetsAccessStrategyToNoSetter_and_SetsNamingStrategyToPascalCaseUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.ReadOnlyPropertyThroughPascalCaseField(Prefix.Underscore);
})
.Element("class/bag").HasAttribute("access", "nosetter.pascalcase-underscore");
}
[Test]
public void AccessAsReadOnlyPropertyThroughPascalCaseFieldWithMPrefix_SetsAccessStrategyToNoSetter_and_SetsNamingStrategyToPascalCaseM()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.ReadOnlyPropertyThroughPascalCaseField(Prefix.m);
})
.Element("class/bag").HasAttribute("access", "nosetter.pascalcase-m");
}
[Test]
public void AccessAsReadOnlyPropertyThroughPascalCaseFieldWithMUnderscorePrefix_SetsAccessStrategyToNoSetter_and_SetsNamingStrategyToPascalCaseMUnderscore()
{
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.ReadOnlyPropertyThroughPascalCaseField(Prefix.mUnderscore);
})
.Element("class/bag").HasAttribute("access", "nosetter.pascalcase-m-underscore");
}
[Test]
public void AccessUsingClassName_SetsAccessAttributeToClassName()
{
string className = typeof(FakePropertyAccessor).AssemblyQualifiedName;
new MappingTester<PropertyTarget>()
.ForMapping(m =>
{
m.Id(x => x.Id);
m.HasMany(x => x.References).Access.Using(className);
})
.Element("class/bag").HasAttribute("access", className);
}
[Test]
public void AccessUsingClassType_SetsAccessAttributeToAssemblyQualifiedName()
{
var className = typeof(FakePropertyAccessor).AssemblyQualifiedName;
new MappingTester<PropertyTarget>()
.ForMapping(c => c.HasMany(x => x.References).Access.Using(typeof(FakePropertyAccessor)))
.Element("class/bag").HasAttribute("access", className);
}
[Test]
public void AccessUsingClassGenericParameter_SetsAccessAttributeToAssemblyQualifiedName()
{
var className = typeof(FakePropertyAccessor).AssemblyQualifiedName;
new MappingTester<PropertyTarget>()
.ForMapping(c => c.HasMany(x => x.References).Access.Using<FakePropertyAccessor>())
.Element("class/bag").HasAttribute("access", className);
}
}
}
| |
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using DotNetShipping.ShippingProviders;
using Xunit;
namespace DotNetShipping.Tests.Features
{
public class UPSRates
{
private Address InternationalAddress2;
private Package Package2;
private readonly Address DomesticAddress1;
private readonly Address DomesticAddress2;
private readonly Address InternationalAddress1;
private readonly Package Package1;
private readonly Package Package1SignatureRequired;
private readonly string UPSLicenseNumber;
private readonly string UPSPassword;
private readonly string UPSUserId;
public UPSRates()
{
DomesticAddress1 = new Address("278 Buckley Jones Road", "", "", "Cleveland", "MS", "38732", "US");
DomesticAddress2 = new Address("One Microsoft Way", "", "", "Redmond", "WA", "98052", "US");
InternationalAddress1 = new Address("Porscheplatz 1", "", "", "70435 Stuttgart", "", "", "DE");
InternationalAddress2 = new Address("80-100 Victoria St", "", "", "London SW1E 5JL", "", "", "GB");
Package1 = new Package(4, 4, 4, 5, 0);
Package2 = new Package(6, 6, 6, 5, 100);
Package1SignatureRequired = new Package(4, 4, 4, 5, 0, null, true);
UPSUserId = ConfigurationManager.AppSettings["UPSUserId"];
UPSPassword = ConfigurationManager.AppSettings["UPSPassword"];
UPSLicenseNumber = ConfigurationManager.AppSettings["UPSLicenseNumber"];
}
[Fact]
public void UPS_Domestic_Returns_Rates_When_Using_International_Addresses_For_Single_Service()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword, "UPS Worldwide Express"));
var response = rateManager.GetRates(DomesticAddress1, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
Assert.NotNull(response);
Assert.NotEmpty(response.Rates);
Assert.Empty(response.ServerErrors);
foreach (var rate in response.Rates)
{
Assert.NotNull(rate);
Assert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
[Fact]
public void UPS_Returns_Multiple_Rates_When_Using_Valid_Addresses_For_All_Services()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword));
var response = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
Assert.NotNull(response);
Assert.NotEmpty(response.Rates);
Assert.Empty(response.ServerErrors);
foreach (var rate in response.Rates)
{
Assert.NotNull(rate);
Assert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
[Fact]
public void UPS_Returns_Multiple_Rates_When_Using_Valid_Addresses_For_All_Services_And_Multple_Packages()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword));
var response = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
Assert.NotNull(response);
Assert.NotEmpty(response.Rates);
Assert.Empty(response.ServerErrors);
foreach (var rate in response.Rates)
{
Assert.NotNull(rate);
Assert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
[Fact]
public void UPS_Returns_Rates_When_Using_International_Origin_And_Destination_Addresses_For_All_Services()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword));
var response = rateManager.GetRates(InternationalAddress2, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
Assert.NotNull(response);
Assert.NotEmpty(response.Rates);
Assert.Empty(response.ServerErrors);
foreach (var rate in response.Rates)
{
Assert.NotNull(rate);
Assert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
[Fact]
public void UPS_Returns_Rates_When_Using_International_Destination_Addresses_And_RetailRates_For_All_Services()
{
var rateManager = new RateManager();
var provider = new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword);
provider.UseRetailRates = true;
rateManager.AddProvider(provider);
var response = rateManager.GetRates(DomesticAddress1, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
Assert.NotNull(response);
Assert.NotEmpty(response.Rates);
Assert.Empty(response.ServerErrors);
foreach (var rate in response.Rates)
{
Assert.NotNull(rate);
Assert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
[Fact]
public void UPS_Returns_Rates_When_Using_International_Destination_Addresses_For_All_Services()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword));
var response = rateManager.GetRates(DomesticAddress1, InternationalAddress1, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
Assert.NotNull(response);
Assert.NotEmpty(response.Rates);
Assert.Empty(response.ServerErrors);
foreach (var rate in response.Rates)
{
Assert.NotNull(rate);
Assert.True(rate.TotalCharges > 0);
Debug.WriteLine(rate.Name + ": " + rate.TotalCharges);
}
}
[Fact]
public void UPS_Returns_Single_Rate_When_Using_Domestic_Addresses_For_Single_Service()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword, "UPS Ground"));
var response = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
Debug.WriteLine($"Rates returned: {(response.Rates.Any() ? response.Rates.Count.ToString() : "0")}");
Assert.NotNull(response);
Assert.NotEmpty(response.Rates);
Assert.Empty(response.ServerErrors);
Assert.Equal(response.Rates.Count, 1);
Assert.True(response.Rates.First().TotalCharges > 0);
Debug.WriteLine(response.Rates.First().Name + ": " + response.Rates.First().TotalCharges);
}
[Fact]
public void CanGetUpsServiceCodes()
{
var provider = new UPSProvider();
var serviceCodes = provider.GetServiceCodes();
Assert.NotNull(serviceCodes);
Assert.NotEmpty(serviceCodes);
}
[Fact]
public void Can_Get_Different_Rates_For_Signature_Required_Lookup()
{
var rateManager = new RateManager();
rateManager.AddProvider(new UPSProvider(UPSLicenseNumber, UPSUserId, UPSPassword, "UPS Ground"));
var nonSignatureResponse = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1);
var signatureResponse = rateManager.GetRates(DomesticAddress1, DomesticAddress2, Package1SignatureRequired);
Debug.WriteLine(string.Format("Rates returned: {0}", nonSignatureResponse.Rates.Any() ? nonSignatureResponse.Rates.Count.ToString() : "0"));
Assert.NotNull(nonSignatureResponse);
Assert.NotEmpty(nonSignatureResponse.Rates);
Assert.Empty(nonSignatureResponse.ServerErrors);
Assert.Equal(nonSignatureResponse.Rates.Count, 1);
Assert.True(nonSignatureResponse.Rates.First().TotalCharges > 0);
Debug.WriteLine(string.Format("Rates returned: {0}", signatureResponse.Rates.Any() ? signatureResponse.Rates.Count.ToString() : "0"));
Assert.NotNull(signatureResponse);
Assert.NotEmpty(signatureResponse.Rates);
Assert.Empty(signatureResponse.ServerErrors);
Assert.Equal(signatureResponse.Rates.Count, 1);
Assert.True(signatureResponse.Rates.First().TotalCharges > 0);
// Now compare prices
foreach (var signatureRate in signatureResponse.Rates)
{
var nonSignatureRate = nonSignatureResponse.Rates.FirstOrDefault(x => x.Name == signatureRate.Name);
if (nonSignatureRate != null)
{
var signatureTotalCharges = signatureRate.TotalCharges;
var nonSignatureTotalCharges = nonSignatureRate.TotalCharges;
Assert.NotEqual(signatureTotalCharges, nonSignatureTotalCharges);
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel
{
using System.Runtime;
using System.Runtime.CompilerServices;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.ComponentModel;
public class MessageSecurityOverHttp
{
internal const MessageCredentialType DefaultClientCredentialType = MessageCredentialType.Windows;
internal const bool DefaultNegotiateServiceCredential = true;
MessageCredentialType clientCredentialType;
bool negotiateServiceCredential;
SecurityAlgorithmSuite algorithmSuite;
bool wasAlgorithmSuiteSet;
public MessageSecurityOverHttp()
{
clientCredentialType = DefaultClientCredentialType;
negotiateServiceCredential = DefaultNegotiateServiceCredential;
algorithmSuite = SecurityAlgorithmSuite.Default;
}
public MessageCredentialType ClientCredentialType
{
get { return this.clientCredentialType; }
set
{
if (!MessageCredentialTypeHelper.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.clientCredentialType = value;
}
}
public bool NegotiateServiceCredential
{
get { return this.negotiateServiceCredential; }
set { this.negotiateServiceCredential = value; }
}
public SecurityAlgorithmSuite AlgorithmSuite
{
get { return this.algorithmSuite; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.algorithmSuite = value;
wasAlgorithmSuiteSet = true;
}
}
internal bool WasAlgorithmSuiteSet
{
get { return this.wasAlgorithmSuiteSet; }
}
protected virtual bool IsSecureConversationEnabled()
{
return true;
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal SecurityBindingElement CreateSecurityBindingElement(bool isSecureTransportMode, bool isReliableSession, MessageSecurityVersion version)
{
if (isReliableSession && !this.IsSecureConversationEnabled())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecureConversationRequiredByReliableSession)));
}
SecurityBindingElement result;
SecurityBindingElement oneShotSecurity;
bool isKerberosSelected = false;
bool emitBspAttributes = true;
if (isSecureTransportMode)
{
switch (this.clientCredentialType)
{
case MessageCredentialType.None:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ClientCredentialTypeMustBeSpecifiedForMixedMode)));
case MessageCredentialType.UserName:
oneShotSecurity = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
break;
case MessageCredentialType.Certificate:
oneShotSecurity = SecurityBindingElement.CreateCertificateOverTransportBindingElement();
break;
case MessageCredentialType.Windows:
oneShotSecurity = SecurityBindingElement.CreateSspiNegotiationOverTransportBindingElement(true);
break;
case MessageCredentialType.IssuedToken:
oneShotSecurity = SecurityBindingElement.CreateIssuedTokenOverTransportBindingElement(IssuedSecurityTokenParameters.CreateInfoCardParameters(new SecurityStandardsManager(new WSSecurityTokenSerializer(emitBspAttributes)), this.algorithmSuite));
break;
default:
Fx.Assert("unknown ClientCredentialType");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
if (this.IsSecureConversationEnabled())
{
result = SecurityBindingElement.CreateSecureConversationBindingElement(oneShotSecurity, true);
}
else
{
result = oneShotSecurity;
}
}
else
{
if (negotiateServiceCredential)
{
switch (this.clientCredentialType)
{
case MessageCredentialType.None:
oneShotSecurity = SecurityBindingElement.CreateSslNegotiationBindingElement(false, true);
break;
case MessageCredentialType.UserName:
oneShotSecurity = SecurityBindingElement.CreateUserNameForSslBindingElement(true);
break;
case MessageCredentialType.Certificate:
oneShotSecurity = SecurityBindingElement.CreateSslNegotiationBindingElement(true, true);
break;
case MessageCredentialType.Windows:
oneShotSecurity = SecurityBindingElement.CreateSspiNegotiationBindingElement(true);
break;
case MessageCredentialType.IssuedToken:
oneShotSecurity = SecurityBindingElement.CreateIssuedTokenForSslBindingElement(IssuedSecurityTokenParameters.CreateInfoCardParameters(new SecurityStandardsManager(new WSSecurityTokenSerializer(emitBspAttributes)), this.algorithmSuite), true);
break;
default:
Fx.Assert("unknown ClientCredentialType");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
else
{
switch (this.clientCredentialType)
{
case MessageCredentialType.None:
oneShotSecurity = SecurityBindingElement.CreateAnonymousForCertificateBindingElement();
break;
case MessageCredentialType.UserName:
oneShotSecurity = SecurityBindingElement.CreateUserNameForCertificateBindingElement();
break;
case MessageCredentialType.Certificate:
oneShotSecurity = SecurityBindingElement.CreateMutualCertificateBindingElement();
break;
case MessageCredentialType.Windows:
oneShotSecurity = SecurityBindingElement.CreateKerberosBindingElement();
isKerberosSelected = true;
break;
case MessageCredentialType.IssuedToken:
oneShotSecurity = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(IssuedSecurityTokenParameters.CreateInfoCardParameters(new SecurityStandardsManager(new WSSecurityTokenSerializer(emitBspAttributes)), this.algorithmSuite));
break;
default:
Fx.Assert("unknown ClientCredentialType");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
if (this.IsSecureConversationEnabled())
{
result = SecurityBindingElement.CreateSecureConversationBindingElement(oneShotSecurity, true);
}
else
{
result = oneShotSecurity;
}
}
// set the algorithm suite and issued token params if required
if (wasAlgorithmSuiteSet || (!isKerberosSelected))
{
result.DefaultAlgorithmSuite = oneShotSecurity.DefaultAlgorithmSuite = this.AlgorithmSuite;
}
else if (isKerberosSelected)
{
result.DefaultAlgorithmSuite = oneShotSecurity.DefaultAlgorithmSuite = SecurityAlgorithmSuite.KerberosDefault;
}
result.IncludeTimestamp = true;
oneShotSecurity.MessageSecurityVersion = version;
result.MessageSecurityVersion = version;
if (!isReliableSession)
{
result.LocalServiceSettings.ReconnectTransportOnFailure = false;
result.LocalClientSettings.ReconnectTransportOnFailure = false;
}
else
{
result.LocalServiceSettings.ReconnectTransportOnFailure = true;
result.LocalClientSettings.ReconnectTransportOnFailure = true;
}
if (this.IsSecureConversationEnabled())
{
// issue the transition SCT for a short duration only
oneShotSecurity.LocalServiceSettings.IssuedCookieLifetime = SpnegoTokenAuthenticator.defaultServerIssuedTransitionTokenLifetime;
}
return result;
}
internal static bool TryCreate<TSecurity>(SecurityBindingElement sbe, bool isSecureTransportMode, bool isReliableSession, out TSecurity messageSecurity)
where TSecurity : MessageSecurityOverHttp
{
Fx.Assert(null != sbe, string.Empty);
messageSecurity = null;
// do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
if (!sbe.IncludeTimestamp)
{
return false;
}
// Do not check MessageSecurityVersion: it maybe changed by the wrapper element and gets checked later in the SecuritySection.AreBindingsMatching()
if (sbe.SecurityHeaderLayout != SecurityProtocolFactory.defaultSecurityHeaderLayout)
{
return false;
}
bool negotiateServiceCredential = DefaultNegotiateServiceCredential;
MessageCredentialType clientCredentialType;
SecurityAlgorithmSuite algorithmSuite = SecurityAlgorithmSuite.Default;
bool isSecureConversation;
SecurityBindingElement bootstrapSecurity;
if (!SecurityBindingElement.IsSecureConversationBinding(sbe, true, out bootstrapSecurity))
{
isSecureConversation = false;
bootstrapSecurity = sbe;
}
else
{
isSecureConversation = true;
}
if (!isSecureConversation && typeof(TSecurity).Equals(typeof(MessageSecurityOverHttp)))
{
return false;
}
if (!isSecureConversation && isReliableSession)
{
return false;
}
if (isSecureTransportMode && !(bootstrapSecurity is TransportSecurityBindingElement))
{
return false;
}
IssuedSecurityTokenParameters infocardParameters;
if (isSecureTransportMode)
{
if (SecurityBindingElement.IsUserNameOverTransportBinding(bootstrapSecurity))
{
clientCredentialType = MessageCredentialType.UserName;
}
else if (SecurityBindingElement.IsCertificateOverTransportBinding(bootstrapSecurity))
{
clientCredentialType = MessageCredentialType.Certificate;
}
else if (SecurityBindingElement.IsSspiNegotiationOverTransportBinding(bootstrapSecurity, true))
{
clientCredentialType = MessageCredentialType.Windows;
}
else if (SecurityBindingElement.IsIssuedTokenOverTransportBinding(bootstrapSecurity, out infocardParameters))
{
if (!IssuedSecurityTokenParameters.IsInfoCardParameters(
infocardParameters,
new SecurityStandardsManager(
sbe.MessageSecurityVersion,
new WSSecurityTokenSerializer(
sbe.MessageSecurityVersion.SecurityVersion,
sbe.MessageSecurityVersion.TrustVersion,
sbe.MessageSecurityVersion.SecureConversationVersion,
true,
null, null, null))))
{
return false;
}
clientCredentialType = MessageCredentialType.IssuedToken;
}
else
{
// the standard binding does not support None client credential type in mixed mode
return false;
}
}
else
{
if (SecurityBindingElement.IsSslNegotiationBinding(bootstrapSecurity, false, true))
{
negotiateServiceCredential = true;
clientCredentialType = MessageCredentialType.None;
}
else if (SecurityBindingElement.IsUserNameForSslBinding(bootstrapSecurity, true))
{
negotiateServiceCredential = true;
clientCredentialType = MessageCredentialType.UserName;
}
else if (SecurityBindingElement.IsSslNegotiationBinding(bootstrapSecurity, true, true))
{
negotiateServiceCredential = true;
clientCredentialType = MessageCredentialType.Certificate;
}
else if (SecurityBindingElement.IsSspiNegotiationBinding(bootstrapSecurity, true))
{
negotiateServiceCredential = true;
clientCredentialType = MessageCredentialType.Windows;
}
else if (SecurityBindingElement.IsIssuedTokenForSslBinding(bootstrapSecurity, true, out infocardParameters))
{
if (!IssuedSecurityTokenParameters.IsInfoCardParameters(
infocardParameters,
new SecurityStandardsManager(
sbe.MessageSecurityVersion,
new WSSecurityTokenSerializer(
sbe.MessageSecurityVersion.SecurityVersion,
sbe.MessageSecurityVersion.TrustVersion,
sbe.MessageSecurityVersion.SecureConversationVersion,
true,
null, null, null))))
{
return false;
}
negotiateServiceCredential = true;
clientCredentialType = MessageCredentialType.IssuedToken;
}
else if (SecurityBindingElement.IsUserNameForCertificateBinding(bootstrapSecurity))
{
negotiateServiceCredential = false;
clientCredentialType = MessageCredentialType.UserName;
}
else if (SecurityBindingElement.IsMutualCertificateBinding(bootstrapSecurity))
{
negotiateServiceCredential = false;
clientCredentialType = MessageCredentialType.Certificate;
}
else if (SecurityBindingElement.IsKerberosBinding(bootstrapSecurity))
{
negotiateServiceCredential = false;
clientCredentialType = MessageCredentialType.Windows;
}
else if (SecurityBindingElement.IsIssuedTokenForCertificateBinding(bootstrapSecurity, out infocardParameters))
{
if (!IssuedSecurityTokenParameters.IsInfoCardParameters(
infocardParameters,
new SecurityStandardsManager(
sbe.MessageSecurityVersion,
new WSSecurityTokenSerializer(
sbe.MessageSecurityVersion.SecurityVersion,
sbe.MessageSecurityVersion.TrustVersion,
sbe.MessageSecurityVersion.SecureConversationVersion,
true,
null, null, null))))
{
return false;
}
negotiateServiceCredential = false;
clientCredentialType = MessageCredentialType.IssuedToken;
}
else if (SecurityBindingElement.IsAnonymousForCertificateBinding(bootstrapSecurity))
{
negotiateServiceCredential = false;
clientCredentialType = MessageCredentialType.None;
}
else
{
return false;
}
}
// Do not check any Local* settings
// Do not check DefaultAlgorithmSuite: is it often changed after the Security element is created, it will verified by SecuritySectionBase.AreBindingsMatching().
if (typeof(NonDualMessageSecurityOverHttp).Equals(typeof(TSecurity)))
{
messageSecurity = (TSecurity)(object)new NonDualMessageSecurityOverHttp();
((NonDualMessageSecurityOverHttp)(object)messageSecurity).EstablishSecurityContext = isSecureConversation;
}
else
{
messageSecurity = (TSecurity)(object)new MessageSecurityOverHttp();
}
messageSecurity.ClientCredentialType = clientCredentialType;
messageSecurity.NegotiateServiceCredential = negotiateServiceCredential;
messageSecurity.AlgorithmSuite = sbe.DefaultAlgorithmSuite;
return true;
}
internal bool InternalShouldSerialize()
{
return this.ShouldSerializeAlgorithmSuite()
|| this.ShouldSerializeClientCredentialType()
|| ShouldSerializeNegotiateServiceCredential();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeAlgorithmSuite()
{
return this.AlgorithmSuite != SecurityAlgorithmSuite.Default;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeClientCredentialType()
{
return this.ClientCredentialType != DefaultClientCredentialType;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeNegotiateServiceCredential()
{
return this.NegotiateServiceCredential != DefaultNegotiateServiceCredential;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using TASKView.lib;
namespace TASKView.app
{
/**
* The GUI definition for the TASKView application.
*
* @author Martin Turon
* @version 2004/4/9 mturon Initial version
*
* $Id: formMain.cs,v 1.12 2004/05/04 03:32:30 mturon Exp $
*/
public class FormMain : System.Windows.Forms.Form
{
internal System.Windows.Forms.MainMenu MainMenu1;
internal System.Windows.Forms.MenuItem MenuItem1;
internal System.Windows.Forms.MenuItem MenuItem5;
internal System.Windows.Forms.MenuItem MenuItem6;
internal System.Windows.Forms.MenuItem MenuItem24;
internal System.Windows.Forms.MenuItem MenuItem2;
internal System.Windows.Forms.MenuItem MenuItem7;
internal System.Windows.Forms.MenuItem MenuItem9;
internal System.Windows.Forms.MenuItem MenuItem10;
internal System.Windows.Forms.MenuItem MenuItem11;
internal System.Windows.Forms.MenuItem MenuItem12;
internal System.Windows.Forms.MenuItem MenuItem8;
internal System.Windows.Forms.MenuItem MenuItem13;
internal System.Windows.Forms.MenuItem MenuItem14;
internal System.Windows.Forms.MenuItem MenuItem15;
internal System.Windows.Forms.MenuItem MenuItem16;
internal System.Windows.Forms.MenuItem MenuItem17;
internal System.Windows.Forms.MenuItem MenuItem18;
internal System.Windows.Forms.MenuItem MenuItem19;
internal System.Windows.Forms.MenuItem MenuItem20;
internal System.Windows.Forms.MenuItem MenuItem21;
internal System.Windows.Forms.MenuItem MenuItem22;
internal System.Windows.Forms.MenuItem MenuItem3;
internal System.Windows.Forms.MenuItem MenuItem4;
internal System.Windows.Forms.MenuItem MenuItem23;
internal System.Windows.Forms.Panel PanelTools;
internal System.Windows.Forms.ToolBar ToolBar1;
internal System.Windows.Forms.ToolBarButton ToolBarButton1;
internal System.Windows.Forms.ToolBarButton ToolBarButton2;
internal System.Windows.Forms.Panel PanelMsgs;
internal System.Windows.Forms.Panel PanelMain;
internal System.Windows.Forms.Panel PanelViews;
internal System.Windows.Forms.Splitter Splitter1;
internal System.Windows.Forms.Panel PanelNodes;
internal System.Windows.Forms.TabControl TabControl1;
internal System.Windows.Forms.TabPage TabPage1;
internal System.Windows.Forms.TabPage TabPage4;
internal System.Windows.Forms.TextBox TextBox5;
internal System.Windows.Forms.Label Label13;
internal System.Windows.Forms.Label Label3;
internal System.Windows.Forms.Button Button6;
internal System.Windows.Forms.Button Button5;
internal System.Windows.Forms.Button Button2;
internal System.Windows.Forms.Button Button1;
internal System.Windows.Forms.Label Label2;
internal System.Windows.Forms.CheckedListBox CheckedListBox1;
internal System.Windows.Forms.Label Label1;
internal System.Windows.Forms.TextBox TextBox1;
internal System.Windows.Forms.ListBox ListBox1;
internal System.Windows.Forms.TabPage TabPage2;
internal System.Windows.Forms.Panel Panel1;
internal System.Windows.Forms.Label Label12;
internal System.Windows.Forms.Label Label11;
internal System.Windows.Forms.Label Label10;
internal System.Windows.Forms.TabPage TabPage3;
internal System.Windows.Forms.TabPage TabPage5;
internal System.Windows.Forms.Button Button8;
internal System.Windows.Forms.Button Button7;
internal System.Windows.Forms.Button Button4;
internal System.Windows.Forms.Label Label6;
internal System.Windows.Forms.Label Label5;
internal System.Windows.Forms.Label Label4;
internal System.Windows.Forms.TreeView TreeView1;
internal System.Windows.Forms.Splitter Splitter2;
private TASKView.lib.NodeList NodeList1;
private TASKView.lib.DataGrid DataGrid1;
private TASKView.lib.MoteMap MoteMap1;
private System.Windows.Forms.RichTextBox StatusWindow1;
private System.Windows.Forms.Panel panel3;
internal System.Windows.Forms.ListView ListView1;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Button MMapButtonLoad;
private System.Windows.Forms.Button MMapButtonSave;
private System.Windows.Forms.Button MMapButtonRefresh;
private System.Windows.Forms.Panel Panel2;
internal System.Windows.Forms.TextBox TextBoxPassword;
internal System.Windows.Forms.TextBox TextBoxUser;
internal System.Windows.Forms.TextBox TextBoxServer;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox TextBoxPort;
private System.Windows.Forms.ComboBox ComboBoxClient;
private System.Windows.Forms.Label label14;
internal System.Windows.Forms.ComboBox ComboBoxTable;
internal System.Windows.Forms.Label Label8;
internal System.Windows.Forms.ComboBox ComboBoxDatabase;
internal System.Windows.Forms.Label Label7;
internal System.Windows.Forms.Button ButtonSetupConnect;
private TASKView.lib.ChartComboBox ComboBoxChart1;
private TASKView.lib.ChartComboBox ComboBoxChart2;
private TASKView.lib.ChartComboBox ComboBoxChart3;
private TASKView.lib.ChartsPanel ChartPanel5;
private System.Windows.Forms.TabPage TabPage6;
private System.Windows.Forms.TabPage TabPage7;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FormMain()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
ComboBoxDatabase_Initialize();
ComboBoxTable_Initialize();
DataGrid1.Initialize();
MoteMap1.Initialize();
NodeList1.Initialize();
NodeList1.CheckClick +=new AxCTLISTLib._DctListEvents_CheckClickEventHandler(NodeList1_CheckClick);
}
/** The read-only Instance property returns the one and only instance. */
public RichTextBox OutputLog
{
get { return StatusWindow1; }
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FormMain));
this.MainMenu1 = new System.Windows.Forms.MainMenu();
this.MenuItem1 = new System.Windows.Forms.MenuItem();
this.MenuItem5 = new System.Windows.Forms.MenuItem();
this.MenuItem6 = new System.Windows.Forms.MenuItem();
this.MenuItem24 = new System.Windows.Forms.MenuItem();
this.MenuItem2 = new System.Windows.Forms.MenuItem();
this.MenuItem7 = new System.Windows.Forms.MenuItem();
this.MenuItem9 = new System.Windows.Forms.MenuItem();
this.MenuItem10 = new System.Windows.Forms.MenuItem();
this.MenuItem11 = new System.Windows.Forms.MenuItem();
this.MenuItem12 = new System.Windows.Forms.MenuItem();
this.MenuItem8 = new System.Windows.Forms.MenuItem();
this.MenuItem13 = new System.Windows.Forms.MenuItem();
this.MenuItem14 = new System.Windows.Forms.MenuItem();
this.MenuItem15 = new System.Windows.Forms.MenuItem();
this.MenuItem16 = new System.Windows.Forms.MenuItem();
this.MenuItem17 = new System.Windows.Forms.MenuItem();
this.MenuItem18 = new System.Windows.Forms.MenuItem();
this.MenuItem19 = new System.Windows.Forms.MenuItem();
this.MenuItem20 = new System.Windows.Forms.MenuItem();
this.MenuItem21 = new System.Windows.Forms.MenuItem();
this.MenuItem22 = new System.Windows.Forms.MenuItem();
this.MenuItem3 = new System.Windows.Forms.MenuItem();
this.MenuItem4 = new System.Windows.Forms.MenuItem();
this.MenuItem23 = new System.Windows.Forms.MenuItem();
this.PanelTools = new System.Windows.Forms.Panel();
this.ToolBar1 = new System.Windows.Forms.ToolBar();
this.ToolBarButton1 = new System.Windows.Forms.ToolBarButton();
this.ToolBarButton2 = new System.Windows.Forms.ToolBarButton();
this.PanelMsgs = new System.Windows.Forms.Panel();
this.StatusWindow1 = new System.Windows.Forms.RichTextBox();
this.PanelMain = new System.Windows.Forms.Panel();
this.PanelViews = new System.Windows.Forms.Panel();
this.TabControl1 = new System.Windows.Forms.TabControl();
this.TabPage1 = new System.Windows.Forms.TabPage();
this.DataGrid1 = new TASKView.lib.DataGrid();
this.TabPage2 = new System.Windows.Forms.TabPage();
this.Panel2 = new System.Windows.Forms.Panel();
this.ChartPanel5 = new TASKView.lib.ChartsPanel();
this.Panel1 = new System.Windows.Forms.Panel();
this.ComboBoxChart3 = new TASKView.lib.ChartComboBox();
this.ComboBoxChart2 = new TASKView.lib.ChartComboBox();
this.ComboBoxChart1 = new TASKView.lib.ChartComboBox();
this.Label12 = new System.Windows.Forms.Label();
this.Label11 = new System.Windows.Forms.Label();
this.Label10 = new System.Windows.Forms.Label();
this.TabPage3 = new System.Windows.Forms.TabPage();
this.panel3 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.MMapButtonRefresh = new System.Windows.Forms.Button();
this.MMapButtonSave = new System.Windows.Forms.Button();
this.MMapButtonLoad = new System.Windows.Forms.Button();
this.ListView1 = new System.Windows.Forms.ListView();
this.MoteMap1 = new TASKView.lib.MoteMap();
this.TabPage4 = new System.Windows.Forms.TabPage();
this.TextBox5 = new System.Windows.Forms.TextBox();
this.Label13 = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
this.Button6 = new System.Windows.Forms.Button();
this.Button5 = new System.Windows.Forms.Button();
this.Button2 = new System.Windows.Forms.Button();
this.Button1 = new System.Windows.Forms.Button();
this.Label2 = new System.Windows.Forms.Label();
this.CheckedListBox1 = new System.Windows.Forms.CheckedListBox();
this.Label1 = new System.Windows.Forms.Label();
this.TextBox1 = new System.Windows.Forms.TextBox();
this.ListBox1 = new System.Windows.Forms.ListBox();
this.TabPage6 = new System.Windows.Forms.TabPage();
this.TabPage7 = new System.Windows.Forms.TabPage();
this.TabPage5 = new System.Windows.Forms.TabPage();
this.ComboBoxTable = new System.Windows.Forms.ComboBox();
this.Label8 = new System.Windows.Forms.Label();
this.ComboBoxDatabase = new System.Windows.Forms.ComboBox();
this.Label7 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.ComboBoxClient = new System.Windows.Forms.ComboBox();
this.label9 = new System.Windows.Forms.Label();
this.TextBoxPort = new System.Windows.Forms.TextBox();
this.Button8 = new System.Windows.Forms.Button();
this.Button7 = new System.Windows.Forms.Button();
this.Button4 = new System.Windows.Forms.Button();
this.ButtonSetupConnect = new System.Windows.Forms.Button();
this.TextBoxPassword = new System.Windows.Forms.TextBox();
this.TextBoxUser = new System.Windows.Forms.TextBox();
this.Label6 = new System.Windows.Forms.Label();
this.Label5 = new System.Windows.Forms.Label();
this.Label4 = new System.Windows.Forms.Label();
this.TextBoxServer = new System.Windows.Forms.TextBox();
this.TreeView1 = new System.Windows.Forms.TreeView();
this.Splitter1 = new System.Windows.Forms.Splitter();
this.PanelNodes = new System.Windows.Forms.Panel();
this.NodeList1 = new TASKView.lib.NodeList();
this.Splitter2 = new System.Windows.Forms.Splitter();
this.PanelTools.SuspendLayout();
this.PanelMsgs.SuspendLayout();
this.PanelMain.SuspendLayout();
this.PanelViews.SuspendLayout();
this.TabControl1.SuspendLayout();
this.TabPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.DataGrid1)).BeginInit();
this.TabPage2.SuspendLayout();
this.Panel2.SuspendLayout();
this.Panel1.SuspendLayout();
this.TabPage3.SuspendLayout();
this.panel3.SuspendLayout();
this.panel4.SuspendLayout();
this.TabPage4.SuspendLayout();
this.TabPage5.SuspendLayout();
this.PanelNodes.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NodeList1)).BeginInit();
this.SuspendLayout();
//
// MainMenu1
//
this.MainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem1,
this.MenuItem2,
this.MenuItem3,
this.MenuItem4});
//
// MenuItem1
//
this.MenuItem1.Index = 0;
this.MenuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem5,
this.MenuItem6,
this.MenuItem24});
this.MenuItem1.Text = "File";
//
// MenuItem5
//
this.MenuItem5.Index = 0;
this.MenuItem5.Text = "Load Config";
//
// MenuItem6
//
this.MenuItem6.Index = 1;
this.MenuItem6.Text = "Save Config";
//
// MenuItem24
//
this.MenuItem24.Index = 2;
this.MenuItem24.Text = "Exit";
//
// MenuItem2
//
this.MenuItem2.Index = 1;
this.MenuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem7,
this.MenuItem8,
this.MenuItem19});
this.MenuItem2.Text = "Units";
//
// MenuItem7
//
this.MenuItem7.Index = 0;
this.MenuItem7.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem9,
this.MenuItem10,
this.MenuItem11,
this.MenuItem12});
this.MenuItem7.Text = "Temperature";
//
// MenuItem9
//
this.MenuItem9.Index = 0;
this.MenuItem9.Text = "Celcius (C)";
//
// MenuItem10
//
this.MenuItem10.Index = 1;
this.MenuItem10.Text = "Fahrenheit (F)";
//
// MenuItem11
//
this.MenuItem11.Index = 2;
this.MenuItem11.Text = "Kelvin (K)";
//
// MenuItem12
//
this.MenuItem12.Index = 3;
this.MenuItem12.Text = "Raw sensor data";
//
// MenuItem8
//
this.MenuItem8.Index = 1;
this.MenuItem8.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem13,
this.MenuItem14,
this.MenuItem15,
this.MenuItem16,
this.MenuItem17,
this.MenuItem18});
this.MenuItem8.Text = "Pressure";
//
// MenuItem13
//
this.MenuItem13.Index = 0;
this.MenuItem13.Text = "Atmosphere (atm)";
//
// MenuItem14
//
this.MenuItem14.Index = 1;
this.MenuItem14.Text = "Bar (bar)";
//
// MenuItem15
//
this.MenuItem15.Index = 2;
this.MenuItem15.Text = "Pascal (Pa)";
//
// MenuItem16
//
this.MenuItem16.Index = 3;
this.MenuItem16.Text = "Per mm Hg (torr)";
//
// MenuItem17
//
this.MenuItem17.Index = 4;
this.MenuItem17.Text = "Pounds per square inch (psi)";
//
// MenuItem18
//
this.MenuItem18.Index = 5;
this.MenuItem18.Text = "Raw sensor data";
//
// MenuItem19
//
this.MenuItem19.Index = 2;
this.MenuItem19.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem20,
this.MenuItem21,
this.MenuItem22});
this.MenuItem19.Text = "Acceleration";
//
// MenuItem20
//
this.MenuItem20.Index = 0;
this.MenuItem20.Text = "Meters per second squared (m/s^2)";
//
// MenuItem21
//
this.MenuItem21.Index = 1;
this.MenuItem21.Text = "Relative gravity (g)";
//
// MenuItem22
//
this.MenuItem22.Index = 2;
this.MenuItem22.Text = "Raw sensor data";
//
// MenuItem3
//
this.MenuItem3.Index = 2;
this.MenuItem3.Text = "Window";
//
// MenuItem4
//
this.MenuItem4.Index = 3;
this.MenuItem4.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem23});
this.MenuItem4.Text = "Help";
//
// MenuItem23
//
this.MenuItem23.Index = 0;
this.MenuItem23.Text = "About";
//
// PanelTools
//
this.PanelTools.Controls.Add(this.ToolBar1);
this.PanelTools.Dock = System.Windows.Forms.DockStyle.Top;
this.PanelTools.Location = new System.Drawing.Point(0, 0);
this.PanelTools.Name = "PanelTools";
this.PanelTools.Size = new System.Drawing.Size(727, 24);
this.PanelTools.TabIndex = 8;
//
// ToolBar1
//
this.ToolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.ToolBarButton1,
this.ToolBarButton2});
this.ToolBar1.DropDownArrows = true;
this.ToolBar1.Location = new System.Drawing.Point(0, 0);
this.ToolBar1.Name = "ToolBar1";
this.ToolBar1.ShowToolTips = true;
this.ToolBar1.Size = new System.Drawing.Size(727, 28);
this.ToolBar1.TabIndex = 0;
this.ToolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.ToolBar1_ButtonClick);
//
// ToolBarButton1
//
this.ToolBarButton1.ToolTipText = "Tool 1";
//
// ToolBarButton2
//
this.ToolBarButton2.ToolTipText = "Tool 2";
//
// PanelMsgs
//
this.PanelMsgs.Controls.Add(this.StatusWindow1);
this.PanelMsgs.Dock = System.Windows.Forms.DockStyle.Bottom;
this.PanelMsgs.Location = new System.Drawing.Point(0, 436);
this.PanelMsgs.Name = "PanelMsgs";
this.PanelMsgs.Size = new System.Drawing.Size(727, 65);
this.PanelMsgs.TabIndex = 9;
//
// StatusWindow1
//
this.StatusWindow1.Dock = System.Windows.Forms.DockStyle.Fill;
this.StatusWindow1.Location = new System.Drawing.Point(0, 0);
this.StatusWindow1.Name = "StatusWindow1";
this.StatusWindow1.Size = new System.Drawing.Size(727, 65);
this.StatusWindow1.TabIndex = 0;
this.StatusWindow1.Text = "Server Messages:";
//
// PanelMain
//
this.PanelMain.Controls.Add(this.PanelViews);
this.PanelMain.Controls.Add(this.Splitter1);
this.PanelMain.Controls.Add(this.PanelNodes);
this.PanelMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.PanelMain.Location = new System.Drawing.Point(0, 24);
this.PanelMain.Name = "PanelMain";
this.PanelMain.Size = new System.Drawing.Size(727, 412);
this.PanelMain.TabIndex = 10;
//
// PanelViews
//
this.PanelViews.Controls.Add(this.TabControl1);
this.PanelViews.Dock = System.Windows.Forms.DockStyle.Fill;
this.PanelViews.Location = new System.Drawing.Point(200, 0);
this.PanelViews.Name = "PanelViews";
this.PanelViews.Size = new System.Drawing.Size(527, 412);
this.PanelViews.TabIndex = 4;
//
// TabControl1
//
this.TabControl1.Controls.Add(this.TabPage1);
this.TabControl1.Controls.Add(this.TabPage2);
this.TabControl1.Controls.Add(this.TabPage3);
this.TabControl1.Controls.Add(this.TabPage4);
this.TabControl1.Controls.Add(this.TabPage6);
this.TabControl1.Controls.Add(this.TabPage7);
this.TabControl1.Controls.Add(this.TabPage5);
this.TabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.TabControl1.Location = new System.Drawing.Point(0, 0);
this.TabControl1.Name = "TabControl1";
this.TabControl1.SelectedIndex = 0;
this.TabControl1.Size = new System.Drawing.Size(527, 412);
this.TabControl1.TabIndex = 2;
//
// TabPage1
//
this.TabPage1.Controls.Add(this.DataGrid1);
this.TabPage1.Location = new System.Drawing.Point(4, 25);
this.TabPage1.Name = "TabPage1";
this.TabPage1.Size = new System.Drawing.Size(519, 383);
this.TabPage1.TabIndex = 2;
this.TabPage1.Text = "Data";
//
// DataGrid1
//
this.DataGrid1.AlternatingBackColor = System.Drawing.Color.Lavender;
this.DataGrid1.BackColor = System.Drawing.Color.WhiteSmoke;
this.DataGrid1.BackgroundColor = System.Drawing.Color.LightGray;
this.DataGrid1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.DataGrid1.CaptionBackColor = System.Drawing.Color.LightSteelBlue;
this.DataGrid1.CaptionForeColor = System.Drawing.Color.MidnightBlue;
this.DataGrid1.CaptionText = "Data Grid";
this.DataGrid1.DataMember = "";
this.DataGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
this.DataGrid1.FlatMode = true;
this.DataGrid1.Font = new System.Drawing.Font("Tahoma", 8F);
this.DataGrid1.ForeColor = System.Drawing.Color.MidnightBlue;
this.DataGrid1.GridLineColor = System.Drawing.Color.Gainsboro;
this.DataGrid1.GridLineStyle = System.Windows.Forms.DataGridLineStyle.None;
this.DataGrid1.HeaderBackColor = System.Drawing.Color.MidnightBlue;
this.DataGrid1.HeaderFont = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.DataGrid1.HeaderForeColor = System.Drawing.Color.WhiteSmoke;
this.DataGrid1.LinkColor = System.Drawing.Color.Teal;
this.DataGrid1.Location = new System.Drawing.Point(0, 0);
this.DataGrid1.Name = "DataGrid1";
this.DataGrid1.ParentRowsBackColor = System.Drawing.Color.Gainsboro;
this.DataGrid1.ParentRowsForeColor = System.Drawing.Color.MidnightBlue;
this.DataGrid1.ReadOnly = true;
this.DataGrid1.SelectionBackColor = System.Drawing.Color.CadetBlue;
this.DataGrid1.SelectionForeColor = System.Drawing.Color.WhiteSmoke;
this.DataGrid1.Size = new System.Drawing.Size(519, 383);
this.DataGrid1.TabIndex = 1;
//
// TabPage2
//
this.TabPage2.Controls.Add(this.Panel2);
this.TabPage2.Controls.Add(this.Panel1);
this.TabPage2.Location = new System.Drawing.Point(4, 25);
this.TabPage2.Name = "TabPage2";
this.TabPage2.Size = new System.Drawing.Size(519, 383);
this.TabPage2.TabIndex = 0;
this.TabPage2.Text = "Charts";
this.TabPage2.Visible = false;
//
// Panel2
//
this.Panel2.Controls.Add(this.ChartPanel5);
this.Panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.Panel2.Location = new System.Drawing.Point(0, 40);
this.Panel2.Name = "Panel2";
this.Panel2.Size = new System.Drawing.Size(519, 343);
this.Panel2.TabIndex = 2;
//
// ChartPanel5
//
this.ChartPanel5.Dock = System.Windows.Forms.DockStyle.Fill;
this.ChartPanel5.Location = new System.Drawing.Point(0, 0);
this.ChartPanel5.Name = "ChartPanel5";
this.ChartPanel5.Size = new System.Drawing.Size(519, 343);
this.ChartPanel5.TabIndex = 0;
//
// Panel1
//
this.Panel1.Controls.Add(this.ComboBoxChart3);
this.Panel1.Controls.Add(this.ComboBoxChart2);
this.Panel1.Controls.Add(this.ComboBoxChart1);
this.Panel1.Controls.Add(this.Label12);
this.Panel1.Controls.Add(this.Label11);
this.Panel1.Controls.Add(this.Label10);
this.Panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.Panel1.Location = new System.Drawing.Point(0, 0);
this.Panel1.Name = "Panel1";
this.Panel1.Size = new System.Drawing.Size(519, 40);
this.Panel1.TabIndex = 1;
//
// ComboBoxChart3
//
this.ComboBoxChart3.Items.AddRange(new object[] {
"(none)",
"thmtemp",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"taosbot",
"qual",
"timelo",
"hamatop",
"qlen",
"depth",
"voltage",
"freeram",
"mhqlen",
"press",
"taostop",
"prcalib",
"(none)",
"thmtemp",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"taosbot",
"qual",
"timelo",
"hamatop",
"qlen",
"depth",
"voltage",
"freeram",
"mhqlen",
"press",
"taostop",
"prcalib",
"(none)",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x"});
this.ComboBoxChart3.Location = new System.Drawing.Point(336, 9);
this.ComboBoxChart3.Name = "ComboBoxChart3";
this.ComboBoxChart3.Size = new System.Drawing.Size(106, 24);
this.ComboBoxChart3.TabIndex = 16;
this.ComboBoxChart3.Text = "(none)";
this.ComboBoxChart3.SelectedIndexChanged += new System.EventHandler(this.ComboBoxChart3_SelectedIndexChanged);
//
// ComboBoxChart2
//
this.ComboBoxChart2.Items.AddRange(new object[] {
"(none)",
"thmtemp",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"taosbot",
"qual",
"timelo",
"hamatop",
"qlen",
"depth",
"voltage",
"freeram",
"mhqlen",
"press",
"taostop",
"prcalib",
"(none)",
"thmtemp",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"taosbot",
"qual",
"timelo",
"hamatop",
"qlen",
"depth",
"voltage",
"freeram",
"mhqlen",
"press",
"taostop",
"prcalib",
"(none)",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x"});
this.ComboBoxChart2.Location = new System.Drawing.Point(182, 9);
this.ComboBoxChart2.Name = "ComboBoxChart2";
this.ComboBoxChart2.Size = new System.Drawing.Size(116, 24);
this.ComboBoxChart2.TabIndex = 15;
this.ComboBoxChart2.Text = "(none)";
this.ComboBoxChart2.SelectedIndexChanged += new System.EventHandler(this.ComboBoxChart2_SelectedIndexChanged);
//
// ComboBoxChart1
//
this.ComboBoxChart1.Items.AddRange(new object[] {
"(none)",
"thmtemp",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"taosbot",
"qual",
"timelo",
"hamatop",
"qlen",
"depth",
"voltage",
"freeram",
"mhqlen",
"press",
"taostop",
"prcalib",
"(none)",
"thmtemp",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"taosbot",
"qual",
"timelo",
"hamatop",
"qlen",
"depth",
"voltage",
"freeram",
"mhqlen",
"press",
"taostop",
"prcalib",
"(none)",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x",
"(none)",
"mag_y",
"light",
"humtemp",
"prtemp",
"hamabot",
"nodeid",
"thermo",
"humid",
"parent",
"timehi",
"thmtemp",
"rawmic",
"qual",
"accel_y",
"accel_x",
"timelo",
"hamatop",
"qlen",
"temp",
"taosbot",
"depth",
"rawtone",
"tones",
"voltage",
"freeram",
"mhqlen",
"noise",
"press",
"taostop",
"prcalib",
"mag_x"});
this.ComboBoxChart1.Location = new System.Drawing.Point(29, 9);
this.ComboBoxChart1.Name = "ComboBoxChart1";
this.ComboBoxChart1.Size = new System.Drawing.Size(115, 24);
this.ComboBoxChart1.TabIndex = 14;
this.ComboBoxChart1.Text = "(none)";
this.ComboBoxChart1.SelectedIndexChanged += new System.EventHandler(this.ComboBoxChart1_SelectedIndexChanged);
//
// Label12
//
this.Label12.Location = new System.Drawing.Point(304, 8);
this.Label12.Name = "Label12";
this.Label12.Size = new System.Drawing.Size(24, 23);
this.Label12.TabIndex = 5;
this.Label12.Text = "Y3:";
//
// Label11
//
this.Label11.Location = new System.Drawing.Point(152, 8);
this.Label11.Name = "Label11";
this.Label11.Size = new System.Drawing.Size(24, 16);
this.Label11.TabIndex = 3;
this.Label11.Text = "Y2";
//
// Label10
//
this.Label10.Location = new System.Drawing.Point(0, 8);
this.Label10.Name = "Label10";
this.Label10.Size = new System.Drawing.Size(24, 16);
this.Label10.TabIndex = 2;
this.Label10.Text = "Y1:";
//
// TabPage3
//
this.TabPage3.Controls.Add(this.panel3);
this.TabPage3.Controls.Add(this.MoteMap1);
this.TabPage3.Location = new System.Drawing.Point(4, 25);
this.TabPage3.Name = "TabPage3";
this.TabPage3.Size = new System.Drawing.Size(519, 383);
this.TabPage3.TabIndex = 1;
this.TabPage3.Text = "Network Map";
this.TabPage3.Visible = false;
//
// panel3
//
this.panel3.Controls.Add(this.panel4);
this.panel3.Controls.Add(this.ListView1);
this.panel3.Dock = System.Windows.Forms.DockStyle.Right;
this.panel3.Location = new System.Drawing.Point(447, 0);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(72, 383);
this.panel3.TabIndex = 6;
//
// panel4
//
this.panel4.Controls.Add(this.MMapButtonRefresh);
this.panel4.Controls.Add(this.MMapButtonSave);
this.panel4.Controls.Add(this.MMapButtonLoad);
this.panel4.Dock = System.Windows.Forms.DockStyle.Top;
this.panel4.Location = new System.Drawing.Point(0, 0);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(72, 104);
this.panel4.TabIndex = 8;
//
// MMapButtonRefresh
//
this.MMapButtonRefresh.Location = new System.Drawing.Point(8, 72);
this.MMapButtonRefresh.Name = "MMapButtonRefresh";
this.MMapButtonRefresh.Size = new System.Drawing.Size(64, 23);
this.MMapButtonRefresh.TabIndex = 8;
this.MMapButtonRefresh.Text = "Refresh";
this.MMapButtonRefresh.Click += new System.EventHandler(this.MMapButtonRefresh_Click);
//
// MMapButtonSave
//
this.MMapButtonSave.Location = new System.Drawing.Point(8, 40);
this.MMapButtonSave.Name = "MMapButtonSave";
this.MMapButtonSave.Size = new System.Drawing.Size(64, 23);
this.MMapButtonSave.TabIndex = 7;
this.MMapButtonSave.Text = "Save";
this.MMapButtonSave.Click += new System.EventHandler(this.MMapButtonSave_Click);
//
// MMapButtonLoad
//
this.MMapButtonLoad.Location = new System.Drawing.Point(8, 8);
this.MMapButtonLoad.Name = "MMapButtonLoad";
this.MMapButtonLoad.Size = new System.Drawing.Size(64, 24);
this.MMapButtonLoad.TabIndex = 6;
this.MMapButtonLoad.Text = "Load";
//
// ListView1
//
this.ListView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.ListView1.Location = new System.Drawing.Point(0, 0);
this.ListView1.Name = "ListView1";
this.ListView1.Size = new System.Drawing.Size(72, 383);
this.ListView1.TabIndex = 2;
//
// MoteMap1
//
this.MoteMap1.AllowDrop = true;
this.MoteMap1.Dock = System.Windows.Forms.DockStyle.Fill;
this.MoteMap1.Location = new System.Drawing.Point(0, 0);
this.MoteMap1.Name = "MoteMap1";
this.MoteMap1.Size = new System.Drawing.Size(519, 383);
this.MoteMap1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.MoteMap1.TabIndex = 2;
this.MoteMap1.TabStop = false;
//
// TabPage4
//
this.TabPage4.Controls.Add(this.TextBox5);
this.TabPage4.Controls.Add(this.Label13);
this.TabPage4.Controls.Add(this.Label3);
this.TabPage4.Controls.Add(this.Button6);
this.TabPage4.Controls.Add(this.Button5);
this.TabPage4.Controls.Add(this.Button2);
this.TabPage4.Controls.Add(this.Button1);
this.TabPage4.Controls.Add(this.Label2);
this.TabPage4.Controls.Add(this.CheckedListBox1);
this.TabPage4.Controls.Add(this.Label1);
this.TabPage4.Controls.Add(this.TextBox1);
this.TabPage4.Controls.Add(this.ListBox1);
this.TabPage4.Location = new System.Drawing.Point(4, 25);
this.TabPage4.Name = "TabPage4";
this.TabPage4.Size = new System.Drawing.Size(519, 383);
this.TabPage4.TabIndex = 3;
this.TabPage4.Text = "Query";
this.TabPage4.Visible = false;
//
// TextBox5
//
this.TextBox5.Location = new System.Drawing.Point(288, 32);
this.TextBox5.Name = "TextBox5";
this.TextBox5.Size = new System.Drawing.Size(192, 22);
this.TextBox5.TabIndex = 11;
this.TextBox5.Text = "2500";
//
// Label13
//
this.Label13.Location = new System.Drawing.Point(128, 32);
this.Label13.Name = "Label13";
this.Label13.Size = new System.Drawing.Size(144, 25);
this.Label13.TabIndex = 10;
this.Label13.Text = "Sample Period (msec):";
//
// Label3
//
this.Label3.Location = new System.Drawing.Point(8, 8);
this.Label3.Name = "Label3";
this.Label3.Size = new System.Drawing.Size(112, 24);
this.Label3.TabIndex = 9;
this.Label3.Text = "Query List:";
//
// Button6
//
this.Button6.Location = new System.Drawing.Point(400, 344);
this.Button6.Name = "Button6";
this.Button6.Size = new System.Drawing.Size(80, 32);
this.Button6.TabIndex = 8;
this.Button6.Text = "Delete";
//
// Button5
//
this.Button5.Location = new System.Drawing.Point(312, 344);
this.Button5.Name = "Button5";
this.Button5.Size = new System.Drawing.Size(80, 32);
this.Button5.TabIndex = 7;
this.Button5.Text = "Stop";
//
// Button2
//
this.Button2.Location = new System.Drawing.Point(224, 344);
this.Button2.Name = "Button2";
this.Button2.Size = new System.Drawing.Size(80, 32);
this.Button2.TabIndex = 6;
this.Button2.Text = "Resend";
//
// Button1
//
this.Button1.Location = new System.Drawing.Point(136, 344);
this.Button1.Name = "Button1";
this.Button1.Size = new System.Drawing.Size(80, 32);
this.Button1.TabIndex = 5;
this.Button1.Text = "Start";
//
// Label2
//
this.Label2.Location = new System.Drawing.Point(128, 57);
this.Label2.Name = "Label2";
this.Label2.Size = new System.Drawing.Size(152, 23);
this.Label2.TabIndex = 4;
this.Label2.Text = "Enabled Sensors:";
//
// CheckedListBox1
//
this.CheckedListBox1.Items.AddRange(new object[] {
"temperature",
"voltage",
"intersema temperature",
"intersema humidity",
"accel_x",
"accel_y",
"magno_x",
"magno_y",
"gps"});
this.CheckedListBox1.Location = new System.Drawing.Point(136, 88);
this.CheckedListBox1.Name = "CheckedListBox1";
this.CheckedListBox1.Size = new System.Drawing.Size(344, 208);
this.CheckedListBox1.TabIndex = 3;
//
// Label1
//
this.Label1.Location = new System.Drawing.Point(128, 8);
this.Label1.Name = "Label1";
this.Label1.Size = new System.Drawing.Size(48, 24);
this.Label1.TabIndex = 2;
this.Label1.Text = "Query:";
//
// TextBox1
//
this.TextBox1.Location = new System.Drawing.Point(192, 8);
this.TextBox1.Name = "TextBox1";
this.TextBox1.Size = new System.Drawing.Size(288, 22);
this.TextBox1.TabIndex = 1;
this.TextBox1.Text = "query1_results";
//
// ListBox1
//
this.ListBox1.ItemHeight = 16;
this.ListBox1.Location = new System.Drawing.Point(8, 32);
this.ListBox1.Name = "ListBox1";
this.ListBox1.Size = new System.Drawing.Size(112, 324);
this.ListBox1.TabIndex = 0;
//
// TabPage6
//
this.TabPage6.Location = new System.Drawing.Point(4, 25);
this.TabPage6.Name = "TabPage6";
this.TabPage6.Size = new System.Drawing.Size(519, 383);
this.TabPage6.TabIndex = 5;
this.TabPage6.Text = "Command";
//
// TabPage7
//
this.TabPage7.Location = new System.Drawing.Point(4, 25);
this.TabPage7.Name = "TabPage7";
this.TabPage7.Size = new System.Drawing.Size(519, 383);
this.TabPage7.TabIndex = 6;
this.TabPage7.Text = "Alerts";
//
// TabPage5
//
this.TabPage5.Controls.Add(this.ComboBoxTable);
this.TabPage5.Controls.Add(this.Label8);
this.TabPage5.Controls.Add(this.ComboBoxDatabase);
this.TabPage5.Controls.Add(this.Label7);
this.TabPage5.Controls.Add(this.label14);
this.TabPage5.Controls.Add(this.ComboBoxClient);
this.TabPage5.Controls.Add(this.label9);
this.TabPage5.Controls.Add(this.TextBoxPort);
this.TabPage5.Controls.Add(this.Button8);
this.TabPage5.Controls.Add(this.Button7);
this.TabPage5.Controls.Add(this.Button4);
this.TabPage5.Controls.Add(this.ButtonSetupConnect);
this.TabPage5.Controls.Add(this.TextBoxPassword);
this.TabPage5.Controls.Add(this.TextBoxUser);
this.TabPage5.Controls.Add(this.Label6);
this.TabPage5.Controls.Add(this.Label5);
this.TabPage5.Controls.Add(this.Label4);
this.TabPage5.Controls.Add(this.TextBoxServer);
this.TabPage5.Controls.Add(this.TreeView1);
this.TabPage5.Location = new System.Drawing.Point(4, 25);
this.TabPage5.Name = "TabPage5";
this.TabPage5.Size = new System.Drawing.Size(519, 383);
this.TabPage5.TabIndex = 4;
this.TabPage5.Text = "Setup";
this.TabPage5.Visible = false;
//
// ComboBoxTable
//
this.ComboBoxTable.Location = new System.Drawing.Point(248, 240);
this.ComboBoxTable.Name = "ComboBoxTable";
this.ComboBoxTable.Size = new System.Drawing.Size(240, 24);
this.ComboBoxTable.TabIndex = 24;
this.ComboBoxTable.Text = "query1_results";
//
// Label8
//
this.Label8.Location = new System.Drawing.Point(160, 240);
this.Label8.Name = "Label8";
this.Label8.Size = new System.Drawing.Size(72, 25);
this.Label8.TabIndex = 23;
this.Label8.Text = "Table:";
//
// ComboBoxDatabase
//
this.ComboBoxDatabase.Location = new System.Drawing.Point(248, 200);
this.ComboBoxDatabase.Name = "ComboBoxDatabase";
this.ComboBoxDatabase.Size = new System.Drawing.Size(240, 24);
this.ComboBoxDatabase.TabIndex = 22;
this.ComboBoxDatabase.Text = "task";
//
// Label7
//
this.Label7.Location = new System.Drawing.Point(160, 200);
this.Label7.Name = "Label7";
this.Label7.Size = new System.Drawing.Size(80, 24);
this.Label7.TabIndex = 21;
this.Label7.Text = "Database:";
//
// label14
//
this.label14.Location = new System.Drawing.Point(160, 280);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(72, 23);
this.label14.TabIndex = 20;
this.label14.Text = "Client:";
//
// ComboBoxClient
//
this.ComboBoxClient.Location = new System.Drawing.Point(248, 280);
this.ComboBoxClient.Name = "ComboBoxClient";
this.ComboBoxClient.Size = new System.Drawing.Size(240, 24);
this.ComboBoxClient.TabIndex = 19;
this.ComboBoxClient.Text = "TASKView";
//
// label9
//
this.label9.Location = new System.Drawing.Point(160, 48);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(72, 24);
this.label9.TabIndex = 18;
this.label9.Text = "Port:";
//
// TextBoxPort
//
this.TextBoxPort.Location = new System.Drawing.Point(248, 48);
this.TextBoxPort.Name = "TextBoxPort";
this.TextBoxPort.Size = new System.Drawing.Size(240, 22);
this.TextBoxPort.TabIndex = 17;
this.TextBoxPort.Text = "5432";
//
// Button8
//
this.Button8.Location = new System.Drawing.Point(400, 336);
this.Button8.Name = "Button8";
this.Button8.Size = new System.Drawing.Size(88, 24);
this.Button8.TabIndex = 16;
this.Button8.Text = "Delete";
//
// Button7
//
this.Button7.Location = new System.Drawing.Point(288, 336);
this.Button7.Name = "Button7";
this.Button7.Size = new System.Drawing.Size(96, 24);
this.Button7.TabIndex = 15;
this.Button7.Text = "Cancel";
//
// Button4
//
this.Button4.Location = new System.Drawing.Point(168, 336);
this.Button4.Name = "Button4";
this.Button4.Size = new System.Drawing.Size(96, 24);
this.Button4.TabIndex = 14;
this.Button4.Text = "Apply";
//
// ButtonSetupConnect
//
this.ButtonSetupConnect.Location = new System.Drawing.Point(392, 152);
this.ButtonSetupConnect.Name = "ButtonSetupConnect";
this.ButtonSetupConnect.Size = new System.Drawing.Size(96, 25);
this.ButtonSetupConnect.TabIndex = 11;
this.ButtonSetupConnect.Text = "Connect";
this.ButtonSetupConnect.Click += new System.EventHandler(this.ButtonSetupConnect_Click);
//
// TextBoxPassword
//
this.TextBoxPassword.Location = new System.Drawing.Point(248, 112);
this.TextBoxPassword.Name = "TextBoxPassword";
this.TextBoxPassword.Size = new System.Drawing.Size(240, 22);
this.TextBoxPassword.TabIndex = 6;
this.TextBoxPassword.Text = "tiny";
//
// TextBoxUser
//
this.TextBoxUser.Location = new System.Drawing.Point(248, 80);
this.TextBoxUser.Name = "TextBoxUser";
this.TextBoxUser.Size = new System.Drawing.Size(240, 22);
this.TextBoxUser.TabIndex = 5;
this.TextBoxUser.Text = "tele";
//
// Label6
//
this.Label6.Location = new System.Drawing.Point(160, 112);
this.Label6.Name = "Label6";
this.Label6.Size = new System.Drawing.Size(72, 23);
this.Label6.TabIndex = 4;
this.Label6.Text = "Password:";
//
// Label5
//
this.Label5.Location = new System.Drawing.Point(160, 80);
this.Label5.Name = "Label5";
this.Label5.Size = new System.Drawing.Size(72, 24);
this.Label5.TabIndex = 3;
this.Label5.Text = "User:";
//
// Label4
//
this.Label4.Location = new System.Drawing.Point(160, 16);
this.Label4.Name = "Label4";
this.Label4.Size = new System.Drawing.Size(72, 24);
this.Label4.TabIndex = 2;
this.Label4.Text = "Server:";
//
// TextBoxServer
//
this.TextBoxServer.Location = new System.Drawing.Point(248, 16);
this.TextBoxServer.Name = "TextBoxServer";
this.TextBoxServer.Size = new System.Drawing.Size(240, 22);
this.TextBoxServer.TabIndex = 1;
this.TextBoxServer.Text = "localhost";
//
// TreeView1
//
this.TreeView1.ImageIndex = -1;
this.TreeView1.Location = new System.Drawing.Point(8, 16);
this.TreeView1.Name = "TreeView1";
this.TreeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
new System.Windows.Forms.TreeNode("localhost", new System.Windows.Forms.TreeNode[] {
new System.Windows.Forms.TreeNode("task", new System.Windows.Forms.TreeNode[] {
new System.Windows.Forms.TreeNode("query1_results"),
new System.Windows.Forms.TreeNode("query2_results")}),
new System.Windows.Forms.TreeNode("labapp_task")}),
new System.Windows.Forms.TreeNode("mturon.xbow.com")});
this.TreeView1.SelectedImageIndex = -1;
this.TreeView1.Size = new System.Drawing.Size(144, 360);
this.TreeView1.TabIndex = 0;
//
// Splitter1
//
this.Splitter1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Splitter1.Location = new System.Drawing.Point(192, 0);
this.Splitter1.Name = "Splitter1";
this.Splitter1.Size = new System.Drawing.Size(8, 412);
this.Splitter1.TabIndex = 2;
this.Splitter1.TabStop = false;
//
// PanelNodes
//
this.PanelNodes.Controls.Add(this.NodeList1);
this.PanelNodes.Dock = System.Windows.Forms.DockStyle.Left;
this.PanelNodes.Location = new System.Drawing.Point(0, 0);
this.PanelNodes.Name = "PanelNodes";
this.PanelNodes.Size = new System.Drawing.Size(192, 412);
this.PanelNodes.TabIndex = 1;
//
// NodeList1
//
this.NodeList1.ContainingControl = this;
this.NodeList1.Dock = System.Windows.Forms.DockStyle.Fill;
this.NodeList1.Location = new System.Drawing.Point(0, 0);
this.NodeList1.Name = "NodeList1";
this.NodeList1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("NodeList1.OcxState")));
this.NodeList1.Size = new System.Drawing.Size(192, 412);
this.NodeList1.TabIndex = 1;
//
// Splitter2
//
this.Splitter2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.Splitter2.Location = new System.Drawing.Point(0, 428);
this.Splitter2.Name = "Splitter2";
this.Splitter2.Size = new System.Drawing.Size(727, 8);
this.Splitter2.TabIndex = 11;
this.Splitter2.TabStop = false;
//
// FormMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(727, 501);
this.Controls.Add(this.Splitter2);
this.Controls.Add(this.PanelMain);
this.Controls.Add(this.PanelMsgs);
this.Controls.Add(this.PanelTools);
this.Menu = this.MainMenu1;
this.Name = "FormMain";
this.Text = "TASKView";
this.PanelTools.ResumeLayout(false);
this.PanelMsgs.ResumeLayout(false);
this.PanelMain.ResumeLayout(false);
this.PanelViews.ResumeLayout(false);
this.TabControl1.ResumeLayout(false);
this.TabPage1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.DataGrid1)).EndInit();
this.TabPage2.ResumeLayout(false);
this.Panel2.ResumeLayout(false);
this.Panel1.ResumeLayout(false);
this.TabPage3.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.TabPage4.ResumeLayout(false);
this.TabPage5.ResumeLayout(false);
this.PanelNodes.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.NodeList1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
FormMain mainForm = theMainForm.Instance;
Application.Run(mainForm);
//Application.Run(new FormMain());
}
private void ToolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
theOdbcManager.Instance.ErrorLog("\nTesting: " + new Random().Next());
}
private void MMapButtonSave_Click(object sender, System.EventArgs e)
{
theOdbcManager.Instance.SaveMotePositions();
}
private void MMapButtonRefresh_Click(object sender, System.EventArgs e)
{
theMoteTable.Instance.Load();
MoteMap1.Refresh();
}
private void ComboBoxChart1_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.ChartPanel5.ChartSensor(0, ComboBoxChart1.Text);
}
private void ComboBoxChart2_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.ChartPanel5.ChartSensor(1, ComboBoxChart2.Text);
}
private void ComboBoxChart3_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.ChartPanel5.ChartSensor(2, ComboBoxChart3.Text);
}
private void NodeList1_CheckClick(object sender, AxCTLISTLib._DctListEvents_CheckClickEvent e)
{
this.ChartPanel5.ChartUpdate(0);
this.ChartPanel5.ChartUpdate(1);
this.ChartPanel5.ChartUpdate(2);
this.ChartPanel5.BuildLegend();
this.ChartPanel5.Refresh();
}
private void ButtonSetupConnect_Click(object sender, System.EventArgs e)
{
OdbcManager db = theOdbcManager.Instance;
db.Server = TextBoxServer.Text;
db.m_Port = TextBoxPort.Text;
db.m_User = TextBoxUser.Text;
db.m_Password = TextBoxPassword.Text;
db.Database = ComboBoxDatabase.Text;
db.m_Table = ComboBoxTable.Text;
db.m_Client = ComboBoxClient.Text;
NodeList1.Initialize();
DataGrid1.Initialize();
MoteMap1.Initialize();
ComboBoxDatabase_Initialize();
ComboBoxTable_Initialize();
}
private void ComboBoxDatabase_Initialize()
{
OdbcManager db = theOdbcManager.Instance;
db.Connect();
DataSet dSet = db.CreateDataSet(db.GetDatabasesCommand());
db.Disconnect();
if (null == dSet) return;
ComboBoxDatabase.Items.Clear();
foreach (DataRow dRow in dSet.Tables[0].Rows)
{
ComboBoxDatabase.Items.Add(dRow["datname"].ToString());
}
}
private void ComboBoxTable_Initialize()
{
OdbcManager db = theOdbcManager.Instance;
db.Connect();
DataSet dSet = db.CreateDataSet(db.GetTablesCommand());
db.Disconnect();
if (null == dSet) return;
this.ComboBoxTable.Items.Clear();
foreach (DataRow dRow in dSet.Tables[0].Rows)
{
ComboBoxTable.Items.Add(dRow["table_name"].ToString());
}
}
private void ComboBoxChart1_SelectedIndexChanged_1(object sender, System.EventArgs e)
{
}
}
/**
* Singleton version of FormMain
*
* @version 2004/4/14 mturon Initial version
*/
public sealed class theMainForm : FormMain
{
/** The internal singular instance of the OdbcManager. */
private static readonly theMainForm instance = new theMainForm();
private theMainForm() {}
/** The read-only Instance property returns the one and only instance. */
public static theMainForm Instance
{
get { return instance; }
}
} // class theMainForm
}
| |
/*
* 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 Ostrich.IO
{
using System;
using System.IO;
using System.Text;
/// <summary>
/// Equivalent of System.IO.BinaryWriter, but with either endianness, depending on
/// the EndianBitConverter it is constructed with.
/// </summary>
public class EndianBinaryWriter : IDisposable
{
#region Fields not directly related to properties
/// <summary>
/// Whether or not this writer has been disposed yet.
/// </summary>
private bool disposed;
/// <summary>
/// Buffer used for temporary storage during conversion from primitives
/// </summary>
private readonly byte[] buffer = new byte[16];
/// <summary>
/// Buffer used for Write(char)
/// </summary>
private readonly char[] charBuffer = new char[1];
#endregion
#region Constructors
/// <summary>
/// Constructs a new binary writer with the given bit converter, writing
/// to the given stream, using UTF-8 encoding.
/// </summary>
/// <param name="bitConverter">Converter to use when writing data</param>
/// <param name="stream">Stream to write data to</param>
public EndianBinaryWriter(EndianBitConverter bitConverter,
Stream stream) : this(bitConverter, stream, Encoding.UTF8)
{
}
/// <summary>
/// Constructs a new binary writer with the given bit converter, writing
/// to the given stream, using the given encoding.
/// </summary>
/// <param name="bitConverter">Converter to use when writing data</param>
/// <param name="stream">Stream to write data to</param>
/// <param name="encoding">Encoding to use when writing character data</param>
public EndianBinaryWriter(EndianBitConverter bitConverter, Stream stream, Encoding encoding)
{
if (bitConverter == null)
{
throw new ArgumentNullException("bitConverter");
}
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
if (!stream.CanWrite)
{
throw new ArgumentException("Stream isn't writable", "stream");
}
this.BaseStream = stream;
this.BitConverter = bitConverter;
this.Encoding = encoding;
}
#endregion
#region Properties
/// <summary>
/// The bit converter used to write values to the stream
/// </summary>
public EndianBitConverter BitConverter { get; }
/// <summary>
/// The encoding used to write strings
/// </summary>
public Encoding Encoding { get; }
/// <summary>
/// Gets the underlying stream of the EndianBinaryWriter.
/// </summary>
public Stream BaseStream { get; }
#endregion
#region Public methods
/// <summary>
/// Closes the writer, including the underlying stream.
/// </summary>
public void Close()
{
Dispose();
}
/// <summary>
/// Flushes the underlying stream.
/// </summary>
public void Flush()
{
CheckDisposed();
BaseStream.Flush();
}
/// <summary>
/// Seeks within the stream.
/// </summary>
/// <param name="offset">Offset to seek to.</param>
/// <param name="origin">Origin of seek operation.</param>
public void Seek(int offset, SeekOrigin origin)
{
CheckDisposed();
BaseStream.Seek(offset, origin);
}
/// <summary>
/// Writes a boolean value to the stream. 1 byte is written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(bool value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 1);
}
/// <summary>
/// Writes a 16-bit signed integer to the stream, using the bit converter
/// for this writer. 2 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(short value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 2);
}
/// <summary>
/// Writes a 32-bit signed integer to the stream, using the bit converter
/// for this writer. 4 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(int value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 4);
}
/// <summary>
/// Writes a 64-bit signed integer to the stream, using the bit converter
/// for this writer. 8 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(long value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 8);
}
/// <summary>
/// Writes a 16-bit unsigned integer to the stream, using the bit converter
/// for this writer. 2 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(ushort value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 2);
}
/// <summary>
/// Writes a 32-bit unsigned integer to the stream, using the bit converter
/// for this writer. 4 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(uint value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 4);
}
/// <summary>
/// Writes a 64-bit unsigned integer to the stream, using the bit converter
/// for this writer. 8 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(ulong value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 8);
}
/// <summary>
/// Writes a single-precision floating-point value to the stream, using the bit converter
/// for this writer. 4 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(float value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 4);
}
/// <summary>
/// Writes a double-precision floating-point value to the stream, using the bit converter
/// for this writer. 8 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(double value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 8);
}
/// <summary>
/// Writes a decimal value to the stream, using the bit converter for this writer.
/// 16 bytes are written.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(decimal value)
{
BitConverter.CopyBytes(value, buffer, 0);
WriteInternal(buffer, 16);
}
/// <summary>
/// Writes a signed byte to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(byte value)
{
buffer[0] = value;
WriteInternal(buffer, 1);
}
/// <summary>
/// Writes an unsigned byte to the stream.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(sbyte value)
{
buffer[0] = unchecked((byte) value);
WriteInternal(buffer, 1);
}
/// <summary>
/// Writes an array of bytes to the stream.
/// </summary>
/// <param name="value">The values to write</param>
public void Write(byte[] value)
{
if (value == null)
{
throw (new ArgumentNullException("value"));
}
WriteInternal(value, value.Length);
}
/// <summary>
/// Writes a portion of an array of bytes to the stream.
/// </summary>
/// <param name="value">An array containing the bytes to write</param>
/// <param name="offset">The index of the first byte to write within the array</param>
/// <param name="count">The number of bytes to write</param>
public void Write(byte[] value, int offset, int count)
{
CheckDisposed();
BaseStream.Write(value, offset, count);
}
/// <summary>
/// Writes a single character to the stream, using the encoding for this writer.
/// </summary>
/// <param name="value">The value to write</param>
public void Write(char value)
{
charBuffer[0] = value;
Write(charBuffer);
}
/// <summary>
/// Writes an array of characters to the stream, using the encoding for this writer.
/// </summary>
/// <param name="value">An array containing the characters to write</param>
public void Write(char[] value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
CheckDisposed();
byte[] data = Encoding.GetBytes(value, 0, value.Length);
WriteInternal(data, data.Length);
}
/// <summary>
/// Writes a string to the stream, using the encoding for this writer.
/// </summary>
/// <param name="value">The value to write. Must not be null.</param>
/// <exception cref="ArgumentNullException">value is null</exception>
public void Write(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
CheckDisposed();
byte[] data = Encoding.GetBytes(value);
Write7BitEncodedInt(data.Length);
WriteInternal(data, data.Length);
}
/// <summary>
/// Writes a 7-bit encoded integer from the stream. This is stored with the least significant
/// information first, with 7 bits of information per byte of value, and the top
/// bit as a continuation flag.
/// </summary>
/// <param name="value">The 7-bit encoded integer to write to the stream</param>
public void Write7BitEncodedInt(int value)
{
CheckDisposed();
if (value < 0)
{
throw new ArgumentOutOfRangeException("value", "Value must be greater than or equal to 0.");
}
int index = 0;
while (value >= 128)
{
buffer[index++] = (byte) ((value & 0x7f) | 0x80);
value = value >> 7;
index++;
}
buffer[index++] = (byte) value;
BaseStream.Write(buffer, 0, index);
}
#endregion
#region Private methods
/// <summary>
/// Checks whether or not the writer has been disposed, throwing an exception if so.
/// </summary>
private void CheckDisposed()
{
if (disposed)
{
throw new ObjectDisposedException("EndianBinaryWriter");
}
}
/// <summary>
/// Writes the specified number of bytes from the start of the given byte array,
/// after checking whether or not the writer has been disposed.
/// </summary>
/// <param name="bytes">The array of bytes to write from</param>
/// <param name="length">The number of bytes to write</param>
private void WriteInternal(byte[] bytes, int length)
{
CheckDisposed();
BaseStream.Write(bytes, 0, length);
}
#endregion
#region IDisposable Members
/// <summary>
/// Disposes of the underlying stream.
/// </summary>
public void Dispose()
{
if (!disposed)
{
Flush();
disposed = true;
((IDisposable) BaseStream).Dispose();
}
}
#endregion
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// 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.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.dao;
using gov.va.medora.mdo.dao.sql.cdw;
namespace gov.va.medora.mdo.api
{
public class EncounterApi
{
string DAO_NAME = "IEncounterDao";
public EncounterApi() { }
public IndexedHashtable getAppointments(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getAppointments", new object[] { });
}
public Dictionary<string, HashSet<string>> getUpdatedFutureAppointments(AbstractConnection cxn, DateTime updatedSince)
{
CdwEncounterDao dao = new CdwEncounterDao(cxn);
return dao.getUpdatedFutureAppointments(updatedSince);
}
public Appointment[] getAppointments(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAppointments();
}
public IndexedHashtable getAppointments(ConnectionSet cxns, int pastDays, int futureDays)
{
return cxns.query(DAO_NAME, "getAppointments", new object[] { pastDays, futureDays });
}
public Appointment[] getAppointments(AbstractConnection cxn, int pastDays, int futureDays)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAppointments(pastDays,futureDays);
}
public IndexedHashtable getFutureAppointments(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getFutureAppointments", new object[] { });
}
public Appointment[] getFutureAppointments(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getFutureAppointments();
}
public string getAppointmentText(AbstractConnection cxn, string apptId)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAppointmentText(apptId);
}
public IndexedHashtable getInpatientMoves(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getInpatientMoves", new object[] { });
}
public Adt[] getInpatientMoves(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getInpatientMoves();
}
public IndexedHashtable getInpatientMoves(ConnectionSet cxns, string fromDate, string toDate)
{
return cxns.query(DAO_NAME, "getInpatientMoves", new object[] { fromDate,toDate });
}
public IndexedHashtable getInpatientMoves(ConnectionSet cxns, string fromDate, string toDate, string iterLength)
{
return cxns.query(DAO_NAME, "getInpatientMoves", new object[] { fromDate, toDate, iterLength });
}
public Adt[] getInpatientMoves(AbstractConnection cxn, string fromDate, string toDate)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getInpatientMoves(fromDate, toDate);
}
public Adt[] getInpatientMovesByCheckinId(AbstractConnection cxn, string checkinId)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getInpatientMovesByCheckinId(checkinId);
}
public IndexedHashtable getInpatientMovesByCheckinId(ConnectionSet cxns, string checkinId)
{
return cxns.query(DAO_NAME, "getInpatientMovesByCheckinId", new object[] { checkinId });
}
public IndexedHashtable getLocations(ConnectionSet cxns, string target, string direction)
{
return cxns.query(DAO_NAME, "lookupLocations", new object[] { target, direction });
}
public HospitalLocation[] getLocations(AbstractConnection cxn, string target, string direction)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.lookupLocations(target, direction);
}
public IndexedHashtable getWards(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getWards", new object[] { });
}
public HospitalLocation[] getWards(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getWards();
}
public DictionaryHashList getSpecialties(AbstractConnection cxn)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getSpecialties();
}
public DictionaryHashList getTeams(AbstractConnection cxn)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getTeams();
}
public HospitalLocation[] getClinics(AbstractConnection cxn, string target, string direction)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getClinics(target, direction);
}
public InpatientStay[] getStaysForWard(AbstractConnection cxn, string wardId)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getStaysForWard(wardId);
}
public IndexedHashtable getDRGRecords(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getDRGRecords", new object[] { });
}
public Drg[] getDRGRecords(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getDRGRecords();
}
public IndexedHashtable getOutpatientEncounterReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getOutpatientEncounterReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getAdmissionsReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getAdmissionsReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getExpandedAdtReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getExpandedAdtReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getDischargesReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getDischargesReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getTransfersReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getTransfersReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getFutureClinicVisitsReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME,"getFutureClinicVisitsReport", new object[]{fromDate,toDate,nrpts});
}
public IndexedHashtable getPastClinicVisitsReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getPastClinicVisitsReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getTreatingSpecialtyReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getTreatingSpecialtyReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getCareTeamReports(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getCareTeamReport", new object[] { });
}
public IndexedHashtable getDischargeDiagnosisReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getDischargeDiagnosisReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getCompAndPenReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getCompAndPenReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getIcdProceduresReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getIcdProceduresReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getIcdSurgeryReports(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getIcdSurgeryReport", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getAdmissions(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getAdmissions", new object[] { });
}
public InpatientStay[] getAdmissions(AbstractConnection cxn)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getAdmissions();
}
public IndexedHashtable getVisits(ConnectionSet cxns, string fromDate, string toDate)
{
return cxns.query(DAO_NAME,"getVisits",new object[]{fromDate, toDate});
}
public Visit[] getVisits(AbstractConnection cxn, string fromDate, string toDate)
{
IEncounterDao dao = (IEncounterDao)cxn.getDao(DAO_NAME);
if (dao == null)
{
return null;
}
return dao.getVisits(fromDate, toDate);
}
public Adt[] getInpatientDischarges(AbstractConnection cxn, string pid)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getInpatientDischarges(pid);
}
public IndexedHashtable getStayMovementsByDateRange(ConnectionSet cxns, string fromDate, string toDate)
{
return cxns.query(DAO_NAME, "getStayMovementsByDateRange", new object[] { fromDate, toDate });
}
public InpatientStay[] getStayMovementsByDateRange(AbstractConnection cxn, string fromDate, string toDate)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getStayMovementsByDateRange(fromDate, toDate);
}
public IndexedHashtable getStayMovementsByPatient(ConnectionSet cxns, string dfn)
{
return cxns.query(DAO_NAME, "getStayMovementsByPatient", new object[] { dfn });
}
public InpatientStay getStayMovements(AbstractConnection cxn, string checkinId)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getStayMovements(checkinId);
}
public Site[] getSiteDivisions(AbstractConnection cxn, string siteId)
{
return ((IEncounterDao)cxn.getDao(DAO_NAME)).getSiteDivisions(siteId);
}
}
}
| |
// 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.Threading;
using System.Collections;
using Xunit;
public class CollectionBase_OnMethods
{
public bool runTest()
{
//////////// Global Variables used for all tests
int iCountErrors = 0;
int iCountTestcases = 0;
MyCollectionBase mycol;
Foo f, newF;
string expectedExceptionMessage;
try
{
do
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
//[] Vanilla Add
iCountTestcases++;
mycol = new MyCollectionBase();
f = new Foo();
mycol.Add(f);
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (!mycol.OnInsertCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_4072ayps OnInsertComplete was never called");
}
else if (0 != mycol.IndexOf(f))
{
iCountErrors++;
Console.WriteLine("Err_0181salh Item was added");
}
//[] Add where Validate throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnValidateThrow = true;
expectedExceptionMessage = "OnValidate";
f = new Foo();
try
{
mycol.Add(f);
iCountErrors++;
Console.WriteLine("Err_1570pyqa Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_2708apsa Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnInsertCalled)
{
iCountErrors++;
Console.WriteLine("Err_56707awwaps OnInsert was called");
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_2708apsa Expected Empty Collection actual {0} elements", mycol.Count);
}
//[] Add where OnInsert throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnInsertThrow = true;
expectedExceptionMessage = "OnInsert";
f = new Foo();
try
{
mycol.Add(f);
iCountErrors++;
Console.WriteLine("Err_35208asdo Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_30437sfdah Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnInsertCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_370asjhs OnInsertComplete was called");
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_3y07aza Expected Empty Collection actual {0} elements", mycol.Count);
}
//[] Add where OnInsertComplete throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnInsertCompleteThrow = true;
expectedExceptionMessage = "OnInsertComplete";
f = new Foo();
try
{
mycol.Add(f);
iCountErrors++;
Console.WriteLine("Err_2548ashz Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_2708alkw Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_3680ahksd Expected Empty Collection actual {0} elements", mycol.Count);
}
/******* Insert ******************************************************************************************/
//[] Vanilla Insert
iCountTestcases++;
mycol = new MyCollectionBase();
f = new Foo();
mycol.Insert(0, f);
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (!mycol.OnInsertCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_270ash OnInsertComplete was never called");
}
else if (0 != mycol.IndexOf(f))
{
iCountErrors++;
Console.WriteLine("Err_208anla Item was added");
}
//[] Insert where Validate throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnValidateThrow = true;
expectedExceptionMessage = "OnValidate";
f = new Foo();
try
{
mycol.Insert(0, f);
iCountErrors++;
Console.WriteLine("Err_270ahsw Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_48708awhoh Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnInsertCalled)
{
iCountErrors++;
Console.WriteLine("Err_3708anw OnInsert was called");
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_707j2awn Expected Empty Collection actual {0} elements", mycol.Count);
}
//[] Insert where OnInsert throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnInsertThrow = true;
expectedExceptionMessage = "OnInsert";
f = new Foo();
try
{
mycol.Insert(0, f);
iCountErrors++;
Console.WriteLine("Err_70378sanw Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_7302nna Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnInsertCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_1270jqna OnInsertComplete was called");
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_2707nqnq Expected Empty Collection actual {0} elements", mycol.Count);
}
//[] Insert where OnInsertComplete throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnInsertCompleteThrow = true;
expectedExceptionMessage = "OnInsertComplete";
f = new Foo();
try
{
mycol.Insert(0, f);
iCountErrors++;
Console.WriteLine("Err_27087nqlkha Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_270hy1na Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_270978aw Expected Empty Collection actual {0} elements", mycol.Count);
}
/************** Remove ***************************************************************************************************************/
//[] Vanilla Remove
iCountTestcases++;
mycol = new MyCollectionBase();
f = new Foo();
mycol.Add(f);
mycol.Remove(f);
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (!mycol.OnRemoveCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_348awq OnRemoveComplete was never called");
}
else if (-1 != mycol.IndexOf(f))
{
iCountErrors++;
Console.WriteLine("Err_0824answ Item was not removed");
}
//[] Remove where Validate throws
iCountTestcases++;
mycol = new MyCollectionBase();
expectedExceptionMessage = "OnValidate";
f = new Foo();
try
{
mycol.Add(f);
mycol.OnValidateThrow = true;
mycol.Remove(f);
iCountErrors++;
Console.WriteLine("Err_08207hnas Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_87082aspz Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnRemoveCalled)
{
iCountErrors++;
Console.WriteLine("Err_7207snmqla OnRemove was called");
}
else if (0 != mycol.IndexOf(f))
{
iCountErrors++;
Console.WriteLine("Err_7270pahnz Element was actually removed {0}", mycol.IndexOf(f));
}
//[] Remove where OnRemove throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnRemoveThrow = true;
expectedExceptionMessage = "OnRemove";
f = new Foo();
try
{
mycol.Add(f);
mycol.Remove(f);
iCountErrors++;
Console.WriteLine("Err_7708aqyy Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_08281naws Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnRemoveCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_10871aklsj OnRemoveComplete was called");
}
else if (0 != mycol.IndexOf(f))
{
iCountErrors++;
Console.WriteLine("Err_2081aslkjs Element was actually removed {0}", mycol.IndexOf(f));
}
//[] Remove where OnRemoveComplete throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnRemoveCompleteThrow = true;
expectedExceptionMessage = "OnRemoveComplete";
f = new Foo();
try
{
mycol.Add(f);
mycol.Remove(f);
iCountErrors++;
Console.WriteLine("Err_10981nlskj Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_20981askjs Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (0 != mycol.IndexOf(f))
{
iCountErrors++;
Console.WriteLine("Err_20909assfd Element was actually removed {0}", mycol.IndexOf(f));
}
/******************* Clear ************************************************************************************************/
//[] Vanilla Clear
iCountTestcases++;
mycol = new MyCollectionBase();
f = new Foo();
mycol.Add(f);
mycol.Clear();
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (!mycol.OnClearCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_2136sdf OnClearComplete was never called");
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_9494aswa Items were not Cleared");
}
//[] Clear where Validate throws
iCountTestcases++;
mycol = new MyCollectionBase();
expectedExceptionMessage = "OnValidate";
f = new Foo();
mycol.Add(f);
mycol.OnValidateThrow = true;
mycol.Clear();
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (!mycol.OnClearCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_6549asff OnClearComplete was not called");
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_4649awajm Items were Cleared");
}
//[] Clear where OnClear throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnClearThrow = true;
expectedExceptionMessage = "OnClear";
f = new Foo();
try
{
mycol.Add(f);
mycol.Clear();
iCountErrors++;
Console.WriteLine("Err_9444sjpjnException was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_78941joaException message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnClearCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_94944awfuu OnClearComplete was called");
}
else if (1 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_6498 Items were not Cleared");
}
//[] Clear where OnClearComplete throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnClearCompleteThrow = true;
expectedExceptionMessage = "OnClearComplete";
f = new Foo();
try
{
mycol.Add(f);
mycol.Clear();
iCountErrors++;
Console.WriteLine("Err_64977awad Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_0877asaw Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (0 != mycol.Count)
{
iCountErrors++;
Console.WriteLine("Err_1081lkajs Items were not Cleared");
}
/**************************** Set ***********************************************************************************************************************/
//[] Vanilla Set
iCountTestcases++;
mycol = new MyCollectionBase();
f = new Foo(1, "1");
newF = new Foo(2, "2");
mycol.Add(f);
mycol[0] = newF;
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (!mycol.OnSetCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_1698asdf OnSetComplete was never called");
}
else if (-1 != mycol.IndexOf(f) || 0 != mycol.IndexOf(newF))
{
iCountErrors++;
Console.WriteLine("Err_9494safs Item was not Set");
}
//[] Set where Validate throws
iCountTestcases++;
mycol = new MyCollectionBase();
expectedExceptionMessage = "OnValidate";
f = new Foo(1, "1");
newF = new Foo(2, "2");
try
{
mycol.Add(f);
mycol.OnValidateThrow = true;
mycol[0] = newF;
iCountErrors++;
Console.WriteLine("Err_611awwa Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_69498hph Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnSetCalled)
{
iCountErrors++;
Console.WriteLine("Err_94887jio OnSet was called");
}
else if (0 != mycol.IndexOf(f) || -1 != mycol.IndexOf(newF))
{
iCountErrors++;
Console.WriteLine("Err_6549ihyopiu Element was actually Set {0}", mycol.IndexOf(f));
}
//[] Set where OnSet throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnSetThrow = true;
expectedExceptionMessage = "OnSet";
f = new Foo(1, "1");
newF = new Foo(2, "2");
try
{
mycol.Add(f);
mycol[0] = newF;
iCountErrors++;
Console.WriteLine("Err_61518haiosd Exception was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_196198sdklhsException message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (mycol.OnSetCompleteCalled)
{
iCountErrors++;
Console.WriteLine("Err_6548dasfs OnSetComplete was called");
}
else if (0 != mycol.IndexOf(f) || -1 != mycol.IndexOf(newF))
{
iCountErrors++;
Console.WriteLine("Err_2797sah Element was actually Set {0}", mycol.IndexOf(f));
}
//[] Set where OnSetComplete throws
iCountTestcases++;
mycol = new MyCollectionBase();
mycol.OnSetCompleteThrow = true;
expectedExceptionMessage = "OnSetComplete";
f = new Foo(1, "1");
newF = new Foo(2, "2");
try
{
mycol.Add(f);
mycol[0] = newF;
iCountErrors++;
Console.WriteLine("Err_56498hkashException was not thrown");
}
catch (Exception e)
{
if (expectedExceptionMessage != e.Message)
{
iCountErrors++;
Console.WriteLine("Err_13168hsaiuh Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message);
}
}
if (mycol.IsError)
{
iCountErrors++;
Console.WriteLine(mycol.ErrorMsg);
}
else if (0 != mycol.IndexOf(f) || -1 != mycol.IndexOf(newF))
{
iCountErrors++;
Console.WriteLine("Err_64198ahihos Element was actually Set {0}", mycol.IndexOf(f));
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
} while (false);
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine(" : Error Err_8888yyy! exc_general==\n" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors == 0)
{
return true;
}
else
{
return false;
}
}
[Fact]
public static void ExecuteCollectionBase_OnMethods()
{
bool bResult = false;
var test = new CollectionBase_OnMethods();
try
{
bResult = test.runTest();
}
catch (Exception exc_main)
{
bResult = false;
Console.WriteLine("Fail! Error Err_main! Uncaught Exception in main(), exc_main==" + exc_main);
}
Assert.True(bResult);
}
//CollectionBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here
public class MyCollectionBase : CollectionBase
{
public bool IsError = false;
public string ErrorMsg = String.Empty;
public bool OnValidateCalled, OnSetCalled, OnSetCompleteCalled, OnInsertCalled, OnInsertCompleteCalled,
OnClearCalled, OnClearCompleteCalled, OnRemoveCalled, OnRemoveCompleteCalled;
public bool OnValidateThrow, OnSetThrow, OnSetCompleteThrow, OnInsertThrow, OnInsertCompleteThrow,
OnClearThrow, OnClearCompleteThrow, OnRemoveThrow, OnRemoveCompleteThrow;
public MyCollectionBase()
{
OnValidateCalled = false;
OnSetCalled = false;
OnSetCompleteCalled = false;
OnInsertCalled = false;
OnInsertCompleteCalled = false;
OnClearCalled = false;
OnClearCompleteCalled = false;
OnRemoveCalled = false;
OnRemoveCompleteCalled = false;
OnValidateThrow = false;
OnSetThrow = false;
OnSetCompleteThrow = false;
OnInsertThrow = false;
OnInsertCompleteThrow = false;
OnClearThrow = false;
OnClearCompleteThrow = false;
OnRemoveThrow = false;
OnRemoveCompleteThrow = false;
}
public int Add(Foo f1)
{
return List.Add(f1);
}
public Foo this[int indx]
{
get { return (Foo)List[indx]; }
set { List[indx] = value; }
}
public void CopyTo(Array array, Int32 index)
{
((ICollection)List).CopyTo(array, index);
}
public Int32 IndexOf(Foo f)
{
return ((IList)List).IndexOf(f);
}
public Boolean Contains(Foo f)
{
return ((IList)List).Contains(f);
}
public void Insert(Int32 index, Foo f)
{
List.Insert(index, f);
}
public void Remove(Foo f)
{
List.Remove(f);
}
protected override void OnSet(int index, Object oldValue, Object newValue)
{
if (!OnValidateCalled)
{
IsError = true;
ErrorMsg += "Err_0882pxnk OnValidate has not been called\n";
}
if (this[index] != oldValue)
{
IsError = true;
ErrorMsg += "Err_1204phzn Value was already set\n";
}
OnSetCalled = true;
if (OnSetThrow)
throw new Exception("OnSet");
}
protected override void OnInsert(int index, Object value)
{
if (!OnValidateCalled)
{
IsError = true;
ErrorMsg += "Err_0834halkh OnValidate has not been called\n";
}
if (index > Count)
{
IsError = true;
ErrorMsg += "Err_7332pghh Value was already set\n";
}
if (index != Count && this[index] == value)
{
IsError = true;
ErrorMsg += "Err_2702apqh OnInsert called with a bad index\n";
}
OnInsertCalled = true;
if (OnInsertThrow)
throw new Exception("OnInsert");
}
protected override void OnClear()
{
if (Count == 0 || InnerList.Count == 0)
{
//Assumes Clear not called on an empty list
IsError = true;
ErrorMsg += "Err_2247alkhz List already empty\n";
}
OnClearCalled = true;
if (OnClearThrow)
throw new Exception("OnClear");
}
protected override void OnRemove(int index, Object value)
{
if (!OnValidateCalled)
{
IsError = true;
ErrorMsg += "Err_3703pyaa OnValidate has not been called\n";
}
if (this[index] != value)
{
IsError = true;
ErrorMsg += "Err_1708afsw Value was already set\n";
}
OnRemoveCalled = true;
if (OnRemoveThrow)
throw new Exception("OnRemove");
}
protected override void OnValidate(Object value)
{
OnValidateCalled = true;
if (OnValidateThrow)
throw new Exception("OnValidate");
}
protected override void OnSetComplete(int index, Object oldValue, Object newValue)
{
if (!OnSetCalled)
{
IsError = true;
ErrorMsg += "Err_0282pyahn OnSet has not been called\n";
}
if (this[index] != newValue)
{
IsError = true;
ErrorMsg += "Err_2134pyqt Value has not been set\n";
}
OnSetCompleteCalled = true;
if (OnSetCompleteThrow)
throw new Exception("OnSetComplete");
}
protected override void OnInsertComplete(int index, Object value)
{
if (!OnInsertCalled)
{
IsError = true;
ErrorMsg += "Err_5607aspyu OnInsert has not been called\n";
}
if (this[index] != value)
{
IsError = true;
ErrorMsg += "Err_3407ahpqValue has not been set\n";
}
OnInsertCompleteCalled = true;
if (OnInsertCompleteThrow)
throw new Exception("OnInsertComplete");
}
protected override void OnClearComplete()
{
if (!OnClearCalled)
{
IsError = true;
ErrorMsg += "Err_3470sfas OnClear has not been called\n";
}
if (Count != 0 || InnerList.Count != 0)
{
IsError = true;
ErrorMsg += "Err_2507yuznb Value has not been set\n";
}
OnClearCompleteCalled = true;
if (OnClearCompleteThrow)
throw new Exception("OnClearComplete");
}
protected override void OnRemoveComplete(int index, Object value)
{
if (!OnRemoveCalled)
{
IsError = true;
ErrorMsg += "Err_70782sypz OnRemve has not been called\n";
}
if (IndexOf((Foo)value) == index)
{
IsError = true;
ErrorMsg += "Err_3097saq Value still exists\n";
}
OnRemoveCompleteCalled = true;
if (OnRemoveCompleteThrow)
throw new Exception("OnRemoveComplete");
}
public void ClearTest()
{
IsError = false;
ErrorMsg = String.Empty;
OnValidateCalled = false;
OnSetCalled = false;
OnSetCompleteCalled = false;
OnInsertCalled = false;
OnInsertCompleteCalled = false;
OnClearCalled = false;
OnClearCompleteCalled = false;
OnRemoveCalled = false;
OnRemoveCompleteCalled = false;
OnValidateThrow = false;
OnSetThrow = false;
OnSetCompleteThrow = false;
OnInsertThrow = false;
OnInsertCompleteThrow = false;
OnClearThrow = false;
OnClearCompleteThrow = false;
OnRemoveThrow = false;
OnRemoveCompleteThrow = false;
}
}
public class Foo
{
private Int32 _iValue;
private String _strValue;
public Foo()
{
}
public Foo(Int32 i, String str)
{
_iValue = i;
_strValue = str;
}
public Int32 IValue
{
get { return _iValue; }
set { _iValue = value; }
}
public String SValue
{
get { return _strValue; }
set { _strValue = value; }
}
public override Boolean Equals(Object obj)
{
if (obj == null)
return false;
if (!(obj is Foo))
return false;
if ((((Foo)obj).IValue == _iValue) && (((Foo)obj).SValue == _strValue))
return true;
return false;
}
public override Int32 GetHashCode()
{
return _iValue;
}
}
}
| |
// <copyright file="Arguments.cs" company="Bau contributors">
// Copyright (c) Bau contributors. (baubuildch@gmail.com)
// </copyright>
namespace BauCore
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
public class Arguments
{
private readonly ReadOnlyCollection<string> tasks;
private readonly LogLevel logLevel;
private readonly TaskListType? taskListType;
private readonly bool help;
public Arguments(
IEnumerable<string> tasks,
LogLevel logLevel,
TaskListType? taskListType,
bool help)
{
Guard.AgainstNullArgument("tasks", tasks);
this.tasks = new ReadOnlyCollection<string>(tasks.ToList());
this.logLevel = logLevel;
this.taskListType = taskListType;
this.help = help;
}
public IEnumerable<string> Tasks
{
get { return this.tasks; }
}
public LogLevel LogLevel
{
get { return this.logLevel; }
}
public TaskListType? TaskListType
{
get { return this.taskListType; }
}
public bool Help
{
get { return this.help; }
}
public static void ShowUsage(ColorText header)
{
ColorConsole.WriteLine(header);
ColorConsole.WriteLine(null);
ShowUsage();
}
public static void ShowUsage()
{
ColorConsole.WriteLine(new ColorText(
new ColorToken("Usage: ", ConsoleColor.White),
new ColorToken("scriptcs ", ConsoleColor.DarkGreen),
new ColorToken("<", ConsoleColor.Gray),
new ColorToken("filename", ConsoleColor.DarkCyan),
new ColorToken("> ", ConsoleColor.Gray),
new ColorToken("-- ", ConsoleColor.DarkGreen),
new ColorToken("[", ConsoleColor.Gray),
new ColorToken("tasks", ConsoleColor.DarkCyan),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("default", ConsoleColor.DarkGreen),
new ColorToken("*] ", ConsoleColor.Gray),
new ColorToken("[", ConsoleColor.Gray),
new ColorToken("options", ConsoleColor.DarkCyan),
new ColorToken("]", ConsoleColor.Gray)));
ColorConsole.WriteLine(null);
ColorConsole.WriteLine(new ColorToken("Options:", ConsoleColor.White));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -T", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.DarkGray),
new ColorToken("-tasklist", ConsoleColor.DarkGreen),
new ColorToken(" Display the list of tasks", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" (", ConsoleColor.Gray),
new ColorToken("d", ConsoleColor.DarkGreen),
new ColorToken("*", ConsoleColor.Gray),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("descriptive", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("a", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("all", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("p", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("prerequisites", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("j", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("json", ConsoleColor.DarkGreen),
new ColorToken(").", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -A ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-tasklist all", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -P ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-tasklist prerequisites", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -J ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-tasklist json", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -l", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("-loglevel ", ConsoleColor.DarkGreen),
new ColorToken("<", ConsoleColor.Gray),
new ColorToken("level", ConsoleColor.DarkCyan),
new ColorToken(">", ConsoleColor.Gray),
new ColorToken(" Log at the specified level", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" (", ConsoleColor.Gray),
new ColorToken("a", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("all", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("t", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("trace", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("d", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("debug", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("i", ConsoleColor.DarkGreen),
new ColorToken("*", ConsoleColor.Gray),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("info", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("w", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("warn", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("e", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("error", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("f", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("fatal", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("o", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("off", ConsoleColor.DarkGreen),
new ColorToken(").", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -t ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-loglevel trace", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -d ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-loglevel debug", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -q ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-loglevel warn", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -qq ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-loglevel error", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -s ", ConsoleColor.DarkGreen),
new ColorToken("Alias for ", ConsoleColor.Gray),
new ColorToken("-loglevel off", ConsoleColor.DarkGreen),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" -?", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("-h", ConsoleColor.DarkGreen),
new ColorToken("|", ConsoleColor.Gray),
new ColorToken("-help", ConsoleColor.DarkGreen),
new ColorToken(" Show help.", ConsoleColor.Gray)));
ColorConsole.WriteLine(null);
ColorConsole.WriteLine(new ColorText(
new ColorToken(" One and two character option aliases are ", ConsoleColor.Gray),
new ColorToken("case-sensitive", ConsoleColor.White),
new ColorToken(".", ConsoleColor.Gray)));
ColorConsole.WriteLine(null);
ColorConsole.WriteLine(new ColorText(
new ColorToken("Examples:", ConsoleColor.White)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" scriptcs baufile.csx ", ConsoleColor.DarkGreen),
new ColorToken("Run the '", ConsoleColor.Gray),
new ColorToken("default", ConsoleColor.DarkCyan),
new ColorToken("' task.", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" scriptcs baufile.csx -- build test ", ConsoleColor.DarkGreen),
new ColorToken("Run the '", ConsoleColor.Gray),
new ColorToken("build", ConsoleColor.DarkCyan),
new ColorToken("' and '", ConsoleColor.Gray),
new ColorToken("test", ConsoleColor.DarkCyan),
new ColorToken("' tasks.", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" scriptcs baufile.csx -- -l d ", ConsoleColor.DarkGreen),
new ColorToken("Run the '", ConsoleColor.Gray),
new ColorToken("default", ConsoleColor.DarkCyan),
new ColorToken("' task and log at debug level.", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" scriptcs baufile.csx -- -T ", ConsoleColor.DarkGreen),
new ColorToken("Display the list of tasks with descriptions.", ConsoleColor.Gray)));
ColorConsole.WriteLine(new ColorText(
new ColorToken(" scriptcs baufile.csx -- -T p ", ConsoleColor.DarkGreen),
new ColorToken("Display the list of tasks and prerequisites.", ConsoleColor.Gray)));
ColorConsole.WriteLine(null);
ColorConsole.WriteLine(new ColorText(
new ColorToken("* Default value.", ConsoleColor.Gray)));
ColorConsole.WriteLine(null);
}
public static Arguments Parse(IEnumerable<string> args)
{
Guard.AgainstNullArgument("args", args);
var tasks = new List<string>();
var logLevel = LogLevel.Info;
var help = false;
var taskListType = default(TaskListType?);
foreach (var option in Parse(args, tasks))
{
switch (option.Key.ToUpperInvariant())
{
case "LOGLEVEL":
var logLevels = option.Value;
if (logLevels.Any())
{
logLevel = MapLogLevel(logLevels.First());
}
break;
case "TASKLIST":
var taskListTypes = option.Value;
taskListType = taskListTypes.Any()
? MapTaskListType(taskListTypes.First())
: BauCore.TaskListType.Descriptive;
break;
case "HELP":
help = true;
break;
default:
var message = string.Format(
CultureInfo.InvariantCulture, "The option '{0}' is not recognised.", option.Key);
throw new ArgumentException(message, "args");
}
}
return new Arguments(tasks, logLevel, taskListType, help);
}
private static Dictionary<string, List<string>> Parse(IEnumerable<string> args, ICollection<string> tasks)
{
var options = new Dictionary<string, List<string>>(StringComparer.Create(CultureInfo.InvariantCulture, true));
string currentName = null;
foreach (var arg in args
.Where(a => !string.IsNullOrWhiteSpace(a))
.Select(a => a.Trim()))
{
if (!arg.StartsWith("-", StringComparison.Ordinal))
{
if (currentName == null)
{
tasks.Add(arg);
continue;
}
options[currentName].Add(arg);
continue;
}
string impliedValue;
var name = Map(arg.TrimStart('-').Trim(), out impliedValue);
if (name.Length > 0)
{
currentName = name;
if (!options.ContainsKey(name))
{
var values = new List<string>();
if (!string.IsNullOrWhiteSpace(impliedValue))
{
values.Add(impliedValue);
}
options.Add(currentName, values);
}
}
}
return options;
}
private static string Map(string optionName, out string impliedValue)
{
impliedValue = null;
switch (optionName)
{
case "TASKLIST":
case "T":
return "TASKLIST";
case "A":
impliedValue = "ALL";
return "TASKLIST";
case "P":
impliedValue = "PREREQUISITES";
return "TASKLIST";
case "J":
impliedValue = "JSON";
return "TASKLIST";
case "l":
return "LOGLEVEL";
case "t":
impliedValue = "TRACE";
return "LOGLEVEL";
case "d":
impliedValue = "DEBUG";
return "LOGLEVEL";
case "q":
impliedValue = "WARN";
return "LOGLEVEL";
case "qq":
impliedValue = "ERROR";
return "LOGLEVEL";
case "s":
impliedValue = "OFF";
return "LOGLEVEL";
case "h":
case "?":
return "HELP";
default:
return optionName;
}
}
private static LogLevel MapLogLevel(string logLevelString)
{
switch (logLevelString.ToUpperInvariant())
{
case "A":
case "ALL":
return LogLevel.All;
case "T":
case "TRACE":
return LogLevel.Trace;
case "D":
case "DEBUG":
return LogLevel.Debug;
case "I":
case "INFO":
return LogLevel.Info;
case "W":
case "WARN":
return LogLevel.Warn;
case "E":
case "ERROR":
return LogLevel.Error;
case "F":
case "FATAL":
return LogLevel.Fatal;
case "O":
case "OFF":
return LogLevel.Off;
default:
var message = string.Format(
CultureInfo.InvariantCulture, "The log level '{0}' is not recognised.", logLevelString);
throw new ArgumentException(message, "logLevelString");
}
}
private static TaskListType MapTaskListType(string taskListTypeString)
{
switch (taskListTypeString.ToUpperInvariant())
{
case "DESCRIPTIVE":
case "D":
return BauCore.TaskListType.Descriptive;
case "ALL":
case "A":
return BauCore.TaskListType.All;
case "PREREQUISITES":
case "P":
return BauCore.TaskListType.Prerequisites;
case "JSON":
case "J":
return BauCore.TaskListType.Json;
default:
var message = string.Format(
CultureInfo.InvariantCulture, "The task list type '{0}' is not recognised.", taskListTypeString);
throw new ArgumentException(message, taskListTypeString);
}
}
}
}
| |
// 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.Dynamic;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Reflection;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Runtime.CompilerServices
{
//
// A CallSite provides a fast mechanism for call-site caching of dynamic dispatch
// behavior. Each site will hold onto a delegate that provides a fast-path dispatch
// based on previous types that have been seen at the call-site. This delegate will
// call UpdateAndExecute if it is called with types that it hasn't seen before.
// Updating the binding will typically create (or lookup) a new delegate
// that supports fast-paths for both the new type and for any types that
// have been seen previously.
//
// DynamicSites will generate the fast-paths specialized for sets of runtime argument
// types. However, they will generate exactly the right amount of code for the types
// that are seen in the program so that int addition will remain as fast as it would
// be with custom implementation of the addition, and the user-defined types can be
// as fast as ints because they will all have the same optimal dynamically generated
// fast-paths.
//
// DynamicSites don't encode any particular caching policy, but use their
// CallSiteBinding to encode a caching policy.
//
/// <summary>
/// A Dynamic Call Site base class. This type is used as a parameter type to the
/// dynamic site targets. The first parameter of the delegate (T) below must be
/// of this type.
/// </summary>
public class CallSite
{
/// <summary>
/// String used for generated CallSite methods.
/// </summary>
internal const string CallSiteTargetMethodName = "CallSite.Target";
/// <summary>
/// Cache of CallSite constructors for a given delegate type.
/// </summary>
private static volatile CacheDict<Type, Func<CallSiteBinder, CallSite>> s_siteCtors;
/// <summary>
/// The Binder responsible for binding operations at this call site.
/// This binder is invoked by the UpdateAndExecute below if all Level 0,
/// Level 1 and Level 2 caches experience cache miss.
/// </summary>
internal readonly CallSiteBinder _binder;
// only CallSite<T> derives from this
internal CallSite(CallSiteBinder binder)
{
_binder = binder;
}
/// <summary>
/// Used by Matchmaker sites to indicate rule match.
/// </summary>
internal bool _match;
/// <summary>
/// Class responsible for binding dynamic operations on the dynamic site.
/// </summary>
public CallSiteBinder Binder => _binder;
/// <summary>
/// Creates a CallSite with the given delegate type and binder.
/// </summary>
/// <param name="delegateType">The CallSite delegate type.</param>
/// <param name="binder">The CallSite binder.</param>
/// <returns>The new CallSite.</returns>
public static CallSite Create(Type delegateType, CallSiteBinder binder)
{
ContractUtils.RequiresNotNull(delegateType, nameof(delegateType));
ContractUtils.RequiresNotNull(binder, nameof(binder));
if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate();
CacheDict<Type, Func<CallSiteBinder, CallSite>> ctors = s_siteCtors;
if (ctors == null)
{
// It's okay to just set this, worst case we're just throwing away some data
s_siteCtors = ctors = new CacheDict<Type, Func<CallSiteBinder, CallSite>>(100);
}
if (!ctors.TryGetValue(delegateType, out Func<CallSiteBinder, CallSite> ctor))
{
MethodInfo method = typeof(CallSite<>).MakeGenericType(delegateType).GetMethod(nameof(Create));
if (delegateType.IsCollectible)
{
// slow path
return (CallSite)method.Invoke(null, new object[] { binder });
}
ctor = (Func<CallSiteBinder, CallSite>)method.CreateDelegate(typeof(Func<CallSiteBinder, CallSite>));
ctors.Add(delegateType, ctor);
}
return ctor(binder);
}
}
/// <summary>
/// Dynamic site type.
/// </summary>
/// <typeparam name="T">The delegate type.</typeparam>
public class CallSite<T> : CallSite where T : class
{
/// <summary>
/// The update delegate. Called when the dynamic site experiences cache miss.
/// </summary>
/// <returns>The update delegate.</returns>
public T Update
{
get
{
// if this site is set up for match making, then use NoMatch as an Update
if (_match)
{
Debug.Assert(s_cachedNoMatch != null, "all normal sites should have Update cached once there is an instance.");
return s_cachedNoMatch;
}
else
{
Debug.Assert(s_cachedUpdate != null, "all normal sites should have Update cached once there is an instance.");
return s_cachedUpdate;
}
}
}
/// <summary>
/// The Level 0 cache - a delegate specialized based on the site history.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
public T Target;
/// <summary>
/// The Level 1 cache - a history of the dynamic site.
/// </summary>
internal T[] Rules;
// Cached update delegate for all sites with a given T
private static T s_cachedUpdate;
// Cached noMatch delegate for all sites with a given T
private static volatile T s_cachedNoMatch;
private CallSite(CallSiteBinder binder)
: base(binder)
{
Target = GetUpdateDelegate();
}
private CallSite()
: base(null)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
internal CallSite<T> CreateMatchMaker()
{
return new CallSite<T>();
}
/// <summary>
/// Creates an instance of the dynamic call site, initialized with the binder responsible for the
/// runtime binding of the dynamic operations at this call site.
/// </summary>
/// <param name="binder">The binder responsible for the runtime binding of the dynamic operations at this call site.</param>
/// <returns>The new instance of dynamic call site.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
public static CallSite<T> Create(CallSiteBinder binder)
{
if (!typeof(T).IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate();
ContractUtils.RequiresNotNull(binder, nameof(binder));
return new CallSite<T>(binder);
}
private T GetUpdateDelegate()
{
// This is intentionally non-static to speed up creation - in particular MakeUpdateDelegate
// as static generic methods are more expensive than instance methods. We call a ref helper
// so we only access the generic static field once.
return GetUpdateDelegate(ref s_cachedUpdate);
}
private T GetUpdateDelegate(ref T addr)
{
if (addr == null)
{
// reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes
// us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely
// create 2 delegates with no other harm caused.
addr = MakeUpdateDelegate();
}
return addr;
}
/// <summary>
/// Clears the rule cache ... used by the call site tests.
/// </summary>
private void ClearRuleCache()
{
// make sure it initialized/atomized etc...
Binder.GetRuleCache<T>();
Dictionary<Type, object> cache = Binder.Cache;
if (cache != null)
{
lock (cache)
{
cache.Clear();
}
}
}
private const int MaxRules = 10;
internal void AddRule(T newRule)
{
T[] rules = Rules;
if (rules == null)
{
Rules = new[] { newRule };
return;
}
T[] temp;
if (rules.Length < (MaxRules - 1))
{
temp = new T[rules.Length + 1];
Array.Copy(rules, 0, temp, 1, rules.Length);
}
else
{
temp = new T[MaxRules];
Array.Copy(rules, 0, temp, 1, MaxRules - 1);
}
temp[0] = newRule;
Rules = temp;
}
// moves rule +2 up.
internal void MoveRule(int i)
{
if (i > 1)
{
T[] rules = Rules;
T rule = rules[i];
rules[i] = rules[i - 1];
rules[i - 1] = rules[i - 2];
rules[i - 2] = rule;
}
}
internal T MakeUpdateDelegate()
{
#if !FEATURE_COMPILE
Type target = typeof(T);
MethodInfo invoke = target.GetInvokeMethod();
s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke);
return CreateCustomUpdateDelegate(invoke);
#else
Type target = typeof(T);
Type[] args;
MethodInfo invoke = target.GetInvokeMethod();
if (target.IsGenericType && IsSimpleSignature(invoke, out args))
{
MethodInfo method = null;
MethodInfo noMatchMethod = null;
if (invoke.ReturnType == typeof(void))
{
if (target == System.Linq.Expressions.Compiler.DelegateHelpers.GetActionType(args.AddFirst(typeof(CallSite))))
{
method = typeof(UpdateDelegates).GetMethod("UpdateAndExecuteVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatchVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
}
}
else
{
if (target == System.Linq.Expressions.Compiler.DelegateHelpers.GetFuncType(args.AddFirst(typeof(CallSite))))
{
method = typeof(UpdateDelegates).GetMethod("UpdateAndExecute" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatch" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
}
}
if (method != null)
{
s_cachedNoMatch = (T)(object)noMatchMethod.MakeGenericMethod(args).CreateDelegate(target);
return (T)(object)method.MakeGenericMethod(args).CreateDelegate(target);
}
}
s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke);
return CreateCustomUpdateDelegate(invoke);
#endif
}
#if FEATURE_COMPILE
private static bool IsSimpleSignature(MethodInfo invoke, out Type[] sig)
{
ParameterInfo[] pis = invoke.GetParametersCached();
ContractUtils.Requires(pis.Length > 0 && pis[0].ParameterType == typeof(CallSite), nameof(T));
Type[] args = new Type[invoke.ReturnType != typeof(void) ? pis.Length : pis.Length - 1];
bool supported = true;
for (int i = 1; i < pis.Length; i++)
{
ParameterInfo pi = pis[i];
if (pi.IsByRefParameter())
{
supported = false;
}
args[i - 1] = pi.ParameterType;
}
if (invoke.ReturnType != typeof(void))
{
args[args.Length - 1] = invoke.ReturnType;
}
sig = args;
return supported;
}
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private T CreateCustomUpdateDelegate(MethodInfo invoke)
{
Type returnType = invoke.GetReturnType();
bool isVoid = returnType == typeof(void);
var body = new ArrayBuilder<Expression>(13);
var vars = new ArrayBuilder<ParameterExpression>(8 + (isVoid ? 0 : 1));
ParameterExpression[] @params = Array.ConvertAll(invoke.GetParametersCached(), p => Expression.Parameter(p.ParameterType, p.Name));
LabelTarget @return = Expression.Label(returnType);
Type[] typeArgs = new[] { typeof(T) };
ParameterExpression site = @params[0];
ParameterExpression[] arguments = @params.RemoveFirst();
ParameterExpression @this = Expression.Variable(typeof(CallSite<T>), "this");
vars.UncheckedAdd(@this);
body.UncheckedAdd(Expression.Assign(@this, Expression.Convert(site, @this.Type)));
ParameterExpression applicable = Expression.Variable(typeof(T[]), "applicable");
vars.UncheckedAdd(applicable);
ParameterExpression rule = Expression.Variable(typeof(T), "rule");
vars.UncheckedAdd(rule);
ParameterExpression originalRule = Expression.Variable(typeof(T), "originalRule");
vars.UncheckedAdd(originalRule);
Expression target = Expression.Field(@this, nameof(Target));
body.UncheckedAdd(Expression.Assign(originalRule, target));
ParameterExpression result = null;
if (!isVoid)
{
vars.UncheckedAdd(result = Expression.Variable(@return.Type, "result"));
}
ParameterExpression count = Expression.Variable(typeof(int), "count");
vars.UncheckedAdd(count);
ParameterExpression index = Expression.Variable(typeof(int), "index");
vars.UncheckedAdd(index);
body.UncheckedAdd(
Expression.Assign(
site,
Expression.Call(
CallSiteOps_CreateMatchmaker.MakeGenericMethod(typeArgs),
@this
)
)
);
Expression processRule;
Expression getMatch = Expression.Call(CallSiteOps_GetMatch, site);
Expression resetMatch = Expression.Call(CallSiteOps_ClearMatch, site);
Expression invokeRule = Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params));
Expression onMatch = Expression.Call(
CallSiteOps_UpdateRules.MakeGenericMethod(typeArgs),
@this,
index
);
if (isVoid)
{
processRule = Expression.Block(
invokeRule,
Expression.IfThen(
getMatch,
Expression.Block(onMatch, Expression.Return(@return))
)
);
}
else
{
processRule = Expression.Block(
Expression.Assign(result, invokeRule),
Expression.IfThen(
getMatch,
Expression.Block(onMatch, Expression.Return(@return, result))
)
);
}
Expression getApplicableRuleAtIndex = Expression.Assign(rule, Expression.ArrayAccess(applicable, new TrueReadOnlyCollection<Expression>(index)));
Expression getRule = getApplicableRuleAtIndex;
LabelTarget @break = Expression.Label();
Expression breakIfDone = Expression.IfThen(
Expression.Equal(index, count),
Expression.Break(@break)
);
Expression incrementIndex = Expression.PreIncrementAssign(index);
body.UncheckedAdd(
Expression.IfThen(
Expression.NotEqual(
Expression.Assign(
applicable,
Expression.Call(
CallSiteOps_GetRules.MakeGenericMethod(typeArgs),
@this
)
),
Expression.Constant(null, applicable.Type)
),
Expression.Block(
Expression.Assign(count, Expression.ArrayLength(applicable)),
Expression.Assign(index, Utils.Constant(0)),
Expression.Loop(
Expression.Block(
breakIfDone,
getRule,
Expression.IfThen(
Expression.NotEqual(
Expression.Convert(rule, typeof(object)),
Expression.Convert(originalRule, typeof(object))
),
Expression.Block(
Expression.Assign(
target,
rule
),
processRule,
resetMatch
)
),
incrementIndex
),
@break,
@continue: null
)
)
)
);
////
//// Level 2 cache lookup
////
//
////
//// Any applicable rules in level 2 cache?
////
ParameterExpression cache = Expression.Variable(typeof(RuleCache<T>), "cache");
vars.UncheckedAdd(cache);
body.UncheckedAdd(
Expression.Assign(
cache,
Expression.Call(CallSiteOps_GetRuleCache.MakeGenericMethod(typeArgs), @this)
)
);
body.UncheckedAdd(
Expression.Assign(
applicable,
Expression.Call(CallSiteOps_GetCachedRules.MakeGenericMethod(typeArgs), cache)
)
);
// L2 invokeRule is different (no onMatch)
if (isVoid)
{
processRule = Expression.Block(
invokeRule,
Expression.IfThen(
getMatch,
Expression.Return(@return)
)
);
}
else
{
processRule = Expression.Block(
Expression.Assign(result, invokeRule),
Expression.IfThen(
getMatch,
Expression.Return(@return, result)
)
);
}
Expression tryRule = Expression.TryFinally(
processRule,
Expression.IfThen(
getMatch,
Expression.Block(
Expression.Call(CallSiteOps_AddRule.MakeGenericMethod(typeArgs), @this, rule),
Expression.Call(CallSiteOps_MoveRule.MakeGenericMethod(typeArgs), cache, rule, index)
)
)
);
getRule = Expression.Assign(
target,
getApplicableRuleAtIndex
);
body.UncheckedAdd(Expression.Assign(index, Utils.Constant(0)));
body.UncheckedAdd(Expression.Assign(count, Expression.ArrayLength(applicable)));
body.UncheckedAdd(
Expression.Loop(
Expression.Block(
breakIfDone,
getRule,
tryRule,
resetMatch,
incrementIndex
),
@break,
@continue: null
)
);
////
//// Miss on Level 0, 1 and 2 caches. Create new rule
////
body.UncheckedAdd(Expression.Assign(rule, Expression.Constant(null, rule.Type)));
ParameterExpression args = Expression.Variable(typeof(object[]), "args");
Expression[] argsElements = Array.ConvertAll(arguments, p => Convert(p, typeof(object)));
vars.UncheckedAdd(args);
body.UncheckedAdd(
Expression.Assign(
args,
Expression.NewArrayInit(typeof(object), new TrueReadOnlyCollection<Expression>(argsElements))
)
);
Expression setOldTarget = Expression.Assign(
target,
originalRule
);
getRule = Expression.Assign(
target,
Expression.Assign(
rule,
Expression.Call(
CallSiteOps_Bind.MakeGenericMethod(typeArgs),
Expression.Property(@this, nameof(Binder)),
@this,
args
)
)
);
tryRule = Expression.TryFinally(
processRule,
Expression.IfThen(
getMatch,
Expression.Call(
CallSiteOps_AddRule.MakeGenericMethod(typeArgs),
@this,
rule
)
)
);
body.UncheckedAdd(
Expression.Loop(
Expression.Block(setOldTarget, getRule, tryRule, resetMatch),
@break: null,
@continue: null
)
);
body.UncheckedAdd(Expression.Default(@return.Type));
Expression<T> lambda = Expression.Lambda<T>(
Expression.Label(
@return,
Expression.Block(
vars.ToReadOnly(),
body.ToReadOnly()
)
),
CallSiteTargetMethodName,
true, // always compile the rules with tail call optimization
new TrueReadOnlyCollection<ParameterExpression>(@params)
);
// Need to compile with forceDynamic because T could be invisible,
// or one of the argument types could be invisible
return lambda.Compile();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private T CreateCustomNoMatchDelegate(MethodInfo invoke)
{
ParameterExpression[] @params = Array.ConvertAll(invoke.GetParametersCached(), p => Expression.Parameter(p.ParameterType, p.Name));
return Expression.Lambda<T>(
Expression.Block(
Expression.Call(
typeof(CallSiteOps).GetMethod(nameof(CallSiteOps.SetNotMatched)),
@params[0]
),
Expression.Default(invoke.GetReturnType())
),
new TrueReadOnlyCollection<ParameterExpression>(@params)
).Compile();
}
private static Expression Convert(Expression arg, Type type)
{
if (TypeUtils.AreReferenceAssignable(type, arg.Type))
{
return arg;
}
return Expression.Convert(arg, type);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Xml.Xsl.Xslt
{
using QilName = System.Xml.Xsl.Qil.QilName;
// Compiler scope manager keeps track of
// Variable declarations
// Namespace declarations
// Extension and excluded namespaces
internal sealed class CompilerScopeManager<V>
{
public enum ScopeFlags
{
BackwardCompatibility = 0x1,
ForwardCompatibility = 0x2,
CanHaveApplyImports = 0x4,
NsDecl = 0x10, // NS declaration
NsExcl = 0x20, // NS Extencion (null for ExcludeAll)
Variable = 0x40,
CompatibilityFlags = BackwardCompatibility | ForwardCompatibility,
InheritedFlags = CompatibilityFlags | CanHaveApplyImports,
ExclusiveFlags = NsDecl | NsExcl | Variable
}
public struct ScopeRecord
{
public int scopeCount;
public ScopeFlags flags;
public string ncName; // local-name for variable, prefix for namespace, null for extension or excluded namespace
public string nsUri; // namespace uri
public V value; // value for variable, null for namespace
// Exactly one of these three properties is true for every given record
public bool IsVariable { get { return (flags & ScopeFlags.Variable) != 0; } }
public bool IsNamespace { get { return (flags & ScopeFlags.NsDecl) != 0; } }
// public bool IsExNamespace { get { return (flags & ScopeFlags.NsExcl ) != 0; } }
}
// Number of predefined records minus one
private const int LastPredefRecord = 0;
private ScopeRecord[] _records = new ScopeRecord[32];
private int _lastRecord = LastPredefRecord;
// This is cache of records[lastRecord].scopeCount field;
// most often we will have PushScope()/PopScope pare over the same record.
// It has sence to avoid adresing this field through array access.
private int _lastScopes = 0;
public CompilerScopeManager()
{
// The prefix 'xml' is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace
_records[0].flags = ScopeFlags.NsDecl;
_records[0].ncName = "xml";
_records[0].nsUri = XmlReservedNs.NsXml;
}
public CompilerScopeManager(KeywordsTable atoms)
{
_records[0].flags = ScopeFlags.NsDecl;
_records[0].ncName = atoms.Xml;
_records[0].nsUri = atoms.UriXml;
}
public void EnterScope()
{
_lastScopes++;
}
public void ExitScope()
{
if (0 < _lastScopes)
{
_lastScopes--;
}
else
{
while (_records[--_lastRecord].scopeCount == 0)
{
}
_lastScopes = _records[_lastRecord].scopeCount;
_lastScopes--;
}
}
[Conditional("DEBUG")]
public void CheckEmpty()
{
ExitScope();
Debug.Assert(_lastRecord == 0 && _lastScopes == 0, "PushScope() and PopScope() calls are unbalanced");
}
// returns true if ns decls was added to scope
public bool EnterScope(NsDecl nsDecl)
{
_lastScopes++;
bool hasNamespaces = false;
bool excludeAll = false;
for (; nsDecl != null; nsDecl = nsDecl.Prev)
{
if (nsDecl.NsUri == null)
{
Debug.Assert(nsDecl.Prefix == null, "NS may be null only when prefix is null where it is used for extension-element-prefixes='#all'");
excludeAll = true;
}
else if (nsDecl.Prefix == null)
{
AddExNamespace(nsDecl.NsUri);
}
else
{
hasNamespaces = true;
AddNsDeclaration(nsDecl.Prefix, nsDecl.NsUri);
}
}
if (excludeAll)
{
// #all should be on the top of the stack, becase all NSs on this element should be excluded as well
AddExNamespace(null);
}
return hasNamespaces;
}
private void AddRecord()
{
// Store cached fields:
_records[_lastRecord].scopeCount = _lastScopes;
// Extend record buffer:
if (++_lastRecord == _records.Length)
{
ScopeRecord[] newRecords = new ScopeRecord[_lastRecord * 2];
Array.Copy(_records, 0, newRecords, 0, _lastRecord);
_records = newRecords;
}
// reset scope count:
_lastScopes = 0;
}
private void AddRecord(ScopeFlags flag, string ncName, string uri, V value)
{
Debug.Assert(flag == (flag & ScopeFlags.ExclusiveFlags) && (flag & (flag - 1)) == 0 && flag != 0, "One exclusive flag");
Debug.Assert(uri != null || ncName == null, "null, null means exclude '#all'");
ScopeFlags flags = _records[_lastRecord].flags;
bool canReuseLastRecord = (_lastScopes == 0) && (flags & ScopeFlags.ExclusiveFlags) == 0;
if (!canReuseLastRecord)
{
AddRecord();
flags &= ScopeFlags.InheritedFlags;
}
_records[_lastRecord].flags = flags | flag;
_records[_lastRecord].ncName = ncName;
_records[_lastRecord].nsUri = uri;
_records[_lastRecord].value = value;
}
private void SetFlag(ScopeFlags flag, bool value)
{
Debug.Assert(flag == (flag & ScopeFlags.InheritedFlags) && (flag & (flag - 1)) == 0 && flag != 0, "one inherited flag");
ScopeFlags flags = _records[_lastRecord].flags;
if (((flags & flag) != 0) != value)
{
// lastScopes == records[lastRecord].scopeCount; // we know this because we are cashing it.
bool canReuseLastRecord = _lastScopes == 0; // last record is from last scope
if (!canReuseLastRecord)
{
AddRecord();
flags &= ScopeFlags.InheritedFlags;
}
if (flag == ScopeFlags.CanHaveApplyImports)
{
flags ^= flag;
}
else
{
flags &= ~ScopeFlags.CompatibilityFlags;
if (value)
{
flags |= flag;
}
}
_records[_lastRecord].flags = flags;
}
Debug.Assert((_records[_lastRecord].flags & ScopeFlags.CompatibilityFlags) != ScopeFlags.CompatibilityFlags,
"BackwardCompatibility and ForwardCompatibility flags are mutually exclusive"
);
}
// Add variable to the current scope. Returns false in case of duplicates.
public void AddVariable(QilName varName, V value)
{
Debug.Assert(varName.LocalName != null && varName.NamespaceUri != null);
AddRecord(ScopeFlags.Variable, varName.LocalName, varName.NamespaceUri, value);
}
// Since the prefix might be redefined in an inner scope, we search in descending order in [to, from]
// If interval is empty (from < to), the function returns null.
private string LookupNamespace(string prefix, int from, int to)
{
Debug.Assert(prefix != null);
for (int record = from; to <= record; --record)
{
string recPrefix, recNsUri;
ScopeFlags flags = GetName(ref _records[record], out recPrefix, out recNsUri);
if (
(flags & ScopeFlags.NsDecl) != 0 &&
recPrefix == prefix
)
{
return recNsUri;
}
}
return null;
}
public string LookupNamespace(string prefix)
{
return LookupNamespace(prefix, _lastRecord, 0);
}
private static ScopeFlags GetName(ref ScopeRecord re, out string prefix, out string nsUri)
{
prefix = re.ncName;
nsUri = re.nsUri;
return re.flags;
}
public void AddNsDeclaration(string prefix, string nsUri)
{
AddRecord(ScopeFlags.NsDecl, prefix, nsUri, default(V));
}
public void AddExNamespace(string nsUri)
{
AddRecord(ScopeFlags.NsExcl, null, nsUri, default(V));
}
public bool IsExNamespace(string nsUri)
{
Debug.Assert(nsUri != null);
int exAll = 0;
for (int record = _lastRecord; 0 <= record; record--)
{
string recPrefix, recNsUri;
ScopeFlags flags = GetName(ref _records[record], out recPrefix, out recNsUri);
if ((flags & ScopeFlags.NsExcl) != 0)
{
Debug.Assert(recPrefix == null);
if (recNsUri == nsUri)
{
return true; // This namespace is excluded
}
if (recNsUri == null)
{
exAll = record; // #all namespaces below are excluded
}
}
else if (
exAll != 0 &&
(flags & ScopeFlags.NsDecl) != 0 &&
recNsUri == nsUri
)
{
// We need to check that this namespace wasn't undefined before last "#all"
bool undefined = false;
for (int prev = record + 1; prev < exAll; prev++)
{
string prevPrefix, prevNsUri;
ScopeFlags prevFlags = GetName(ref _records[prev], out prevPrefix, out prevNsUri);
if (
(flags & ScopeFlags.NsDecl) != 0 &&
prevPrefix == recPrefix
)
{
// We don't care if records[prev].nsUri == records[record].nsUri.
// In this case the namespace was already undefined above.
undefined = true;
break;
}
}
if (!undefined)
{
return true;
}
}
}
return false;
}
private int SearchVariable(string localName, string uri)
{
Debug.Assert(localName != null);
for (int record = _lastRecord; 0 <= record; --record)
{
string recLocal, recNsUri;
ScopeFlags flags = GetName(ref _records[record], out recLocal, out recNsUri);
if (
(flags & ScopeFlags.Variable) != 0 &&
recLocal == localName &&
recNsUri == uri
)
{
return record;
}
}
return -1;
}
public V LookupVariable(string localName, string uri)
{
int record = SearchVariable(localName, uri);
return (record < 0) ? default(V) : _records[record].value;
}
public bool IsLocalVariable(string localName, string uri)
{
int record = SearchVariable(localName, uri);
while (0 <= --record)
{
if (_records[record].scopeCount != 0)
{
return true;
}
}
return false;
}
public bool ForwardCompatibility
{
get { return (_records[_lastRecord].flags & ScopeFlags.ForwardCompatibility) != 0; }
set { SetFlag(ScopeFlags.ForwardCompatibility, value); }
}
public bool BackwardCompatibility
{
get { return (_records[_lastRecord].flags & ScopeFlags.BackwardCompatibility) != 0; }
set { SetFlag(ScopeFlags.BackwardCompatibility, value); }
}
public bool CanHaveApplyImports
{
get { return (_records[_lastRecord].flags & ScopeFlags.CanHaveApplyImports) != 0; }
set { SetFlag(ScopeFlags.CanHaveApplyImports, value); }
}
internal System.Collections.Generic.IEnumerable<ScopeRecord> GetActiveRecords()
{
int currentRecord = _lastRecord + 1;
// This logic comes from NamespaceEnumerator.MoveNext but also returns variables
while (LastPredefRecord < --currentRecord)
{
if (_records[currentRecord].IsNamespace)
{
// This is a namespace declaration
if (LookupNamespace(_records[currentRecord].ncName, _lastRecord, currentRecord + 1) != null)
{
continue;
}
// Its prefix has not been redefined later in [currentRecord + 1, lastRecord]
}
yield return _records[currentRecord];
}
}
public NamespaceEnumerator GetEnumerator()
{
return new NamespaceEnumerator(this);
}
internal struct NamespaceEnumerator
{
private CompilerScopeManager<V> _scope;
private int _lastRecord;
private int _currentRecord;
public NamespaceEnumerator(CompilerScopeManager<V> scope)
{
_scope = scope;
_lastRecord = scope._lastRecord;
_currentRecord = _lastRecord + 1;
}
public bool MoveNext()
{
while (LastPredefRecord < --_currentRecord)
{
if (_scope._records[_currentRecord].IsNamespace)
{
// This is a namespace declaration
if (_scope.LookupNamespace(_scope._records[_currentRecord].ncName, _lastRecord, _currentRecord + 1) == null)
{
// Its prefix has not been redefined later in [currentRecord + 1, lastRecord]
return true;
}
}
}
return false;
}
public ScopeRecord Current
{
get
{
Debug.Assert(LastPredefRecord <= _currentRecord && _currentRecord <= _scope._lastRecord, "MoveNext() either was not called or returned false");
Debug.Assert(_scope._records[_currentRecord].IsNamespace);
return _scope._records[_currentRecord];
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.CoreApplicationPlugins
{
public class RegionModulesControllerPlugin : IRegionModulesController, IApplicationPlugin
{
protected List<IRegionModuleBase> IRegionModuleBaseModules = new List<IRegionModuleBase>();
// Config access
// Our name
private const string m_name = "RegionModulesControllerPlugin";
private ISimulationBase m_openSim;
// List of shared module instances, for adding to Scenes
private List<ISharedRegionModule> m_sharedInstances =
new List<ISharedRegionModule>();
#region IApplicationPlugin Members
public string Name
{
get { return m_name; }
}
#endregion
#region IRegionModulesController implementation
// The root of all evil.
// This is where we handle adding the modules to scenes when they
// load. This means that here we deal with replaceable interfaces,
// nonshared modules, etc.
//
protected Dictionary<IScene, Dictionary<string, IRegionModuleBase>> RegionModules =
new Dictionary<IScene, Dictionary<string, IRegionModuleBase>>();
public void AddRegionToModules(IScene scene)
{
Dictionary<Type, ISharedRegionModule> deferredSharedModules =
new Dictionary<Type, ISharedRegionModule>();
Dictionary<Type, INonSharedRegionModule> deferredNonSharedModules =
new Dictionary<Type, INonSharedRegionModule>();
// We need this to see if a module has already been loaded and
// has defined a replaceable interface. It's a generic call,
// so this can't be used directly. It will be used later
Type s = scene.GetType();
MethodInfo mi = s.GetMethod("RequestModuleInterface");
// This will hold the shared modules we actually load
List<ISharedRegionModule> sharedlist =
new List<ISharedRegionModule>();
// Iterate over the shared modules that have been loaded
// Add them to the new Scene
foreach (ISharedRegionModule module in m_sharedInstances)
{
try
{
// Here is where we check if a replaceable interface
// is defined. If it is, the module is checked against
// the interfaces already defined. If the interface is
// defined, we simply skip the module. Else, if the module
// defines a replaceable interface, we add it to the deferred
// list.
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
MainConsole.Instance.DebugFormat(
"[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name,
replaceableInterface);
continue;
}
deferredSharedModules[replaceableInterface] = module;
//MainConsole.Instance.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
continue;
}
//MainConsole.Instance.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1}",
// scene.RegionInfo.RegionName, module.Name);
try
{
module.AddRegion(scene);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
AddRegionModule(scene, module.Name, module);
IRegionModuleBaseModules.Add(module);
sharedlist.Add(module);
}
catch (Exception ex)
{
MainConsole.Instance.Warn("[RegionModulePlugin]: Failed to load plugin, " + ex);
}
}
// Scan for, and load, nonshared modules
List<INonSharedRegionModule> list = new List<INonSharedRegionModule>();
List<INonSharedRegionModule> m_nonSharedModules = AuroraModuleLoader.PickupModules<INonSharedRegionModule>();
foreach (INonSharedRegionModule module in m_nonSharedModules)
{
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
MainConsole.Instance.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}",
module.Name, replaceableInterface);
continue;
}
deferredNonSharedModules[replaceableInterface] = module;
MainConsole.Instance.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name);
continue;
}
if (module is ISharedRegionModule) //Don't load IShared!
{
continue;
}
//MainConsole.Instance.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1}",
// scene.RegionInfo.RegionName, module.Name);
// Initialise the module
module.Initialise(m_openSim.ConfigSource);
IRegionModuleBaseModules.Add(module);
list.Add(module);
}
// Now add the modules that we found to the scene. If a module
// wishes to override a replaceable interface, it needs to
// register it in Initialise, so that the deferred module
// won't load.
foreach (INonSharedRegionModule module in list)
{
try
{
module.AddRegion(scene);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
AddRegionModule(scene, module.Name, module);
}
// Now all modules without a replaceable base interface are loaded
// Replaceable modules have either been skipped, or omitted.
// Now scan the deferred modules here
foreach (ISharedRegionModule module in deferredSharedModules.Values)
{
// Determine if the interface has been replaced
Type replaceableInterface = module.ReplaceableInterface;
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
MainConsole.Instance.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}",
module.Name, replaceableInterface);
continue;
}
MainConsole.Instance.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1} (deferred)",
scene.RegionInfo.RegionName, module.Name);
// Not replaced, load the module
try
{
module.AddRegion(scene);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
AddRegionModule(scene, module.Name, module);
IRegionModuleBaseModules.Add(module);
sharedlist.Add(module);
}
// Same thing for nonshared modules, load them unless overridden
List<INonSharedRegionModule> deferredlist =
new List<INonSharedRegionModule>();
foreach (INonSharedRegionModule module in deferredNonSharedModules.Values)
{
// Check interface override
Type replaceableInterface = module.ReplaceableInterface;
if (replaceableInterface != null)
{
MethodInfo mii = mi.MakeGenericMethod(replaceableInterface);
if (mii.Invoke(scene, new object[0]) != null)
{
MainConsole.Instance.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}",
module.Name, replaceableInterface);
continue;
}
}
MainConsole.Instance.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1} (deferred)",
scene.RegionInfo.RegionName, module.Name);
try
{
module.Initialise(m_openSim.ConfigSource);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
IRegionModuleBaseModules.Add(module);
list.Add(module);
deferredlist.Add(module);
}
// Finally, load valid deferred modules
foreach (INonSharedRegionModule module in deferredlist)
{
try
{
module.AddRegion(scene);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
AddRegionModule(scene, module.Name, module);
}
// This is needed for all module types. Modules will register
// Interfaces with scene in AddScene, and will also need a means
// to access interfaces registered by other modules. Without
// this extra method, a module attempting to use another modules's
// interface would be successful only depending on load order,
// which can't be depended upon, or modules would need to resort
// to ugly kludges to attempt to request interfaces when needed
// and unneccessary caching logic repeated in all modules.
// The extra function stub is just that much cleaner
//
foreach (ISharedRegionModule module in sharedlist)
{
try
{
module.RegionLoaded(scene);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
}
foreach (INonSharedRegionModule module in list)
{
try
{
module.RegionLoaded(scene);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
}
}
public void RemoveRegionFromModules(IScene scene)
{
foreach (IRegionModuleBase module in RegionModules[scene].Values)
{
MainConsole.Instance.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}",
scene.RegionInfo.RegionName, module.Name);
module.RemoveRegion(scene);
if (module is INonSharedRegionModule)
{
// as we were the only user, this instance has to die
module.Close();
}
}
RegionModules[scene].Clear();
}
private void AddRegionModule(IScene scene, string p, IRegionModuleBase module)
{
if (!RegionModules.ContainsKey(scene))
RegionModules.Add(scene, new Dictionary<string, IRegionModuleBase>());
RegionModules[scene][p] = module;
}
#endregion
#region IRegionModulesController Members
public List<IRegionModuleBase> AllModules
{
get { return IRegionModuleBaseModules; }
}
#endregion
#region IApplicationPlugin implementation
public void PreStartup(ISimulationBase simBase)
{
}
public void Initialize(ISimulationBase openSim)
{
m_openSim = openSim;
IConfig handlerConfig = openSim.ConfigSource.Configs["ApplicationPlugins"];
if (handlerConfig.GetString("RegionModulesControllerPlugin", "") != Name)
return;
m_openSim.ApplicationRegistry.RegisterModuleInterface<IRegionModulesController>(this);
// Scan modules and load all that aren't disabled
m_sharedInstances = AuroraModuleLoader.PickupModules<ISharedRegionModule>();
foreach (ISharedRegionModule module in m_sharedInstances)
{
try
{
module.Initialise(m_openSim.ConfigSource);
}
catch(Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
}
}
public void ReloadConfiguration(IConfigSource config)
{
//Update all modules that we have here
foreach (IRegionModuleBase module in AllModules)
{
try
{
module.Initialise(config);
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
}
}
public void PostInitialise()
{
}
public void Start()
{
}
public void PostStart()
{
IConfig handlerConfig = m_openSim.ConfigSource.Configs["ApplicationPlugins"];
if (handlerConfig.GetString("RegionModulesControllerPlugin", "") != Name)
return;
//MainConsole.Instance.DebugFormat("[REGIONMODULES]: PostInitializing...");
// Immediately run PostInitialise on shared modules
foreach (ISharedRegionModule module in m_sharedInstances)
{
try
{
module.PostInitialise();
}
catch (Exception ex)
{
MainConsole.Instance.ErrorFormat("[RegionModulesControllerPlugin]: Failed to load module {0}: {1}", module.Name, ex.ToString());
}
}
}
public void Close()
{
}
#endregion
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* 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;
using System.Drawing;
namespace Reporting.Rdl
{
///<summary>
/// Line chart definition and processing.
///</summary>
[Serializable]
internal class ChartBubble: ChartBase
{
internal ChartBubble(Report r, Row row, Chart c, MatrixCellEntry[,] m, Expression showTooltips, Expression showTooltipsX,Expression _ToolTipYFormat, Expression _ToolTipXFormat)
: base(r, row, c, m,showTooltips,showTooltipsX,_ToolTipYFormat, _ToolTipXFormat)
{
}
override internal void Draw(Report rpt)
{
CreateSizedBitmap();
using (Graphics g1 = Graphics.FromImage(_bm))
{
_aStream = new System.IO.MemoryStream();
IntPtr HDC = g1.GetHdc();
_mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel);
g1.ReleaseHdc(HDC);
}
using(Graphics g = Graphics.FromImage(_mf))
{
// 06122007AJM Used to Force Higher Quality
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.PageUnit = GraphicsUnit.Pixel;
// Adjust the top margin to depend on the title height
Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title);
Layout.TopMargin = titleSize.Height;
// 20022008 AJM GJL - Added new required info
double ymax=0,ymin=0; // Get the max and min values for the y axis
GetValueMaxMin(rpt, ref ymax, ref ymin, 1,1);
double xmax = 0, xmin = 0; // Get the max and min values for the x axis
GetValueMaxMin(rpt, ref xmax, ref xmin, 0,1);
double bmax = 0, bmin = 0; // Get the max and min values for the bubble size
if (ChartDefn.Type == ChartTypeEnum.Bubble) // only applies to bubble (not scatter)
GetValueMaxMin(rpt, ref bmax, ref bmin, 2,1);
DrawChartStyle(rpt, g);
// Draw title; routine determines if necessary
DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, Layout.Width, Layout.TopMargin));
// Adjust the left margin to depend on the Value Axis
Size vaSize = ValueAxisSize(rpt, g, ymin, ymax);
Layout.LeftMargin = vaSize.Width;
// Draw legend
System.Drawing.Rectangle lRect = DrawLegend(rpt,g, false, true);
// Adjust the bottom margin to depend on the Category Axis
Size caSize = CategoryAxisSize(rpt, g, xmin, xmax);
Layout.BottomMargin = caSize.Height;
AdjustMargins(lRect,rpt,g); // Adjust margins based on legend.
// Draw Plot area
DrawPlotAreaStyle(rpt, g, lRect);
// Draw Value Axis
if (vaSize.Width > 0) // If we made room for the axis - we need to draw it
DrawValueAxis(rpt, g, ymin, ymax,
new System.Drawing.Rectangle(Layout.LeftMargin - vaSize.Width, Layout.TopMargin, vaSize.Width, Layout.PlotArea.Height), Layout.LeftMargin, _bm.Width - Layout.RightMargin);
// Draw Category Axis
if (caSize.Height > 0)
DrawCategoryAxis(rpt, g, xmin, xmax,
new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height - Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height),
Layout.TopMargin, _bm.Height - Layout.BottomMargin);
// Draw Plot area data
DrawPlot(rpt, g, xmin, xmax, ymin, ymax, bmin, bmax);
DrawLegend(rpt, g, false, false);
}
}
void DrawPlot(Report rpt, Graphics g, double xmin, double xmax, double ymin, double ymax, double bmin, double bmax)
{
// Draw Plot area data
int maxPointHeight = (int)Layout.PlotArea.Height;
int maxPointWidth = (int)Layout.PlotArea.Width;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
//handle either line scatter or line plot type GJL 020308
Point lastPoint = new Point();
Point[] Points = new Point[2];
bool isLine = GetPlotType(rpt, iCol, 1).ToUpper() == "LINE";
for (int iRow = 1; iRow <= CategoryCount; iRow++)
{
double xv = this.GetDataValue(rpt, iRow, iCol, 0);
double yv = this.GetDataValue(rpt, iRow, iCol, 1);
double bv = this.ChartDefn.Type == ChartTypeEnum.Bubble ?
this.GetDataValue(rpt, iRow, iCol, 2) : 0;
if (xv < xmin || yv < ymin || xv > xmax || yv > ymax)
continue;
int x = (int)(((Math.Min(xv, xmax) - xmin) / (xmax - xmin)) * maxPointWidth);
int y = (int)(((Math.Min(yv, ymax) - ymin) / (ymax - ymin)) * maxPointHeight);
if (y != int.MinValue && x != int.MinValue)
{
Point p = new Point(Layout.PlotArea.Left + x, Layout.PlotArea.Top + (maxPointHeight - y));
//GJL 010308 Line subtype scatter plot
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Line || (ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.SmoothLine || isLine)
{
if (!(lastPoint.IsEmpty))
{
Points[0] = lastPoint;
Points[1] = p;
String LineSize = getLineSize(rpt, iCol, 1);
int intLineSize = 2;
switch (LineSize)
{
case "Small": intLineSize = 1;
break;
case "Regular": intLineSize = 2;
break;
case "Large": intLineSize = 3;
break;
case "Extra Large": intLineSize = 4;
break;
case "Super Size": intLineSize = 5;
break;
}
DrawLineBetweenPoints(g, rpt, GetSeriesBrush(rpt, iRow, iCol), Points, intLineSize);
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips || _showToolTipsX)
{
string display = "";
if (_showToolTipsX) display = xv.ToString(_tooltipXFormat);
if (_showToolTips)
{
if (display.Length > 0) display += " , ";
display += yv.ToString(_tooltipYFormat);
}
String val = "ToolTip:" + display + "|X:" + (int)(p.X - 3) + "|Y:" + (int)(p.Y - 3) + "|W:" + 6 + "|H:" + 6;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
}
}
else
{
DrawBubble(rpt, g, GetSeriesBrush(rpt, iRow, iCol), p, iRow, iCol, bmin, bmax, bv,xv,yv);
}
lastPoint = p;
}
}
}
return;
}
/* This code was copied from the Line drawing class.
* 010308 GJL */
void DrawLineBetweenPoints(Graphics g, Report rpt, Brush brush, Point[] points)
{
DrawLineBetweenPoints(g, rpt, brush, points, 2);
}
void DrawLineBetweenPoints(Graphics g, Report rpt, Brush brush, Point[] points,int intLineSize)
{
if (points.Length <= 1) // Need at least 2 points
return;
Pen p = null;
try
{
if (brush.GetType() == typeof(System.Drawing.Drawing2D.HatchBrush))
{
System.Drawing.Drawing2D.HatchBrush tmpBrush = (System.Drawing.Drawing2D.HatchBrush)brush;
p = new Pen(new SolidBrush(tmpBrush.ForegroundColor), intLineSize); //1.5F); // todo - use line from style ????
}
else
{
p = new Pen(brush, intLineSize);
}
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Smooth && points.Length > 2)
g.DrawCurve(p, points, 0.5F);
else
g.DrawLines(p, points);
}
finally
{
if (p != null)
p.Dispose();
}
return;
}
void DrawBubble(Report rpt, Graphics g, Brush brush, Point p, int iRow, int iCol, double bmin, double bmax, double bv,double xv,double yv)
{
Pen pen=null;
int diameter = BubbleSize(rpt, iRow, iCol, bmin, bmax, bv); // set diameter of bubble
int radius= diameter /2;
try
{
if (this.ChartDefn.Type == ChartTypeEnum.Scatter &&
brush.GetType() == typeof(System.Drawing.Drawing2D.HatchBrush))
{
System.Drawing.Drawing2D.HatchBrush tmpBrush = (System.Drawing.Drawing2D.HatchBrush)brush;
SolidBrush br = new SolidBrush(tmpBrush.ForegroundColor);
pen = new Pen(new SolidBrush(tmpBrush.ForegroundColor));
DrawLegendMarker(g, br, pen, SeriesMarker[iCol - 1], p.X - radius, p.Y - radius, diameter);
DrawDataPoint(rpt, g, new Point(p.X - 3, p.Y + 3), iRow, iCol);
}
else
{
pen = new Pen(brush);
DrawLegendMarker(g, brush, pen, ChartMarkerEnum.Bubble, p.X - radius, p.Y - radius, diameter);
DrawDataPoint(rpt, g, new Point(p.X - 3, p.Y + 3), iRow, iCol);
}
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips || _showToolTipsX)
{
string display = "";
if (_showToolTipsX) display = xv.ToString(_tooltipXFormat);
if (_showToolTips)
{
if (display.Length > 0) display += " , ";
display += yv.ToString(_tooltipYFormat);
}
String val = "ToolTip:" + display + "|X:" + (int)(p.X - 3) + "|Y:" + (int)(p.Y - 3) + "|W:" + 6 + "|H:" + 6;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
}
finally
{
if (pen != null)
pen.Dispose();
}
return;
}
private int BubbleSize(Report rpt, int iRow, int iCol, double minB, double maxB, double bv)
{
int diameter = 5;
if (ChartDefn.Type != ChartTypeEnum.Bubble)
return diameter;
int bubbleMax = 30; // maximum bubble size
int bubbleMin = 4; // minimum bubble size
double diff = maxB - minB;
double vdiff = bv - minB;
if (Math.Abs(diff) < 1e-9d) // very small difference between max and min?
return diameter; // just use the smallest
diameter = (int) ((vdiff / diff) * (bubbleMax - bubbleMin) + bubbleMin);
return diameter;
}
// Calculate the size of the value axis; width is max value width + title width
// height is max value height
protected Size ValueAxisSize(Report rpt, Graphics g, double min, double max)
{
Size size = Size.Empty;
if (ChartDefn.ValueAxis == null)
return size;
Axis a = ChartDefn.ValueAxis.Axis;
if (a == null)
return size;
Size minSize;
Size maxSize;
if (!a.Visible)
{
minSize = maxSize = Size.Empty;
}
else if (a.Style != null)
{
minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
else
{
minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
// Choose the largest
size.Width = Math.Max(minSize.Width, maxSize.Width);
size.Height = Math.Max(minSize.Height, maxSize.Height);
// Now we need to add in the width of the title (if any)
Size titleSize = DrawTitleMeasure(rpt, g, a.Title);
size.Width += titleSize.Width;
return size;
}
protected void DrawValueAxis(Report rpt, Graphics g, double min, double max,
System.Drawing.Rectangle rect, int plotLeft, int plotRight)
{
if (this.ChartDefn.ValueAxis == null)
return;
Axis a = this.ChartDefn.ValueAxis.Axis;
if (a == null)
return;
Style s = a.Style;
int intervalCount;
double incr;
SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title, new System.Drawing.Rectangle(rect.Left, rect.Top, tSize.Width, rect.Height));
double v = min;
for (int i = 0; i < intervalCount + 1; i++)
{
int h = (int)(((Math.Min(v, max) - min) / (max - min)) * rect.Height);
if (h < 0) // this is really some form of error
{
v += incr;
continue;
}
if (!a.Visible)
{
// nothing to do
}
else if (s != null)
{
Size size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + tSize.Width, rect.Top + rect.Height - h - size.Height / 2, rect.Width - tSize.Width, size.Height);
s.DrawString(rpt, g, v, TypeCode.Double, null, vRect);
}
else
{
Size size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + tSize.Width, rect.Top + rect.Height - h - size.Height / 2, rect.Width - tSize.Width, size.Height);
Style.DrawStringDefaults(g, v, vRect);
}
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(plotLeft, rect.Top + rect.Height - h), new Point(plotRight, rect.Top + rect.Height - h));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(plotLeft, rect.Top + rect.Height - h));
v += incr;
}
// Draw the end points of the major grid lines
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(plotLeft, rect.Top), new Point(plotLeft, rect.Bottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(plotLeft, rect.Top));
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(plotRight, rect.Top), new Point(plotRight, rect.Bottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(plotRight, rect.Bottom));
return;
}
protected void DrawValueAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e)
{
if (gl == null || !gl.ShowGridLines)
return;
if (gl.Style != null)
gl.Style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
protected void DrawValueAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p)
{
if (tickType == AxisTickMarksEnum.None)
return;
int len = bMajor ? AxisTickMarkMajorLen : AxisTickMarkMinorLen;
Point s, e;
switch (tickType)
{
case AxisTickMarksEnum.Inside:
s = new Point(p.X, p.Y);
e = new Point(p.X + len, p.Y);
break;
case AxisTickMarksEnum.Cross:
s = new Point(p.X - len, p.Y);
e = new Point(p.X + len, p.Y);
break;
case AxisTickMarksEnum.Outside:
default:
s = new Point(p.X - len, p.Y);
e = new Point(p.X, p.Y);
break;
}
Style style = gl.Style;
if (style != null)
style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
/////////////////////////
protected void DrawCategoryAxis(Report rpt, Graphics g, double min, double max, System.Drawing.Rectangle rect, int plotTop, int plotBottom)
{
if (this.ChartDefn.CategoryAxis == null)
return;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return;
Style s = a.Style;
// Account for tick marks
int tickSize = 0;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
tickSize = this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
tickSize += this.AxisTickMarkMinorLen;
int intervalCount;
double incr;
SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count
int maxValueHeight = 0;
double v = min;
Size size = Size.Empty;
for (int i = 0; i < intervalCount + 1; i++)
{
int x = (int)(((Math.Min(v, max) - min) / (max - min)) * rect.Width);
if (!a.Visible)
{
// nothing to do
}
else if (s != null)
{
size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width / 2, rect.Top + tickSize, size.Width, size.Height);
s.DrawString(rpt, g, v, TypeCode.Double, null, vRect);
}
else
{
size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width / 2, rect.Top + tickSize, size.Width, size.Height);
Style.DrawStringDefaults(g, v, vRect);
}
if (size.Height > maxValueHeight) // Need to keep track of the maximum height
maxValueHeight = size.Height; // this is probably overkill since it should always be the same??
DrawCategoryAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left + x, plotTop), new Point(rect.Left + x, plotBottom));
DrawCategoryAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left + x, plotBottom));
v += incr;
}
// Draw the end points of the major grid lines
DrawCategoryAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left, plotTop), new Point(rect.Left, plotBottom));
DrawCategoryAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left, plotBottom));
DrawCategoryAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Right, plotTop), new Point(rect.Right, plotBottom));
DrawCategoryAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Right, plotBottom));
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title,
new System.Drawing.Rectangle(rect.Left, rect.Top + maxValueHeight + tickSize, rect.Width, tSize.Height));
return;
}
protected void DrawCategoryAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e)
{
if (gl == null || !gl.ShowGridLines)
return;
if (gl.Style != null)
gl.Style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
protected void DrawCategoryAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p)
{
if (tickType == AxisTickMarksEnum.None)
return;
int len = bMajor ? AxisTickMarkMajorLen : AxisTickMarkMinorLen;
Point s, e;
switch (tickType)
{
case AxisTickMarksEnum.Inside:
s = new Point(p.X, p.Y);
e = new Point(p.X, p.Y - len);
break;
case AxisTickMarksEnum.Cross:
s = new Point(p.X, p.Y - len);
e = new Point(p.X, p.Y + len);
break;
case AxisTickMarksEnum.Outside:
default:
s = new Point(p.X, p.Y + len);
e = new Point(p.X, p.Y);
break;
}
Style style = gl.Style;
if (style != null)
style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
// Calculate the size of the value axis; width is max value width + title width
// height is max value height
protected Size CategoryAxisSize(Report rpt, Graphics g, double min, double max)
{
Size size = Size.Empty;
if (ChartDefn.CategoryAxis == null)
return size;
Axis a = ChartDefn.CategoryAxis.Axis;//Not ValueAxis...
if (a == null)
return size;
Size minSize;
Size maxSize;
if (!a.Visible)
{
minSize = maxSize = Size.Empty;
}
else if (a.Style != null)
{
minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
else
{
minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
// Choose the largest
size.Width = Math.Max(minSize.Width, maxSize.Width);
size.Height = Math.Max(minSize.Height, maxSize.Height);
// Now we need to add in the height of the title (if any)
Size titleSize = DrawTitleMeasure(rpt, g, a.Title);
size.Height += titleSize.Height;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMinorLen;
return size;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using NetGore.IO;
namespace NetGore.Features.Shops
{
/// <summary>
/// Represents the unique ID of a shop.
/// </summary>
[Serializable]
[TypeConverter(typeof(ShopIDTypeConverter))]
public struct ShopID : IComparable<ShopID>, IConvertible, IFormattable, IComparable<int>, IEquatable<int>
{
/// <summary>
/// Represents the largest possible value of ShopID. This field is constant.
/// </summary>
public const int MaxValue = ushort.MaxValue;
/// <summary>
/// Represents the smallest possible value of ShopID. This field is constant.
/// </summary>
public const int MinValue = ushort.MinValue;
/// <summary>
/// The underlying value. This contains the actual value of the struct instance.
/// </summary>
readonly ushort _value;
/// <summary>
/// Initializes a new instance of the <see cref="ShopID"/> struct.
/// </summary>
/// <param name="value">Value to assign to the new ShopID.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception>
public ShopID(int value)
{
if (value < MinValue || value > MaxValue)
throw new ArgumentOutOfRangeException("value");
_value = (ushort)value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public bool Equals(ShopID other)
{
return other._value == _value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
return obj is ShopID && this == (ShopID)obj;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
return _value.GetHashCode();
}
/// <summary>
/// Gets the raw internal value of this ShopID.
/// </summary>
/// <returns>The raw internal value.</returns>
public ushort GetRawValue()
{
return _value;
}
/// <summary>
/// Reads an ShopID from an IValueReader.
/// </summary>
/// <param name="reader">IValueReader to read from.</param>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>The ShopID read from the IValueReader.</returns>
public static ShopID Read(IValueReader reader, string name)
{
var value = reader.ReadUShort(name);
return new ShopID(value);
}
/// <summary>
/// Reads an ShopID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="i">The index of the field to find.</param>
/// <returns>The ShopID read from the <see cref="IDataRecord"/>.</returns>
public static ShopID Read(IDataRecord reader, int i)
{
var value = reader.GetValue(i);
if (value is ushort)
return new ShopID((ushort)value);
var convertedValue = Convert.ToUInt16(value);
return new ShopID(convertedValue);
}
/// <summary>
/// Reads an ShopID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="name">The name of the field to find.</param>
/// <returns>The ShopID read from the <see cref="IDataRecord"/>.</returns>
public static ShopID Read(IDataRecord reader, string name)
{
return Read(reader, reader.GetOrdinal(name));
}
/// <summary>
/// Reads an ShopID from an IValueReader.
/// </summary>
/// <param name="bitStream">BitStream to read from.</param>
/// <returns>The ShopID read from the BitStream.</returns>
public static ShopID Read(BitStream bitStream)
{
var value = bitStream.ReadUShort();
return new ShopID(value);
}
/// <summary>
/// Converts the numeric value of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance, consisting of a sequence
/// of digits ranging from 0 to 9, without leading zeroes.</returns>
public override string ToString()
{
return _value.ToString();
}
/// <summary>
/// Writes the ShopID to an IValueWriter.
/// </summary>
/// <param name="writer">IValueWriter to write to.</param>
/// <param name="name">Unique name of the ShopID that will be used to distinguish it
/// from other values when reading.</param>
public void Write(IValueWriter writer, string name)
{
writer.Write(name, _value);
}
/// <summary>
/// Writes the ShopID to an IValueWriter.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
public void Write(BitStream bitStream)
{
bitStream.Write(_value);
}
#region IComparable<int> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(int other)
{
return _value.CompareTo(other);
}
#endregion
#region IComparable<ShopID> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(ShopID other)
{
return _value.CompareTo(other._value);
}
#endregion
#region IConvertible Members
/// <summary>
/// Returns the <see cref="T:System.TypeCode"/> for this instance.
/// </summary>
/// <returns>
/// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface.
/// </returns>
public TypeCode GetTypeCode()
{
return _value.GetTypeCode();
}
/// <summary>
/// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation
/// that supplies culture-specific formatting information.</param>
/// <returns>
/// A Boolean value equivalent to the value of this instance.
/// </returns>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return ((IConvertible)_value).ToBoolean(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit unsigned integer equivalent to the value of this instance.
/// </returns>
byte IConvertible.ToByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A Unicode character equivalent to the value of this instance.
/// </returns>
char IConvertible.ToChar(IFormatProvider provider)
{
return ((IConvertible)_value).ToChar(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance.
/// </returns>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return ((IConvertible)_value).ToDateTime(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance.
/// </returns>
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return ((IConvertible)_value).ToDecimal(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A double-precision floating-point number equivalent to the value of this instance.
/// </returns>
double IConvertible.ToDouble(IFormatProvider provider)
{
return ((IConvertible)_value).ToDouble(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit signed integer equivalent to the value of this instance.
/// </returns>
short IConvertible.ToInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit signed integer equivalent to the value of this instance.
/// </returns>
int IConvertible.ToInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit signed integer equivalent to the value of this instance.
/// </returns>
long IConvertible.ToInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt64(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit signed integer equivalent to the value of this instance.
/// </returns>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToSByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A single-precision floating-point number equivalent to the value of this instance.
/// </returns>
float IConvertible.ToSingle(IFormatProvider provider)
{
return ((IConvertible)_value).ToSingle(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.String"/> instance equivalent to the value of this instance.
/// </returns>
public string ToString(IFormatProvider provider)
{
return ((IConvertible)_value).ToString(provider);
}
/// <summary>
/// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information.
/// </summary>
/// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance.
/// </returns>
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ((IConvertible)_value).ToType(conversionType, provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit unsigned integer equivalent to the value of this instance.
/// </returns>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt64(provider);
}
#endregion
#region IEquatable<int> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(int other)
{
return _value.Equals(other);
}
#endregion
#region IFormattable Members
/// <summary>
/// Formats the value of the current instance using the specified format.
/// </summary>
/// <param name="format">The <see cref="T:System.String"/> specifying the format to use.
/// -or-
/// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value.
/// -or-
/// null to obtain the numeric format information from the current locale setting of the operating system.
/// </param>
/// <returns>
/// A <see cref="T:System.String"/> containing the value of the current instance in the specified format.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return _value.ToString(format, formatProvider);
}
#endregion
/// <summary>
/// Implements operator ++.
/// </summary>
/// <param name="l">The ShopID to increment.</param>
/// <returns>The incremented ShopID.</returns>
public static ShopID operator ++(ShopID l)
{
return new ShopID(l._value + 1);
}
/// <summary>
/// Implements operator --.
/// </summary>
/// <param name="l">The ShopID to decrement.</param>
/// <returns>The decremented ShopID.</returns>
public static ShopID operator --(ShopID l)
{
return new ShopID(l._value - 1);
}
/// <summary>
/// Implements operator +.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side plus the right side.</returns>
public static ShopID operator +(ShopID left, ShopID right)
{
return new ShopID(left._value + right._value);
}
/// <summary>
/// Implements operator -.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side minus the right side.</returns>
public static ShopID operator -(ShopID left, ShopID right)
{
return new ShopID(left._value - right._value);
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(ShopID left, int right)
{
return left._value == right;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(ShopID left, int right)
{
return left._value != right;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(int left, ShopID right)
{
return left == right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(int left, ShopID right)
{
return left != right._value;
}
/// <summary>
/// Casts a ShopID to an Int32.
/// </summary>
/// <param name="ShopID">ShopID to cast.</param>
/// <returns>The Int32.</returns>
public static explicit operator int(ShopID ShopID)
{
return ShopID._value;
}
/// <summary>
/// Casts an Int32 to a ShopID.
/// </summary>
/// <param name="value">Int32 to cast.</param>
/// <returns>The ShopID.</returns>
public static explicit operator ShopID(int value)
{
return new ShopID(value);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(int left, ShopID right)
{
return left > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>
/// If the right argument is greater than the left.
/// </returns>
public static bool operator <(int left, ShopID right)
{
return left < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(ShopID left, ShopID right)
{
return left._value > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(ShopID left, ShopID right)
{
return left._value < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(ShopID left, int right)
{
return left._value > right;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(ShopID left, int right)
{
return left._value < right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(int left, ShopID right)
{
return left >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(int left, ShopID right)
{
return left <= right._value;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>
/// If the left argument is greater than or equal to the right.
/// </returns>
public static bool operator >=(ShopID left, int right)
{
return left._value >= right;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>
/// If the right argument is greater than or equal to the left.
/// </returns>
public static bool operator <=(ShopID left, int right)
{
return left._value <= right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(ShopID left, ShopID right)
{
return left._value >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(ShopID left, ShopID right)
{
return left._value <= right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(ShopID left, ShopID right)
{
return left._value != right._value;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(ShopID left, ShopID right)
{
return left._value == right._value;
}
}
/// <summary>
/// Adds extensions to some data I/O objects for performing Read and Write operations for the ShopID.
/// All of the operations are implemented in the ShopID struct. These extensions are provided
/// purely for the convenience of accessing all the I/O operations from the same place.
/// </summary>
public static class ShopIDReadWriteExtensions
{
/// <summary>
/// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ShopID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as a ShopID.</returns>
public static ShopID AsShopID<T>(this IDictionary<T, string> dict, T key)
{
return Parser.Invariant.ParseShopID(dict[key]);
}
/// <summary>
/// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ShopID.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as an int, or the
/// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/>
/// or the value at the given <paramref name="key"/> could not be parsed.</returns>
public static ShopID AsShopID<T>(this IDictionary<T, string> dict, T key, ShopID defaultValue)
{
string value;
if (!dict.TryGetValue(key, out value))
return defaultValue;
ShopID parsed;
if (!Parser.Invariant.TryParse(value, out parsed))
return defaultValue;
return parsed;
}
/// <summary>
/// Reads the ShopID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the ShopID from.</param>
/// <param name="i">The field index to read.</param>
/// <returns>The ShopID read from the <see cref="IDataRecord"/>.</returns>
public static ShopID GetShopID(this IDataRecord r, int i)
{
return ShopID.Read(r, i);
}
/// <summary>
/// Reads the ShopID from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the ShopID from.</param>
/// <param name="name">The name of the field to read the value from.</param>
/// <returns>The ShopID read from the <see cref="IDataRecord"/>.</returns>
public static ShopID GetShopID(this IDataRecord r, string name)
{
return ShopID.Read(r, name);
}
/// <summary>
/// Parses the ShopID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <returns>The ShopID parsed from the string.</returns>
public static ShopID ParseShopID(this Parser parser, string value)
{
return new ShopID(parser.ParseUShort(value));
}
/// <summary>
/// Reads the ShopID from a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to read the ShopID from.</param>
/// <returns>The ShopID read from the BitStream.</returns>
public static ShopID ReadShopID(this BitStream bitStream)
{
return ShopID.Read(bitStream);
}
/// <summary>
/// Reads the ShopID from an IValueReader.
/// </summary>
/// <param name="valueReader">IValueReader to read the ShopID from.</param>
/// <param name="name">The unique name of the value to read.</param>
/// <returns>The ShopID read from the IValueReader.</returns>
public static ShopID ReadShopID(this IValueReader valueReader, string name)
{
return ShopID.Read(valueReader, name);
}
/// <summary>
/// Tries to parse the ShopID from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <param name="outValue">If this method returns true, contains the parsed ShopID.</param>
/// <returns>True if the parsing was successfully; otherwise false.</returns>
public static bool TryParse(this Parser parser, string value, out ShopID outValue)
{
ushort tmp;
var ret = parser.TryParse(value, out tmp);
outValue = new ShopID(tmp);
return ret;
}
/// <summary>
/// Writes a ShopID to a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
/// <param name="value">ShopID to write.</param>
public static void Write(this BitStream bitStream, ShopID value)
{
value.Write(bitStream);
}
/// <summary>
/// Writes a ShopID to a IValueWriter.
/// </summary>
/// <param name="valueWriter">IValueWriter to write to.</param>
/// <param name="name">Unique name of the ShopID that will be used to distinguish it
/// from other values when reading.</param>
/// <param name="value">ShopID to write.</param>
public static void Write(this IValueWriter valueWriter, string name, ShopID value)
{
value.Write(valueWriter, name);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using Nini.Config;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Server.Handlers.MapImage
{
public class MapRemoveServiceConnector : ServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IMapImageService m_MapService;
private IGridService m_GridService;
private string m_ConfigName = "MapImageService";
public MapRemoveServiceConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
string mapService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (mapService == String.Empty)
throw new Exception("No LocalServiceModule in config file");
Object[] args = new Object[] { config };
m_MapService = ServerUtils.LoadPlugin<IMapImageService>(mapService, args);
string gridService = serverConfig.GetString("GridService", String.Empty);
if (gridService != string.Empty)
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
if (m_GridService != null)
m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is ON");
else
m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is OFF");
bool proxy = serverConfig.GetBoolean("HasProxy", false);
server.AddStreamHandler(new MapServerRemoveHandler(m_MapService, m_GridService, proxy));
}
}
class MapServerRemoveHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IMapImageService m_MapService;
private IGridService m_GridService;
bool m_Proxy;
public MapServerRemoveHandler(IMapImageService service, IGridService grid, bool proxy) :
base("POST", "/removemap")
{
m_MapService = service;
m_GridService = grid;
m_Proxy = proxy;
}
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
// m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path);
string body;
using(StreamReader sr = new StreamReader(requestData))
body = sr.ReadToEnd();
body = body.Trim();
try
{
Dictionary<string, object> request = ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("X") || !request.ContainsKey("Y"))
{
httpResponse.StatusCode = (int)OSHttpStatusCode.ClientErrorBadRequest;
return FailureResult("Bad request.");
}
int x = 0, y = 0;
Int32.TryParse(request["X"].ToString(), out x);
Int32.TryParse(request["Y"].ToString(), out y);
// UUID scopeID = new UUID("07f8d88e-cd5e-4239-a0ed-843f75d09992");
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPE"))
UUID.TryParse(request["SCOPE"].ToString(), out scopeID);
m_log.DebugFormat("[MAP REMOVE SERVER CONNECTOR]: Received position data for region at {0}-{1}", x, y);
if (m_GridService != null)
{
System.Net.IPAddress ipAddr = GetCallerIP(httpRequest);
GridRegion r = m_GridService.GetRegionByPosition(UUID.Zero, (int)Util.RegionToWorldLoc((uint)x), (int)Util.RegionToWorldLoc((uint)y));
if (r != null)
{
if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString())
{
m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address);
return FailureResult("IP address of caller does not match IP address of registered region");
}
}
else
{
m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}",
ipAddr, x, y);
return FailureResult("Region not found at given coordinates");
}
}
string reason = string.Empty;
bool result = m_MapService.RemoveMapTile(x, y, scopeID, out reason);
if (result)
return SuccessResult();
else
return FailureResult(reason);
}
catch (Exception e)
{
m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace);
}
return FailureResult("Unexpected server error");
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult(string msg)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
XmlElement message = doc.CreateElement("", "Message", "");
message.AppendChild(doc.CreateTextNode(msg));
rootElement.AppendChild(message);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
using(MemoryStream ms = new MemoryStream())
{
using(XmlTextWriter xw = new XmlTextWriter(ms,null))
{
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
}
return ms.ToArray();
}
}
private System.Net.IPAddress GetCallerIP(IOSHttpRequest request)
{
// if (!m_Proxy)
// return request.RemoteIPEndPoint.Address;
// We're behind a proxy
string xff = "X-Forwarded-For";
string xffValue = request.Headers[xff.ToLower()];
if (xffValue == null || (xffValue != null && xffValue == string.Empty))
xffValue = request.Headers[xff];
if (xffValue == null || (xffValue != null && xffValue == string.Empty))
{
// m_log.WarnFormat("[MAP IMAGE HANDLER]: No XFF header");
return request.RemoteIPEndPoint.Address;
}
System.Net.IPEndPoint ep = Util.GetClientIPFromXFF(xffValue);
if (ep != null)
return ep.Address;
// Oops
return request.RemoteIPEndPoint.Address;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(MegaShapeLoft))]
public class MegaShapeLoftEditor : Editor
{
static public string[] layers;
bool hidewire = false;
bool showlimits = false;
static public Stack<Color> bcol = new Stack<Color>();
static public Stack<Color> ccol = new Stack<Color>();
static public Stack<Color> col = new Stack<Color>();
//static int layernum = 0;
//static float pathcrossalpha = 0.0f;
//static float pathstart = 0.0f;
//static float pathlength = 1.0f;
//static float pathdist = 0.1f;
//static float twist = 0.0f;
[MenuItem("GameObject/Create Other/MegaShape/Loft")]
static void CreateShapeLoft()
{
Vector3 pos = Vector3.zero;
if ( UnityEditor.SceneView.lastActiveSceneView != null )
pos = UnityEditor.SceneView.lastActiveSceneView.pivot;
GameObject go = new GameObject("Loft");
MeshFilter mf = go.AddComponent<MeshFilter>();
mf.sharedMesh = new Mesh();
go.AddComponent<MeshRenderer>();
go.AddComponent<MegaShapeLoft>();
go.transform.position = pos;
Selection.activeObject = go;
}
string[] GetLayers(MegaShapeLoft loft)
{
if ( loft.Layers == null )
{
string[] lyers1 = new string[1];
lyers1[0] = "None";
return lyers1;
}
string[] lyers = new string[loft.Layers.Length + 1];
lyers[0] = "None";
for ( int i = 0; i < loft.Layers.Length; i++ )
{
if ( loft.Layers[i] != null )
lyers[i + 1] = loft.Layers[i].LayerName;
else
lyers[i + 1] = "Deleted";
}
return lyers;
}
void CheckVal(ref float low, ref float high)
{
if ( low > high )
{
float t = low;
low = high;
high = t;
}
}
public override void OnInspectorGUI()
{
MegaShapeLoft loft = (MegaShapeLoft)target;
layers = GetLayers(loft);
EditorGUIUtility.LookLikeControls();
// Common params
//if ( GUILayout.Button("Build Loft") )
//{
// loft.rebuild = true;
//}
loft.rebuild = EditorGUILayout.Toggle("Rebuild", loft.rebuild);
loft.realtime = EditorGUILayout.Toggle("Realtime", loft.realtime);
loft.up = EditorGUILayout.Vector3Field("Up", loft.up);
loft.tangent = EditorGUILayout.FloatField("Tangent", loft.tangent * 100.0f) * 0.01f;
loft.Tangents = EditorGUILayout.Toggle("Tangents", loft.Tangents);
loft.Optimize = EditorGUILayout.Toggle("Optimize", loft.Optimize);
loft.DoBounds = EditorGUILayout.Toggle("Bounds", loft.DoBounds);
loft.DoCollider = EditorGUILayout.Toggle("Collider", loft.DoCollider);
loft.useColors = EditorGUILayout.Toggle("Use Colors", loft.useColors);
//loft.defaultColor = EditorGUILayout.ColorField("Color", loft.defaultColor);
//EditorGUILayout.EndToggleGroup();
loft.conformAmount = EditorGUILayout.Slider("Conform Amount", loft.conformAmount, 0.0f, 1.0f);
loft.undo = EditorGUILayout.Toggle("Undo", loft.undo);
bool hidewire1 = EditorGUILayout.Toggle("Hide Wire", hidewire);
if ( hidewire != hidewire1 )
{
hidewire = hidewire1;
EditorUtility.SetSelectedWireframeHidden(loft.GetComponent<Renderer>(), hidewire);
}
//loft.genLightMap = EditorGUILayout.BeginToggleGroup("Gen LightMap", loft.genLightMap);
//loft.angleError = EditorGUILayout.Slider("Angle Error",loft.angleError, 0.0f, 1.0f);
//loft.areaError = EditorGUILayout.Slider("Area Error",loft.areaError, 0.0f, 1.0f);
//loft.hardAngle = EditorGUILayout.FloatField("Hard Angle", loft.hardAngle);
//loft.packMargin = EditorGUILayout.FloatField("Pack Margin", loft.packMargin);
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Build LightMap") )
{
MegaLoftLightMapWindow.Init();
}
if ( GUILayout.Button("Copy") )
{
loft.Clone();
}
EditorGUILayout.EndHorizontal();
//EditorGUILayout.EndToggleGroup();
showlimits = EditorGUILayout.Foldout(showlimits, "Limits");
if ( showlimits )
{
EditorGUILayout.BeginVertical("Box");
loft.startLow = EditorGUILayout.FloatField("Start Low", loft.startLow);
loft.startHigh = EditorGUILayout.FloatField("Start High", loft.startHigh);
loft.lenLow = EditorGUILayout.FloatField("Len Low", loft.lenLow);
loft.lenHigh = EditorGUILayout.FloatField("Len High", loft.lenHigh);
loft.crossLow = EditorGUILayout.FloatField("Cross Start Low", loft.crossLow);
loft.crossHigh = EditorGUILayout.FloatField("Cross Start High", loft.crossHigh);
loft.crossLenLow = EditorGUILayout.FloatField("Cross Len Low", loft.crossLenLow);
loft.crossLenHigh = EditorGUILayout.FloatField("Cross Len High", loft.crossLenHigh);
loft.distlow = EditorGUILayout.FloatField("Dist Low", loft.distlow);
loft.disthigh = EditorGUILayout.FloatField("Dist High", loft.disthigh);
loft.cdistlow = EditorGUILayout.FloatField("CDist Low", loft.cdistlow);
loft.cdisthigh = EditorGUILayout.FloatField("CDist High", loft.cdisthigh);
EditorGUILayout.EndVertical();
CheckVal(ref loft.startLow, ref loft.startHigh);
CheckVal(ref loft.lenLow, ref loft.lenHigh);
CheckVal(ref loft.crossLow, ref loft.crossHigh);
CheckVal(ref loft.crossLenLow, ref loft.crossLenHigh);
if ( loft.lenLow < 0.001f )
loft.lenLow = 0.001f;
if ( loft.crossLenLow < 0.001f )
loft.crossLenLow = 0.001f;
}
EditorGUILayout.LabelField("Stats", "Verts: " + loft.vertcount.ToString() + " Tris: " + (loft.polycount / 3).ToString());
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Add Layer") )
{
MegaCreateLayerPopupEx.Init();
EditorUtility.SetDirty(loft);
}
EditorGUILayout.EndHorizontal();
if ( GUI.changed )
{
loft.rebuild = true;
EditorUtility.SetDirty(loft);
}
}
static public void PushCols()
{
bcol.Push(GUI.backgroundColor);
ccol.Push(GUI.contentColor);
col.Push(GUI.color);
}
static public void PopCols()
{
GUI.backgroundColor = bcol.Pop();
GUI.contentColor = ccol.Pop();
GUI.color = col.Pop();
}
#if false
[DrawGizmo(GizmoType.NotSelected | GizmoType.Pickable)]
static void RenderGizmo(MegaShapeLoft shape, GizmoType gizmoType)
{
if ( (gizmoType & GizmoType.NotSelected) != 0 )
{
if ( (gizmoType & GizmoType.Active) != 0 )
{
//DrawPath(shape);
}
}
}
static void DrawPath(MegaShapeLoft loft)
{
if ( loft.Layers == null )
return;
if ( layernum >= loft.Layers.Length )
layernum = loft.Layers.Length - 1;
if ( layernum >= 0 )
{
MegaLoftLayerBase blayer = loft.Layers[layernum];
if ( blayer.LayerEnabled && blayer.layerPath != null )
{
MegaSpline pathspline;
pathspline = blayer.layerPath.splines[0];
// Method to get layer length or path
float len = pathspline.length;
float dst = pathdist / len;
if ( dst < 0.002f )
dst = 0.002f;
float ca = pathcrossalpha;
Vector3 first = blayer.GetPos(loft, ca, pathstart);
Color col = Gizmos.color;
int i = 0;
for ( float alpha = pathstart + dst; alpha < pathlength; alpha += dst )
{
ca = pathcrossalpha + (twist * alpha);
Vector3 p = blayer.GetPos(loft, ca, alpha);
if ( (i & 1) == 0 )
Gizmos.color = Color.yellow;
else
Gizmos.color = Color.blue;
Gizmos.DrawLine(loft.transform.TransformPoint(first), loft.transform.TransformPoint(p));
first = p;
i++;
}
Gizmos.color = col;
}
}
}
#endif
}
| |
using EncompassRest.Loans.Enums;
namespace EncompassRest.Loans
{
/// <summary>
/// StateLicense
/// </summary>
[Entity(PropertiesToAlwaysSerialize = nameof(StateLicenseType))]
public sealed partial class StateLicense : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _aK;
private DirtyValue<string?>? _aL;
private DirtyValue<string?>? _aR;
private DirtyValue<string?>? _aZ;
private DirtyValue<string?>? _cA;
private DirtyValue<string?>? _cO;
private DirtyValue<string?>? _cT;
private DirtyValue<string?>? _dC;
private DirtyValue<string?>? _dE;
private DirtyValue<string?>? _fL;
private DirtyValue<string?>? _gA;
private DirtyValue<string?>? _gU;
private DirtyValue<string?>? _hI;
private DirtyValue<string?>? _iA;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _idaho;
private DirtyValue<string?>? _iL;
private DirtyValue<string?>? _iN;
private DirtyValue<string?>? _kS;
private DirtyValue<string?>? _kY;
private DirtyValue<string?>? _lA;
private DirtyValue<string?>? _mA;
private DirtyValue<string?>? _mD;
private DirtyValue<string?>? _mE;
private DirtyValue<string?>? _mI;
private DirtyValue<string?>? _mN;
private DirtyValue<string?>? _mO;
private DirtyValue<string?>? _mS;
private DirtyValue<string?>? _mT;
private DirtyValue<string?>? _nC;
private DirtyValue<string?>? _nD;
private DirtyValue<string?>? _nE;
private DirtyValue<string?>? _nH;
private DirtyValue<string?>? _nJ;
private DirtyValue<string?>? _nM;
private DirtyValue<string?>? _nV;
private DirtyValue<string?>? _nY;
private DirtyValue<string?>? _oH;
private DirtyValue<string?>? _oK;
private DirtyValue<string?>? _oR;
private DirtyValue<string?>? _pA;
private DirtyValue<string?>? _pR;
private DirtyValue<string?>? _rI;
private DirtyValue<string?>? _sC;
private DirtyValue<string?>? _sD;
private DirtyValue<StringEnumValue<StateLicenseType>>? _stateLicenseType;
private DirtyValue<string?>? _tN;
private DirtyValue<string?>? _tX;
private DirtyValue<string?>? _uT;
private DirtyValue<string?>? _vA;
private DirtyValue<string?>? _vI;
private DirtyValue<string?>? _vT;
private DirtyValue<string?>? _wA;
private DirtyValue<string?>? _wI;
private DirtyValue<string?>? _wV;
private DirtyValue<string?>? _wY;
/// <summary>
/// StateLicense AK [LIC.AK], [LO.ALLOWED.AK]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AK { get => _aK; set => SetField(ref _aK, value); }
/// <summary>
/// StateLicense AL [LIC.AL], [LO.ALLOWED.AL]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AL { get => _aL; set => SetField(ref _aL, value); }
/// <summary>
/// StateLicense AR [LIC.AR], [LO.ALLOWED.AR]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AR { get => _aR; set => SetField(ref _aR, value); }
/// <summary>
/// StateLicense AZ [LIC.AZ], [LO.ALLOWED.AZ]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AZ { get => _aZ; set => SetField(ref _aZ, value); }
/// <summary>
/// StateLicense CA [LIC.CA], [LO.ALLOWED.CA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? CA { get => _cA; set => SetField(ref _cA, value); }
/// <summary>
/// StateLicense CO [LIC.CO], [LO.ALLOWED.CO]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? CO { get => _cO; set => SetField(ref _cO, value); }
/// <summary>
/// StateLicense CT [LIC.CT], [LO.ALLOWED.CT]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? CT { get => _cT; set => SetField(ref _cT, value); }
/// <summary>
/// StateLicense DC [LIC.DC], [LO.ALLOWED.DC]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? DC { get => _dC; set => SetField(ref _dC, value); }
/// <summary>
/// StateLicense DE [LIC.DE], [LO.ALLOWED.DE]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? DE { get => _dE; set => SetField(ref _dE, value); }
/// <summary>
/// StateLicense FL [LIC.FL], [LO.ALLOWED.FL]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? FL { get => _fL; set => SetField(ref _fL, value); }
/// <summary>
/// StateLicense GA [LIC.GA], [LO.ALLOWED.GA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? GA { get => _gA; set => SetField(ref _gA, value); }
/// <summary>
/// StateLicense GU [LIC.GU], [LO.ALLOWED.GU]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? GU { get => _gU; set => SetField(ref _gU, value); }
/// <summary>
/// StateLicense HI [LIC.HI], [LO.ALLOWED.HI]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? HI { get => _hI; set => SetField(ref _hI, value); }
/// <summary>
/// StateLicense IA [LIC.IA], [LO.ALLOWED.IA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? IA { get => _iA; set => SetField(ref _iA, value); }
/// <summary>
/// StateLicense Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// StateLicense Idaho [LIC.ID], [LO.ALLOWED.ID]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? Idaho { get => _idaho; set => SetField(ref _idaho, value); }
/// <summary>
/// StateLicense IL [LIC.IL], [LO.ALLOWED.IL]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? IL { get => _iL; set => SetField(ref _iL, value); }
/// <summary>
/// StateLicense IN [LIC.IN], [LO.ALLOWED.IN]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? IN { get => _iN; set => SetField(ref _iN, value); }
/// <summary>
/// StateLicense KS [LIC.KS], [LO.ALLOWED.KS]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? KS { get => _kS; set => SetField(ref _kS, value); }
/// <summary>
/// StateLicense KY [LIC.KY], [LO.ALLOWED.KY]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? KY { get => _kY; set => SetField(ref _kY, value); }
/// <summary>
/// StateLicense LA [LIC.LA], [LO.ALLOWED.LA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LA { get => _lA; set => SetField(ref _lA, value); }
/// <summary>
/// StateLicense MA [LIC.MA], [LO.ALLOWED.MA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MA { get => _mA; set => SetField(ref _mA, value); }
/// <summary>
/// StateLicense MD [LIC.MD], [LO.ALLOWED.MD]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MD { get => _mD; set => SetField(ref _mD, value); }
/// <summary>
/// StateLicense ME [LIC.ME], [LO.ALLOWED.ME]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ME { get => _mE; set => SetField(ref _mE, value); }
/// <summary>
/// StateLicense MI [LIC.MI], [LO.ALLOWED.MI]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MI { get => _mI; set => SetField(ref _mI, value); }
/// <summary>
/// StateLicense MN [LIC.MN], [LO.ALLOWED.MN]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MN { get => _mN; set => SetField(ref _mN, value); }
/// <summary>
/// StateLicense MO [LIC.MO], [LO.ALLOWED.MO]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MO { get => _mO; set => SetField(ref _mO, value); }
/// <summary>
/// StateLicense MS [LIC.MS], [LO.ALLOWED.MS]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MS { get => _mS; set => SetField(ref _mS, value); }
/// <summary>
/// StateLicense MT [LIC.MT], [LO.ALLOWED.MT]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MT { get => _mT; set => SetField(ref _mT, value); }
/// <summary>
/// StateLicense NC [LIC.NC], [LO.ALLOWED.NC]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? NC { get => _nC; set => SetField(ref _nC, value); }
/// <summary>
/// StateLicense ND [LIC.ND], [LO.ALLOWED.ND]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ND { get => _nD; set => SetField(ref _nD, value); }
/// <summary>
/// StateLicense NE [LIC.NE], [LO.ALLOWED.NE]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? NE { get => _nE; set => SetField(ref _nE, value); }
/// <summary>
/// StateLicense NH [LIC.NH], [LO.ALLOWED.NH]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? NH { get => _nH; set => SetField(ref _nH, value); }
/// <summary>
/// StateLicense NJ [LIC.NJ], [LO.ALLOWED.NJ]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? NJ { get => _nJ; set => SetField(ref _nJ, value); }
/// <summary>
/// StateLicense NM [LIC.NM], [LO.ALLOWED.NM]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? NM { get => _nM; set => SetField(ref _nM, value); }
/// <summary>
/// StateLicense NV [LIC.NV], [LO.ALLOWED.NV]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? NV { get => _nV; set => SetField(ref _nV, value); }
/// <summary>
/// StateLicense NY [LIC.NY], [LO.ALLOWED.NY]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? NY { get => _nY; set => SetField(ref _nY, value); }
/// <summary>
/// StateLicense OH [LIC.OH], [LO.ALLOWED.OH]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? OH { get => _oH; set => SetField(ref _oH, value); }
/// <summary>
/// StateLicense OK [LIC.OK], [LO.ALLOWED.OK]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? OK { get => _oK; set => SetField(ref _oK, value); }
/// <summary>
/// StateLicense OR [LIC.OR], [LO.ALLOWED.OR]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? OR { get => _oR; set => SetField(ref _oR, value); }
/// <summary>
/// StateLicense PA [LIC.PA], [LO.ALLOWED.PA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? PA { get => _pA; set => SetField(ref _pA, value); }
/// <summary>
/// StateLicense PR [LIC.PR], [LO.ALLOWED.PR]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? PR { get => _pR; set => SetField(ref _pR, value); }
/// <summary>
/// StateLicense RI [LIC.RI], [LO.ALLOWED.RI]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? RI { get => _rI; set => SetField(ref _rI, value); }
/// <summary>
/// StateLicense SC [LIC.SC], [LO.ALLOWED.SC]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SC { get => _sC; set => SetField(ref _sC, value); }
/// <summary>
/// StateLicense SD [LIC.SD], [LO.ALLOWED.SD]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SD { get => _sD; set => SetField(ref _sD, value); }
/// <summary>
/// StateLicense StateLicenseType
/// </summary>
public StringEnumValue<StateLicenseType> StateLicenseType { get => _stateLicenseType; set => SetField(ref _stateLicenseType, value); }
/// <summary>
/// StateLicense TN [LIC.TN], [LO.ALLOWED.TN]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? TN { get => _tN; set => SetField(ref _tN, value); }
/// <summary>
/// StateLicense TX [LIC.TX], [LO.ALLOWED.TX]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? TX { get => _tX; set => SetField(ref _tX, value); }
/// <summary>
/// StateLicense UT [LIC.UT], [LO.ALLOWED.UT]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? UT { get => _uT; set => SetField(ref _uT, value); }
/// <summary>
/// StateLicense VA [LIC.VA], [LO.ALLOWED.VA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? VA { get => _vA; set => SetField(ref _vA, value); }
/// <summary>
/// StateLicense VI [LIC.VI], [LO.ALLOWED.VI]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? VI { get => _vI; set => SetField(ref _vI, value); }
/// <summary>
/// StateLicense VT [LIC.VT], [LO.ALLOWED.VT]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? VT { get => _vT; set => SetField(ref _vT, value); }
/// <summary>
/// StateLicense WA [LIC.WA], [LO.ALLOWED.WA]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? WA { get => _wA; set => SetField(ref _wA, value); }
/// <summary>
/// StateLicense WI [LIC.WI], [LO.ALLOWED.WI]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? WI { get => _wI; set => SetField(ref _wI, value); }
/// <summary>
/// StateLicense WV [LIC.WV], [LO.ALLOWED.WV]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? WV { get => _wV; set => SetField(ref _wV, value); }
/// <summary>
/// StateLicense WY [LIC.WY], [LO.ALLOWED.WY]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? WY { get => _wY; set => SetField(ref _wY, value); }
}
}
| |
#define IOS_ID
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
/// <summary>
/// The GA_Settings object contains an array of options which allows you to customize your use of GameAnalytics. Most importantly you will need to fill in your Game Key and Secret Key on the GA_Settings object to use the service.
/// </summary>
///
public class GA_Settings : ScriptableObject
{
#if UNITY_IPHONE && !UNITY_EDITOR && IOS_ID
[DllImport ("__Internal")]
private static extern string GetUserID ();
#endif
/// <summary>
/// Types of help given in the help box of the GA inspector
/// </summary>
public enum HelpTypes { None, FpsCriticalAndTrackTargetHelp, GuiAndTrackTargetHelp, IncludeSystemSpecsHelp, ProvideCustomUserID };
public enum MessageTypes { None, Error, Info, Warning };
/// <summary>
/// A message and message type for the help box displayed on the GUI inspector
/// </summary>
public struct HelpInfo
{
public string Message;
public MessageTypes MsgType;
public HelpTypes HelpType;
}
#region public static values
/// <summary>
/// The version of the GA Unity Wrapper plugin
/// </summary>
[HideInInspector]
public static string VERSION = "0.6.5";
#endregion
#region public values
public int TotalMessagesSubmitted;
public int TotalMessagesFailed;
public int DesignMessagesSubmitted;
public int DesignMessagesFailed;
public int QualityMessagesSubmitted;
public int QualityMessagesFailed;
public int ErrorMessagesSubmitted;
public int ErrorMessagesFailed;
public int BusinessMessagesSubmitted;
public int BusinessMessagesFailed;
public int UserMessagesSubmitted;
public int UserMessagesFailed;
public string CustomArea = string.Empty;
//Set the track target to use for predefined events, such as CriticalFPS (position of track target is sent with these events).
public Transform TrackTarget;
[SerializeField]
public string GameKey = "";
[SerializeField]
public string SecretKey = "";
[SerializeField]
public string ApiKey = "";
[SerializeField]
public string Build = "0.1";
public bool SignUpOpen = true;
public string FirstName = "";
public string LastName = "";
public string StudioName = "";
public string GameName = "";
public string PasswordConfirm = "";
public bool EmailOptIn = true;
public string EmailGA = "";
[System.NonSerialized]
public string PasswordGA = "";
[System.NonSerialized]
public string TokenGA = "";
[System.NonSerialized]
public string ExpireTime = "";
[System.NonSerialized]
public string LoginStatus = "Not logged in.";
[System.NonSerialized]
public int SelectedStudio = 0;
[System.NonSerialized]
public int SelectedGame = 0;
[System.NonSerialized]
public bool JustSignedUp = false;
[System.NonSerialized]
public bool HideSignupWarning = false;
public bool IntroScreen = true;
[System.NonSerialized]
public List<Studio> Studios;
public bool DebugMode = true;
public bool DebugAddEvent = false;
public bool SendExampleGameDataToMyGame = false;
public bool RunInEditorPlayMode = true;
public bool UseBundleVersion = false;
public bool AllowRoaming = true;
public bool ArchiveData = true;
public bool NewSessionOnResume = true;
public bool AutoSubmitUserInfo = true;
public bool DelayQuitToSendData = true;
public Vector3 HeatmapGridSize = Vector3.one;
//bytes
public long ArchiveMaxFileSize = 2000;
public bool CustomUserID;
public float SubmitInterval = 10;
public bool InternetConnectivity;
//ad support
public bool Start_AlwaysShowAds = true;
public bool Start_TimePlayed = false;
public bool Start_Sessions = false;
public int TimePlayed = 300;
public int Sessions = 1;
public bool Trigger_AdsEnabled = false;
public GA_AdSupport.GAAdNetwork Trigger_AdsEnabled_network = GA_AdSupport.GAAdNetwork.Any;
public bool Trigger_SceneChange = true;
public GA_AdSupport.GAAdNetwork Trigger_SceneChange_network = GA_AdSupport.GAAdNetwork.Any;
public bool IAD_foldout = true;
public static bool IAD_DEFAULT = true;
public static bool CB_DEFAULT = false;
public bool IAD_enabled = IAD_DEFAULT;
public bool CB_enabled = CB_DEFAULT;
#if UNITY_IPHONE || UNITY_EDITOR
public ADBannerView.Type IAD_type = ADBannerView.Type.Banner;
public ADBannerView.Layout IAD_layout = ADBannerView.Layout.Top;
#endif
public Vector2 IAD_position = Vector2.zero;
public float IAD_Duration = 10;
public bool CB_foldout = true;
public string CB_appID;
public string CB_appSig;
//These values are used for the GA_Inspector only
public enum InspectorStates { Account, Basic, Debugging, Pref, Ads }
public InspectorStates CurrentInspectorState;
public List<HelpTypes> ClosedHints = new List<HelpTypes>();
public bool DisplayHints;
public Vector2 DisplayHintsScrollState;
public Texture2D Logo;
public Texture2D UpdateIcon;
[System.NonSerialized]
public GUIStyle SignupButton;
[SerializeField]
public List<GA_CustomAdTrigger> CustomAdTriggers = new List<GA_CustomAdTrigger>();
#endregion
#region public methods
/// <summary>
/// Help/hints/tips messages used for the GA inspector hints box. This function decides which hint to display.
/// Garbos: Depricated because: Was duplicated to return list of messages instead. Use GetHelpMessageList
/// </summary>
/// <returns>
/// The help message.
/// </returns>
public List<HelpInfo> GetHelpMessageList()
{
List<HelpInfo> result = new List<HelpInfo>();
if (GameKey.Equals("") || SecretKey.Equals(""))
{
result.Add( new HelpInfo() { Message = "Please fill in your Game Key and Secret Key, obtained from the GameAnalytics website where you created your game.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None });
}
if (Build.Equals(""))
{
result.Add( new HelpInfo() { Message = "Please fill in a name for your build, representing the current version of the game. Updating the build name for each version of the game will allow you to filter by build when viewing your data on the GA website.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None });
}
if (CustomUserID && !ClosedHints.Contains(HelpTypes.ProvideCustomUserID))
{
result.Add( new HelpInfo() { Message = "You have indicated that you will provide a custom user ID - no data will be submitted until it is provided. This should be defined from code through: GA.Settings.SetCustomUserID", MsgType = MessageTypes.Info, HelpType = HelpTypes.ProvideCustomUserID });
}
return result;
}
/// <summary>
/// Help/hints/tips messages used for the GA inspector hints box. This function decides which hint to display.
/// Garbos: Depricated because: Was duplicated to return list of messages instead. Use GetHelpMessageList
/// </summary>
/// <returns>
/// The help message.
/// </returns>
public HelpInfo GetHelpMessage()
{
if (GameKey.Equals("") || SecretKey.Equals(""))
{
return new HelpInfo() { Message = "Please fill in your Game Key and Secret Key, obtained from the GameAnalytics website where you created your game.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None };
}
else if (Build.Equals(""))
{
return new HelpInfo() { Message = "Please fill in a name for your build, representing the current version of the game. Updating the build name for each version of the game will allow you to filter by build when viewing your data on the GA website.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None };
}
else if (CustomUserID && !ClosedHints.Contains(HelpTypes.ProvideCustomUserID))
{
return new HelpInfo() { Message = "You have indicated that you will provide a custom user ID - no data will be submitted until it is provided. This should be defined from code through: GA.Settings.SetCustomUserID", MsgType = MessageTypes.Info, HelpType = HelpTypes.ProvideCustomUserID };
}
return new HelpInfo() { Message = "No hints to display. The \"Reset Hints\" button resets closed hints.", MsgType = MessageTypes.None, HelpType = HelpTypes.None };
}
/// <summary>
/// Checks the internet connectivity, and sets INTERNETCONNECTIVITY
/// </summary>
public IEnumerator CheckInternetConnectivity(bool startQueue)
{
// Application.internetReachability returns the type of Internet reachability currently possible on the device, but does not check if the there is an actual route to the network. So we can check this instantly.
if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork && !GA.SettingsGA.AllowRoaming)
{
InternetConnectivity = false;
}
else
{
//Try to ping the server
WWW www = new WWW(GA_Submit.GetBaseURL(true) + "/ping");
//Wait for response
yield return www;
try
{
if (GA_Submit.CheckServerReply(www))
{
InternetConnectivity = true;
}
else if (!string.IsNullOrEmpty(www.error))
{
InternetConnectivity = false;
}
else
{
//Get the JSON object from the response
Hashtable returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
//If the response contains the key "status" with the value "ok" we know that we are connected
if (returnParam != null && returnParam.ContainsKey("status") && returnParam["status"].ToString().Equals("ok"))
{
InternetConnectivity = true;
}
else
{
InternetConnectivity = false;
}
}
}
catch
{
InternetConnectivity = false;
}
}
if (startQueue)
{
if (InternetConnectivity)
GA.Log("GA has confirmed connection to the server..");
else
GA.Log("GA has no connection to the server..");
//Try to add additional IDs
if (AddUniqueIDs())
{
#if UNITY_EDITOR
//Start the submit queue for sending messages to the server
GA.RunCoroutine(GA_Queue.SubmitQueue());
GA.Log("GameAnalytics: Submission queue started.");
//GameObject gaTracking = new GameObject("GA_Tracking");
//gaTracking.AddComponent<GA_Tracking>();
#else
while (GA.SettingsGA.CustomUserID && GA.API.GenericInfo.UserID == string.Empty)
{
yield return new WaitForSeconds(5f);
}
GA_Queue.ForceSubmit();
GameObject fbGameObject = new GameObject("GA_FacebookSDK");
fbGameObject.AddComponent<GA_FacebookSDK>();
#endif
}
else
{
GA.LogWarning("GA failed to add unique IDs and will not send any data. If you are using iOS or Android please see the readme file in the iOS/Android folder in the GameAnalytics/Plugins directory.");
}
}
}
private bool AddUniqueIDs()
{
bool returnValue = false;
#if !UNITY_EDITOR && UNITY_WEBPLAYER
if (Application.absoluteURL.StartsWith("http"))
{
Application.ExternalEval(
"try{var __scr = document.createElement('script'); __scr.setAttribute('async', 'true'); __scr.type = 'text/javascript'; __scr.src = 'https://d17ay18sztndlo.cloudfront.net/resources/js/ga_sdk_tracking.js'; ((document.getElementsByTagName('head') || [null])[0] || document.getElementsByTagName('script')[0].parentNode).appendChild(__scr);}catch(e){}"
);
}
#endif
#if !UNITY_EDITOR && UNITY_STANDALONE_WIN
string device = "PC";
#elif !UNITY_EDITOR
string device = SystemInfo.deviceModel;
#endif
#if !UNITY_EDITOR
string os = "";
string[] osSplit = SystemInfo.operatingSystem.Split(' ');
#if UNITY_IPHONE
if (osSplit.Length > 0)
os = "iOS " + osSplit[2].Substring(0, 1);
#elif UNITY_ANDROID
if (osSplit.Length > 0)
{
string[] osvSplit = osSplit[2].Split('.');
os = osSplit[0] + " " + osvSplit[0] + "." + osvSplit[1];
}
#else
if (osSplit.Length > 0)
os = osSplit[0];
#endif
#endif
#if UNITY_IPHONE && !UNITY_EDITOR && IOS_ID
string os_minor = "";
string[] osmSplit = SystemInfo.operatingSystem.Split(' ');
if (osmSplit.Length > 0)
os_minor = "iOS " + osmSplit[2];
try
{
string iOSid = GetUniqueIDiOS();
if (iOSid != null && iOSid != string.Empty)
{
if (iOSid.StartsWith("VENDOR-"))
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, null, AutoSubmitUserInfo?GA_GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?os_minor:null, "GA Unity SDK " + VERSION, null);
else
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, iOSid, null, AutoSubmitUserInfo?GA_GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?os_minor:null, "GA Unity SDK " + VERSION, null);
returnValue = true;
}
}
catch
{ }
#elif UNITY_ANDROID && !UNITY_EDITOR
string os_minor = "";
string[] osmSplit = SystemInfo.operatingSystem.Split(' ');
if (osmSplit.Length > 0)
os_minor = osmSplit[0] + " " + osmSplit[2];
try
{
string androidAdID = GetAdvertisingIDAndroid();
if (androidAdID != null && androidAdID != string.Empty)
{
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, null, AutoSubmitUserInfo?GA_GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?os_minor:null, "GA Unity SDK " + VERSION, androidAdID);
returnValue = true;
}
}
catch
{ }
#elif UNITY_FLASH && !UNITY_EDITOR
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, null, AutoSubmitUserInfo?GA_GenericInfo.GetSystem():null, "Flash", AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?SystemInfo.operatingSystem:null, "GA Unity SDK " + VERSION, null);
returnValue = true;
#elif !UNITY_EDITOR && !UNITY_IPHONE && !UNITY_ANDROID
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, null, AutoSubmitUserInfo?GA_GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?SystemInfo.operatingSystem:null, "GA Unity SDK " + VERSION, null);
returnValue = true;
#elif UNITY_IPHONE && UNITY_EDITOR && !IOS_ID
GetUniqueIDiOS ();
returnValue = true;
#elif UNITY_EDITOR
returnValue = true;
#endif
return returnValue;
}
public string GetUniqueIDiOS ()
{
string uid = "";
#if UNITY_IPHONE && !UNITY_EDITOR && IOS_ID
uid = GetUserID();
#endif
#if UNITY_IPHONE && UNITY_EDITOR && !IOS_ID
GA.LogWarning("GA Warning: Remember to read the iOS_Readme in the GameAnalytics > Plugins > iOS folder, for information on how to setup advertiser ID for iOS. GA will not work on iOS if you do not follow these steps.");
#endif
return uid;
}
public string GetAdvertisingIDAndroid ()
{
string uid = null;
#if UNITY_ANDROID && !UNITY_EDITOR
try
{
AndroidJavaClass up = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = up.GetStatic<AndroidJavaObject> ("currentActivity");
AndroidJavaClass client = new AndroidJavaClass ("com.google.android.gms.ads.identifier.AdvertisingIdClient");
AndroidJavaObject adInfo = client.CallStatic<AndroidJavaObject> ("getAdvertisingIdInfo",currentActivity);
if (!adInfo.Call<bool> ("isLimitAdTrackingEnabled"))
{
uid = adInfo.Call<string> ("getId").ToString();
}
}
catch
{ }
#endif
return uid;
}
/// <summary>
/// Sets a custom user ID.
/// Make sure each user has a unique user ID. This is useful if you have your own log-in system with unique user IDs.
/// NOTE: Only use this method if you have enabled "Custom User ID" on the GA inspector!
/// </summary>
/// <param name="customID">
/// The custom user ID - this should be unique for each user
/// </param>
public void SetCustomUserID(string customID)
{
if (customID != string.Empty)
{
GA.API.GenericInfo.SetCustomUserID(customID);
}
}
/// <summary>
/// Sets a custom area string. An area is often just a level, but you can set it to whatever makes sense for your game. F.x. in a big open world game you will probably need custom areas to identify regions etc.
/// By default, if no custom area is set, the Application.loadedLevelName string is used.
/// </summary>
/// <param name="customID">
/// The custom area.
/// </param>
public void SetCustomArea(string customArea)
{
CustomArea = customArea;
}
public void SetKeys (string gamekey, string secretkey)
{
GA.API.Submit.SetupKeys(gamekey, secretkey);
GameKey = gamekey;
SecretKey = secretkey;
}
#endregion
}
//[System.Serializable]
public class Studio
{
public string Name { get; private set; }
//[SerializeField]
public List<string> Games { get; private set; }
//[SerializeField]
public List<string> Tokens { get; private set; }
//[SerializeField]
public List<int> GameIDs { get; private set; }
public Studio (string name, List<string> games, List<string> tokens, List<int> ids)
{
Name = name;
Games = games;
Tokens = tokens;
GameIDs = ids;
}
public static string[] GetStudioNames (List<Studio> studios)
{
if (studios == null)
{
return new string[] { "-" };
}
string[] names = new string[studios.Count + 1];
names[0] = "-";
string spaceAdd = "";
for (int i = 0; i < studios.Count; i++)
{
names[i+1] = studios[i].Name + spaceAdd;
spaceAdd += " ";
}
return names;
}
public static string[] GetGameNames (int index, List<Studio> studios)
{
if (studios == null || studios[index].Games == null)
{
return new string[] { "-" };
}
string[] names = new string[studios[index].Games.Count + 1];
names[0] = "-";
string spaceAdd = "";
for (int i = 0; i < studios[index].Games.Count; i++)
{
names[i+1] = studios[index].Games[i] + spaceAdd;
spaceAdd += " ";
}
return names;
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace Foundation.Services.Security
{
/// <summary>
/// Salts and Hashes
/// </summary>
public class SaltedHasher : Hasher
{
/// <summary>
/// Default salt length
/// </summary>
protected const int DefaultSaltLength = 8;
/// <summary>
/// Default constructor, which defaults to using the MD5 algorithm with a prefixed salt of 8 characters
/// </summary>
public SaltedHasher() : this(HashProvider.MD5, DefaultSaltLength, SaltPosition.Prefix, new PasswordGenerator()) {}
/// <summary>
/// Creates a SaltedHasher, configuring it to use the specified hashing provider and using a default prefixed salt of 8 characters
/// </summary>
/// <param name="provider">Hash algorithm to use by default</param>
public SaltedHasher(HashProvider provider) : this(provider, DefaultSaltLength, SaltPosition.Prefix, new PasswordGenerator()) {}
/// <summary>
/// Creates a SaltedHasher, configuring it to use the specified hashing provider and salt length, prefixing the salt by default
/// </summary>
/// <param name="provider">Hash algorithm to use by default</param>
/// <param name="saltLength">Length for the salt</param>
public SaltedHasher(HashProvider provider, int saltLength) : this(provider, saltLength, SaltPosition.Prefix, new PasswordGenerator()) {}
/// <summary>
/// Creates a SaltedHasher, configuring it to use the specified hashing provider, salt position and salt length
/// </summary>
/// <param name="provider">Hash algorithm to use by default</param>
/// <param name="saltLength">Length for the salt</param>
/// <param name="saltPosition">Position for the salt</param>
public SaltedHasher(HashProvider provider, int saltLength, SaltPosition saltPosition) : this(provider, saltLength, saltPosition, new PasswordGenerator()) {}
/// <summary>
/// Creates a SaltedHasher, configuring it to use the specified hashing provider, salt position and salt length, and password generator
/// </summary>
/// <param name="provider">Hash algorithm to use by default</param>
/// <param name="saltLength">Length for the salt</param>
/// <param name="saltPosition">Position for the salt</param>
/// <param name="passwordGenerator">Password generator for generating the salts</param>
SaltedHasher(HashProvider provider, int saltLength, SaltPosition saltPosition, PasswordGenerator passwordGenerator)
{
Provider = provider;
SaltPosition = saltPosition;
SaltLength = saltLength;
PasswordGenerator = passwordGenerator;
}
#region Salt Methods
/// <summary>
/// Generates a random salt value
/// </summary>
/// <returns></returns>
public string GenerateSalt()
{
return PasswordGenerator.Generate(SaltLength);
}
/// <summary>
/// Finds a salt value from the passed hash, using the salt config
/// </summary>
/// <param name="hash">Hash to find salt value of</param>
/// <returns></returns>
public string FindSalt(string hash)
{
var salt = FindSalt(Convert.FromBase64String(hash));
return Encoding.UTF8.GetString(salt);
}
/// <summary>
/// Finds a salt value from the passed hash, using the salt config
/// </summary>
/// <param name="hash">Hash to find salt value of</param>
/// <returns></returns>
public byte[] FindSalt(byte[] hash)
{
if (hash == null) throw new ArgumentNullException("hash");
// To hold the salt data once we find it
var salt = new byte[SaltLength];
switch( SaltPosition )
{
// Salt at the start of the hash
case SaltPosition.Prefix:
Array.Copy(hash, salt, SaltLength);
break;
// Salt at the end of the hash
case SaltPosition.Suffix:
Array.Copy(hash, hash.Length - salt.Length, salt, 0, salt.Length);
break;
default:
throw new FoundationException("Unknown salt position '{0}'!", SaltPosition);
}
return salt;
}
#endregion
#region Hash Methods
/// <summary>
/// Hashes an array of bytes using a random salt
/// </summary>
/// <param name="data">Bytes to hash</param>
/// <returns>Computed hash</returns>
public override byte[] HashBytes(byte[] data)
{
return HashBytes(data, null);
}
/// <summary>
/// Hashes an array of bytes using the specified salt
/// </summary>
/// <param name="data">Bytes to hash</param>
/// <param name="salt">Salt to use (null to use a random salt)</param>
/// <returns>Computed hash</returns>
public byte[] HashBytes(byte[] data, byte[] salt)
{
if (data == null) throw new ArgumentNullException("data");
// Get the hasher
var hasher = GetHashAlgorithm(Provider);
// Generate a salt value if none was specified
if( salt == null )
{
var saltValue = GenerateSalt();
salt = Encoding.UTF8.GetBytes(saltValue); // Convert the salt to bytes
}
// Concatenate the salt and the data
var result = new byte[salt.Length + data.Length];
// Salt before or after the hash?
switch( SaltPosition )
{
// Salt before the hash
case SaltPosition.Prefix:
Array.Copy(salt, result, salt.Length);
Array.Copy(data, 0, result, salt.Length, data.Length);
break;
// Salt after the hash
case SaltPosition.Suffix:
Array.Copy(data, result, data.Length);
Array.Copy(salt, 0, result, data.Length, salt.Length);
break;
}
// Get the hash
var hash = hasher.ComputeHash(result);
// Now we need to also place the salt with the hash
result = new byte[hash.Length + salt.Length];
// Salt before or after the hash?
switch( SaltPosition )
{
// Salt before the hash
case SaltPosition.Prefix:
// Copy the salt to the start of the result array
Array.Copy(salt, result, salt.Length);
// Copy the hash to the result array after the salt
Array.Copy(hash, 0, result, salt.Length, hash.Length);
break;
// Salt after the hash
case SaltPosition.Suffix:
// Copy the hash to the start of the result array
Array.Copy(hash, result, hash.Length);
// Copy the salt to the result array after the hash
Array.Copy(salt, 0, result, hash.Length, salt.Length);
break;
}
// Finally, return our result
return result;
}
/// <summary>
/// Hashes a string with a random salt and returns the result as a hex string
/// </summary>
/// <param name="data">The string to hash</param>
/// <returns>Hashed string made up of hex characters</returns>
public override string HashString(string data)
{
return HashString(data, null);
}
/// <summary>
/// Hashes a string using the passed salt and returns the hex string result
/// </summary>
/// <param name="data">The string to hash</param>
/// <param name="salt">Salt to use</param>
/// <returns></returns>
public string HashString(string data, string salt)
{
var bytes = Encoding.UTF8.GetBytes(data); // Convert string to bytes
// If the salt is null, autogenerate a random salt
if( salt == null )
{
salt = GenerateSalt();
}
var saltBytes = Encoding.UTF8.GetBytes(salt); // Convert salt to bytes
bytes = HashBytes(bytes, saltBytes); // Hash the bytes
return Convert.ToBase64String(bytes);
}
#endregion
#region Comparison Methods
/// <summary>
/// Hashes a normal string and compares with another hash to see if they are equal
/// </summary>
/// <param name="value">Normal string to compare</param>
/// <param name="expectedHashValue">Expected hash result</param>
/// <returns>True if the string hashes to the expected hash result, otherwise false</returns>
public override bool Compare(string value, string expectedHashValue)
{
// Find the salt value
var salt = FindSalt(expectedHashValue);
return HashString(value, salt).Equals(expectedHashValue);
}
/// <summary>
/// Hashes a normal byte array and compares with another hash to see if they are equal
/// </summary>
/// <param name="value">Normal byte array to compare</param>
/// <param name="expectedHashValue">Expected hash result</param>
/// <returns>True if the array hashes to the expected hash result, otherwise false</returns>
public override bool Compare(byte[] value, byte[] expectedHashValue)
{
var compareHash = HashBytes(value);
return Equals(compareHash, expectedHashValue);
}
#endregion
/// <summary>
/// Computes the 32-character hex string MD5 Hash of the passed string
/// </summary>
/// <param name="toHash">The string to hash</param>
/// <returns>32-character hex MD5 hash</returns>
public new static string MD5Hash(string toHash)
{
var hasher = new SaltedHasher(HashProvider.MD5);
return hasher.HashString(toHash);
}
/// <summary>
/// Compares a string to a hash to see if they match
/// </summary>
/// <param name="compare">String to hash and compare</param>
/// <param name="hash">Expected hash result</param>
/// <returns>true if they match, otherwise false</returns>
public new static bool MD5Compare(string compare, string hash)
{
var hasher = new SaltedHasher(HashProvider.MD5);
return hasher.Compare(compare, hash);
}
/// <summary>
/// Computes the 32-character hex string SHA256 Hash of the passed string
/// </summary>
/// <param name="toHash">The string to hash</param>
/// <returns>32-character hex SHA256 hash</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha")]
public new static string Sha256Hash(string toHash)
{
return Sha256Hash(toHash, null);
}
/// <summary>
/// Computes the 32-character hex string SHA256 Hash of the passed string and salt
/// </summary>
/// <param name="toHash">The string to hash</param>
/// <param name="salt"></param>
/// <returns>32-character hex SHA256 hash</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha")]
public static string Sha256Hash(string toHash, string salt)
{
var hasher = new SaltedHasher(HashProvider.SHA256);
// Use the predefined salt if specified
return salt != null ? hasher.HashString(toHash, salt) : hasher.HashString(toHash);
}
/// <summary>
/// Compares a string to a hash to see if they match
/// </summary>
/// <param name="compare">String to hash and compare</param>
/// <param name="hash">Expected hash result</param>
/// <returns>true if they match, otherwise false</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha")]
public new static bool Sha256Compare(string compare, string hash)
{
var hasher = new SaltedHasher(HashProvider.SHA256);
return hasher.Compare(compare, hash);
}
/// <summary>
/// The password generator used for auto-generating salts
/// </summary>
public PasswordGenerator PasswordGenerator { get; private set; }
/// <summary>
/// Length for the salt value
/// </summary>
public int SaltLength { get; set; }
/// <summary>
/// Location of the salt value (at the start, or the end of the hash)
/// </summary>
public SaltPosition SaltPosition { get; set; }
}
}
| |
using System;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using PrimerProForms;
using PrimerProObjects;
using GenLib;
namespace PrimerProSearch
{
/// <summary>
///
/// </summary>
public class ResidueSearch : Search
{
//Search parameters
private ArrayList m_Graphemes; //list of graphemes for untaught residue
private string m_GraphemeToBeCounted; //grapheme to be counted in text data file
private bool m_ParaFmt; //how to display results
private bool m_IgnoreSightWords; //Ignore sight words or not
private bool m_UseCurrentTextData; //Use the current text data file for checking
private bool m_ReadingLevelInfo; //Display base reading level information
private string m_TextDataFile; //Selected text data file for checking
private Settings m_Settings;
private string m_Title;
private string m_DataFolder; //Data Folder
private GraphemeTaughtOrder m_GraphemesTaught; //Graphemes Taught List
private bool m_ViewParaSentWord; //Flag for viewing ParaSentWord number.
private Font m_DefaultFont; //Default Font
//Search Definition tags
private const string kGrapheme = "grapheme";
private const string kGrapheme2BCnt = "graphemetobecounted";
private const string kParaFromat = "paraformat";
private const string kIgnoreSightWords = "ignoresightwords";
private const string kReadingLevelInfo = "readinglevelinfo";
private const string kUseCurrentTextData = "usecurrenttextdata";
private const string kTextDataFile = "textdatafile";
private const string kSeparator = Constants.Tab;
public ResidueSearch(int number, Settings s)
: base(number, SearchDefinition.kResidue)
{
m_Graphemes = null;
m_GraphemeToBeCounted = "";
m_ParaFmt = false;
m_IgnoreSightWords = false;
m_ReadingLevelInfo = false;
m_UseCurrentTextData = false;
m_TextDataFile = "";
m_Settings = s;
//m_Title = "UnTaught Residue Search"e;
m_Title = m_Settings.LocalizationTable.GetMessage("ResidueSearchT");
if (m_Title == "")
m_Title = "UnTaught Residue Search";
m_DataFolder = m_Settings.OptionSettings.DataFolder;
m_GraphemesTaught = m_Settings.GraphemesTaught;
m_ViewParaSentWord = m_Settings.OptionSettings.ViewParaSentWord;
m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont();
}
public ArrayList Graphemes
{
get { return m_Graphemes; }
set { m_Graphemes = value; }
}
public string GraphemeToBeCounted
{
get { return m_GraphemeToBeCounted; }
set { m_GraphemeToBeCounted = value; }
}
public bool ParaFormat
{
get {return m_ParaFmt;}
set {m_ParaFmt = value;}
}
public bool IgnoreSightWords
{
get { return m_IgnoreSightWords; }
set { m_IgnoreSightWords = value; }
}
public bool ReadingLevelInfo
{
get { return m_ReadingLevelInfo; }
set { m_ReadingLevelInfo = value; }
}
public bool UseCurrentTextData
{
get { return m_UseCurrentTextData; }
set { m_UseCurrentTextData = value; }
}
public string TextDataFile
{
get { return m_TextDataFile; }
set { m_TextDataFile = value; }
}
public string Title
{
get {return m_Title;}
}
public string DataFolder
{
get { return m_DataFolder; }
}
public GraphemeTaughtOrder GraphemesTaught
{
get { return m_GraphemesTaught; }
}
public bool ViewParaSentWord
{
get { return m_ViewParaSentWord; }
}
public Font DefaultFont
{
get { return m_DefaultFont; }
}
public bool SetupSearch()
{
bool flag = false;
//FormResidue fpb = new FormResidue(this.GraphemesTaught,this.DefaultFont, this.DataFolder);
FormResidue form = new FormResidue(m_GraphemesTaught, m_DefaultFont, m_DataFolder, m_Settings.LocalizationTable);
DialogResult dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
this.Graphemes = form.Graphemes;
this.GraphemeToBeCounted = form.GraphemeToBeCounted;
this.ParaFormat = form.ParaFormat;
this.IgnoreSightWords = form.IgnoreSightWords;
this.ReadingLevelInfo = form.ReadingLevelInfo;
this.UseCurrentTextData = form.UseCurrentTextData;
this.TextDataFile = form.TextDataFile;
if (this.Graphemes != null)
{
SearchDefinition sd = new SearchDefinition(SearchDefinition.kResidue);
SearchDefinitionParm sdp = null;
this.SearchDefinition = sd;
string strSym = "";
string strSegs = "";
string strFile = "";
for (int i = 0; i < this.Graphemes.Count; i++)
{
strSym = this.Graphemes[i].ToString();
sdp = new SearchDefinitionParm(ResidueSearch.kGrapheme, strSym);
sd.AddSearchParm(sdp);
strSegs += strSym + Constants.Space;
}
if (this.GraphemeToBeCounted != "")
{
strSym = this.GraphemeToBeCounted.Trim();
sdp = new SearchDefinitionParm(ResidueSearch.kGrapheme2BCnt, strSym);
sd.AddSearchParm(sdp);
}
if (this.ParaFormat)
{
sdp = new SearchDefinitionParm(ResidueSearch.kParaFromat);
sd.AddSearchParm(sdp);
}
if (this.IgnoreSightWords)
{
sdp = new SearchDefinitionParm(ResidueSearch.kIgnoreSightWords);
sd.AddSearchParm(sdp);
}
if (this.ReadingLevelInfo)
{
sdp = new SearchDefinitionParm(ResidueSearch.kReadingLevelInfo);
sd.AddSearchParm(sdp);
}
if (this.UseCurrentTextData)
{
sdp = new SearchDefinitionParm(ResidueSearch.kUseCurrentTextData);
sd.AddSearchParm(sdp);
}
else
{
strFile = this.TextDataFile;
sdp = new SearchDefinitionParm(ResidueSearch.kTextDataFile, strFile);
sd.AddSearchParm(sdp);
}
m_Title = m_Title + " - [" + strSegs.Trim() + "]";
flag = true;
this.SearchDefinition = sd;
}
}
return flag;
}
public bool SetupSearch(SearchDefinition sd)
{
bool flag = false;
SearchDefinitionParm sdp = null;
string strTag = "";
string strContent = "";
string strSegs = "";
this.SearchDefinition = sd;
ArrayList al = new ArrayList();
for (int i = 0; i < sd.SearchParmsCount(); i++)
{
sdp = sd.GetSearchParmAt(i);
strTag = sdp.GetTag();
strContent = sdp.GetContent();
if (strTag == ResidueSearch.kGrapheme)
{
al.Add(strContent);
strSegs += strContent + Constants.Space;
flag = true;
}
if (strTag == ResidueSearch.kGrapheme2BCnt)
this.GraphemeToBeCounted = strContent;
if (strTag == ResidueSearch.kParaFromat)
this.ParaFormat = true;
if (strTag == ResidueSearch.kIgnoreSightWords)
this.IgnoreSightWords = true;
if (strTag == ResidueSearch.kReadingLevelInfo)
this.ReadingLevelInfo = true;
if (strTag == ResidueSearch.kUseCurrentTextData)
this.UseCurrentTextData = true;
if (strTag == ResidueSearch.kTextDataFile)
this.TextDataFile = strContent;
}
this.Graphemes = al;
m_Title = m_Title + " - [" + strSegs.Trim() + "]";
return flag;
}
public string BuildResults()
{
string strText = "";
string str = "";
string strSN = Search.TagSN + this.SearchNumber.ToString().Trim();
strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine;
strText += this.Title + Environment.NewLine + Environment.NewLine;
strText += this.SearchResults;
strText += Environment.NewLine;
//strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine;
str = m_Settings.LocalizationTable.GetMessage("Search2");
if (str == "")
str = "entries found";
strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine;
strText += Environment.NewLine;
strText += Search.TagOpener + Search.TagForwardSlash + strSN
+ Search.TagCloser + Environment.NewLine;
return strText;
}
public ResidueSearch ExecuteResidueSearch(TextData td)
{
if (this.ParaFormat)
ExecuteResidueSearchP(td);
else ExecuteResidueSearchL(td);
return this;
}
private ResidueSearch ExecuteResidueSearchP(TextData td)
{
int nCount = 0;
string strRslt = "";
int nGrfCount = 0;
Paragraph para = null;
Sentence sent = null;
Word wrd = null;
int nPara = td.ParagraphCount();
for (int i = 0; i < nPara; i++)
{
para = td.GetParagraph(i);
int nSent = para.SentenceCount();
for (int j = 0; j < nSent; j++)
{
sent = para.GetSentence(j);
int nWord = sent.WordCount();
for (int k = 0; k < nWord; k++)
{
wrd = sent.GetWord(k);
if (wrd.IsBuildableWord(this.Graphemes))
{
strRslt += wrd.DisplayWord + Constants.Space;
}
else if ((this.IgnoreSightWords) && (wrd.IsSightWord()))
{
strRslt += wrd.DisplayWord + Constants.Space;
}
else
{
strRslt += wrd.HighlightMissingGraphemes(this.Graphemes);
strRslt += Constants.Space;
nCount++;
}
if (wrd.ContainInWord(this.GraphemeToBeCounted))
nGrfCount++;
}
strRslt = strRslt.TrimEnd(); //get ride of last space
strRslt += sent.EndingPunctuation;
strRslt += Constants.Space;
}
strRslt += Environment.NewLine + Environment.NewLine;
}
if (this.GraphemeToBeCounted != "")
{
// this.this.GraphemeToBeCounted + " (count): " + nGrfCount.ToString()
string strMsg = m_Settings.LocalizationTable.GetMessage("ResidueSearch1");
if (strMsg == "")
strMsg = "(count):";
strRslt += this.GraphemeToBeCounted + Constants.Space + strMsg + Constants.Space + nGrfCount.ToString() + Environment.NewLine + Environment.NewLine;
}
if (this.ReadingLevelInfo)
{
strRslt += this.GetReadingLevelInfo(td);
strRslt += Environment.NewLine;
}
this.SearchResults = strRslt;
this.SearchCount = nCount;
return this;
}
private ResidueSearch ExecuteResidueSearchL(TextData td)
{
int nCount = 0;
string strRslt = "";
int nGrfCount = 0;
Paragraph para = null;
Sentence sent = null;
Word wrd = null;
int nTmp = 0;
int nPara = td.ParagraphCount();
for (int i = 0; i < nPara; i++)
{
para = td.GetParagraph(i);
int nSent = para.SentenceCount();
for (int j = 0; j < nSent; j++)
{
sent = para.GetSentence(j);
int nWord = sent.WordCount();
for (int k = 0; k < nWord; k++)
{
wrd = sent.GetWord(k);
if (!wrd.IsBuildableWord(this.Graphemes))
{
if ((!this.IgnoreSightWords) || (!wrd.IsSightWord()))
{
nCount++;
if (this.ViewParaSentWord)
{
nTmp = i + 1;
strRslt += TextData.kPara + Search.Colon + nTmp.ToString().PadLeft(4);
strRslt += ResidueSearch.kSeparator;
nTmp = j + 1;
strRslt += TextData.kSent + Search.Colon + nTmp.ToString().PadLeft(4);
strRslt += ResidueSearch.kSeparator;
nTmp = k + 1;
strRslt += TextData.kWord + Search.Colon + nTmp.ToString().PadLeft(4);
strRslt += ResidueSearch.kSeparator;
}
strRslt += wrd.HighlightMissingGraphemes(this.Graphemes) + Environment.NewLine;
}
}
if (wrd.ContainInWord(this.GraphemeToBeCounted))
nGrfCount++;
}
}
}
strRslt += Environment.NewLine;
if (this.GraphemeToBeCounted != "")
{
string strMsg = " (count): ";
strRslt += this.GraphemeToBeCounted + strMsg + nGrfCount.ToString() + Environment.NewLine;
strRslt += Environment.NewLine;
}
if (this.ReadingLevelInfo)
{
strRslt += this.GetReadingLevelInfo(td);
strRslt += Environment.NewLine;
}
this.SearchResults = strRslt;
this.SearchCount = nCount;
return this;
}
private string GetReadingLevelInfo(TextData td)
{
string strInfo = "";
string strText = "";
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch2");
if (strText == "")
strText = "Max number of words in sentences:";
strInfo += strText + Constants.Space + td.MaxNumberOfWordsInSentences().ToString() + Environment.NewLine;
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch3");
if (strText == "")
strText = "Max number of syllables in words";
strInfo += strText + Constants.Space + td.MaxNumberOfSyllablesInWords().ToString() + Environment.NewLine;
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch4");
if (strText == "")
strText = "Average number of words in sentences is less than:";
strInfo += strText + Constants.Space + (td.AvgNumberOfWordsInSentences() + 1).ToString() + Environment.NewLine;
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch5");
if (strText == "")
strText = "Average number of syllables in words is less than:";
strInfo += strText + Constants.Space + (td.AvgNumberOfSyllablesInWords() + 1).ToString() + Environment.NewLine;
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch6");
if (strText == "")
strText = "Number of unique words in story:";
strInfo += strText + Constants.Space + td.BuildWordListWithNoDuplicates().WordCount().ToString() + Environment.NewLine;
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch7");
if (strText == "")
strText = "Number of words in story:";
strInfo += strText + Constants.Space + td.WordCount().ToString() + Environment.NewLine;
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch8");
if (strText == "")
strText = "Number of syllables in story:";
strInfo += strText + Constants.Space + td.SyllableCount().ToString() + Environment.NewLine;
strText = m_Settings.LocalizationTable.GetMessage("ResidueSearch9");
if (strText == "")
strText = "Number of sentences in story:";
strInfo += strText + Constants.Space + td.SentenceCount().ToString() + Environment.NewLine;
return strInfo;
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2009 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
#if NETFX_CORE
using MarkerMetro.Unity.WinLegacy.Plugin.Collections;
#endif
#if NETFX_CORE
using MarkerMetro.Unity.WinLegacy.Reflection;
#endif
namespace Pathfinding.Serialization.JsonFx
{
/// <summary>
/// Reader for consuming JSON data
/// </summary>
public class JsonReader
{
#region Constants
internal const string LiteralFalse = "false";
internal const string LiteralTrue = "true";
internal const string LiteralNull = "null";
internal const string LiteralUndefined = "undefined";
internal const string LiteralNotANumber = "NaN";
internal const string LiteralPositiveInfinity = "Infinity";
internal const string LiteralNegativeInfinity = "-Infinity";
internal const char OperatorNegate = '-';
internal const char OperatorUnaryPlus = '+';
internal const char OperatorArrayStart = '[';
internal const char OperatorArrayEnd = ']';
internal const char OperatorObjectStart = '{';
internal const char OperatorObjectEnd = '}';
internal const char OperatorStringDelim = '"';
internal const char OperatorStringDelimAlt = '\'';
internal const char OperatorValueDelim = ',';
internal const char OperatorNameDelim = ':';
internal const char OperatorCharEscape = '\\';
private const string CommentStart = "/*";
private const string CommentEnd = "*/";
private const string CommentLine = "//";
private const string LineEndings = "\r\n";
internal const string TypeGenericIDictionary = "System.Collections.Generic.IDictionary`2";
private const string ErrorUnrecognizedToken = "Illegal JSON sequence.";
private const string ErrorUnterminatedComment = "Unterminated comment block.";
private const string ErrorUnterminatedObject = "Unterminated JSON object.";
private const string ErrorUnterminatedArray = "Unterminated JSON array.";
private const string ErrorUnterminatedString = "Unterminated JSON string.";
private const string ErrorIllegalNumber = "Illegal JSON number.";
private const string ErrorExpectedString = "Expected JSON string.";
private const string ErrorExpectedObject = "Expected JSON object.";
private const string ErrorExpectedArray = "Expected JSON array.";
private const string ErrorExpectedPropertyName = "Expected JSON object property name.";
private const string ErrorExpectedPropertyNameDelim = "Expected JSON object property name delimiter.";
private const string ErrorGenericIDictionary = "Types which implement Generic IDictionary<TKey, TValue> also need to implement IDictionary to be deserialized. ({0})";
private const string ErrorGenericIDictionaryKeys = "Types which implement Generic IDictionary<TKey, TValue> need to have string keys to be deserialized. ({0})";
#endregion Constants
#region Fields
private readonly JsonReaderSettings Settings = new JsonReaderSettings();
private readonly string Source = null;
private readonly int SourceLength = 0;
private int index;
/** List of previously deserialized objects.
* Used for reference cycle handling.
*/
private readonly List<object> previouslyDeserialized = new List<object>();
/** Cache ArrayLists. Otherwise every new deseriaization of an array wil allocate
* a new ArrayList.
*/
private readonly Stack<ArrayList> jsArrays = new Stack<ArrayList>();
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">TextReader containing source</param>
public JsonReader(TextReader input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">TextReader containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(TextReader input, JsonReaderSettings settings)
{
this.Settings = settings;
this.Source = input.ReadToEnd();
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">Stream containing source</param>
public JsonReader(Stream input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">Stream containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(Stream input, JsonReaderSettings settings)
{
this.Settings = settings;
using (StreamReader reader = new StreamReader(input, true))
{
this.Source = reader.ReadToEnd();
}
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">string containing source</param>
public JsonReader(string input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">string containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(string input, JsonReaderSettings settings)
{
this.Settings = settings;
this.Source = input;
this.SourceLength = this.Source.Length;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">StringBuilder containing source</param>
public JsonReader(StringBuilder input)
: this(input, new JsonReaderSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="input">StringBuilder containing source</param>
/// <param name="settings">JsonReaderSettings</param>
public JsonReader(StringBuilder input, JsonReaderSettings settings)
{
this.Settings = settings;
this.Source = input.ToString();
this.SourceLength = this.Source.Length;
}
#endregion Init
#region Properties
/// <summary>
/// Gets and sets if ValueTypes can accept values of null
/// </summary>
/// <remarks>
/// Only affects deserialization: if a ValueType is assigned the
/// value of null, it will receive the value default(TheType).
/// Setting this to false, throws an exception if null is
/// specified for a ValueType member.
/// </remarks>
[Obsolete("This has been deprecated in favor of JsonReaderSettings object")]
public bool AllowNullValueTypes
{
get { return this.Settings.AllowNullValueTypes; }
set { this.Settings.AllowNullValueTypes = value; }
}
/// <summary>
/// Gets and sets the property name used for type hinting.
/// </summary>
[Obsolete("This has been deprecated in favor of JsonReaderSettings object")]
public string TypeHintName
{
get { return this.Settings.TypeHintName; }
set { this.Settings.TypeHintName = value; }
}
#endregion Properties
#region Parsing Methods
/// <summary>
/// Convert from JSON string to Object graph
/// </summary>
/// <returns></returns>
public object Deserialize()
{
return this.Deserialize((Type)null);
}
/// <summary>
/// Convert from JSON string to Object graph
/// </summary>
/// <returns></returns>
public object Deserialize(int start)
{
this.index = start;
return this.Deserialize((Type)null);
}
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public object Deserialize(Type type)
{
// should this run through a preliminary test here?
return this.Read(type, false);
}
/*
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public T Deserialize<T>()
{
// should this run through a preliminary test here?
return (T)this.Read(typeof(T), false);
}*/
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public object Deserialize(int start, Type type)
{
this.index = start;
// should this run through a preliminary test here?
return this.Read(type, false);
}
/// <summary>
/// Convert from JSON string to Object graph of specific Type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/*public T Deserialize<T>(int start)
{
this.index = start;
// should this run through a preliminary test here?
return (T)this.Read(typeof(T), false);
}*/
private object Read(Type expectedType, bool typeIsHint)
{
if (expectedType == typeof(Object))
{
expectedType = null;
}
JsonToken token = this.Tokenize();
#if NETFX_CORE
if (expectedType != null && !expectedType.IsPrimitive())
{
#else
if (expectedType != null && !expectedType.IsPrimitive) {
#endif
JsonConverter converter = this.Settings.GetConverter(expectedType);
if (converter != null) {
object val;
try {
val = Read(typeof(Dictionary<string,object>),false);
Dictionary<string,object> dict = val as Dictionary<string,object>;
if (dict == null) return null;
object obj = converter.Read (this,expectedType,dict);
return obj;
} catch (JsonTypeCoercionException e) {
#if !NETFX_CORE
Console.WriteLine ("Could not cast to dictionary for converter processing. Ignoring field.\n"+e);
#else
System.Diagnostics.LogMgr.WriteLine("Could not cast to dictionary for converter processing. Ignoring field.\n"+e);
#endif
}
return null;
}
}
switch (token)
{
case JsonToken.ObjectStart:
{
return this.ReadObject(typeIsHint ? null : expectedType);
}
case JsonToken.ArrayStart:
{
return this.ReadArray(typeIsHint ? null : expectedType);
}
case JsonToken.String:
{
return this.ReadString(typeIsHint ? null : expectedType);
}
case JsonToken.Number:
{
return this.ReadNumber(typeIsHint ? null : expectedType);
}
case JsonToken.False:
{
this.index += JsonReader.LiteralFalse.Length;
return false;
}
case JsonToken.True:
{
this.index += JsonReader.LiteralTrue.Length;
return true;
}
case JsonToken.Null:
{
this.index += JsonReader.LiteralNull.Length;
return null;
}
case JsonToken.NaN:
{
this.index += JsonReader.LiteralNotANumber.Length;
return Double.NaN;
}
case JsonToken.PositiveInfinity:
{
this.index += JsonReader.LiteralPositiveInfinity.Length;
return Double.PositiveInfinity;
}
case JsonToken.NegativeInfinity:
{
this.index += JsonReader.LiteralNegativeInfinity.Length;
return Double.NegativeInfinity;
}
case JsonToken.Undefined:
{
this.index += JsonReader.LiteralUndefined.Length;
return null;
}
case JsonToken.End:
default:
{
return null;
}
}
}
// IZ: Added
public void PopulateObject(object obj)
{
object other = obj;
PopulateObject(ref other);
if(!object.ReferenceEquals(other, obj))
throw new InvalidOperationException("Object reference has changed, please use ref call, which you can't do because it is private :)");
}
/** Populates an object with serialized data.
* Note that in case the object has been loaded before (another reference to it)
* the passed object will be changed to the previously loaded object (this only applies
* if you have enabled CyclicReferenceHandling in the settings).
*/
private void PopulateObject (ref object obj) {
Type objectType = obj.GetType();
Dictionary<string, MemberInfo> memberMap = this.Settings.Coercion.GetMemberMap(objectType);
Type genericDictionaryType = null;
if (memberMap == null)
{
genericDictionaryType = GetGenericDictionaryType(objectType);
}
PopulateObject (ref obj, objectType, memberMap, genericDictionaryType);
}
private object ReadObject (Type objectType) {
Type genericDictionaryType = null;
Dictionary<string, MemberInfo> memberMap = null;
Object result;
if (objectType != null)
{
result = this.Settings.Coercion.InstantiateObject(objectType, out memberMap);
Debug.WriteLine(string.Format("Adding: {0} ({1})", result, previouslyDeserialized.Count));
previouslyDeserialized.Add (result);
if (memberMap == null)
{
genericDictionaryType = GetGenericDictionaryType(objectType);
}
}
else
{
result = new Dictionary<String, Object>();
}
object prev = result;
PopulateObject (ref result, objectType, memberMap, genericDictionaryType);
if (prev != result)
{
// If prev != result, then the PopulateObject method has used a previously loaded object
// then we should not add the object to the list of deserialized objects since it
// already is there (the correct version of it, that is)
Debug.WriteLine(string.Format("Removing: {0} ({1})", result, previouslyDeserialized.Count));
previouslyDeserialized.RemoveAt(previouslyDeserialized.Count-1);
}
return result;
}
private Type GetGenericDictionaryType (Type objectType) {
// this allows specific IDictionary<string, T> to deserialize T
Type genericDictionary = objectType.GetInterface(JsonReader.TypeGenericIDictionary);
if (genericDictionary != null)
{
Type[] genericArgs = genericDictionary.GetGenericArguments();
if (genericArgs.Length == 2)
{
if (genericArgs[0] != typeof(String))
{
throw new JsonDeserializationException(
String.Format(JsonReader.ErrorGenericIDictionaryKeys, objectType),
this.index);
}
if (genericArgs[1] != typeof(Object))
{
return genericArgs[1];
}
}
}
return null;
}
private void PopulateObject (ref object result, Type objectType, Dictionary<string, MemberInfo> memberMap, Type genericDictionaryType)
{
if (this.Source[this.index] != JsonReader.OperatorObjectStart)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedObject, this.index);
}
IDictionary idict = result as IDictionary;
if (idict == null && objectType.GetInterface(JsonReader.TypeGenericIDictionary) != null )
{
throw new JsonDeserializationException(
String.Format(JsonReader.ErrorGenericIDictionary, objectType),
this.index);
}
JsonToken token;
do
{
Type memberType;
MemberInfo memberInfo;
// consume opening brace or delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
// get next token
token = this.Tokenize(this.Settings.AllowUnquotedObjectKeys);
if (token == JsonToken.ObjectEnd)
{
break;
}
if (token != JsonToken.String && token != JsonToken.UnquotedName)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyName, this.index);
}
// parse object member value
string memberName = (token == JsonToken.String) ?
(String)this.ReadString(null) :
this.ReadUnquotedKey();
//
if (genericDictionaryType == null && memberMap != null)
{
// determine the type of the property/field
memberType = TypeCoercionUtility.GetMemberInfo(memberMap, memberName, out memberInfo);
}
else
{
memberType = genericDictionaryType;
memberInfo = null;
}
// get next token
token = this.Tokenize();
if (token != JsonToken.NameDelim)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyNameDelim, this.index);
}
// consume delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
object value;
// Reference to previously deserialized value
if (Settings.HandleCyclicReferences && memberName == "@ref") {
// parse object member value
int refId = (int)this.Read(typeof(int), false);
// Change result object to the one previously deserialized
result = previouslyDeserialized[refId];
// get next token
// this will probably be the end of the object
token = this.Tokenize();
continue;
}
else
{
// Normal serialized value
// parse object member value
value = this.Read(memberType, false);
}
if (idict != null)
{
if (objectType == null && this.Settings.IsTypeHintName(memberName))
{
result = this.Settings.Coercion.ProcessTypeHint(idict, value as string, out objectType, out memberMap);
}
else
{
idict[memberName] = value;
}
}
else
{
this.Settings.Coercion.SetMemberValue(result, memberType, memberInfo, value);
}
// get next token
token = this.Tokenize();
} while (token == JsonToken.ValueDelim);
if (token != JsonToken.ObjectEnd)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index);
}
// consume closing brace
this.index++;
//return result;
}
private IEnumerable ReadArray(Type arrayType)
{
if (this.Source[this.index] != JsonReader.OperatorArrayStart)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedArray, this.index);
}
bool isArrayItemTypeSet = (arrayType != null);
bool isArrayTypeAHint = !isArrayItemTypeSet;
Type arrayItemType = null;
if (isArrayItemTypeSet)
{
if (arrayType.HasElementType)
{
arrayItemType = arrayType.GetElementType();
}
#if NETFX_CORE
else if (arrayType.IsGenericType())
#else
else if (arrayType.IsGenericType)
#endif
{
Type[] generics = arrayType.GetGenericArguments();
if (generics.Length == 1)
{
// could use the first or last, but this more correct
arrayItemType = generics[0];
}
}
}
// using ArrayList since has .ToArray(Type) method
// cannot create generic list at runtime
ArrayList jsArray = jsArrays.Count > 0 ? jsArrays.Pop() : new ArrayList();
jsArray.Clear();
JsonToken token;
do
{
// consume opening bracket or delim
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index);
}
// get next token
token = this.Tokenize();
if (token == JsonToken.ArrayEnd)
{
break;
}
// parse array item
object value = this.Read(arrayItemType, isArrayTypeAHint);
jsArray.Add(value);
// establish if array is of common type
if (value == null)
{
#if NETFX_CORE
if (arrayItemType != null && arrayItemType.IsValueType())
#else
if (arrayItemType != null && arrayItemType.IsValueType)
#endif
{
// use plain object to hold null
arrayItemType = null;
}
isArrayItemTypeSet = true;
}
else if (arrayItemType != null && !arrayItemType.IsAssignableFrom(value.GetType()))
{
if (value.GetType().IsAssignableFrom(arrayItemType))
{
// attempt to use the more general type
arrayItemType = value.GetType();
}
else
{
// use plain object to hold value
arrayItemType = null;
isArrayItemTypeSet = true;
}
}
else if (!isArrayItemTypeSet)
{
// try out a hint type
// if hasn't been set before
arrayItemType = value.GetType();
isArrayItemTypeSet = true;
}
// get next token
token = this.Tokenize();
} while (token == JsonToken.ValueDelim);
if (token != JsonToken.ArrayEnd)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index);
}
// consume closing bracket
this.index++;
// TODO: optimize to reduce number of conversions on lists
jsArrays.Push (jsArray);
if (arrayItemType != null && arrayItemType != typeof(object))
{
// if all items are of same type then convert to array of that type
return jsArray.ToArray(arrayItemType);
}
// convert to an object array for consistency
return jsArray.ToArray();
}
/// <summary>
/// Reads an unquoted JSON object key
/// </summary>
/// <returns></returns>
private string ReadUnquotedKey()
{
int start = this.index;
do
{
// continue scanning until reach a valid token
this.index++;
} while (this.Tokenize(true) == JsonToken.UnquotedName);
return this.Source.Substring(start, this.index - start);
}
/// <summary>
/// Reads a JSON string
/// </summary>
/// <param name="expectedType"></param>
/// <returns>string or value which is represented as a string in JSON</returns>
private object ReadString(Type expectedType)
{
if (this.Source[this.index] != JsonReader.OperatorStringDelim &&
this.Source[this.index] != JsonReader.OperatorStringDelimAlt)
{
throw new JsonDeserializationException(JsonReader.ErrorExpectedString, this.index);
}
char startStringDelim = this.Source[this.index];
// consume opening quote
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
int start = this.index;
StringBuilder builder = new StringBuilder();
while (this.Source[this.index] != startStringDelim)
{
if (this.Source[this.index] == JsonReader.OperatorCharEscape)
{
// copy chunk before decoding
builder.Append(this.Source, start, this.index - start);
// consume escape char
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
// decode
switch (this.Source[this.index])
{
case '0':
{
// don't allow NULL char '\0'
// causes CStrings to terminate
break;
}
case 'b':
{
// backspace
builder.Append('\b');
break;
}
case 'f':
{
// formfeed
builder.Append('\f');
break;
}
case 'n':
{
// newline
builder.Append('\n');
break;
}
case 'r':
{
// carriage return
builder.Append('\r');
break;
}
case 't':
{
// tab
builder.Append('\t');
break;
}
case 'u':
{
// Unicode escape sequence
// e.g. Copyright: "\u00A9"
// unicode ordinal
int utf16;
if (this.index+4 < this.SourceLength &&
Int32.TryParse(
this.Source.Substring(this.index+1, 4),
NumberStyles.AllowHexSpecifier,
NumberFormatInfo.InvariantInfo,
out utf16))
{
builder.Append(Char.ConvertFromUtf32(utf16));
this.index += 4;
}
else
{
// using FireFox style recovery, if not a valid hex
// escape sequence then treat as single escaped 'u'
// followed by rest of string
builder.Append(this.Source[this.index]);
}
break;
}
default:
{
builder.Append(this.Source[this.index]);
break;
}
}
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
start = this.index;
}
else
{
// next char
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index);
}
}
}
// copy rest of string
builder.Append(this.Source, start, this.index-start);
// consume closing quote
this.index++;
if (expectedType != null && expectedType != typeof(String))
{
return this.Settings.Coercion.CoerceType(expectedType, builder.ToString());
}
return builder.ToString();
}
private object ReadNumber(Type expectedType)
{
bool hasDecimal = false;
bool hasExponent = false;
int start = this.index;
int precision = 0;
int exponent = 0;
// optional minus part
if (this.Source[this.index] == JsonReader.OperatorNegate)
{
// consume sign
this.index++;
if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index]))
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
// integer part
while ((this.index < this.SourceLength) && Char.IsDigit(this.Source[this.index]))
{
// consume digit
this.index++;
}
// optional decimal part
if ((this.index < this.SourceLength) && (this.Source[this.index] == '.'))
{
hasDecimal = true;
// consume decimal
this.index++;
if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index]))
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
// fraction part
while (this.index < this.SourceLength && Char.IsDigit(this.Source[this.index]))
{
// consume digit
this.index++;
}
}
// note the number of significant digits
precision = this.index-start - (hasDecimal ? 1 : 0);
// optional exponent part
if (this.index < this.SourceLength && (this.Source[this.index] == 'e' || this.Source[this.index] == 'E'))
{
hasExponent = true;
// consume 'e'
this.index++;
if (this.index >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
int expStart = this.index;
// optional minus/plus part
if (this.Source[this.index] == JsonReader.OperatorNegate || this.Source[this.index] == JsonReader.OperatorUnaryPlus)
{
// consume sign
this.index++;
if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index]))
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
}
else
{
if (!Char.IsDigit(this.Source[this.index]))
{
throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index);
}
}
// exp part
while (this.index < this.SourceLength && Char.IsDigit(this.Source[this.index]))
{
// consume digit
this.index++;
}
Int32.TryParse(this.Source.Substring(expStart, this.index-expStart), NumberStyles.Integer,
NumberFormatInfo.InvariantInfo, out exponent);
}
// at this point, we have the full number string and know its characteristics
string numberString = this.Source.Substring(start, this.index - start);
if (!hasDecimal && !hasExponent && precision < 19)
{
// is Integer value
// parse as most flexible
decimal number = Decimal.Parse(
numberString,
NumberStyles.Integer,
NumberFormatInfo.InvariantInfo);
if (expectedType != null)
{
return this.Settings.Coercion.CoerceType(expectedType, number);
}
if (number >= Int32.MinValue && number <= Int32.MaxValue)
{
// use most common
return (int)number;
}
if (number >= Int64.MinValue && number <= Int64.MaxValue)
{
// use more flexible
return (long)number;
}
// use most flexible
return number;
}
else
{
// is Floating Point value
if (expectedType == typeof(Decimal))
{
// special case since Double does not convert to Decimal
return Decimal.Parse(
numberString,
NumberStyles.Float,
NumberFormatInfo.InvariantInfo);
}
// use native EcmaScript number (IEEE 754)
double number = Double.Parse(
numberString,
NumberStyles.Float,
NumberFormatInfo.InvariantInfo);
if (expectedType != null)
{
return this.Settings.Coercion.CoerceType(expectedType, number);
}
return number;
}
}
#endregion Parsing Methods
#region Static Methods
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object Deserialize(string value)
{
return JsonReader.Deserialize(value, 0, null);
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T Deserialize<T>(string value)
{
return (T)JsonReader.Deserialize(value, 0, typeof(T));
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value"></param>
/// <param name="start"></param>
/// <returns></returns>
public static object Deserialize(string value, int start)
{
return JsonReader.Deserialize(value, start, null);
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="start"></param>
/// <returns></returns>
public static T Deserialize<T>(string value, int start)
{
return (T)JsonReader.Deserialize(value, start, typeof(T));
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object Deserialize(string value, Type type)
{
return JsonReader.Deserialize(value, 0, type);
}
/// <summary>
/// A fast method for deserializing an object from JSON
/// </summary>
/// <param name="value">source text</param>
/// <param name="start">starting position</param>
/// <param name="type">expected type</param>
/// <returns></returns>
public static object Deserialize(string value, int start, Type type)
{
return (new JsonReader(value)).Deserialize(start, type);
}
#endregion Static Methods
#region Tokenizing Methods
private JsonToken Tokenize()
{
// unquoted object keys are only allowed in object properties
return this.Tokenize(false);
}
private JsonToken Tokenize(bool allowUnquotedString)
{
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
// skip whitespace
while (Char.IsWhiteSpace(this.Source[this.index]))
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
#region Skip Comments
// skip block and line comments
if (this.Source[this.index] == JsonReader.CommentStart[0])
{
if (this.index+1 >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index);
}
// skip over first char of comment start
this.index++;
bool isBlockComment = false;
if (this.Source[this.index] == JsonReader.CommentStart[1])
{
isBlockComment = true;
}
else if (this.Source[this.index] != JsonReader.CommentLine[1])
{
throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index);
}
// skip over second char of comment start
this.index++;
if (isBlockComment)
{
// store index for unterminated case
int commentStart = this.index-2;
if (this.index+1 >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedComment, commentStart);
}
// skip over everything until reach block comment ending
while (this.Source[this.index] != JsonReader.CommentEnd[0] ||
this.Source[this.index+1] != JsonReader.CommentEnd[1])
{
this.index++;
if (this.index+1 >= this.SourceLength)
{
throw new JsonDeserializationException(JsonReader.ErrorUnterminatedComment, commentStart);
}
}
// skip block comment end token
this.index += 2;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
else
{
// skip over everything until reach line ending
while (JsonReader.LineEndings.IndexOf(this.Source[this.index]) < 0)
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
}
// skip whitespace again
while (Char.IsWhiteSpace(this.Source[this.index]))
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
}
#endregion Skip Comments
// consume positive signing (as is extraneous)
if (this.Source[this.index] == JsonReader.OperatorUnaryPlus)
{
this.index++;
if (this.index >= this.SourceLength)
{
return JsonToken.End;
}
}
switch (this.Source[this.index])
{
case JsonReader.OperatorArrayStart:
{
return JsonToken.ArrayStart;
}
case JsonReader.OperatorArrayEnd:
{
return JsonToken.ArrayEnd;
}
case JsonReader.OperatorObjectStart:
{
return JsonToken.ObjectStart;
}
case JsonReader.OperatorObjectEnd:
{
return JsonToken.ObjectEnd;
}
case JsonReader.OperatorStringDelim:
case JsonReader.OperatorStringDelimAlt:
{
return JsonToken.String;
}
case JsonReader.OperatorValueDelim:
{
return JsonToken.ValueDelim;
}
case JsonReader.OperatorNameDelim:
{
return JsonToken.NameDelim;
}
default:
{
break;
}
}
// number
if (Char.IsDigit(this.Source[this.index]) ||
((this.Source[this.index] == JsonReader.OperatorNegate) && (this.index+1 < this.SourceLength) && Char.IsDigit(this.Source[this.index+1])))
{
return JsonToken.Number;
}
// "false" literal
if (this.MatchLiteral(JsonReader.LiteralFalse))
{
return JsonToken.False;
}
// "true" literal
if (this.MatchLiteral(JsonReader.LiteralTrue))
{
return JsonToken.True;
}
// "null" literal
if (this.MatchLiteral(JsonReader.LiteralNull))
{
return JsonToken.Null;
}
// "NaN" literal
if (this.MatchLiteral(JsonReader.LiteralNotANumber))
{
return JsonToken.NaN;
}
// "Infinity" literal
if (this.MatchLiteral(JsonReader.LiteralPositiveInfinity))
{
return JsonToken.PositiveInfinity;
}
// "-Infinity" literal
if (this.MatchLiteral(JsonReader.LiteralNegativeInfinity))
{
return JsonToken.NegativeInfinity;
}
// "undefined" literal
if (this.MatchLiteral(JsonReader.LiteralUndefined))
{
return JsonToken.Undefined;
}
if (allowUnquotedString)
{
return JsonToken.UnquotedName;
}
throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index);
}
/// <summary>
/// Determines if the next token is the given literal
/// </summary>
/// <param name="literal"></param>
/// <returns></returns>
private bool MatchLiteral(string literal)
{
int literalLength = literal.Length;
for (int i=0, j=this.index; i<literalLength && j<this.SourceLength; i++, j++)
{
if (literal[i] != this.Source[j])
{
return false;
}
}
return true;
}
#endregion Tokenizing Methods
#region Type Methods
/// <summary>
/// Converts a value into the specified type using type inference.
/// </summary>
/// <typeparam name="T">target type</typeparam>
/// <param name="value">value to convert</param>
/// <param name="typeToMatch">example object to get the type from</param>
/// <returns></returns>
public static T CoerceType<T>(object value, T typeToMatch)
{
return (T)new TypeCoercionUtility().CoerceType(typeof(T), value);
}
/// <summary>
/// Converts a value into the specified type.
/// </summary>
/// <typeparam name="T">target type</typeparam>
/// <param name="value">value to convert</param>
/// <returns></returns>
public static T CoerceType<T>(object value)
{
return (T)new TypeCoercionUtility().CoerceType(typeof(T), value);
}
/// <summary>
/// Converts a value into the specified type.
/// </summary>
/// <param name="targetType">target type</param>
/// <param name="value">value to convert</param>
/// <returns></returns>
public static object CoerceType(Type targetType, object value)
{
return new TypeCoercionUtility().CoerceType(targetType, value);
}
#endregion Type Methods
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
[CanEditMultipleObjects]
[CustomEditor(typeof(tk2dSprite))]
class tk2dSpriteEditor : Editor
{
// Serialized properties are going to be far too much hassle
private tk2dBaseSprite[] targetSprites = new tk2dBaseSprite[0];
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
private Renderer[] renderers = new Renderer[0];
#endif
public override void OnInspectorGUI()
{
DrawSpriteEditorGUI();
}
public void OnSceneGUI()
{
if (tk2dPreferences.inst.enableSpriteHandles == false || !tk2dEditorUtility.IsEditable(target)) {
return;
}
tk2dSprite spr = (tk2dSprite)target;
var sprite = spr.CurrentSprite;
if (sprite == null) {
return;
}
Transform t = spr.transform;
Bounds b = spr.GetUntrimmedBounds();
Rect localRect = new Rect(b.min.x, b.min.y, b.size.x, b.size.y);
// Draw rect outline
Handles.color = new Color(1,1,1,0.5f);
tk2dSceneHelper.DrawRect (localRect, t);
Handles.BeginGUI ();
// Resize handles
if (tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck ();
Rect resizeRect = tk2dSceneHelper.RectControl (999888, localRect, t);
if (EditorGUI.EndChangeCheck ()) {
tk2dUndo.RecordObjects(new Object[] {t, spr}, "Resize");
spr.ReshapeBounds(new Vector3(resizeRect.xMin, resizeRect.yMin) - new Vector3(localRect.xMin, localRect.yMin),
new Vector3(resizeRect.xMax, resizeRect.yMax) - new Vector3(localRect.xMax, localRect.yMax));
EditorUtility.SetDirty(spr);
}
}
// Rotate handles
if (!tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck();
float theta = tk2dSceneHelper.RectRotateControl (888999, localRect, t, new List<int>());
if (EditorGUI.EndChangeCheck()) {
tk2dUndo.RecordObject (t, "Rotate");
if (Mathf.Abs(theta) > Mathf.Epsilon) {
t.Rotate(t.forward, theta, Space.World);
}
}
}
Handles.EndGUI ();
// Sprite selecting
tk2dSceneHelper.HandleSelectSprites();
// Move targeted sprites
tk2dSceneHelper.HandleMoveSprites(t, localRect);
if (GUI.changed) {
EditorUtility.SetDirty(target);
}
}
protected T[] GetTargetsOfType<T>( Object[] objects ) where T : UnityEngine.Object {
List<T> ts = new List<T>();
foreach (Object o in objects) {
T s = o as T;
if (s != null)
ts.Add(s);
}
return ts.ToArray();
}
protected void OnEnable()
{
targetSprites = GetTargetsOfType<tk2dBaseSprite>( targets );
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
List<Renderer> rs = new List<Renderer>();
foreach (var v in targetSprites) {
if (v != null && v.renderer != null) {
rs.Add(v.renderer);
}
}
renderers = rs.ToArray();
#endif
}
void OnDestroy()
{
targetSprites = new tk2dBaseSprite[0];
tk2dSpriteThumbnailCache.Done();
tk2dGrid.Done();
tk2dEditorSkin.Done();
}
// Callback and delegate
void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data)
{
tk2dUndo.RecordObjects(targetSprites, "Sprite Change");
foreach (tk2dBaseSprite s in targetSprites) {
s.SetSprite(spriteCollection, spriteId);
s.EditMode__CreateCollider();
EditorUtility.SetDirty(s);
}
}
tk2dSpriteGuiUtility.SpriteChangedCallback _spriteChangedCallbackInstance = null;
tk2dSpriteGuiUtility.SpriteChangedCallback spriteChangedCallbackInstance {
get {
if (_spriteChangedCallbackInstance == null) {
_spriteChangedCallbackInstance = new tk2dSpriteGuiUtility.SpriteChangedCallback( SpriteChangedCallbackImpl );
}
return _spriteChangedCallbackInstance;
}
}
protected void DrawSpriteEditorGUI()
{
Event ev = Event.current;
tk2dSpriteGuiUtility.SpriteSelector( targetSprites[0].Collection, targetSprites[0].spriteId, spriteChangedCallbackInstance, null );
if (targetSprites[0].Collection != null)
{
if (tk2dPreferences.inst.displayTextureThumbs) {
tk2dBaseSprite sprite = targetSprites[0];
tk2dSpriteDefinition def = sprite.GetCurrentSpriteDef();
if (sprite.Collection.version < 1 || def.texelSize == Vector2.zero)
{
string message = "";
message = "No thumbnail data.";
if (sprite.Collection.version < 1)
message += "\nPlease rebuild Sprite Collection.";
tk2dGuiUtility.InfoBox(message, tk2dGuiUtility.WarningLevel.Info);
}
else
{
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(" ");
int tileSize = 128;
Rect r = GUILayoutUtility.GetRect(tileSize, tileSize, GUILayout.ExpandWidth(false));
tk2dGrid.Draw(r);
tk2dSpriteThumbnailCache.DrawSpriteTextureInRect(r, def, Color.white);
GUILayout.EndHorizontal();
r = GUILayoutUtility.GetLastRect();
if (ev.type == EventType.MouseDown && ev.button == 0 && r.Contains(ev.mousePosition)) {
tk2dSpriteGuiUtility.SpriteSelectorPopup( sprite.Collection, sprite.spriteId, spriteChangedCallbackInstance, null );
}
}
}
Color newColor = EditorGUILayout.ColorField("Color", targetSprites[0].color);
if (newColor != targetSprites[0].color) {
tk2dUndo.RecordObjects(targetSprites, "Sprite Color");
foreach (tk2dBaseSprite s in targetSprites) {
s.color = newColor;
}
}
GUILayout.Space(8);
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
int sortingOrder = EditorGUILayout.IntField("Sorting Order In Layer", targetSprites[0].SortingOrder);
if (sortingOrder != targetSprites[0].SortingOrder) {
tk2dUndo.RecordObjects(targetSprites, "Sorting Order In Layer");
foreach (tk2dBaseSprite s in targetSprites) {
s.SortingOrder = sortingOrder;
}
}
#else
if (renderers.Length > 0) {
string sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", renderers[0].sortingLayerName);
if (sortingLayerName != renderers[0].sortingLayerName) {
tk2dUndo.RecordObjects(renderers, "Sorting Layer");
foreach (Renderer r in renderers) {
r.sortingLayerName = sortingLayerName;
}
}
int sortingOrder = EditorGUILayout.IntField("Order In Layer", targetSprites[0].SortingOrder);
if (sortingOrder != targetSprites[0].SortingOrder) {
tk2dUndo.RecordObjects(targetSprites, "Order In Layer");
tk2dUndo.RecordObjects(renderers, "Order In Layer");
foreach (tk2dBaseSprite s in targetSprites) {
s.SortingOrder = sortingOrder;
}
}
}
#endif
GUILayout.Space(8);
Vector3 newScale = EditorGUILayout.Vector3Field("Scale", targetSprites[0].scale);
if (newScale != targetSprites[0].scale)
{
tk2dUndo.RecordObjects(targetSprites, "Sprite Scale");
foreach (tk2dBaseSprite s in targetSprites) {
s.scale = newScale;
s.EditMode__CreateCollider();
}
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("HFlip", EditorStyles.miniButton))
{
tk2dUndo.RecordObjects(targetSprites, "Sprite HFlip");
foreach (tk2dBaseSprite sprite in targetSprites) {
sprite.EditMode__CreateCollider();
Vector3 scale = sprite.scale;
scale.x *= -1.0f;
sprite.scale = scale;
}
GUI.changed = true;
}
if (GUILayout.Button("VFlip", EditorStyles.miniButton))
{
tk2dUndo.RecordObjects(targetSprites, "Sprite VFlip");
foreach (tk2dBaseSprite sprite in targetSprites) {
Vector3 s = sprite.scale;
s.y *= -1.0f;
sprite.scale = s;
GUI.changed = true;
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(new GUIContent("Reset Scale", "Set scale to 1"), EditorStyles.miniButton))
{
tk2dUndo.RecordObjects(targetSprites, "Sprite Reset Scale");
foreach (tk2dBaseSprite sprite in targetSprites) {
Vector3 s = sprite.scale;
s.x = Mathf.Sign(s.x);
s.y = Mathf.Sign(s.y);
s.z = Mathf.Sign(s.z);
sprite.scale = s;
GUI.changed = true;
}
}
if (GUILayout.Button(new GUIContent("Bake Scale", "Transfer scale from transform.scale -> sprite"), EditorStyles.miniButton))
{
foreach (tk2dBaseSprite sprite in targetSprites) {
tk2dScaleUtility.Bake(sprite.transform);
}
GUI.changed = true;
}
GUIContent pixelPerfectButton = new GUIContent("1:1", "Make Pixel Perfect for camera");
if ( GUILayout.Button(pixelPerfectButton, EditorStyles.miniButton ))
{
if (tk2dPixelPerfectHelper.inst) tk2dPixelPerfectHelper.inst.Setup();
tk2dUndo.RecordObjects(targetSprites, "Sprite Pixel Perfect");
foreach (tk2dBaseSprite sprite in targetSprites) {
sprite.MakePixelPerfect();
}
GUI.changed = true;
}
EditorGUILayout.EndHorizontal();
}
else
{
tk2dGuiUtility.InfoBox("Please select a sprite collection.", tk2dGuiUtility.WarningLevel.Error);
}
bool needUpdatePrefabs = false;
if (GUI.changed)
{
foreach (tk2dBaseSprite sprite in targetSprites) {
if (PrefabUtility.GetPrefabType(sprite) == PrefabType.Prefab)
needUpdatePrefabs = true;
EditorUtility.SetDirty(sprite);
}
}
// This is a prefab, and changes need to be propagated. This isn't supported in Unity 3.4
if (needUpdatePrefabs)
{
// Rebuild prefab instances
tk2dBaseSprite[] allSprites = Resources.FindObjectsOfTypeAll(typeof(tk2dBaseSprite)) as tk2dBaseSprite[];
foreach (var spr in allSprites)
{
if (PrefabUtility.GetPrefabType(spr) == PrefabType.PrefabInstance)
{
Object parent = PrefabUtility.GetPrefabParent(spr.gameObject);
bool found = false;
foreach (tk2dBaseSprite sprite in targetSprites) {
if (sprite.gameObject == parent) {
found = true;
break;
}
}
if (found) {
// Reset all prefab states
var propMod = PrefabUtility.GetPropertyModifications(spr);
PrefabUtility.ResetToPrefabState(spr);
PrefabUtility.SetPropertyModifications(spr, propMod);
spr.ForceBuild();
}
}
}
}
}
protected void WarnSpriteRenderType(tk2dSpriteDefinition sprite) {
if (sprite.positions.Length != 4 || sprite.complexGeometry) {
EditorGUILayout.HelpBox("Sprite type incompatible with Render Mesh setting.\nPlease use Default Render Mesh.", MessageType.Error);
}
}
static void PerformActionOnGlobalSelection(string actionName, System.Action<GameObject> action) {
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo(actionName);
#else
int undoGroup = Undo.GetCurrentGroup();
#endif
foreach (GameObject go in Selection.gameObjects) {
if (go.GetComponent<tk2dBaseSprite>() != null) {
action(go);
}
}
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.CollapseUndoOperations(undoGroup);
#endif
}
static void ConvertSpriteType(GameObject go, System.Type targetType) {
tk2dBaseSprite spr = go.GetComponent<tk2dBaseSprite>();
System.Type sourceType = spr.GetType();
if (sourceType != targetType) {
tk2dBatchedSprite batchedSprite = new tk2dBatchedSprite();
tk2dStaticSpriteBatcherEditor.FillBatchedSprite(batchedSprite, go);
if (targetType == typeof(tk2dSprite)) batchedSprite.type = tk2dBatchedSprite.Type.Sprite;
else if (targetType == typeof(tk2dTiledSprite)) batchedSprite.type = tk2dBatchedSprite.Type.TiledSprite;
else if (targetType == typeof(tk2dSlicedSprite)) batchedSprite.type = tk2dBatchedSprite.Type.SlicedSprite;
else if (targetType == typeof(tk2dClippedSprite)) batchedSprite.type = tk2dBatchedSprite.Type.ClippedSprite;
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (spr.collider != null) {
Object.DestroyImmediate(spr.collider);
}
Object.DestroyImmediate(spr, true);
#else
{
Collider[] colliders = spr.GetComponents<Collider>();
foreach (Collider c in colliders) {
Undo.DestroyObjectImmediate(c);
}
Collider2D[] collider2Ds = spr.GetComponents<Collider2D>();
foreach (Collider2D c in collider2Ds) {
Undo.DestroyObjectImmediate(c);
}
}
Undo.DestroyObjectImmediate(spr);
#endif
bool sourceHasDimensions = sourceType == typeof(tk2dSlicedSprite) || sourceType == typeof(tk2dTiledSprite);
bool targetHasDimensions = targetType == typeof(tk2dSlicedSprite) || targetType == typeof(tk2dTiledSprite);
// Some minor fixups
if (!sourceHasDimensions && targetHasDimensions) {
batchedSprite.Dimensions = new Vector2(100, 100);
}
if (targetType == typeof(tk2dClippedSprite)) {
batchedSprite.ClippedSpriteRegionBottomLeft = Vector2.zero;
batchedSprite.ClippedSpriteRegionTopRight = Vector2.one;
}
if (targetType == typeof(tk2dSlicedSprite)) {
batchedSprite.SlicedSpriteBorderBottomLeft = new Vector2(0.1f, 0.1f);
batchedSprite.SlicedSpriteBorderTopRight = new Vector2(0.1f, 0.1f);
}
tk2dStaticSpriteBatcherEditor.RestoreBatchedSprite(go, batchedSprite);
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
{
tk2dBaseSprite tmpSprite = go.GetComponent<tk2dBaseSprite>();
if (tmpSprite != null) {
Undo.RegisterCreatedObjectUndo( tmpSprite, "Convert Sprite Type" );
}
}
#endif
}
}
// This is used by derived classes only
protected bool DrawCreateBoxColliderCheckbox(bool value) {
tk2dBaseSprite sprite = target as tk2dBaseSprite;
bool newCreateBoxCollider = EditorGUILayout.Toggle("Create Box Collider", value);
if (newCreateBoxCollider != value) {
tk2dUndo.RecordObjects(targetSprites, "Create Box Collider");
if (!newCreateBoxCollider) {
var boxCollider = sprite.GetComponent<BoxCollider>();
if (boxCollider != null) {
DestroyImmediate(boxCollider);
}
sprite.boxCollider = null;
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
var boxCollider2D = sprite.GetComponent<BoxCollider2D>();
if (boxCollider2D != null) {
DestroyImmediate(boxCollider2D);
}
sprite.boxCollider2D = null;
#endif
}
}
return newCreateBoxCollider;
}
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Sprite")]
static void DoConvertSprite() { PerformActionOnGlobalSelection( "Convert to Sprite", (go) => ConvertSpriteType(go, typeof(tk2dSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Sliced Sprite")]
static void DoConvertSlicedSprite() { PerformActionOnGlobalSelection( "Convert to Sliced Sprite", (go) => ConvertSpriteType(go, typeof(tk2dSlicedSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Tiled Sprite")]
static void DoConvertTiledSprite() { PerformActionOnGlobalSelection( "Convert to Tiled Sprite", (go) => ConvertSpriteType(go, typeof(tk2dTiledSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Clipped Sprite")]
static void DoConvertClippedSprite() { PerformActionOnGlobalSelection( "Convert to Clipped Sprite", (go) => ConvertSpriteType(go, typeof(tk2dClippedSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Add animator", true, 10000)]
static bool ValidateAddAnimator() {
if (Selection.activeGameObject == null) return false;
return Selection.activeGameObject.GetComponent<tk2dSpriteAnimator>() == null;
}
[MenuItem("CONTEXT/tk2dBaseSprite/Add animator", false, 10000)]
static void DoAddAnimator() {
tk2dSpriteAnimation anim = null;
int clipId = -1;
if (!tk2dSpriteAnimatorEditor.GetDefaultSpriteAnimation(out anim, out clipId)) {
EditorUtility.DisplayDialog("Create Sprite Animation", "Unable to create animated sprite as no SpriteAnimations have been found.", "Ok");
return;
}
else {
PerformActionOnGlobalSelection("Add animator", delegate(GameObject go) {
tk2dSpriteAnimator animator = go.GetComponent<tk2dSpriteAnimator>();
if (animator == null) {
animator = go.AddComponent<tk2dSpriteAnimator>();
animator.Library = anim;
animator.DefaultClipId = clipId;
tk2dSpriteAnimationClip clip = anim.GetClipById(clipId);
animator.SetSprite( clip.frames[0].spriteCollection, clip.frames[0].spriteId );
}
});
}
}
[MenuItem("CONTEXT/tk2dBaseSprite/Add AttachPoint", false, 10002)]
static void DoRemoveAnimator() {
PerformActionOnGlobalSelection("Add AttachPoint", delegate(GameObject go) {
tk2dSpriteAttachPoint ap = go.GetComponent<tk2dSpriteAttachPoint>();
if (ap == null) {
go.AddComponent<tk2dSpriteAttachPoint>();
}
});
}
[MenuItem("GameObject/Create Other/tk2d/Sprite", false, 12900)]
static void DoCreateSpriteObject()
{
tk2dSpriteGuiUtility.GetSpriteCollectionAndCreate( (sprColl) => {
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("Sprite");
tk2dSprite sprite = go.AddComponent<tk2dSprite>();
sprite.SetSprite(sprColl, sprColl.FirstValidDefinitionIndex);
sprite.renderer.material = sprColl.FirstValidDefinition.material;
sprite.Build();
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Sprite");
} );
}
}
| |
/*******************************************************************************
* Copyright (c) 2016, George Sedov
* 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.
*
* 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 UnityEngine;
using UnityEngine.UI;
using KSP.Localization;
namespace KSPPreciseManeuver {
internal static class GUIComponentManager {
static UISkinDef skin = UISkinManager.defaultSkin;
internal static void ProcessLocalization (GameObject gameObject) {
if (gameObject == null)
return;
foreach (var localizator in gameObject.GetComponentsInChildren<UI.LocalizationComponent> (true)) {
localizator.SetLocalizedString (Localizer.Format (localizator.GetTemplate ()));
Object.DestroyImmediate (localizator);
}
}
static private KSP.UI.TooltipTypes.Tooltip_Text prefab = null;
static private KSP.UI.TooltipTypes.Tooltip_Text Prefab {
get {
if (prefab == null) {
prefab = AssetBase.GetPrefab<KSP.UI.TooltipTypes.Tooltip_Text> ("Tooltip_Text");
}
return prefab;
}
}
internal static void ProcessTooltips (GameObject gameObject) {
if (gameObject == null)
return;
foreach (var tooltip in gameObject.GetComponentsInChildren<UI.TooltipComponent> (true)) {
var controller = tooltip.gameObject.AddOrGetComponent<KSP.UI.TooltipTypes.TooltipController_Text> ();
controller.SetText (tooltip.Text);
controller.prefab = Prefab;
}
}
internal static void ReplaceLabelsWithTMPro (GameObject gameObject) {
if (gameObject == null)
return;
foreach (var text in gameObject.GetComponentsInChildren<Text> (true))
if (text.gameObject.name == "Label")
ReplaceTextWithTMPro (text);
}
internal static TMPro.TextMeshProUGUI ReplaceTextWithTMPro (Text text) {
if (text == null)
return null;
var str = text.text;
var alignment = text.alignment;
var fontSize = text.fontSize;
var fontStyle = text.fontStyle;
var horizontalOverflow = text.horizontalOverflow;
var lineSpacing = text.lineSpacing;
var resizeTextForBestFit = text.resizeTextForBestFit;
var resizeTextMaxSize = text.resizeTextMaxSize;
var resizeTextMinSize = text.resizeTextMinSize;
var supportRichText = text.supportRichText;
var verticalOverflow = text.verticalOverflow;
var color = text.color;
var go = text.gameObject;
var rt = go.GetComponent<RectTransform> ();
var delta = rt.sizeDelta;
Object.DestroyImmediate (text);
var t = go.AddComponent<TMPro.TextMeshProUGUI> ();
rt.sizeDelta = delta;
t.text = str;
t.font = UISkinManager.TMPFont;
t.fontSize = fontSize;
t.lineSpacing = lineSpacing;
t.richText = supportRichText;
t.enableAutoSizing = resizeTextForBestFit;
t.fontSizeMin = resizeTextMinSize;
t.fontSizeMax = resizeTextMaxSize;
t.color = color;
t.enableWordWrapping = horizontalOverflow == HorizontalWrapMode.Wrap;
switch (fontStyle) {
case FontStyle.Normal: {
t.fontStyle = TMPro.FontStyles.Normal;
break;
}
case FontStyle.Bold: {
t.fontStyle = TMPro.FontStyles.Bold;
break;
}
case FontStyle.Italic: {
t.fontStyle = TMPro.FontStyles.Italic;
break;
}
case FontStyle.BoldAndItalic: {
t.fontStyle = TMPro.FontStyles.Bold | TMPro.FontStyles.Italic;
break;
}
}
switch (alignment) {
case TextAnchor.UpperLeft: {
t.alignment = TMPro.TextAlignmentOptions.TopLeft;
break;
}
case TextAnchor.UpperCenter: {
t.alignment = TMPro.TextAlignmentOptions.Top;
break;
}
case TextAnchor.UpperRight: {
t.alignment = TMPro.TextAlignmentOptions.TopRight;
break;
}
case TextAnchor.MiddleLeft: {
t.alignment = TMPro.TextAlignmentOptions.Left;
break;
}
case TextAnchor.MiddleCenter: {
t.alignment = TMPro.TextAlignmentOptions.Center;
break;
}
case TextAnchor.MiddleRight: {
t.alignment = TMPro.TextAlignmentOptions.Right;
break;
}
case TextAnchor.LowerLeft: {
t.alignment = TMPro.TextAlignmentOptions.BottomLeft;
break;
}
case TextAnchor.LowerCenter: {
t.alignment = TMPro.TextAlignmentOptions.Bottom;
break;
}
case TextAnchor.LowerRight: {
t.alignment = TMPro.TextAlignmentOptions.BottomRight;
break;
}
}
return t;
}
internal static void ProcessStyle (GameObject gameObject) {
if (gameObject == null)
return;
foreach (var applicator in gameObject.GetComponentsInChildren<UI.StyleApplicator> (true))
ProcessStyle (applicator);
}
private static void ProcessStyle (UI.StyleApplicator applicator) {
switch (applicator.ElementType) {
case UI.StyleApplicator.ElementTypes.Window:
applicator.SetImage (skin.window.normal.background, Image.Type.Sliced);
break;
case UI.StyleApplicator.ElementTypes.Input:
applicator.SetSelectable (skin.textField.normal.background,
skin.textField.highlight.background,
skin.textField.active.background,
skin.textField.normal.background);
break;
case UI.StyleApplicator.ElementTypes.Button:
applicator.SetSelectable (skin.button.normal.background,
skin.button.highlight.background,
skin.button.active.background,
skin.button.disabled.background);
break;
case UI.StyleApplicator.ElementTypes.ButtonToggle:
applicator.SetToggle (skin.button.normal.background,
skin.button.highlight.background,
skin.button.active.background,
skin.button.disabled.background);
break;
case UI.StyleApplicator.ElementTypes.Scrollbar:
applicator.SetScrollbar (skin.verticalScrollbarThumb.normal.background,
skin.verticalScrollbarThumb.highlight.background,
skin.verticalScrollbarThumb.active.background,
skin.verticalScrollbarThumb.disabled.background,
skin.verticalScrollbar.normal.background);
break;
case UI.StyleApplicator.ElementTypes.Slider:
applicator.SetSlider (skin.horizontalSliderThumb.normal.background,
skin.horizontalSliderThumb.highlight.background,
skin.horizontalSliderThumb.active.background,
skin.horizontalSliderThumb.disabled.background,
skin.horizontalSlider.normal.background);
break;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SubnetsOperations operations.
/// </summary>
internal partial class SubnetsOperations : IServiceOperations<NetworkManagementClient>, ISubnetsOperations
{
/// <summary>
/// Initializes a new instance of the SubnetsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubnetsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (subnetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("subnetName", subnetName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Subnet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Subnet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (subnetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("subnetName", subnetName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (subnetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetName");
}
if (subnetParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("subnetName", subnetName);
tracingParameters.Add("subnetParameters", subnetParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(subnetParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(subnetParameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Subnet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Subnet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Pomelo.EntityFrameworkCore.MySql.Internal;
using Pomelo.EntityFrameworkCore.MySql.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Metadata
{
/// <summary>
/// Properties for MySql-specific annotations accessed through
/// <see cref="MySqlMetadataExtensions.MySql(IMutableProperty)" />.
/// </summary>
public class MySqlPropertyAnnotations : RelationalPropertyAnnotations, IMySqlPropertyAnnotations
{
/// <summary>
/// Constructs an instance for annotations of the given <see cref="IProperty" />.
/// </summary>
/// <param name="property"> The <see cref="IProperty" /> to use. </param>
public MySqlPropertyAnnotations([NotNull] IProperty property)
: base(property)
{
}
/// <summary>
/// Constructs an instance for annotations of the <see cref="IProperty" />
/// represented by the given annotation helper.
/// </summary>
/// <param name="annotations">
/// The <see cref="RelationalAnnotations" /> helper representing the <see cref="IProperty" /> to annotate.
/// </param>
protected MySqlPropertyAnnotations([NotNull] RelationalAnnotations annotations)
: base(annotations)
{
}
/// <summary>
/// <para>
/// Gets or sets the <see cref="MySqlValueGenerationStrategy" /> to use for the property.
/// </para>
/// <para>
/// If no strategy is set for the property, then the strategy to use will be taken from the <see cref="IModel" />
/// </para>
/// </summary>
public virtual MySqlValueGenerationStrategy? ValueGenerationStrategy
{
get => GetMySqlValueGenerationStrategy(fallbackToModel: true);
set => SetValueGenerationStrategy(value);
}
/// <summary>
/// Gets or sets the <see cref="MySqlValueGenerationStrategy" /> to use for the property.
/// </summary>
/// <param name="fallbackToModel">
/// If <c>true</c>, then if no strategy is set for the property,
/// then the strategy to use will be taken from the <see cref="IModel" />.
/// </param>
/// <returns> The strategy, or <c>null</c> if none was set. </returns>
public virtual MySqlValueGenerationStrategy? GetMySqlValueGenerationStrategy(bool fallbackToModel)
{
var annotation = Annotations.Metadata.FindAnnotation(MySqlAnnotationNames.ValueGenerationStrategy);
if (annotation != null)
{
return (MySqlValueGenerationStrategy?)annotation.Value;
}
var relationalProperty = Property.Relational();
if (!fallbackToModel
|| relationalProperty.DefaultValue != null
|| relationalProperty.DefaultValueSql != null
|| relationalProperty.ComputedColumnSql != null)
{
return null;
}
if (Property.ValueGenerated == ValueGenerated.Never)
{
var sharedTablePrincipalPrimaryKeyProperty = Property.FindSharedTableRootPrimaryKeyProperty();
return sharedTablePrincipalPrimaryKeyProperty?.MySql().ValueGenerationStrategy;
}
if (IsCompatibleIdentityColumn(Property) && Property.ValueGenerated == ValueGenerated.OnAdd)
{
return MySqlValueGenerationStrategy.IdentityColumn;
}
if (IsCompatibleComputedColumn(Property) && Property.ValueGenerated == ValueGenerated.OnAddOrUpdate)
{
return MySqlValueGenerationStrategy.ComputedColumn;
}
return null;
}
/// <summary>
/// Sets the <see cref="MySqlValueGenerationStrategy" /> to use for the property.
/// </summary>
/// <param name="value"> The strategy to use. </param>
/// <returns> <c>True</c> if the annotation was set; <c>false</c> otherwise. </returns>
protected virtual bool SetValueGenerationStrategy(MySqlValueGenerationStrategy? value)
{
if (value != null)
{
var propertyType = Property.ClrType;
if (value == MySqlValueGenerationStrategy.IdentityColumn
&& !IsCompatibleIdentityColumn(Property))
{
if (ShouldThrowOnInvalidConfiguration)
{
throw new ArgumentException(
MySqlStrings.IdentityBadType(
Property.Name, Property.DeclaringEntityType.DisplayName(), propertyType.ShortDisplayName()));
}
return false;
}
if (value == MySqlValueGenerationStrategy.ComputedColumn
&& !IsCompatibleComputedColumn(Property))
{
if (ShouldThrowOnInvalidConfiguration)
{
throw new ArgumentException(
MySqlStrings.ComputedBadType(
Property.Name, Property.DeclaringEntityType.DisplayName(), propertyType.ShortDisplayName()));
}
return false;
}
}
if (!CanSetValueGenerationStrategy(value))
{
return false;
}
if (!ShouldThrowOnConflict
&& ValueGenerationStrategy != value
&& value != null)
{
ClearAllServerGeneratedValues();
}
return Annotations.SetAnnotation(MySqlAnnotationNames.ValueGenerationStrategy, value);
}
/// <summary>
/// Checks whether or not it is valid to set the given <see cref="MySqlValueGenerationStrategy" />
/// for the property.
/// </summary>
/// <param name="value"> The strategy to check. </param>
/// <returns> <c>True</c> if it is valid to set; <c>false</c> otherwise. </returns>
protected virtual bool CanSetValueGenerationStrategy(MySqlValueGenerationStrategy? value)
{
if (GetMySqlValueGenerationStrategy(fallbackToModel: false) == value)
{
return true;
}
if (!Annotations.CanSetAnnotation(MySqlAnnotationNames.ValueGenerationStrategy, value))
{
return false;
}
if (ShouldThrowOnConflict)
{
if (GetDefaultValue(false) != null)
{
throw new InvalidOperationException(
RelationalStrings.ConflictingColumnServerGeneration(nameof(ValueGenerationStrategy), Property.Name, nameof(DefaultValue)));
}
if (GetDefaultValueSql(false) != null)
{
throw new InvalidOperationException(
RelationalStrings.ConflictingColumnServerGeneration(nameof(ValueGenerationStrategy), Property.Name, nameof(DefaultValueSql)));
}
if (GetComputedColumnSql(false) != null)
{
throw new InvalidOperationException(
RelationalStrings.ConflictingColumnServerGeneration(nameof(ValueGenerationStrategy), Property.Name, nameof(ComputedColumnSql)));
}
}
else if (value != null
&& (!CanSetDefaultValue(null)
|| !CanSetDefaultValueSql(null)
|| !CanSetComputedColumnSql(null)))
{
return false;
}
return true;
}
/// <summary>
/// Gets the default value set for the property.
/// </summary>
/// <param name="fallback">
/// If <c>true</c>, and some MySql specific
/// <see cref="ValueGenerationStrategy" /> has been set, then this method will always
/// return <c>null</c> because these strategies do not use default values.
/// </param>
/// <returns> The default value, or <c>null</c> if none has been set. </returns>
protected override object GetDefaultValue(bool fallback)
{
if (fallback
&& ValueGenerationStrategy != null)
{
return null;
}
return base.GetDefaultValue(fallback);
}
/// <summary>
/// Checks whether or not it is valid to set a default value for the property.
/// </summary>
/// <param name="value"> The value to check. </param>
/// <returns> <c>True</c> if it is valid to set this value; <c>false</c> otherwise. </returns>
protected override bool CanSetDefaultValue(object value)
{
if (ShouldThrowOnConflict)
{
if (ValueGenerationStrategy != null)
{
throw new InvalidOperationException(
RelationalStrings.ConflictingColumnServerGeneration(nameof(DefaultValue), Property.Name, nameof(ValueGenerationStrategy)));
}
}
else if (value != null
&& !CanSetValueGenerationStrategy(null))
{
return false;
}
return base.CanSetDefaultValue(value);
}
/// <summary>
/// Gets the default SQL expression set for the property.
/// </summary>
/// <param name="fallback">
/// If <c>true</c>, and some MySql specific
/// <see cref="ValueGenerationStrategy" /> has been set, then this method will always
/// return <c>null</c> because these strategies do not use default expressions.
/// </param>
/// <returns> The default expression, or <c>null</c> if none has been set. </returns>
protected override string GetDefaultValueSql(bool fallback)
{
if (fallback
&& ValueGenerationStrategy != null)
{
return null;
}
return base.GetDefaultValueSql(fallback);
}
/// <summary>
/// Checks whether or not it is valid to set a default SQL expression for the property.
/// </summary>
/// <param name="value"> The expression to check. </param>
/// <returns> <c>True</c> if it is valid to set this expression; <c>false</c> otherwise. </returns>
protected override bool CanSetDefaultValueSql(string value)
{
if (ShouldThrowOnConflict)
{
if (ValueGenerationStrategy != null)
{
throw new InvalidOperationException(
RelationalStrings.ConflictingColumnServerGeneration(nameof(DefaultValueSql), Property.Name, nameof(ValueGenerationStrategy)));
}
}
else if (value != null
&& !CanSetValueGenerationStrategy(null))
{
return false;
}
return base.CanSetDefaultValueSql(value);
}
/// <summary>
/// Gets the computed SQL expression set for the property.
/// </summary>
/// <param name="fallback">
/// If <c>true</c>, and some MySql specific
/// <see cref="ValueGenerationStrategy" /> has been set, then this method will always
/// return <c>null</c> because these strategies do not use computed expressions.
/// </param>
/// <returns> The computed expression, or <c>null</c> if none has been set. </returns>
protected override string GetComputedColumnSql(bool fallback)
{
if (fallback
&& ValueGenerationStrategy != null)
{
return null;
}
return base.GetComputedColumnSql(fallback);
}
/// <summary>
/// Checks whether or not it is valid to set a computed SQL expression for the property.
/// </summary>
/// <param name="value"> The expression to check. </param>
/// <returns> <c>True</c> if it is valid to set this expression; <c>false</c> otherwise. </returns>
protected override bool CanSetComputedColumnSql(string value)
{
if (ShouldThrowOnConflict)
{
if (ValueGenerationStrategy != null)
{
throw new InvalidOperationException(
RelationalStrings.ConflictingColumnServerGeneration(nameof(ComputedColumnSql), Property.Name, nameof(ValueGenerationStrategy)));
}
}
else if (value != null
&& !CanSetValueGenerationStrategy(null))
{
return false;
}
return base.CanSetComputedColumnSql(value);
}
/// <summary>
/// Resets value-generation for the property to defaults.
/// </summary>
protected override void ClearAllServerGeneratedValues()
{
SetValueGenerationStrategy(null);
base.ClearAllServerGeneratedValues();
}
private static bool IsCompatibleIdentityColumn(IProperty property)
{
var type = property.ClrType;
return (type.IsInteger() || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset)) && !HasConverter(property);
}
private static bool IsCompatibleComputedColumn(IProperty property)
{
var type = property.ClrType;
return (type == typeof(DateTime) || type == typeof(DateTimeOffset)) && !HasConverter(property);
}
private static bool HasConverter(IProperty property)
=> (property.FindMapping()?.Converter
?? property.GetValueConverter()) != null;
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#if __UNIFIED__
using Foundation;
using AVFoundation;
using CoreFoundation;
using CoreGraphics;
using CoreMedia;
using CoreVideo;
using ObjCRuntime;
using UIKit;
#else
using MonoTouch.AVFoundation;
using MonoTouch.CoreFoundation;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreMedia;
using MonoTouch.CoreVideo;
using MonoTouch.Foundation;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
using System.Drawing;
using CGRect = global::System.Drawing.RectangleF;
using CGPoint = global::System.Drawing.PointF;
#endif
using ZXing.Common;
using ZXing.Mobile;
namespace ZXing.Mobile
{
public class AVCaptureScannerView : UIView, IZXingScanner<UIView>
{
public AVCaptureScannerView()
{
}
public AVCaptureScannerView(IntPtr handle) : base(handle)
{
}
public AVCaptureScannerView (CGRect frame) : base(frame)
{
}
AVCaptureSession session;
AVCaptureVideoPreviewLayer previewLayer;
//AVCaptureVideoDataOutput output;
//OutputRecorder outputRecorder;
//DispatchQueue queue;
Action<ZXing.Result> resultCallback;
volatile bool stopped = true;
//BarcodeReader barcodeReader;
volatile bool foundResult = false;
UIView layerView;
UIView overlayView = null;
public string CancelButtonText { get;set; }
public string FlashButtonText { get;set; }
MobileBarcodeScanningOptions options = new MobileBarcodeScanningOptions();
void Setup()
{
if (overlayView != null)
overlayView.RemoveFromSuperview ();
if (UseCustomOverlayView && CustomOverlayView != null)
overlayView = CustomOverlayView;
else
overlayView = new ZXingDefaultOverlayView (new CGRect(0, 0, this.Frame.Width, this.Frame.Height),
TopText, BottomText, CancelButtonText, FlashButtonText,
() => { StopScanning (); resultCallback (null); }, ToggleTorch);
if (overlayView != null)
{
/* UITapGestureRecognizer tapGestureRecognizer = new UITapGestureRecognizer ();
tapGestureRecognizer.AddTarget (() => {
var pt = tapGestureRecognizer.LocationInView(overlayView);
Focus(pt);
Console.WriteLine("OVERLAY TOUCH: " + pt.X + ", " + pt.Y);
});
tapGestureRecognizer.CancelsTouchesInView = false;
tapGestureRecognizer.NumberOfTapsRequired = 1;
tapGestureRecognizer.NumberOfTouchesRequired = 1;
overlayView.AddGestureRecognizer (tapGestureRecognizer);*/
overlayView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
overlayView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
}
}
bool torch = false;
bool analyzing = true;
bool SetupCaptureSession ()
{
// configure the capture session for low resolution, change this if your code
// can cope with more data or volume
session = new AVCaptureSession () {
SessionPreset = AVCaptureSession.Preset640x480
};
// create a device input and attach it to the session
// var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
AVCaptureDevice captureDevice = null;
var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
foreach (var device in devices)
{
captureDevice = device;
if (options.UseFrontCameraIfAvailable.HasValue &&
options.UseFrontCameraIfAvailable.Value &&
device.Position == AVCaptureDevicePosition.Front)
break; //Front camera successfully set
else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value))
break; //Back camera succesfully set
}
if (captureDevice == null){
Console.WriteLine ("No captureDevice - this won't work on the simulator, try a physical device");
if (overlayView != null)
{
this.AddSubview (overlayView);
this.BringSubviewToFront (overlayView);
}
return false;
}
var input = AVCaptureDeviceInput.FromDevice (captureDevice);
if (input == null){
Console.WriteLine ("No input - this won't work on the simulator, try a physical device");
if (overlayView != null)
{
this.AddSubview (overlayView);
this.BringSubviewToFront (overlayView);
}
return false;
}
else
session.AddInput (input);
foundResult = false;
//Detect barcodes with built in avcapture stuff
AVCaptureMetadataOutput metadataOutput = new AVCaptureMetadataOutput();
var dg = new CaptureDelegate (metaDataObjects =>
{
if (foundResult)
return;
//Console.WriteLine("Found MetaData Objects");
var mdo = metaDataObjects.FirstOrDefault();
if (mdo == null)
return;
var readableObj = mdo as AVMetadataMachineReadableCodeObject;
if (readableObj == null)
return;
foundResult = true;
//Console.WriteLine("Barcode: " + readableObj.StringValue);
var zxingFormat = ZXingBarcodeFormatFromAVCaptureBarcodeFormat(readableObj.Type.ToString());
var rs = new ZXing.Result(readableObj.StringValue, null, null, zxingFormat);
resultCallback(rs);
});
metadataOutput.SetDelegate (dg, DispatchQueue.MainQueue);
session.AddOutput (metadataOutput);
//Setup barcode formats
if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0)
{
var formats = new List<string> ();
foreach (var f in ScanningOptions.PossibleFormats)
formats.AddRange (AVCaptureBarcodeFormatFromZXingBarcodeFormat (f));
metadataOutput.MetadataObjectTypes = (from f in formats.Distinct () select new NSString(f)).ToArray();
}
else
metadataOutput.MetadataObjectTypes = metadataOutput.AvailableMetadataObjectTypes;
previewLayer = new AVCaptureVideoPreviewLayer(session);
//Framerate set here (15 fps)
if (previewLayer.RespondsToSelector(new Selector("connection")))
{
if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
{
var perf1 = PerformanceCounter.Start ();
NSError lockForConfigErr = null;
captureDevice.LockForConfiguration (out lockForConfigErr);
if (lockForConfigErr == null)
{
captureDevice.ActiveVideoMinFrameDuration = new CMTime (1, 10);
captureDevice.UnlockForConfiguration ();
}
PerformanceCounter.Stop (perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms");
}
else
previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);
}
#if __UNIFIED__
previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#else
previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#endif
previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));
layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
layerView.Layer.AddSublayer(previewLayer);
this.AddSubview(layerView);
ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);
if (overlayView != null)
{
this.AddSubview (overlayView);
this.BringSubviewToFront (overlayView);
//overlayView.LayoutSubviews ();
}
session.StartRunning ();
Console.WriteLine ("RUNNING!!!");
//output.AlwaysDiscardsLateVideoFrames = true;
Console.WriteLine("SetupCamera Finished");
//session.AddOutput (output);
//session.StartRunning ();
if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
{
NSError err = null;
if (captureDevice.LockForConfiguration(out err))
{
if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
if (captureDevice.IsExposureModeSupported (AVCaptureExposureMode.ContinuousAutoExposure))
captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
if (captureDevice.IsWhiteBalanceModeSupported (AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
else if (captureDevice.IsWhiteBalanceModeSupported (AVCaptureWhiteBalanceMode.AutoWhiteBalance))
captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
if (captureDevice.FocusPointOfInterestSupported)
captureDevice.FocusPointOfInterest = new CGPoint(0.5f, 0.5f);
if (captureDevice.ExposurePointOfInterestSupported)
captureDevice.ExposurePointOfInterest = new CGPoint (0.5f, 0.5f);
captureDevice.UnlockForConfiguration();
}
else
Console.WriteLine("Failed to Lock for Config: " + err.Description);
}
return true;
}
public void DidRotate(UIInterfaceOrientation orientation)
{
ResizePreview (orientation);
this.LayoutSubviews ();
// if (overlayView != null)
// overlayView.LayoutSubviews ();
}
public void ResizePreview (UIInterfaceOrientation orientation)
{
if (previewLayer == null)
return;
previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
if (previewLayer.RespondsToSelector (new Selector ("connection")))
{
switch (orientation)
{
case UIInterfaceOrientation.LandscapeLeft:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
break;
case UIInterfaceOrientation.LandscapeRight:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight;
break;
case UIInterfaceOrientation.Portrait:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait;
break;
case UIInterfaceOrientation.PortraitUpsideDown:
previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown;
break;
}
}
}
public void Focus(CGPoint pointOfInterest)
{
//Get the device
if (AVMediaType.Video == null)
return;
var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
if (device == null)
return;
//See if it supports focusing on a point
if (device.FocusPointOfInterestSupported && !device.AdjustingFocus)
{
NSError err = null;
//Lock device to config
if (device.LockForConfiguration(out err))
{
Console.WriteLine("Focusing at point: " + pointOfInterest.X + ", " + pointOfInterest.Y);
//Focus at the point touched
device.FocusPointOfInterest = pointOfInterest;
device.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
device.UnlockForConfiguration();
}
}
}
#region IZXingScanner implementation
public void StartScanning (MobileBarcodeScanningOptions options, Action<Result> callback)
{
if (!analyzing)
analyzing = true;
if (!stopped)
return;
Setup ();
this.options = options;
this.resultCallback = callback;
Console.WriteLine("StartScanning");
this.InvokeOnMainThread(() => {
if (!SetupCaptureSession())
{
//Setup 'simulated' view:
Console.WriteLine("Capture Session FAILED");
}
if (Runtime.Arch == Arch.SIMULATOR)
{
var simView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
simView.BackgroundColor = UIColor.LightGray;
simView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
this.InsertSubview(simView, 0);
}
});
stopped = false;
}
public void StartScanning (Action<Result> callback)
{
StartScanning (new MobileBarcodeScanningOptions (), callback);
}
public void StopScanning()
{
if (stopped)
return;
Console.WriteLine("Stopping...");
//Try removing all existing outputs prior to closing the session
try
{
while (session.Outputs.Length > 0)
session.RemoveOutput (session.Outputs [0]);
}
catch { }
//Try to remove all existing inputs prior to closing the session
try
{
while (session.Inputs.Length > 0)
session.RemoveInput (session.Inputs [0]);
}
catch { }
if (session.Running)
session.StopRunning();
stopped = true;
}
public void PauseAnalysis ()
{
analyzing = false;
}
public void ResumeAnalysis ()
{
analyzing = true;
}
public void SetTorch (bool on)
{
try
{
NSError err;
var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
device.LockForConfiguration(out err);
if (on)
{
device.TorchMode = AVCaptureTorchMode.On;
device.FlashMode = AVCaptureFlashMode.On;
}
else
{
device.TorchMode = AVCaptureTorchMode.Off;
device.FlashMode = AVCaptureFlashMode.Off;
}
device.UnlockForConfiguration();
device = null;
torch = on;
}
catch { }
}
public void ToggleTorch()
{
SetTorch(!IsTorchOn);
}
public void AutoFocus ()
{
//Doesn't do much on iOS :(
}
public string TopText { get;set; }
public string BottomText { get;set; }
public UIView CustomOverlayView { get; set; }
public bool UseCustomOverlayView { get; set; }
public MobileBarcodeScanningOptions ScanningOptions { get { return options; } }
public bool IsAnalyzing { get { return analyzing; } }
public bool IsTorchOn { get { return torch; } }
#endregion
public static bool SupportsAllRequestedBarcodeFormats(IEnumerable<BarcodeFormat> formats)
{
var supported = new List<BarcodeFormat> () {
BarcodeFormat.AZTEC, BarcodeFormat.CODE_128, BarcodeFormat.CODE_39,
BarcodeFormat.CODE_93, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8,
BarcodeFormat.PDF_417, BarcodeFormat.QR_CODE, BarcodeFormat.UPC_E,
BarcodeFormat.All_1D
};
return !formats.Any (f => !supported.Contains (f));
}
BarcodeFormat ZXingBarcodeFormatFromAVCaptureBarcodeFormat(string avMetadataObjectType)
{
if (avMetadataObjectType == AVMetadataObject.TypeAztecCode)
return BarcodeFormat.AZTEC;
if (avMetadataObjectType == AVMetadataObject.TypeCode128Code)
return BarcodeFormat.CODE_128;
if (avMetadataObjectType == AVMetadataObject.TypeCode39Code)
return BarcodeFormat.CODE_39;
if (avMetadataObjectType == AVMetadataObject.TypeCode39Mod43Code)
return BarcodeFormat.CODE_39;
if (avMetadataObjectType == AVMetadataObject.TypeCode93Code)
return BarcodeFormat.CODE_93;
if (avMetadataObjectType == AVMetadataObject.TypeEAN13Code)
return BarcodeFormat.EAN_13;
if (avMetadataObjectType == AVMetadataObject.TypeEAN8Code)
return BarcodeFormat.EAN_8;
if (avMetadataObjectType == AVMetadataObject.TypePDF417Code)
return BarcodeFormat.PDF_417;
if (avMetadataObjectType == AVMetadataObject.TypeQRCode)
return BarcodeFormat.QR_CODE;
if (avMetadataObjectType == AVMetadataObject.TypeUPCECode)
return BarcodeFormat.UPC_E;
return BarcodeFormat.QR_CODE;
}
string[] AVCaptureBarcodeFormatFromZXingBarcodeFormat(BarcodeFormat zxingBarcodeFormat)
{
List<string> formats = new List<string> ();
switch (zxingBarcodeFormat)
{
case BarcodeFormat.AZTEC:
formats.Add (AVMetadataObject.TypeAztecCode);
break;
case BarcodeFormat.CODE_128:
formats.Add (AVMetadataObject.TypeCode128Code);
break;
case BarcodeFormat.CODE_39:
formats.Add (AVMetadataObject.TypeCode39Code);
formats.Add (AVMetadataObject.TypeCode39Mod43Code);
break;
case BarcodeFormat.CODE_93:
formats.Add (AVMetadataObject.TypeCode93Code);
break;
case BarcodeFormat.EAN_13:
formats.Add (AVMetadataObject.TypeEAN13Code);
break;
case BarcodeFormat.EAN_8:
formats.Add (AVMetadataObject.TypeEAN8Code);
break;
case BarcodeFormat.PDF_417:
formats.Add (AVMetadataObject.TypePDF417Code);
break;
case BarcodeFormat.QR_CODE:
formats.Add (AVMetadataObject.TypeQRCode);
break;
case BarcodeFormat.UPC_E:
formats.Add (AVMetadataObject.TypeUPCECode);
break;
case BarcodeFormat.All_1D:
formats.Add (AVMetadataObject.TypeUPCECode);
formats.Add (AVMetadataObject.TypeEAN13Code);
formats.Add (AVMetadataObject.TypeEAN8Code);
formats.Add (AVMetadataObject.TypeCode39Code);
formats.Add (AVMetadataObject.TypeCode39Mod43Code);
formats.Add (AVMetadataObject.TypeCode93Code);
break;
case BarcodeFormat.CODABAR:
case BarcodeFormat.DATA_MATRIX:
case BarcodeFormat.ITF:
case BarcodeFormat.MAXICODE:
case BarcodeFormat.MSI:
case BarcodeFormat.PLESSEY:
case BarcodeFormat.RSS_14:
case BarcodeFormat.RSS_EXPANDED:
case BarcodeFormat.UPC_A:
//TODO: Throw exception?
break;
}
return formats.ToArray();
}
}
class CaptureDelegate : AVCaptureMetadataOutputObjectsDelegate
{
public CaptureDelegate (Action<IEnumerable<AVMetadataObject>> onCapture)
{
OnCapture = onCapture;
}
public Action<IEnumerable<AVMetadataObject>> OnCapture { get;set; }
public override void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject[] metadataObjects, AVCaptureConnection connection)
{
if (OnCapture != null && metadataObjects != null)
OnCapture (metadataObjects);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.