context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System.Linq;
using System.Threading.Tasks;
using OrchardCore.Autoroute.Models;
using OrchardCore.ContentFields.Fields;
using OrchardCore.ContentManagement;
using OrchardCore.Lists.Models;
using OrchardCore.Tests.Apis.Context;
using Xunit;
using GraphQLApi = OrchardCore.Apis.GraphQL;
namespace OrchardCore.Tests.Apis.GraphQL
{
public class BlogPostTests
{
[Fact]
public async Task ShouldListAllBlogs()
{
using (var context = new BlogContext())
{
await context.InitializeAsync();
var result = await context
.GraphQLClient
.Content
.Query("Blog", builder =>
{
builder
.WithField("contentItemId");
});
Assert.Single(result["data"]["blog"].Children()["contentItemId"]
.Where(b => b.ToString() == context.BlogContentItemId));
}
}
[Fact]
public async Task ShouldQueryByBlogPostAutoroutePart()
{
using (var context = new BlogContext())
{
await context.InitializeAsync();
var blogPostContentItemId1 = await context
.CreateContentItem("BlogPost", builder =>
{
builder
.DisplayText = "Some sorta blogpost!";
builder
.Weld(new AutoroutePart
{
Path = "Path1"
});
builder
.Weld(new ContainedPart
{
ListContentItemId = context.BlogContentItemId
});
});
var blogPostContentItemId2 = await context
.CreateContentItem("BlogPost", builder =>
{
builder
.DisplayText = "Some sorta other blogpost!";
builder
.Weld(new AutoroutePart
{
Path = "Path2"
});
builder
.Weld(new ContainedPart
{
ListContentItemId = context.BlogContentItemId
});
});
var result = await context
.GraphQLClient
.Content
.Query("BlogPost", builder =>
{
builder
.WithQueryStringArgument("where", "path", "Path1");
builder
.WithField("DisplayText");
});
Assert.Equal(
"Some sorta blogpost!",
result["data"]["blogPost"][0]["displayText"].ToString());
}
}
[Fact]
public async Task WhenThePartHasTheSameNameAsTheContentTypeShouldCollapseFieldsToContentType()
{
using (var context = new BlogContext())
{
await context.InitializeAsync();
var result = await context
.GraphQLClient
.Content
.Query("BlogPost", builder =>
{
builder.WithField("Subtitle");
});
Assert.Equal(
"Problems look mighty small from 150 miles up",
result["data"]["blogPost"][0]["subtitle"].ToString());
}
}
[Fact]
public async Task WhenCreatingABlogPostShouldBeAbleToPopulateField()
{
using (var context = new BlogContext())
{
await context.InitializeAsync();
var blogPostContentItemId = await context
.CreateContentItem("BlogPost", builder =>
{
builder
.DisplayText = "Some sorta blogpost!";
builder
.Weld("BlogPost", new ContentPart());
builder
.Alter<ContentPart>("BlogPost", (cp) =>
{
cp.Weld("Subtitle", new TextField());
cp.Alter<TextField>("Subtitle", tf =>
{
tf.Text = "Hey - Is this working!?!?!?!?";
});
});
builder
.Weld(new ContainedPart
{
ListContentItemId = context.BlogContentItemId
});
});
var result = await context
.GraphQLClient
.Content
.Query("BlogPost", builder =>
{
builder
.WithQueryStringArgument("where", "ContentItemId", blogPostContentItemId);
builder
.WithField("Subtitle");
});
Assert.Equal(
"Hey - Is this working!?!?!?!?",
result["data"]["blogPost"][0]["subtitle"].ToString());
}
}
[Fact]
public async Task ShouldQueryByStatus()
{
using (var context = new BlogContext())
{
await context.InitializeAsync();
var draft = await context
.CreateContentItem("BlogPost", builder =>
{
builder.DisplayText = "Draft blog post";
builder.Published = false;
builder.Latest = true;
builder
.Weld(new ContainedPart
{
ListContentItemId = context.BlogContentItemId
});
}, draft: true);
var result = await context.GraphQLClient.Content
.Query("blogPost(status: PUBLISHED) { displayText, published }");
Assert.Single(result["data"]["blogPost"]);
Assert.Equal(true, result["data"]["blogPost"][0]["published"]);
result = await context.GraphQLClient.Content
.Query("blogPost(status: DRAFT) { displayText, published }");
Assert.Single(result["data"]["blogPost"]);
Assert.Equal(false, result["data"]["blogPost"][0]["published"]);
result = await context.GraphQLClient.Content
.Query("blogPost(status: LATEST) { displayText, published }");
Assert.Equal(2, result["data"]["blogPost"].Count());
}
}
[Fact]
public async Task ShouldNotBeAbleToExecuteAnyQueriesWithoutPermission()
{
using var context = new SiteContext()
.WithPermissionsContext(new PermissionsContext { UsePermissionsContext = true });
await context.InitializeAsync();
var response = await context.GraphQLClient.Client.GetAsync("api/graphql");
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task ShouldReturnBlogsWithViewBlogContentPermission()
{
using var context = new SiteContext()
.WithPermissionsContext(new PermissionsContext
{
UsePermissionsContext = true,
AuthorizedPermissions = new[]
{
GraphQLApi.Permissions.ExecuteGraphQL,
Contents.Permissions.ViewContent
}
});
await context.InitializeAsync();
var result = await context.GraphQLClient.Content
.Query("blog", builder =>
{
builder.WithField("contentItemId");
});
Assert.NotEmpty(result["data"]["blog"]);
}
[Fact]
public async Task ShouldNotReturnBlogsWithoutViewBlogContentPermission()
{
using var context = new SiteContext()
.WithPermissionsContext(new PermissionsContext
{
UsePermissionsContext = true,
AuthorizedPermissions = new[]
{
GraphQLApi.Permissions.ExecuteGraphQL
}
});
await context.InitializeAsync();
var result = await context.GraphQLClient.Content
.Query("blog", builder =>
{
builder.WithField("contentItemId");
});
Assert.Equal(GraphQLApi.ValidationRules.RequiresPermissionValidationRule.ErrorCode, result["errors"][0]["extensions"]["code"]);
}
}
}
| |
// 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 UnityEditor;
using UnityEngine;
namespace Fungus.EditorUtils
{
[CustomEditor (typeof(Portrait))]
public class PortraitEditor : CommandEditor
{
protected SerializedProperty stageProp;
protected SerializedProperty displayProp;
protected SerializedProperty characterProp;
protected SerializedProperty replacedCharacterProp;
protected SerializedProperty portraitProp;
protected SerializedProperty offsetProp;
protected SerializedProperty fromPositionProp;
protected SerializedProperty toPositionProp;
protected SerializedProperty facingProp;
protected SerializedProperty useDefaultSettingsProp;
protected SerializedProperty fadeDurationProp;
protected SerializedProperty moveDurationProp;
protected SerializedProperty shiftOffsetProp;
protected SerializedProperty waitUntilFinishedProp;
protected SerializedProperty moveProp;
protected SerializedProperty shiftIntoPlaceProp;
public override void OnEnable()
{
base.OnEnable();
stageProp = serializedObject.FindProperty("stage");
displayProp = serializedObject.FindProperty("display");
characterProp = serializedObject.FindProperty("character");
replacedCharacterProp = serializedObject.FindProperty("replacedCharacter");
portraitProp = serializedObject.FindProperty("portrait");
offsetProp = serializedObject.FindProperty("offset");
fromPositionProp = serializedObject.FindProperty("fromPosition");
toPositionProp = serializedObject.FindProperty("toPosition");
facingProp = serializedObject.FindProperty("facing");
useDefaultSettingsProp = serializedObject.FindProperty("useDefaultSettings");
fadeDurationProp = serializedObject.FindProperty("fadeDuration");
moveDurationProp = serializedObject.FindProperty("moveDuration");
shiftOffsetProp = serializedObject.FindProperty("shiftOffset");
waitUntilFinishedProp = serializedObject.FindProperty("waitUntilFinished");
moveProp = serializedObject.FindProperty("move");
shiftIntoPlaceProp = serializedObject.FindProperty("shiftIntoPlace");
}
public override void DrawCommandGUI()
{
serializedObject.Update();
Portrait t = target as Portrait;
if (Stage.ActiveStages.Count > 1)
{
CommandEditor.ObjectField<Stage>(stageProp,
new GUIContent("Portrait Stage", "Stage to display the character portraits on"),
new GUIContent("<Default>"),
Stage.ActiveStages);
}
else
{
t._Stage = null;
}
// Format Enum names
string[] displayLabels = StringFormatter.FormatEnumNames(t.Display,"<None>");
displayProp.enumValueIndex = EditorGUILayout.Popup("Display", (int)displayProp.enumValueIndex, displayLabels);
string characterLabel = "Character";
if (t.Display == DisplayType.Replace)
{
CommandEditor.ObjectField<Character>(replacedCharacterProp,
new GUIContent("Replace", "Character to replace"),
new GUIContent("<None>"),
Character.ActiveCharacters);
characterLabel = "With";
}
CommandEditor.ObjectField<Character>(characterProp,
new GUIContent(characterLabel, "Character to display"),
new GUIContent("<None>"),
Character.ActiveCharacters);
bool showOptionalFields = true;
Stage s = t._Stage;
// Only show optional portrait fields once required fields have been filled...
if (t._Character != null) // Character is selected
{
if (t._Character.Portraits == null || // Character has a portraits field
t._Character.Portraits.Count <= 0 ) // Character has at least one portrait
{
EditorGUILayout.HelpBox("This character has no portraits. Please add portraits to the character's prefab before using this command.", MessageType.Error);
showOptionalFields = false;
}
if (t._Stage == null) // If default portrait stage selected
{
if (t._Stage == null) // If no default specified, try to get any portrait stage in the scene
{
s = GameObject.FindObjectOfType<Stage>();
}
}
if (s == null)
{
EditorGUILayout.HelpBox("No portrait stage has been set.", MessageType.Error);
showOptionalFields = false;
}
}
if (t.Display != DisplayType.None && t._Character != null && showOptionalFields)
{
if (t.Display != DisplayType.Hide && t.Display != DisplayType.MoveToFront)
{
// PORTRAIT
CommandEditor.ObjectField<Sprite>(portraitProp,
new GUIContent("Portrait", "Portrait representing character"),
new GUIContent("<Previous>"),
t._Character.Portraits);
if (t._Character.PortraitsFace != FacingDirection.None)
{
// FACING
// Display the values of the facing enum as <-- and --> arrows to avoid confusion with position field
string[] facingArrows = new string[]
{
"<Previous>",
"<--",
"-->",
};
facingProp.enumValueIndex = EditorGUILayout.Popup("Facing", (int)facingProp.enumValueIndex, facingArrows);
}
else
{
t.Facing = FacingDirection.None;
}
}
else
{
t._Portrait = null;
t.Facing = FacingDirection.None;
}
string toPositionPrefix = "";
if (t.Move)
{
// MOVE
EditorGUILayout.PropertyField(moveProp);
}
if (t.Move)
{
if (t.Display != DisplayType.Hide)
{
// START FROM OFFSET
EditorGUILayout.PropertyField(shiftIntoPlaceProp);
}
}
if (t.Move)
{
if (t.Display != DisplayType.Hide)
{
if (t.ShiftIntoPlace)
{
t.FromPosition = null;
// OFFSET
// Format Enum names
string[] offsetLabels = StringFormatter.FormatEnumNames(t.Offset,"<Previous>");
offsetProp.enumValueIndex = EditorGUILayout.Popup("From Offset", (int)offsetProp.enumValueIndex, offsetLabels);
}
else
{
t.Offset = PositionOffset.None;
// FROM POSITION
CommandEditor.ObjectField<RectTransform>(fromPositionProp,
new GUIContent("From Position", "Move the portrait to this position"),
new GUIContent("<Previous>"),
s.Positions);
}
}
toPositionPrefix = "To ";
}
else
{
t.ShiftIntoPlace = false;
t.FromPosition = null;
toPositionPrefix = "At ";
}
if (t.Display == DisplayType.Show || (t.Display == DisplayType.Hide && t.Move) )
{
// TO POSITION
CommandEditor.ObjectField<RectTransform>(toPositionProp,
new GUIContent(toPositionPrefix+"Position", "Move the portrait to this position"),
new GUIContent("<Previous>"),
s.Positions);
}
else
{
t.ToPosition = null;
}
if (!t.Move && t.Display != DisplayType.MoveToFront)
{
// MOVE
EditorGUILayout.PropertyField(moveProp);
}
if (t.Display != DisplayType.MoveToFront)
{
EditorGUILayout.Separator();
// USE DEFAULT SETTINGS
EditorGUILayout.PropertyField(useDefaultSettingsProp);
if (!t.UseDefaultSettings) {
// FADE DURATION
EditorGUILayout.PropertyField(fadeDurationProp);
if (t.Move)
{
// MOVE SPEED
EditorGUILayout.PropertyField(moveDurationProp);
}
if (t.ShiftIntoPlace)
{
// SHIFT OFFSET
EditorGUILayout.PropertyField(shiftOffsetProp);
}
}
}
else
{
t.Move = false;
t.UseDefaultSettings = true;
EditorGUILayout.Separator();
}
EditorGUILayout.PropertyField(waitUntilFinishedProp);
if (t._Portrait != null && t.Display != DisplayType.Hide)
{
Texture2D characterTexture = t._Portrait.texture;
float aspect = (float)characterTexture.width / (float)characterTexture.height;
Rect previewRect = GUILayoutUtility.GetAspectRect(aspect, GUILayout.Width(100), GUILayout.ExpandWidth(true));
if (characterTexture != null)
{
GUI.DrawTexture(previewRect,characterTexture,ScaleMode.ScaleToFit,true,aspect);
}
}
if (t.Display != DisplayType.Hide)
{
string portraitName = "<Previous>";
if (t._Portrait != null)
{
portraitName = t._Portrait.name;
}
string portraitSummary = " " + portraitName;
int toolbarInt = 1;
string[] toolbarStrings = {"<--", portraitSummary, "-->"};
toolbarInt = GUILayout.Toolbar (toolbarInt, toolbarStrings, GUILayout.MinHeight(20));
int portraitIndex = -1;
if (toolbarInt != 1)
{
for(int i=0; i<t._Character.Portraits.Count; i++){
if(portraitName == t._Character.Portraits[i].name)
{
portraitIndex = i;
}
}
}
if (toolbarInt == 0)
{
if(portraitIndex > 0)
{
t._Portrait = t._Character.Portraits[--portraitIndex];
}
else
{
t._Portrait = null;
}
}
if (toolbarInt == 2)
{
if(portraitIndex < t._Character.Portraits.Count-1)
{
t._Portrait = t._Character.Portraits[++portraitIndex];
}
}
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using WebSocket.Portable.Compression;
namespace WebSocket.Portable.Compression
{
internal class DeflateStream// : Stream
{
internal const int DefaultBufferSize = 8192;
// internal delegate void AsyncWriteDelegate(byte[] array, int offset, int count, bool isAsync);
// private readonly CompressionMode _mode;
// private readonly bool _leaveOpen;
// private readonly Inflater _inflater;
// private Deflater _deflater;
// private readonly byte[] _buffer;
// private int _asyncOperations;
// private readonly AsyncCallback _callBack;
// private readonly AsyncWriteDelegate _asyncWriterDelegate;
// private IFileFormatWriter _formatWriter;
// private bool _wroteHeader;
// private bool _wroteBytes;
// public DeflateStream(Stream stream, CompressionMode mode)
// : this(stream, mode, false) { }
// public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen)
// {
// if (stream == null)
// throw new ArgumentNullException("stream");
// if (CompressionMode.Compress != mode && CompressionMode.Decompress != mode)
// throw new ArgumentOutOfRangeException("mode");
// this.BaseStream = stream;
// _mode = mode;
// _leaveOpen = leaveOpen;
// switch (_mode)
// {
// case CompressionMode.Decompress:
// if (!BaseStream.CanRead)
// throw new ArgumentException("Stream is not readable.", "stream");
// _inflater = new Inflater();
// _callBack = ReadCallback;
// break;
// case CompressionMode.Compress:
// if (!BaseStream.CanWrite)
// throw new ArgumentException("Stream is not writeable", "stream");
// _deflater = new Deflater();
// _asyncWriterDelegate = this.InternalWrite;
// _callBack = WriteCallback;
// break;
// }
// _buffer = new byte[DefaultBufferSize];
// }
// // Implies mode = Compress
// public DeflateStream(Stream stream)
// : this(stream, false) { }
// // Implies mode = Compress
// public DeflateStream(Stream stream, bool leaveOpen)
// {
// if (stream == null)
// throw new ArgumentNullException("stream");
// if (!stream.CanWrite)
// throw new ArgumentException("Stream is not writeable.", "stream");
// this.BaseStream = stream;
// _mode = CompressionMode.Compress;
// _leaveOpen = leaveOpen;
// _deflater = new Deflater();
// _asyncWriterDelegate = this.InternalWrite;
// _callBack = WriteCallback;
// _buffer = new byte[DefaultBufferSize];
// }
// internal void SetFileFormatReader(IFileFormatReader reader)
// {
// if (reader != null)
// _inflater.SetFileFormatReader(reader);
// }
// internal void SetFileFormatWriter(IFileFormatWriter writer)
// {
// if (writer != null)
// _formatWriter = writer;
// }
// public Stream BaseStream { get; private set; }
// public override bool CanRead
// {
// get { return this.BaseStream != null && (_mode == CompressionMode.Decompress && this.BaseStream.CanRead); }
// }
// public override bool CanWrite
// {
// get { return this.BaseStream != null && (_mode == CompressionMode.Compress && this.BaseStream.CanWrite); }
// }
// public override bool CanSeek
// {
// get { return false; }
// }
// public override long Length
// {
// get { throw new NotSupportedException(); }
// }
// public override long Position
// {
// get { throw new NotSupportedException(); }
// set { throw new NotSupportedException(); }
// }
// public override void Flush()
// {
// this.EnsureNotDisposed();
// }
// public override long Seek(long offset, SeekOrigin origin)
// {
// throw new NotSupportedException();
// }
// public override void SetLength(long value)
// {
// throw new NotSupportedException();
// }
// public override int Read(byte[] array, int offset, int count)
// {
// this.EnsureDecompressionMode();
// this.ValidateParameters(array, offset, count);
// this.EnsureNotDisposed();
// var currentOffset = offset;
// var remainingCount = count;
// while (true)
// {
// var bytesRead = _inflater.Inflate(array, currentOffset, remainingCount);
// currentOffset += bytesRead;
// remainingCount -= bytesRead;
// if (remainingCount == 0)
// break;
// if (_inflater.Finished())
// {
// // if we finished decompressing, we can't have anything left in the outputwindow.
// Debug.Assert(_inflater.AvailableOutput == 0, "We should have copied all stuff out!");
// break;
// }
// Debug.Assert(_inflater.NeedsInput(), "We can only run into this case if we are short of input");
// var bytes = this.BaseStream.Read(_buffer, 0, _buffer.Length);
// if (bytes == 0)
// break; //Do we want to throw an exception here?
// _inflater.SetInput(_buffer, 0, bytes);
// }
// return count - remainingCount;
// }
// private void ValidateParameters(byte[] array, int offset, int count)
// {
// if (array == null)
// throw new ArgumentNullException("array");
// if (offset < 0)
// throw new ArgumentOutOfRangeException("offset");
// if (count < 0)
// throw new ArgumentOutOfRangeException("count");
// if (array.Length - offset < count)
// throw new ArgumentException("Invalid offset.");
// }
// private void EnsureNotDisposed()
// {
// if (this.BaseStream == null)
// throw new ObjectDisposedException(null);
// }
// private void EnsureDecompressionMode()
// {
// if (_mode != CompressionMode.Decompress)
// throw new InvalidOperationException();
// }
// private void EnsureCompressionMode()
// {
// if (_mode != CompressionMode.Compress)
// throw new InvalidOperationException();
// }
// public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
// {
// EnsureDecompressionMode();
// // We use this checking order for compat to earlier versions:
// if (_asyncOperations != 0)
// throw new InvalidOperationException();
// ValidateParameters(buffer, offset, count);
// EnsureNotDisposed();
// Interlocked.Increment(ref _asyncOperations);
// try
// {
// var userResult = new DeflateStreamAsyncResult(asyncState, asyncCallback, array, offset, count);
// // Try to read decompressed data in output buffer
// var bytesRead = _inflater.Inflate(buffer, offset, count);
// if (bytesRead != 0)
// {
// // If decompression output buffer is not empty, return immediately.
// // 'true' means we complete synchronously.
// userResult.InvokeCallback(true, bytesRead);
// return userResult;
// }
// if (_inflater.Finished())
// {
// // end of compression stream
// userResult.InvokeCallback(true, 0);
// return userResult;
// }
// // If there is no data on the output buffer and we are not at
// // the end of the stream, we need to get more data from the base stream
// this.BaseStream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
// userResult.CompletedSynchronously &= userResult.IsCompleted;
// return userResult;
// }
// catch
// {
// Interlocked.Decrement(ref _asyncOperations);
// throw;
// }
// }
// public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState)
// {
// this.EnsureDecompressionMode();
// // We use this checking order for compat to earlier versions:
// if (_asyncOperations != 0)
// throw new InvalidOperationException();
// this.ValidateParameters(array, offset, count);
// this.EnsureNotDisposed();
// Interlocked.Increment(ref _asyncOperations);
// try
// {
// var userResult = new DeflateStreamAsyncResult(asyncState, asyncCallback, array, offset, count);
// // Try to read decompressed data in output buffer
// var bytesRead = _inflater.Inflate(array, offset, count);
// if (bytesRead != 0)
// {
// // If decompression output buffer is not empty, return immediately.
// // 'true' means we complete synchronously.
// userResult.InvokeCallback(true, bytesRead);
// return userResult;
// }
// if (_inflater.Finished())
// {
// // end of compression stream
// userResult.InvokeCallback(true, 0);
// return userResult;
// }
// // If there is no data on the output buffer and we are not at
// // the end of the stream, we need to get more data from the base stream
// this.BaseStream.BeginRead(_buffer, 0, _buffer.Length, _callBack, userResult);
// userResult.CompletedSynchronously &= userResult.IsCompleted;
// return userResult;
// }
// catch
// {
// Interlocked.Decrement(ref _asyncOperations);
// throw;
// }
// }
// // callback function for asynchrous reading on base stream
// private void ReadCallback(IAsyncResult baseStreamResult)
// {
// var outerResult = (DeflateStreamAsyncResult)baseStreamResult.AsyncState;
// outerResult.CompletedSynchronously &= baseStreamResult.CompletedSynchronously;
// try
// {
// this.EnsureNotDisposed();
// var bytesRead = this.BaseStream.EndRead(baseStreamResult);
// if (bytesRead <= 0)
// {
// // This indicates the base stream has received EOF
// outerResult.InvokeCallback(0);
// return;
// }
// // Feed the data from base stream into decompression engine
// _inflater.SetInput(_buffer, 0, bytesRead);
// bytesRead = _inflater.Inflate(outerResult.Buffer, outerResult.Offset, outerResult.Count);
// if (bytesRead == 0 && !_inflater.Finished())
// {
// // We could have read in head information and didn't get any data.
// // Read from the base stream again.
// // Need to solve recusion.
// this.BaseStream.BeginRead(_buffer, 0, _buffer.Length, _callBack, outerResult);
// }
// else
// {
// outerResult.InvokeCallback(bytesRead);
// }
// }
// catch (Exception exc)
// {
// // Defer throwing this until EndRead where we will likely have user code on the stack.
// outerResult.InvokeCallback(exc);
// }
// }
// public override int EndRead(IAsyncResult asyncResult)
// {
// this.EnsureDecompressionMode();
// this.CheckEndXxxxLegalStateAndParams(asyncResult);
// // We checked that this will work in CheckEndXxxxLegalStateAndParams:
// var deflateStrmAsyncResult = (DeflateStreamAsyncResult)asyncResult;
// this.AwaitAsyncResultCompletion(deflateStrmAsyncResult);
// var previousException = deflateStrmAsyncResult.Result as Exception;
// if (previousException != null)
// {
// // Rethrowing will delete the stack trace. Let's help future debuggers:
// //previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace);
// throw previousException;
// }
// return (int)deflateStrmAsyncResult.Result;
// }
// public override void Write(byte[] array, int offset, int count)
// {
// this.EnsureCompressionMode();
// this.ValidateParameters(array, offset, count);
// this.EnsureNotDisposed();
// this.InternalWrite(array, offset, count, false);
// }
// // isAsync always seems to be false. why do we have it?
// internal void InternalWrite(byte[] array, int offset, int count, bool isAsync)
// {
// this.DoMaintenance(array, offset, count);
// // Write compressed the bytes we already passed to the deflater:
// this.WriteDeflaterOutput(isAsync);
// // Pass new bytes through deflater and write them too:
// _deflater.SetInput(array, offset, count);
// this.WriteDeflaterOutput(isAsync);
// }
// private void WriteDeflaterOutput(bool isAsync)
// {
// while (!_deflater.NeedsInput())
// {
// var compressedBytes = _deflater.GetDeflateOutput(_buffer);
// if (compressedBytes > 0)
// this.DoWrite(_buffer, 0, compressedBytes, isAsync);
// }
// }
// private void DoWrite(byte[] array, int offset, int count, bool isAsync)
// {
// Debug.Assert(array != null);
// Debug.Assert(count != 0);
// if (isAsync)
// {
// var result = this.BaseStream.BeginWrite(array, offset, count, null, null);
// this.BaseStream.EndWrite(result);
// }
// else
// {
// this.BaseStream.Write(array, offset, count);
// }
// }
// // Perform deflate-mode maintenance required due to custom header and footer writers
// // (e.g. set by GZipStream):
// private void DoMaintenance(byte[] array, int offset, int count)
// {
// // If no bytes written, do nothing:
// if (count <= 0)
// return;
// // Note that stream contains more than zero data bytes:
// _wroteBytes = true;
// // If no header/footer formatter present, nothing else to do:
// if (_formatWriter == null)
// return;
// // If formatter has not yet written a header, do it now:
// if (!_wroteHeader)
// {
// byte[] b = _formatWriter.GetHeader();
// this.BaseStream.Write(b, 0, b.Length);
// _wroteHeader = true;
// }
// // Inform formatter of the data bytes written:
// _formatWriter.UpdateWithBytesRead(array, offset, count);
// }
// // This is called by Dispose:
// private void PurgeBuffers(bool disposing)
// {
// if (!disposing)
// return;
// if (this.BaseStream == null)
// return;
// this.Flush();
// if (_mode != CompressionMode.Compress)
// return;
// // Some deflaters (e.g. ZLib write more than zero bytes for zero bytes inputs.
// // This round-trips and we should be ok with this, but our legacy managed deflater
// // always wrote zero output for zero input and upstack code (e.g. GZipStream)
// // took dependencies on it. Thus, make sure to only "flush" when we actually had
// // some input:
// if (_wroteBytes)
// {
// // Compress any bytes left:
// this.WriteDeflaterOutput(false);
// // Pull out any bytes left inside deflater:
// bool finished;
// do
// {
// int compressedBytes;
// finished = _deflater.Finish(_buffer, out compressedBytes);
// if (compressedBytes > 0)
// this.DoWrite(_buffer, 0, compressedBytes, false);
// }
// while (!finished);
// }
// // Write format footer:
// if (_formatWriter == null || !_wroteHeader)
// return;
// var b = _formatWriter.GetFooter();
// this.BaseStream.Write(b, 0, b.Length);
// }
// protected override void Dispose(bool disposing)
// {
// try
// {
// this.PurgeBuffers(disposing);
// }
// finally
// {
// // Close the underlying stream even if PurgeBuffers threw.
// // Stream.Close() may throw here (may or may not be due to the same error).
// // In this case, we still need to clean up internal resources, hence the inner finally blocks.
// try
// {
// if (disposing && !_leaveOpen && BaseStream != null)
// this.BaseStream.Dispose();
// }
// finally
// {
// this.BaseStream = null;
// try
// {
// if (_deflater != null)
// _deflater.Dispose();
// }
// finally
// {
// _deflater = null;
// base.Dispose(disposing);
// }
// }
// }
// }
// public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState)
// {
// this.EnsureCompressionMode();
// // We use this checking order for compat to earlier versions:
// if (_asyncOperations != 0)
// throw new InvalidOperationException();
// this.ValidateParameters(array, offset, count);
// this.EnsureNotDisposed();
// Interlocked.Increment(ref _asyncOperations);
// try
// {
// var userResult = new DeflateStreamAsyncResult(asyncState, asyncCallback, array, offset, count);
// _asyncWriterDelegate.BeginInvoke(array, offset, count, true, _callBack, userResult);
// userResult.CompletedSynchronously &= userResult.IsCompleted;
// return userResult;
// }
// catch
// {
// Interlocked.Decrement(ref _asyncOperations);
// throw;
// }
// }
// // Callback function for asynchrous reading on base stream
// private void WriteCallback(IAsyncResult asyncResult)
// {
// var outerResult = (DeflateStreamAsyncResult)asyncResult.AsyncState;
// outerResult.CompletedSynchronously &= asyncResult.CompletedSynchronously;
// try
// {
// _asyncWriterDelegate.EndInvoke(asyncResult);
// }
// catch (Exception exc)
// {
// // Defer throwing this until EndWrite where there is user code on the stack:
// outerResult.InvokeCallback(exc);
// return;
// }
// outerResult.InvokeCallback(null);
// }
// public override void EndWrite(IAsyncResult asyncResult)
// {
// this.EnsureCompressionMode();
// this.CheckEndXxxxLegalStateAndParams(asyncResult);
// // We checked that this will work in CheckEndXxxxLegalStateAndParams:
// var deflateStrmAsyncResult = (DeflateStreamAsyncResult)asyncResult;
// this.AwaitAsyncResultCompletion(deflateStrmAsyncResult);
// var previousException = deflateStrmAsyncResult.Result as Exception;
// if (previousException != null)
// {
// // Rethrowing will delete the stack trace. Let's help future debuggers:
// //previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace);
// throw previousException;
// }
// }
// private void CheckEndXxxxLegalStateAndParams(IAsyncResult asyncResult)
// {
// if (_asyncOperations != 1)
// throw new InvalidOperationException();
// if (asyncResult == null)
// throw new ArgumentNullException("asyncResult");
// this.EnsureNotDisposed();
// var myResult = asyncResult as DeflateStreamAsyncResult;
// // This should really be an ArgumentException, but we keep this for compat to previous versions:
// if (myResult == null)
// throw new ArgumentNullException("asyncResult");
// }
// private void AwaitAsyncResultCompletion(DeflateStreamAsyncResult asyncResult)
// {
// try
// {
// if (!asyncResult.IsCompleted)
// asyncResult.AsyncWaitHandle.WaitOne();
// }
// finally
// {
// Interlocked.Decrement(ref _asyncOperations);
// asyncResult.Close(); // this will just close the wait handle
// }
// }
}
}
| |
using System;
using NUnit.Framework;
using System.Drawing;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Environment;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Interactions
{
[TestFixture]
public class DragAndDropTest : DriverTestFixture
{
[SetUp]
public void SetupTest()
{
IActionExecutor actionExecutor = driver as IActionExecutor;
if (actionExecutor != null)
{
actionExecutor.ResetInputState();
}
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")]
public void DragAndDropRelative()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test1"));
Point expectedLocation = drag(img, img.Location, 150, 200);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, -50, -25);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, 0, 0);
Assert.AreEqual(expectedLocation, img.Location);
expectedLocation = drag(img, img.Location, 1, -1);
Assert.AreEqual(expectedLocation, img.Location);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")]
public void DragAndDropToElement()
{
driver.Url = dragAndDropPage;
IWebElement img1 = driver.FindElement(By.Id("test1"));
IWebElement img2 = driver.FindElement(By.Id("test2"));
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
[Test]
[Category("Javascript")]
public void DragAndDropToElementInIframe()
{
driver.Url = iframePage;
IWebElement iframe = driver.FindElement(By.TagName("iframe"));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].src = arguments[1]", iframe,
dragAndDropPage);
driver.SwitchTo().Frame(0);
IWebElement img1 = WaitFor<IWebElement>(() =>
{
try
{
IWebElement element1 = driver.FindElement(By.Id("test1"));
return element1;
}
catch (NoSuchElementException)
{
return null;
}
}, "Element with ID 'test1' not found");
IWebElement img2 = driver.FindElement(By.Id("test2"));
new Actions(driver).DragAndDrop(img2, img1).Perform();
Assert.AreEqual(img1.Location, img2.Location);
}
[Test]
[Category("Javascript")]
public void DragAndDropElementWithOffsetInIframeAtBottom()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("iframeAtBottom.html");
IWebElement iframe = driver.FindElement(By.TagName("iframe"));
driver.SwitchTo().Frame(iframe);
IWebElement img1 = driver.FindElement(By.Id("test1"));
Point initial = img1.Location;
new Actions(driver).DragAndDropToOffset(img1, 20, 20).Perform();
initial.Offset(20, 20);
Assert.AreEqual(initial, img1.Location);
}
[Test]
[Category("Javascript")]
public void DragAndDropElementWithOffsetInScrolledDiv()
{
if (TestUtilities.IsFirefox(driver) && TestUtilities.IsNativeEventsEnabled(driver))
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("dragAndDropInsideScrolledDiv.html");
IWebElement el = driver.FindElement(By.Id("test1"));
Point initial = el.Location;
new Actions(driver).DragAndDropToOffset(el, 3700, 3700).Perform();
initial.Offset(3700, 3700);
Assert.AreEqual(initial, el.Location);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")]
public void ElementInDiv()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test3"));
Point startLocation = img.Location;
Point expectedLocation = drag(img, startLocation, 100, 100);
Point endLocation = img.Location;
Assert.AreEqual(expectedLocation, endLocation);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IE, "Dragging too far in IE causes the element not to move, instead of moving to 0,0.")]
//[IgnoreBrowser(Browser.Chrome, "Dragging too far in Chrome causes the element not to move, instead of moving to 0,0.")]
[IgnoreBrowser(Browser.PhantomJS, "Dragging too far in PhantomJS causes the element not to move, as PhantomJS doesn't support dragging outside the viewport.")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")]
public void DragTooFar()
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test1"));
// Dragging too far left and up does not move the element. It will be at
// its original location after the drag.
Point originalLocation = new Point(0, 0);
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDropToOffset(img, int.MinValue, int.MinValue).Perform();
Point newLocation = img.Location;
Assert.LessOrEqual(newLocation.X, 0);
Assert.LessOrEqual(newLocation.Y, 0);
// TODO(jimevans): re-enable this test once moveto does not exceed the
// coordinates accepted by the browsers (Firefox in particular). At the
// moment, even though the maximal coordinates are limited, mouseUp
// fails because it cannot get the element at the given coordinates.
//actionProvider.DragAndDropToOffset(img, int.MaxValue, int.MaxValue).Perform();
//We don't know where the img is dragged to , but we know it's not too
//far, otherwise this function will not return for a long long time
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.Firefox, "Problem with drag off viewport. See issue #1771")]
[IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")]
public void ShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort()
{
driver.Url = dragAndDropPage;
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
int height = Convert.ToInt32(js.ExecuteScript("return window.outerHeight;"));
int width = Convert.ToInt32(js.ExecuteScript("return window.outerWidth;"));
bool mustUseOffsetHeight = width == 0 && height == 0;
if (mustUseOffsetHeight)
{
width = Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;"));
height = Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;"));
}
js.ExecuteScript("window.resizeTo(300, 300);");
if (mustUseOffsetHeight)
{
width = width + 300 - Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;"));
height = height + 300 - Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;"));
}
try
{
driver.Url = dragAndDropPage;
IWebElement img = driver.FindElement(By.Id("test3"));
Point expectedLocation = drag(img, img.Location, 100, 100);
Assert.AreEqual(expectedLocation, img.Location);
}
finally
{
js.ExecuteScript("window.resizeTo(arguments[0], arguments[1]);", width, height);
}
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")]
[IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")]
public void DragAndDropOnJQueryItems()
{
driver.Url = droppableItems;
IWebElement toDrag = driver.FindElement(By.Id("draggable"));
IWebElement dropInto = driver.FindElement(By.Id("droppable"));
// Wait until all event handlers are installed.
System.Threading.Thread.Sleep(500);
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDrop(toDrag, dropInto).Perform();
string text = dropInto.FindElement(By.TagName("p")).Text;
DateTime endTime = DateTime.Now.Add(TimeSpan.FromSeconds(15));
while (text != "Dropped!" && (DateTime.Now < endTime))
{
System.Threading.Thread.Sleep(200);
text = dropInto.FindElement(By.TagName("p")).Text;
}
Assert.AreEqual("Dropped!", text);
IWebElement reporter = driver.FindElement(By.Id("drop_reports"));
// Assert that only one mouse click took place and the mouse was moved
// during it.
string reporterText = reporter.Text;
Assert.IsTrue(Regex.IsMatch(reporterText, "start( move)* down( move)+ up"));
Assert.AreEqual(1, Regex.Matches(reporterText, "down").Count, "Reporter text:" + reporterText);
Assert.AreEqual(1, Regex.Matches(reporterText, "up").Count, "Reporter text:" + reporterText);
Assert.IsTrue(reporterText.Contains("move"), "Reporter text:" + reporterText);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Opera, "Untested")]
[IgnoreBrowser(Browser.PhantomJS, "Untested")]
[IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")]
public void CanDragAnElementNotVisibleInTheCurrentViewportDueToAParentOverflow()
{
driver.Url = dragDropOverflowPage;
IWebElement toDrag = driver.FindElement(By.Id("time-marker"));
IWebElement dragTo = driver.FindElement(By.Id("11am"));
Point srcLocation = toDrag.Location;
Point targetLocation = dragTo.Location;
int yOffset = targetLocation.Y - srcLocation.Y;
Assert.AreNotEqual(0, yOffset);
new Actions(driver).DragAndDropToOffset(toDrag, 0, yOffset).Perform();
Assert.AreEqual(dragTo.Location, toDrag.Location);
}
//[Test]
public void MemoryTest()
{
driver.Url = dragAndDropPage;
IWebElement img1 = driver.FindElement(By.Id("test1"));
IWebElement img2 = driver.FindElement(By.Id("test2"));
System.Threading.Thread.Sleep(1000);
for (int i = 0; i < 500; i++)
{
string foo = img1.GetAttribute("id");
//img1 = driver.FindElement(By.Id("test1"));
//Actions a = new Actions(driver);
//a.MoveToElement(img1).Perform();
}
driver.Url = simpleTestPage;
}
private Point drag(IWebElement elem, Point initialLocation, int moveRightBy, int moveDownBy)
{
Point expectedLocation = new Point(initialLocation.X, initialLocation.Y);
expectedLocation.Offset(moveRightBy, moveDownBy);
Actions actionProvider = new Actions(driver);
actionProvider.DragAndDropToOffset(elem, moveRightBy, moveDownBy).Perform();
return expectedLocation;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
// Do not warn about missing documentation.
#pragma warning disable 1591
namespace FalkenTests
{
public class QuaternionTest
{
[Test]
public void ConstructDefaultQuaternion()
{
Falken.RotationQuaternion quaternion = new Falken.RotationQuaternion();
Assert.AreEqual(0.0f, quaternion.X);
Assert.AreEqual(0.0f, quaternion.Y);
Assert.AreEqual(0.0f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
[Test]
public void ConstructQuaternionSameValue()
{
Falken.RotationQuaternion quaternion = new Falken.RotationQuaternion(0.5f);
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(0.5f, quaternion.Y);
Assert.AreEqual(0.5f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
[Test]
public void ConstructQuaternionDifferentComponents()
{
Falken.RotationQuaternion quaternion =
new Falken.RotationQuaternion(0.25f, 0.5f, 0.75f, 0.0f);
Assert.AreEqual(0.25f, quaternion.X);
Assert.AreEqual(0.5f, quaternion.Y);
Assert.AreEqual(0.75f, quaternion.Z);
Assert.AreEqual(0.0f, quaternion.W);
}
[Test]
public void ConstructQuaternionInternalFalkenRotation()
{
FalkenInternal.falken.Rotation falkenRotation =
new FalkenInternal.falken.Rotation();
falkenRotation.x = 0.5f;
falkenRotation.y = 0.25f;
falkenRotation.z = 0.75f;
falkenRotation.w = 0.0f;
Falken.RotationQuaternion quaternion =
new Falken.RotationQuaternion(falkenRotation);
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(0.25f, quaternion.Y);
Assert.AreEqual(0.75f, quaternion.Z);
Assert.AreEqual(0.0f, quaternion.W);
}
[Test]
public void ConstructFromDirectionVector()
{
float kDeltaTolerance = 0.01f;
// Construct from Vector3.
var position = new Falken.Vector3(0.64f, 0.768f, 0.0f);
var rotation = Falken.RotationQuaternion.FromDirectionVector(position);
// Check if the quaternion is correct.
Assert.AreEqual(-0.29f, rotation.X, kDeltaTolerance);
Assert.AreEqual(-0.29f, rotation.Y, kDeltaTolerance);
Assert.AreEqual(0.64f, rotation.Z, kDeltaTolerance);
Assert.AreEqual(0.64f, rotation.W, kDeltaTolerance);
// Construct from direction values.
var rotation2 = Falken.RotationQuaternion.FromDirectionVector(0.64f, 0.768f, 0.0f);
// Compare against the correct quaternion.
Assert.AreEqual(rotation2.X, rotation.X, kDeltaTolerance);
Assert.AreEqual(rotation2.Y, rotation.Y, kDeltaTolerance);
Assert.AreEqual(rotation2.Z, rotation.Z, kDeltaTolerance);
Assert.AreEqual(rotation2.W, rotation.W, kDeltaTolerance);
}
[Test]
public void ConstructFromEulerAngles()
{
float kDeltaTolerance = 0.01f;
// Construct from Vector3.
var angles = new Falken.EulerAngles(35.0f, 130.0f, 90.0f);
var rotation = Falken.RotationQuaternion.FromEulerAngles(angles);
// Check quaternion.
Assert.AreEqual(0.701f, rotation.X, kDeltaTolerance);
Assert.AreEqual(0.521f, rotation.Y, kDeltaTolerance);
Assert.AreEqual(0.092f, rotation.Z, kDeltaTolerance);
Assert.AreEqual(0.477f, rotation.W, kDeltaTolerance);
// Convert to euler and check values.
var convertedAngles = Falken.RotationQuaternion.ToEulerAngles(rotation);
Assert.AreEqual(angles.Roll, convertedAngles.Roll, kDeltaTolerance);
Assert.AreEqual(angles.Pitch, convertedAngles.Pitch, kDeltaTolerance);
Assert.AreEqual(angles.Yaw, convertedAngles.Yaw, kDeltaTolerance);
}
#if UNITY_5_3_OR_NEWER
[Test]
public void ConstructQuaternionUsingUnityQuaternion()
{
UnityEngine.Quaternion unityQuaternion =
new UnityEngine.Quaternion(1.0f, 0.0f, 0.0f, 1.0f);
Falken.RotationQuaternion quaternion =
new Falken.RotationQuaternion(unityQuaternion);
Assert.AreEqual(1.0f, quaternion.X);
Assert.AreEqual(0.0f, quaternion.Y);
Assert.AreEqual(0.0f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
#endif // UNITY_5_3_OR_NEWER
#if UNITY_5_3_OR_NEWER
[Test]
public void ImplicitUnityQuaternionToFalkenQuaternion()
{
Falken.RotationQuaternion quaternion =
new UnityEngine.Quaternion(1.0f, 0.0f, 0.0f, 1.0f);
Assert.AreEqual(1.0f, quaternion.X);
Assert.AreEqual(0.0f, quaternion.Y);
Assert.AreEqual(0.0f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
#endif // UNITY_5_3_OR_NEWER
#if UNITY_5_3_OR_NEWER
[Test]
public void ImplicitFalkenQuaternionToUnityQuaternion()
{
UnityEngine.Quaternion quaternion =
new Falken.RotationQuaternion(1.0f, 0.0f, 0.0f, 1.0f);
Assert.AreEqual(1.0f, quaternion.x);
Assert.AreEqual(0.0f, quaternion.y);
Assert.AreEqual(0.0f, quaternion.z);
Assert.AreEqual(1.0f, quaternion.w);
}
#endif // UNITY_5_3_OR_NEWER
}
public class FalkenQuaternionContainer : Falken.AttributeContainer
{
public Falken.RotationQuaternion quaternion =
new Falken.RotationQuaternion(0.5f, -1.0f, 0.1f, 1.0f);
}
public class FalkenCustomQuaternion
{
private Falken.RotationQuaternion _value;
public FalkenCustomQuaternion(Falken.RotationQuaternion value)
{
_value = value;
}
public Falken.RotationQuaternion Value
{
get
{
return _value;
}
}
public static implicit operator Falken.RotationQuaternion(
FalkenCustomQuaternion value) =>
value._value;
public static implicit operator FalkenCustomQuaternion(
Falken.RotationQuaternion value) =>
new FalkenCustomQuaternion(value);
}
public class CustomQuaternionContainer : Falken.AttributeContainer
{
public FalkenCustomQuaternion quaternion =
new FalkenCustomQuaternion(new Falken.RotationQuaternion(0.5f, -1.0f, 0.1f, 1.0f));
}
#if UNITY_5_3_OR_NEWER
public class UnityQuaternionContainer : Falken.AttributeContainer
{
public UnityEngine.Quaternion quaternion =
new UnityEngine.Quaternion(0.5f, -1.0f, 0.1f, 1.0f);
}
#endif // UNITY_5_3_OR_NEWER
public class InheritedRotationContainer
{
[Falken.FalkenInheritedAttribute]
public Falken.RotationQuaternion inheritedRotation =
new Falken.RotationQuaternion();
}
public class RotationAttributeTest
{
private FalkenInternal.falken.AttributeContainer _falkenContainer;
[SetUp]
public void Setup()
{
_falkenContainer = new FalkenInternal.falken.AttributeContainer();
}
[Test]
public void BindRotation()
{
FalkenQuaternionContainer rotationContainer =
new FalkenQuaternionContainer();
FieldInfo rotationField =
typeof(FalkenQuaternionContainer).GetField("quaternion");
Falken.Rotation rotation = new Falken.Rotation();
rotation.BindAttribute(rotationField, rotationContainer, _falkenContainer);
Falken.RotationQuaternion quaternion = rotation.Value;
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(-1.0f, quaternion.Y);
Assert.AreEqual(0.1f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
Assert.AreEqual("quaternion", rotation.Name);
}
[Test]
public void BindCustomRotation()
{
CustomQuaternionContainer rotationContainer =
new CustomQuaternionContainer();
FieldInfo rotationField =
typeof(CustomQuaternionContainer).GetField("quaternion");
Falken.Rotation rotation = new Falken.Rotation();
rotation.BindAttribute(rotationField, rotationContainer, _falkenContainer);
Falken.RotationQuaternion quaternion = rotation.Value;
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(-1.0f, quaternion.Y);
Assert.AreEqual(0.1f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
Assert.AreEqual("quaternion", rotation.Name);
}
[Test]
public void ModifyRotation()
{
FalkenQuaternionContainer rotationContainer =
new FalkenQuaternionContainer();
FieldInfo rotationField =
typeof(FalkenQuaternionContainer).GetField("quaternion");
Falken.Rotation rotation = new Falken.Rotation();
rotation.BindAttribute(rotationField, rotationContainer, _falkenContainer);
Falken.RotationQuaternion quaternion =
new Falken.RotationQuaternion(1.0f, 0.0f, 0.0f, 1.0f);
rotation.Value = quaternion;
quaternion = rotation.Value;
Assert.AreEqual(1.0f, quaternion.X);
Assert.AreEqual(0.0f, quaternion.Y);
Assert.AreEqual(0.0f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
rotation.Value = new Falken.RotationQuaternion(5.0f);
quaternion = rotation.Value;
Assert.AreEqual(5.0f, quaternion.X);
Assert.AreEqual(5.0f, quaternion.Y);
Assert.AreEqual(5.0f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
#if UNITY_5_3_OR_NEWER
[Test]
public void BindUnityQuaternion()
{
UnityQuaternionContainer rotationContainer = new UnityQuaternionContainer();
FieldInfo unityQuaternionField =
typeof(UnityQuaternionContainer).GetField("quaternion");
Falken.Rotation rotation = new Falken.Rotation();
rotation.BindAttribute(unityQuaternionField, rotationContainer, _falkenContainer);
Falken.RotationQuaternion quaternion = rotation.Value;
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(-1.0f, quaternion.Y);
Assert.AreEqual(0.1f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
rotation.Value = new UnityEngine.Quaternion(1.0f, 0.2f, 0.3f, 0.8f);
quaternion = rotation.Value;
Assert.AreEqual(1.0f, quaternion.X);
Assert.AreEqual(0.2f, quaternion.Y);
Assert.AreEqual(0.3f, quaternion.Z);
Assert.AreEqual(0.8f, quaternion.W);
rotationContainer.quaternion = new UnityEngine.Quaternion(-0.5496546f, 0.5617573f,
-0.2243916f, 0.576157f);
Assert.AreEqual(-0.5496546f, rotation.Value.X);
Assert.AreEqual(0.5617573f, rotation.Value.Y);
Assert.AreEqual(-0.2243916f, rotation.Value.Z);
Assert.AreEqual(0.576157f, rotation.Value.W);
rotation.Value =
new UnityEngine.Quaternion(0.4005763f, -0.4005763f, -0.79923f, 0.20077f);
Assert.AreEqual(0.4005763f, rotationContainer.quaternion.x);
Assert.AreEqual(-0.4005763f, rotationContainer.quaternion.y);
Assert.AreEqual(-0.79923f, rotationContainer.quaternion.z);
Assert.AreEqual(0.20077f, rotationContainer.quaternion.w);
}
#endif // UNITY_5_3_OR_NEWER
[Test]
public void BindInheritedRotation()
{
InheritedRotationContainer rotationContainer =
new InheritedRotationContainer();
FieldInfo rotationField =
typeof(InheritedRotationContainer).GetField("inheritedRotation");
FalkenInternal.falken.AttributeBase attribute =
new FalkenInternal.falken.AttributeBase(
_falkenContainer, rotationField.Name,
FalkenInternal.falken.AttributeBase.Type.kTypeRotation);
Falken.Rotation rotation = new Falken.Rotation();
rotation.BindAttribute(rotationField, rotationContainer, _falkenContainer);
}
[Test]
public void BindInheritedRotationNotFound()
{
InheritedRotationContainer rotationContainer =
new InheritedRotationContainer();
FieldInfo rotationField =
typeof(InheritedRotationContainer).GetField("inheritedRotation");
Falken.Rotation rotation = new Falken.Rotation();
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => rotation.BindAttribute(rotationField, rotationContainer,
_falkenContainer),
Throws.TypeOf<Falken.InheritedAttributeNotFoundException>()
.With.Message.EqualTo("Inherited field 'inheritedRotation' was not " +
"found in the container."));
}
}
[Test]
public void BindInheritedRotationTypeMismatch()
{
InheritedRotationContainer rotationContainer =
new InheritedRotationContainer();
FieldInfo rotationField =
typeof(InheritedRotationContainer).GetField("inheritedRotation");
FalkenInternal.falken.AttributeBase attribute =
new FalkenInternal.falken.AttributeBase(
_falkenContainer, "inheritedRotation",
FalkenInternal.falken.AttributeBase.Type.kTypePosition);
Falken.Rotation rotation = new Falken.Rotation();
Assert.That(() => rotation.BindAttribute(rotationField, rotationContainer,
_falkenContainer),
Throws.TypeOf<Falken.InheritedAttributeNotFoundException>()
.With.Message.EqualTo($"Inherited field '{rotationField.Name}' has a " +
$"rotation type but the attribute type " +
$"is '{attribute.type()}'"));
}
[Test]
public void WriteRotation()
{
FalkenQuaternionContainer rotationContainer =
new FalkenQuaternionContainer();
rotationContainer.BindAttributes(_falkenContainer);
//0.5f, 0.0f, 0.0f, 1.0f
Falken.Rotation attribute = (Falken.Rotation)rotationContainer["quaternion"];
Assert.AreEqual(0.5f, attribute.Value.X);
Assert.AreEqual(-1.0f, attribute.Value.Y);
Assert.AreEqual(0.1f, attribute.Value.Z);
Assert.AreEqual(1.0f, attribute.Value.W);
FalkenInternal.falken.AttributeBase internalAttribute =
attribute.InternalAttribute;
internalAttribute.set_rotation(
new FalkenInternal.falken.Rotation(5.0f, 6.0f, 7.0f, 8.0f));
attribute.Write();
Assert.AreEqual(5.0f, attribute.Value.X);
Assert.AreEqual(6.0f, attribute.Value.Y);
Assert.AreEqual(7.0f, attribute.Value.Z);
Assert.AreEqual(8.0f, attribute.Value.W);
Assert.AreEqual(5.0f, rotationContainer.quaternion.X);
Assert.AreEqual(6.0f, rotationContainer.quaternion.Y);
Assert.AreEqual(7.0f, rotationContainer.quaternion.Z);
Assert.AreEqual(8.0f, rotationContainer.quaternion.W);
}
[Test]
public void WriteCustomRotation()
{
CustomQuaternionContainer rotationContainer = new CustomQuaternionContainer();
rotationContainer.BindAttributes(_falkenContainer);
Falken.Rotation attribute = (Falken.Rotation)rotationContainer["quaternion"];
Assert.AreEqual(0.5f, attribute.Value.X);
Assert.AreEqual(-1.0f, attribute.Value.Y);
Assert.AreEqual(0.1f, attribute.Value.Z);
Assert.AreEqual(1.0f, attribute.Value.W);
FalkenInternal.falken.AttributeBase internalAttribute = attribute.InternalAttribute;
internalAttribute.set_rotation(
new FalkenInternal.falken.Rotation(5.0f, 6.0f, 7.0f, 1.0f));
attribute.Write();
Assert.AreEqual(5.0f, attribute.Value.X);
Assert.AreEqual(6.0f, attribute.Value.Y);
Assert.AreEqual(7.0f, attribute.Value.Z);
Assert.AreEqual(1.0f, attribute.Value.W);
Assert.AreEqual(5.0f, rotationContainer.quaternion.Value.X);
Assert.AreEqual(6.0f, rotationContainer.quaternion.Value.Y);
Assert.AreEqual(7.0f, rotationContainer.quaternion.Value.Z);
Assert.AreEqual(1.0f, rotationContainer.quaternion.Value.W);
}
[Test]
public void RotationValidity()
{
CustomQuaternionContainer rotationContainer = new CustomQuaternionContainer();
FieldInfo quaternionField =
typeof(CustomQuaternionContainer).GetField("quaternion");
Falken.Rotation rotation = new Falken.Rotation();
rotation.BindAttribute(quaternionField, rotationContainer, _falkenContainer);
Falken.RotationQuaternion quaternion = rotation.Value;
Assert.IsNull(rotation.ReadFieldIfValid());
rotation.Value = quaternion;
Assert.IsNotNull(rotation.ReadFieldIfValid());
rotation.InvalidateNonFalkenFieldValue();
Assert.IsNull(rotation.ReadFieldIfValid());
}
[Test]
public void RotationClampingTest()
{
CustomQuaternionContainer rotationContainer =
new CustomQuaternionContainer();
FieldInfo quaternionField =
typeof(CustomQuaternionContainer).GetField("quaternion");
Falken.Rotation attribute = new Falken.Rotation();
attribute.BindAttribute(quaternionField, rotationContainer, _falkenContainer);
var recovered_logs = new List<String>();
System.EventHandler<Falken.Log.MessageArgs> handler = (
object source, Falken.Log.MessageArgs args) =>
{
recovered_logs.Add(args.Message);
};
Falken.Log.OnMessage += handler;
// default clamping value (off)
var expected_logs = new List<String>() {
"Attempted to set the clamping configuration" +
" of attribute quaternion, which is of type Rotation" +
" and therefore it does not support clamping",
"Attempted to read the clamping configuration of attribute" +
" quaternion, which is of type Rotation and therefore it" +
" does not support clamping" };
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
attribute.EnableClamping = true;
Assert.IsTrue(attribute.EnableClamping);
}
Assert.That(recovered_logs, Is.EquivalentTo(expected_logs));
}
}
public class RotationContainerTest
{
private FalkenInternal.falken.AttributeContainer _falkenContainer;
[SetUp]
public void Setup()
{
_falkenContainer = new FalkenInternal.falken.AttributeContainer();
}
[Test]
public void BindRotationContainer()
{
FalkenQuaternionContainer rotationContainer =
new FalkenQuaternionContainer();
rotationContainer.BindAttributes(_falkenContainer);
Assert.IsTrue(rotationContainer["quaternion"] is Falken.Rotation);
Falken.Rotation rotation = (Falken.Rotation)rotationContainer["quaternion"];
Falken.RotationQuaternion quaternion = rotation.Value;
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(-1.0f, quaternion.Y);
Assert.AreEqual(0.1f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
[Test]
public void BindCustomRotationContainer()
{
CustomQuaternionContainer rotationContainer =
new CustomQuaternionContainer();
rotationContainer.BindAttributes(_falkenContainer);
Assert.IsTrue(rotationContainer["quaternion"] is Falken.Rotation);
Falken.Rotation rotation = (Falken.Rotation)rotationContainer["quaternion"];
Falken.RotationQuaternion quaternion = rotation.Value;
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(-1.0f, quaternion.Y);
Assert.AreEqual(0.1f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
#if UNITY_5_3_OR_NEWER
[Test]
public void BindUnityQuaternionContainer()
{
UnityQuaternionContainer rotationContainer =
new UnityQuaternionContainer();
rotationContainer.BindAttributes(_falkenContainer);
Assert.IsTrue(rotationContainer["quaternion"] is Falken.Rotation);
Falken.Rotation rotation = (Falken.Rotation)rotationContainer["quaternion"];
Falken.RotationQuaternion quaternion = rotation.Value;
Assert.AreEqual(0.5f, quaternion.X);
Assert.AreEqual(-1.0f, quaternion.Y);
Assert.AreEqual(0.1f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
rotation.Value = new UnityEngine.Quaternion(0.0f, 0.0f, 1.0f, 1.0f);
quaternion = rotation.Value;
Assert.AreEqual(0.0f, quaternion.X);
Assert.AreEqual(0.0f, quaternion.Y);
Assert.AreEqual(1.0f, quaternion.Z);
Assert.AreEqual(1.0f, quaternion.W);
}
#endif // UNITY_5_3_OR_NEWER
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NuGet.Test.Mocks;
using Xunit;
namespace NuGet.Test
{
public class PackageWalkerTest
{
[Fact]
public void ResolveDependenciesForInstallPackageWithUnknownDependencyThrows()
{
// Arrange
IPackage package = PackageUtility.CreatePackage("A",
"1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(),
new DependencyResolverFromRepo(new MockPackageRepository()),
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
}
[Fact]
public void ReverseDependencyWalkerUsersVersionAndIdToDetermineVisited()
{
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(package), "Unable to resolve dependency 'B'.");
IPackageOperationResolver resolver = new InstallWalker(localRepository,
new DependencyResolverFromRepo(repository.Object),
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
// Arrange
// A 1.0 -> B 1.0
IPackage packageA1 = PackageUtility.CreatePackage("A",
"1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.0]")
});
// A 2.0 -> B 2.0
IPackage packageA2 = PackageUtility.CreatePackage("A",
"2.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[2.0]")
});
IPackage packageB1 = PackageUtility.CreatePackage("B", "1.0");
IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0");
var mockRepository = new MockPackageRepository();
mockRepository.AddPackage(packageA1);
mockRepository.AddPackage(packageA2);
mockRepository.AddPackage(packageB1);
mockRepository.AddPackage(packageB2);
// Act
IDependentsResolver lookup = new DependentsWalker(mockRepository);
// Assert
Assert.Equal(0, lookup.GetDependents(packageA1).Count());
Assert.Equal(0, lookup.GetDependents(packageA2).Count());
Assert.Equal(1, lookup.GetDependents(packageB1).Count());
Assert.Equal(1, lookup.GetDependents(packageB2).Count());
}
[Fact]
public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider()
{
// Arrange
IPackage packageA = PackageUtility.CreatePackage("A",
"1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B");
var repository = new Mock<PackageRepositoryBase>();
repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable());
var dependencyProvider = repository.As<IDependencyResolver>();
dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true, DependencyVersion.Lowest))
.Returns(packageB).Verifiable();
var localRepository = new MockPackageRepository();
IPackageOperationResolver resolver = new InstallWalker(localRepository,
repository.Object,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
// Assert
Assert.Equal(2, operations.Count);
Assert.Equal(PackageAction.Install, operations.First().Action);
Assert.Equal(packageB, operations.First().Package);
Assert.Equal(PackageAction.Install, operations.Last().Action);
Assert.Equal(packageA, operations.Last().Package);
dependencyProvider.Verify();
}
[Fact]
public void ResolveDependenciesForInstallPackageResolvesDependencyWithConstraintsUsingDependencyResolver()
{
// Arrange
var packageDependency = new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.1") });
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> { packageDependency });
IPackage packageB12 = PackageUtility.CreatePackage("B", "1.2");
var repository = new Mock<PackageRepositoryBase>(MockBehavior.Strict);
repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable());
var dependencyProvider = repository.As<IDependencyResolver>();
dependencyProvider.Setup(c => c.ResolveDependency(packageDependency, It.IsAny<IPackageConstraintProvider>(), false, true, DependencyVersion.Lowest))
.Returns(packageB12).Verifiable();
var localRepository = new MockPackageRepository();
IPackageOperationResolver resolver = new InstallWalker(localRepository,
repository.Object,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
// Assert
Assert.Equal(2, operations.Count);
Assert.Equal(PackageAction.Install, operations.First().Action);
Assert.Equal(packageB12, operations.First().Package);
Assert.Equal(PackageAction.Install, operations.Last().Action);
Assert.Equal(packageA, operations.Last().Package);
dependencyProvider.Verify();
}
[Fact]
public void ResolveDependenciesForInstallCircularReferenceThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("A")
});
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.0'.");
}
[Fact]
public void ResolveDependenciesForInstallDiamondDependencyGraph()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D]
// C -> [D]
// A
// / \
// B C
// \ /
// D
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageD = PackageUtility.CreatePackage("D", "1.0");
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var packages = resolver.ResolveOperations(packageA).ToList();
// Assert
var dict = packages.ToDictionary(p => p.Package.Id);
Assert.Equal(4, packages.Count);
Assert.NotNull(dict["A"]);
Assert.NotNull(dict["B"]);
Assert.NotNull(dict["C"]);
Assert.NotNull(dict["D"]);
}
[Fact]
public void ResolveDependenciesForInstallDiamondDependencyGraphWithDifferntVersionOfSamePackage()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D >= 1, E >= 2]
// C -> [D >= 2, E >= 1]
// A
// / \
// B C
// | \ | \
// D1 E2 D2 E1
IPackage packageA = PackageUtility.CreateProjectLevelPackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreateProjectLevelPackage("B", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("D", "1.0"),
PackageDependency.CreateDependency("E", "2.0")
});
IPackage packageC = PackageUtility.CreateProjectLevelPackage("C", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("D", "2.0"),
PackageDependency.CreateDependency("E", "1.0")
});
IPackage packageD10 = PackageUtility.CreateProjectLevelPackage("D", "1.0");
IPackage packageD20 = PackageUtility.CreateProjectLevelPackage("D", "2.0");
IPackage packageE10 = PackageUtility.CreateProjectLevelPackage("E", "1.0");
IPackage packageE20 = PackageUtility.CreateProjectLevelPackage("E", "2.0");
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD20);
sourceRepository.AddPackage(packageD10);
sourceRepository.AddPackage(packageE20);
sourceRepository.AddPackage(packageE10);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
var projectOperations = resolver.ResolveOperations(packageA).ToList();
// Assert
Assert.Equal(5, operations.Count);
Assert.Equal("E", operations[0].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), operations[0].Package.Version);
Assert.Equal("B", operations[1].Package.Id);
Assert.Equal("D", operations[2].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), operations[2].Package.Version);
Assert.Equal("C", operations[3].Package.Id);
Assert.Equal("A", operations[4].Package.Id);
Assert.Equal(5, projectOperations.Count);
Assert.Equal("E", projectOperations[0].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), projectOperations[0].Package.Version);
Assert.Equal("B", projectOperations[1].Package.Id);
Assert.Equal("D", projectOperations[2].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), projectOperations[2].Package.Version);
Assert.Equal("C", projectOperations[3].Package.Id);
Assert.Equal("A", projectOperations[4].Package.Id);
}
[Fact]
public void UninstallWalkerIgnoresMissingDependencies()
{
// Arrange
var localRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D]
// C -> [D]
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageD = PackageUtility.CreatePackage("D", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(3, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["C"]);
Assert.NotNull(packages["D"]);
}
[Fact]
public void ResolveDependenciesForUninstallDiamondDependencyGraph()
{
// Arrange
var localRepository = new MockPackageRepository();
// A -> [B, C]
// B -> [D]
// C -> [D]
// A
// / \
// B C
// \ /
// D
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("D")
});
IPackage packageD = PackageUtility.CreatePackage("D", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(4, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
Assert.NotNull(packages["C"]);
Assert.NotNull(packages["D"]);
}
[Fact]
public void ResolveDependencyForInstallCircularReferenceWithDifferentVersionOfPackageReferenceThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA10 = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageA15 = PackageUtility.CreatePackage("A", "1.5",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB10 = PackageUtility.CreatePackage("B", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("A", "[1.5]")
});
sourceRepository.AddPackage(packageA10);
sourceRepository.AddPackage(packageA15);
sourceRepository.AddPackage(packageB10);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA10), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.5'.");
}
[Fact]
public void ResolvingDependencyForUpdateWithConflictingDependents()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A 1.0 -> B [1.0]
IPackage A10 = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.0]")
}, content: new[] { "a1" });
// A 2.0 -> B (any version)
IPackage A20 = PackageUtility.CreatePackage("A", "2.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
}, content: new[] { "a2" });
IPackage B10 = PackageUtility.CreatePackage("B", "1.0", content: new[] { "b1" });
IPackage B101 = PackageUtility.CreatePackage("B", "1.0.1", content: new[] { "b101" });
IPackage B20 = PackageUtility.CreatePackage("B", "2.0", content: new[] { "a2" });
localRepository.Add(A10);
localRepository.Add(B10);
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B10);
sourceRepository.AddPackage(B101);
sourceRepository.AddPackage(B20);
IPackageOperationResolver resolver = new UpdateWalker(localRepository,
sourceRepository,
new DependentsWalker(localRepository),
NullConstraintProvider.Instance,
NullLogger.Instance,
updateDependencies: true,
allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project };
// Act
var packages = resolver.ResolveOperations(B101).ToList();
// Assert
Assert.Equal(4, packages.Count);
AssertOperation("A", "1.0", PackageAction.Uninstall, packages[0]);
AssertOperation("B", "1.0", PackageAction.Uninstall, packages[1]);
AssertOperation("A", "2.0", PackageAction.Install, packages[2]);
AssertOperation("B", "1.0.1", PackageAction.Install, packages[3]);
}
[Fact]
public void ResolvingDependencyForUpdateThatHasAnUnsatisfiedConstraint()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
var constraintProvider = new Mock<IPackageConstraintProvider>();
constraintProvider.Setup(m => m.GetConstraint("B")).Returns(VersionUtility.ParseVersionSpec("[1.4]"));
constraintProvider.Setup(m => m.Source).Returns("foo");
IPackage A10 = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.5")
});
IPackage A20 = PackageUtility.CreatePackage("A", "2.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0")
});
IPackage B15 = PackageUtility.CreatePackage("B", "1.5");
IPackage B20 = PackageUtility.CreatePackage("B", "2.0");
localRepository.Add(A10);
localRepository.Add(B15);
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B15);
sourceRepository.AddPackage(B20);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
constraintProvider.Object,
null,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(A20), "Unable to resolve dependency 'B (\u2265 2.0)'.'B' has an additional constraint (= 1.4) defined in foo.");
}
[Fact]
public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetMinimumVersionThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.5")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.4");
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (\u2265 1.5)'.");
}
[Fact]
public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetExactVersionThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.5]")
});
sourceRepository.AddPackage(packageA);
IPackage packageB = PackageUtility.CreatePackage("B", "1.4");
sourceRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (= 1.5)'.");
}
[Fact]
public void ResolveOperationsForInstallSameDependencyAtDifferentLevelsInGraph()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A1 -> B1, C1
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("C", "1.0")
});
// B1
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
// C1 -> B1, D1
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("D", "1.0")
});
// D1 -> B1
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0")
});
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new InstallWalker(localRepository,
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
var packages = resolver.ResolveOperations(packageA).ToList();
Assert.Equal(4, packages.Count);
Assert.Equal("B", packages[0].Package.Id);
Assert.Equal("D", packages[1].Package.Id);
Assert.Equal("C", packages[2].Package.Id);
Assert.Equal("A", packages[3].Package.Id);
}
[Fact]
public void ResolveDependenciesForInstallSameDependencyAtDifferentLevelsInGraphDuringUpdate()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
// A1 -> B1, C1
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
content: new[] { "A1" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("C", "1.0")
});
// B1
IPackage packageB = PackageUtility.CreatePackage("B", "1.0", new[] { "B1" });
// C1 -> B1, D1
IPackage packageC = PackageUtility.CreatePackage("C", "1.0",
content: new[] { "C1" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0"),
PackageDependency.CreateDependency("D", "1.0")
});
// D1 -> B1
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
content: new[] { "A1" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "1.0")
});
// A2 -> B2, C2
IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0",
content: new[] { "A2" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0"),
PackageDependency.CreateDependency("C", "2.0")
});
// B2
IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0", new[] { "B2" });
// C2 -> B2, D2
IPackage packageC2 = PackageUtility.CreatePackage("C", "2.0",
content: new[] { "C2" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0"),
PackageDependency.CreateDependency("D", "2.0")
});
// D2 -> B2
IPackage packageD2 = PackageUtility.CreatePackage("D", "2.0",
content: new[] { "D2" },
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "2.0")
});
sourceRepository.AddPackage(packageA);
sourceRepository.AddPackage(packageB);
sourceRepository.AddPackage(packageC);
sourceRepository.AddPackage(packageD);
sourceRepository.AddPackage(packageA2);
sourceRepository.AddPackage(packageB2);
sourceRepository.AddPackage(packageC2);
sourceRepository.AddPackage(packageD2);
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UpdateWalker(localRepository,
sourceRepository,
new DependentsWalker(localRepository),
NullConstraintProvider.Instance,
NullLogger.Instance,
updateDependencies: true,
allowPrereleaseVersions: false);
var operations = resolver.ResolveOperations(packageA2).ToList();
Assert.Equal(8, operations.Count);
AssertOperation("A", "1.0", PackageAction.Uninstall, operations[0]);
AssertOperation("C", "1.0", PackageAction.Uninstall, operations[1]);
AssertOperation("D", "1.0", PackageAction.Uninstall, operations[2]);
AssertOperation("B", "1.0", PackageAction.Uninstall, operations[3]);
AssertOperation("B", "2.0", PackageAction.Install, operations[4]);
AssertOperation("D", "2.0", PackageAction.Install, operations[5]);
AssertOperation("C", "2.0", PackageAction.Install, operations[6]);
AssertOperation("A", "2.0", PackageAction.Install, operations[7]);
}
[Fact]
public void ResolveDependenciesForInstallPackageWithDependencyReturnsPackageAndDependency()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(2, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithDependentThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: false,
forceRemove: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it.");
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithDependentAndRemoveDependenciesThrows()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it.");
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithDependentAndForceReturnsPackage()
{
// Arrange
var localRepository = new MockPackageRepository();
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: false,
forceRemove: true);
// Act
var packages = resolver.ResolveOperations(packageB)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(1, packages.Count);
Assert.NotNull(packages["B"]);
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesExcludesDependencyIfDependencyInUse()
{
// Arrange
var localRepository = new MockPackageRepository();
// A 1.0 -> [B, C]
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
IPackage packageC = PackageUtility.CreatePackage("C", "1.0");
// D -> [C]
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("C"),
});
localRepository.AddPackage(packageD);
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: false);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(2, packages.Count);
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
}
[Fact]
public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesSetAndForceReturnsAllDependencies()
{
// Arrange
var localRepository = new MockPackageRepository();
// A 1.0 -> [B, C]
IPackage packageA = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
});
IPackage packageB = PackageUtility.CreatePackage("B", "1.0");
IPackage packageC = PackageUtility.CreatePackage("C", "1.0");
// D -> [C]
IPackage packageD = PackageUtility.CreatePackage("D", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("C"),
});
localRepository.AddPackage(packageA);
localRepository.AddPackage(packageB);
localRepository.AddPackage(packageC);
localRepository.AddPackage(packageD);
IPackageOperationResolver resolver = new UninstallWalker(localRepository,
new DependentsWalker(localRepository),
NullLogger.Instance,
removeDependencies: true,
forceRemove: true);
// Act
var packages = resolver.ResolveOperations(packageA)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.NotNull(packages["A"]);
Assert.NotNull(packages["B"]);
Assert.NotNull(packages["C"]);
}
[Fact]
public void ProjectInstallWalkerIgnoresSolutionLevelPackages()
{
// Arrange
var localRepository = new MockPackageRepository();
var sourceRepository = new MockPackageRepository();
IPackage projectPackage = PackageUtility.CreatePackage("A", "1.0",
dependencies: new List<PackageDependency> {
PackageDependency.CreateDependency("B", "[1.5]")
},
content: new[] { "content" });
sourceRepository.AddPackage(projectPackage);
IPackage toolsPackage = PackageUtility.CreatePackage("B", "1.5",
content: Enumerable.Empty<string>(),
tools: new[] { "init.ps1" });
sourceRepository.AddPackage(toolsPackage);
IPackageOperationResolver resolver = new UpdateWalker(localRepository,
sourceRepository,
new DependentsWalker(localRepository),
NullConstraintProvider.Instance,
NullLogger.Instance,
updateDependencies: true,
allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project };
// Act
var packages = resolver.ResolveOperations(projectPackage)
.ToDictionary(p => p.Package.Id);
// Assert
Assert.Equal(1, packages.Count);
Assert.NotNull(packages["A"]);
}
[Fact]
public void AfterPackageWalkMetaPackageIsClassifiedTheSameAsDependencies()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage metaPackage = PackageUtility.CreatePackage(
"A", "1.0",
content: Enumerable.Empty<string>(),
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
},
createRealStream: false);
IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" });
IPackage projectPackageB = PackageUtility.CreatePackage("C", "1.0", content: new[] { "contentC" });
mockRepository.AddPackage(projectPackageA);
mockRepository.AddPackage(projectPackageB);
Assert.Equal(PackageTargets.None, walker.GetPackageInfo(metaPackage).Target);
// Act
walker.Walk(metaPackage);
// Assert
Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(metaPackage).Target);
}
[Fact]
public void LocalizedIntelliSenseFileCountsAsProjectTarget()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0",
assemblyReferences: new[] { @"lib\A.dll", @"lib\A.xml" });
IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0",
dependencies: new[] { new PackageDependency("A") },
satelliteAssemblies: new[] { @"lib\fr-fr\A.xml" },
language: "fr-fr");
mockRepository.AddPackage(runtimePackage);
mockRepository.AddPackage(satellitePackage);
// Act
walker.Walk(satellitePackage);
// Assert
Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target);
}
[Fact]
public void AfterPackageWalkSatellitePackageIsClassifiedTheSameAsDependencies()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0",
assemblyReferences: new[] { @"lib\A.dll" });
IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0",
dependencies: new[] { new PackageDependency("A") },
satelliteAssemblies: new[] { @"lib\fr-fr\A.resources.dll" },
language: "fr-fr");
mockRepository.AddPackage(runtimePackage);
mockRepository.AddPackage(satellitePackage);
// Act
walker.Walk(satellitePackage);
// Assert
Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target);
}
[Fact]
public void MetaPackageWithMixedTargetsThrows()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0",
content: Enumerable.Empty<string>(),
dependencies: new List<PackageDependency> {
new PackageDependency("B"),
new PackageDependency("C")
},
createRealStream: false);
IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" });
IPackage solutionPackage = PackageUtility.CreatePackage("C", "1.0", content: Enumerable.Empty<string>(), tools: new[] { "tools" });
mockRepository.AddPackage(projectPackageA);
mockRepository.AddPackage(solutionPackage);
// Act && Assert
ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(metaPackage), "Child dependencies of dependency only packages cannot mix external and project packages.");
}
[Fact]
public void ExternalPackagesThatDepdendOnProjectLevelPackagesThrows()
{
// Arrange
var mockRepository = new MockPackageRepository();
var walker = new TestWalker(mockRepository);
IPackage solutionPackage = PackageUtility.CreatePackage(
"A", "1.0",
dependencies: new List<PackageDependency> {
new PackageDependency("B")
},
content: Enumerable.Empty<string>(),
tools: new[] { "install.ps1" });
IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" });
mockRepository.AddPackage(projectPackageA);
mockRepository.AddPackage(solutionPackage);
// Act && Assert
ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(solutionPackage), "External packages cannot depend on packages that target projects.");
}
[Fact]
public void InstallWalkerResolvesLowestMajorAndMinorVersionForDependencies()
{
// Arrange
// A 1.0 -> B 1.0
// B 1.0 -> C 1.1
// C 1.1 -> D 1.0
var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") });
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.0.1"),
A10,
PackageUtility.CreatePackage("D", "2.0"),
PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") })
};
IPackageOperationResolver resolver = new InstallWalker(
new MockPackageRepository(),
repository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.HighestPatch);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
// Assert
Assert.Equal(4, packages.Count);
Assert.Equal("D", packages[0].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), packages[0].Package.Version);
Assert.Equal("C", packages[1].Package.Id);
Assert.Equal(new SemanticVersion("1.1.3"), packages[1].Package.Version);
Assert.Equal("B", packages[2].Package.Id);
Assert.Equal(new SemanticVersion("1.0.9"), packages[2].Package.Version);
Assert.Equal("A", packages[3].Package.Id);
Assert.Equal(new SemanticVersion("1.0"), packages[3].Package.Version);
}
// Tests that when DependencyVersion is lowest, the dependency with the lowest major minor and patch version
// is picked.
[Fact]
public void InstallWalkerResolvesLowestMajorAndMinorAndPatchVersionOfListedPackagesForDependencies()
{
// Arrange
// A 1.0 -> B 1.0
// B 1.0 -> C 1.1
// C 1.1 -> D 1.0
var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") });
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }, listed: false),
PackageUtility.CreatePackage("B", "1.0.1"),
A10,
PackageUtility.CreatePackage("D", "2.0"),
PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }, listed: false),
PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") })
};
IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(),
repository,
constraintProvider: null,
logger: NullLogger.Instance,
targetFramework: null,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
// Assert
Assert.Equal(2, packages.Count);
Assert.Equal("B", packages[0].Package.Id);
Assert.Equal(new SemanticVersion("1.0.1"), packages[0].Package.Version);
Assert.Equal("A", packages[1].Package.Id);
Assert.Equal(new SemanticVersion("1.0"), packages[1].Package.Version);
}
// Tests that when DependencyVersion is HighestPatch, the dependency with the lowest major minor and highest patch version
// is picked.
[Fact]
public void InstallWalkerResolvesLowestMajorAndMinorHighestPatchVersionOfListedPackagesForDependencies()
{
// Arrange
// A 1.0 -> B 1.0
// B 1.0 -> C 1.1
// C 1.1 -> D 1.0
var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") });
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }, listed: false),
PackageUtility.CreatePackage("B", "1.0.1"),
A10,
PackageUtility.CreatePackage("D", "2.0"),
PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }, listed: false),
PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }),
PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }),
PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") })
};
IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(),
repository,
constraintProvider: null,
logger: NullLogger.Instance,
targetFramework: null,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.HighestPatch);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
// Assert
Assert.Equal(4, packages.Count);
Assert.Equal("D", packages[0].Package.Id);
Assert.Equal(new SemanticVersion("2.0"), packages[0].Package.Version);
Assert.Equal("C", packages[1].Package.Id);
Assert.Equal(new SemanticVersion("1.1.3"), packages[1].Package.Version);
Assert.Equal("B", packages[2].Package.Id);
Assert.Equal(new SemanticVersion("1.0.9"), packages[2].Package.Version);
Assert.Equal("A", packages[3].Package.Id);
Assert.Equal(new SemanticVersion("1.0"), packages[3].Package.Version);
}
[Fact]
public void ResolveOperationsForPackagesWherePackagesOrderIsDifferentFromItsDependencyOrder()
{
// Arrange
// A 1.0 -> B 1.0 to 1.5
// A 2.0 -> B 1.8
// B 1.0
// B 2.0
// C 1.0
// C 2.0
var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "[1.0, 1.5]") });
var A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.8") });
var B10 = PackageUtility.CreatePackage("B", "1.0");
var B20 = PackageUtility.CreatePackage("B", "2.0");
var C10 = PackageUtility.CreatePackage("C", "1.0");
var C20 = PackageUtility.CreatePackage("C", "2.0");
var sourceRepository = new MockPackageRepository() {
A10,
A20,
B10,
B20,
C10,
C20,
};
var localRepository = new MockPackageRepository() {
A10,
B10,
C10
};
var resolver = new InstallWalker(localRepository,
sourceRepository,
constraintProvider: NullConstraintProvider.Instance,
logger: NullLogger.Instance,
targetFramework: null,
ignoreDependencies: false,
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
var updatePackages = new List<IPackage> { A20, B20, C20 };
IList<IPackage> allUpdatePackagesByDependencyOrder;
// Act
var operations = resolver.ResolveOperations(updatePackages, out allUpdatePackagesByDependencyOrder);
// Assert
Assert.True(operations.Count == 3);
Assert.True(operations[0].Package == B20 && operations[0].Action == PackageAction.Install);
Assert.True(operations[1].Package == A20 && operations[1].Action == PackageAction.Install);
Assert.True(operations[2].Package == C20 && operations[2].Action == PackageAction.Install);
Assert.True(allUpdatePackagesByDependencyOrder[0] == B20);
Assert.True(allUpdatePackagesByDependencyOrder[1] == A20);
Assert.True(allUpdatePackagesByDependencyOrder[2] == C20);
}
private void AssertOperation(string expectedId, string expectedVersion, PackageAction expectedAction, PackageOperation operation)
{
Assert.Equal(expectedAction, operation.Action);
Assert.Equal(expectedId, operation.Package.Id);
Assert.Equal(new SemanticVersion(expectedVersion), operation.Package.Version);
}
private class TestWalker : PackageWalker
{
private readonly IPackageRepository _repository;
public TestWalker(IPackageRepository repository)
{
_repository = repository;
}
protected override IPackage ResolveDependency(PackageDependency dependency)
{
return PackageRepositoryExtensions.ResolveDependency(_repository, dependency, AllowPrereleaseVersions, false);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using WixSharp;
using WixSharp.UI.Forms;
namespace WixSharpSetup.Dialogs
{
/// <summary>
/// The logical equivalent of the standard Features dialog. Though it implement slightly
/// different user experience as it has checkboxes bound to the features instead of icons context menu
/// as MSI dialog has.
/// </summary>
public partial class FeaturesDialog : ManagedForm, IManagedDialog
{
/*https://msdn.microsoft.com/en-us/library/aa367536(v=vs.85).aspx
* ADDLOCAL - list of features to install
* REMOVE - list of features to uninstall
* ADDDEFAULT - list of features to set to their default state
* REINSTALL - list of features to repair*/
FeatureItem[] features;
/// <summary>
/// Initializes a new instance of the <see cref="FeaturesDialog"/> class.
/// </summary>
public FeaturesDialog()
{
InitializeComponent();
}
void FeaturesDialog_Load( object sender, System.EventArgs e )
{
//Debug.Assert(false);
string drawTextOnlyProp = MsiRuntime.Session.Property( "WixSharpUI_TreeNode_TexOnlyDrawing" );
bool drawTextOnly = true;
if( drawTextOnlyProp.IsNotEmpty() )
{
if( string.Compare( drawTextOnlyProp, "false", true ) == 0 )
drawTextOnly = false;
}
else
{
float dpi = this.CreateGraphics().DpiY;
if( dpi == 96 ) // the checkbox custom drawing is only compatible with 96 DPI
drawTextOnly = false;
else
drawTextOnly = true;
}
ReadOnlyTreeNode.Behavior.AttachTo( featuresTree, drawTextOnly );
banner.Image = MsiRuntime.MsiSession.GetEmbeddedBitmap( "WixUI_Bmp_Banner" );
BuildFeaturesHierarchy();
ResetLayout();
}
void ResetLayout()
{
// The form controls are properly anchored and will be correctly resized on parent form
// resizing. However the initial sizing by WinForm runtime doesn't a do good job with DPI
// other than 96. Thus manual resizing is the only reliable option apart from going WPF.
float ratio = (float)banner.Image.Width / (float)banner.Image.Height;
topPanel.Height = (int)( banner.Width / ratio );
topBorder.Top = topPanel.Height + 1;
var upShift = (int)( next.Height * 2.3 ) - bottomPanel.Height;
bottomPanel.Top -= upShift;
bottomPanel.Height += upShift;
middlePanel.Top = topBorder.Bottom + 5;
middlePanel.Height = ( bottomPanel.Top - 5 ) - middlePanel.Top;
featuresTree.Width = (int)( ( middlePanel.Width / 3.0 ) * 1.75 );
descriptionPanel.Left = featuresTree.Right + 10;
descriptionPanel.Width = middlePanel.Width - descriptionPanel.Left - 10;
}
/// <summary>
/// The collection of the features selected by user as the features to be installed.
/// </summary>
public static List<string> UserSelectedItems;
void BuildFeaturesHierarchy()
{
//Cannot use MsiRuntime.Session.Features (FeatureInfo collection).
//This WiX feature is just not implemented yet. All members except 'Name' throw InvalidHandeException
//Thus instead of using FeatureInfo just collect the names and query database for the rest of the properties.
string[] names = MsiRuntime.Session.Features.Select( x => x.Name ).ToArray();
features = names.Select( name => new FeatureItem( MsiRuntime.MsiSession, name ) ).ToArray();
//build the hierarchy tree
var rootItems = features.Where( x => x.ParentName.IsEmpty() ).ToArray();
var itemsToProcess = new Queue<FeatureItem>( rootItems ); //features to find the children for
while( itemsToProcess.Any() )
{
var item = itemsToProcess.Dequeue();
//create the view of the feature
var view = new ReadOnlyTreeNode
{
Text = item.Title,
Tag = item, //link view to model
IsReadOnly = item.DisallowAbsent,
Checked = item.DefaultIsToBeInstalled()
};
item.View = view;
if( item.Parent != null )
{
( item.Parent.View as TreeNode ).Nodes.Add( view ); //link child view to parent view
}
//find all children
features.Where( x => x.ParentName == item.Name )
.ForEach( c =>
{
c.Parent = item; //link child model to parent model
itemsToProcess.Enqueue( c ); //schedule for further processing
} );
if( UserSelectedItems != null )
view.Checked = UserSelectedItems.Contains( ( view.Tag as FeatureItem ).Name );
}
//add views to the treeView control
rootItems.Select( x => x.View )
.Cast<TreeNode>()
.ForEach( node => featuresTree.Nodes.Add( node ) );
isAutoCheckingActive = true;
}
void SaveUserSelection()
{
UserSelectedItems = features.Where( x => x.IsViewChecked() )
.Select( x => x.Name )
.ToList();
}
void back_Click( object sender, System.EventArgs e )
{
SaveUserSelection();
Shell.GoPrev();
}
void next_Click( object sender, System.EventArgs e )
{
string itemsToInstall = features.Where( x => x.IsViewChecked() )
.Select( x => x.Name )
.Join( "," );
string itemsToRemove = features.Where( x => !x.IsViewChecked() )
.Select( x => x.Name )
.Join( "," );
if( itemsToRemove.Any() )
MsiRuntime.Session["REMOVE"] = itemsToRemove;
if( itemsToInstall.Any() )
MsiRuntime.Session["ADDLOCAL"] = itemsToInstall;
SaveUserSelection();
Shell.GoNext();
}
void cancel_Click( object sender, System.EventArgs e )
{
Shell.Cancel();
}
void featuresTree_AfterSelect( object sender, TreeViewEventArgs e )
{
description.Text = e.Node.FeatureItem().Description;
}
bool isAutoCheckingActive = false;
void featuresTree_AfterCheck( object sender, TreeViewEventArgs e )
{
if( isAutoCheckingActive )
{
isAutoCheckingActive = false;
bool newState = e.Node.Checked;
var queue = new Queue<TreeNode>();
queue.EnqueueRange( e.Node.Nodes.ToArray() );
while( queue.Any() )
{
var node = queue.Dequeue();
node.Checked = newState;
queue.EnqueueRange( node.Nodes.ToArray() );
}
if( e.Node.Checked )
{
var parent = e.Node.Parent;
while( parent != null )
{
parent.Checked = true;
parent = parent.Parent;
}
}
isAutoCheckingActive = true;
}
}
void reset_LinkClicked( object sender, LinkLabelLinkClickedEventArgs e )
{
isAutoCheckingActive = false;
features.ForEach( f => f.ResetViewChecked() );
isAutoCheckingActive = true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class SizeConverterTests : StringTypeConverterTestBase<Size>
{
protected override TypeConverter Converter { get; } = new SizeConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override Size Default => new Size(1, 1);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<Size, Dictionary<string, object>>> CreateInstancePairs
{
get
{
yield return Tuple.Create(new Size(10, 20), new Dictionary<string, object>
{
["Width"] = 10,
["Height"] = 20,
});
yield return Tuple.Create(new Size(-2, 3), new Dictionary<string, object>
{
["Width"] = -2,
["Height"] = 3,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> SizeData =>
new[]
{
new object[] {0, 0},
new object[] {1, 1},
new object[] {-1, 1},
new object[] {1, -1},
new object[] {-1, -1},
new object[] {int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MaxValue},
new object[] {int.MaxValue, int.MinValue},
new object[] {int.MinValue, int.MinValue},
};
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFrom(int width, int height)
{
TestConvertFromString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData("1")]
[InlineData("1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(1, 1)},
new object[] {new PointF(1, 1)},
new object[] {new Size(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {0x10},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertTo(int width, int height)
{
TestConvertToString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void ConvertTo_NullCulture()
{
string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new Size(1, 1), typeof(string)));
}
[Fact]
public void CreateInstance_CaseSensitive()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["width"] = 1,
["Height"] = 1,
});
});
}
[Fact]
public void GetProperties()
{
var pt = new Size(1, 1);
var props = Converter.GetProperties(new Size(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1), null);
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal((object)false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1), new Attribute[0]);
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal((object)false, props["IsEmpty"].GetValue(pt));
// Pick an attibute that cannot be applied to properties to make sure everything gets filtered
props = Converter.GetProperties(null, new Size(1, 1), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")});
Assert.Equal(0, props.Count);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromInvariantString(int width, int height)
{
var point = (Size)Converter.ConvertFromInvariantString($"{width}, {height}");
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromString(int width, int height)
{
var point =
(Size)Converter.ConvertFromString(string.Format("{0}{2} {1}", width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToInvariantString(int width, int height)
{
var str = Converter.ConvertToInvariantString(new Size(width, height));
Assert.Equal($"{width}, {height}", str);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToString(int width, int height)
{
var str = Converter.ConvertToString(new Size(width, height));
Assert.Equal(string.Format("{0}{2} {1}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcContrib.TestHelper.Fakes;
using Rhino.Mocks;
namespace MvcContrib.TestHelper.FluentController
{
public class ActionExpectations<T> where T : ControllerBase, new()
{
private readonly List<Action<ActionResult>> Expectations = new List<Action<ActionResult>>();
private HttpRequestBase MockRequest { get; set; }
public ControllerBase MockController { get; set; }
/// <summary>
/// Shoulds the specified assertion.
/// <example>
/// <code>
/// [TestClass]
/// public class UserControllerRedirectsTest
/// {
/// [TestMethod]
/// public void CreateReturnsOK()
/// {
/// GivenController.As<UserController>()
/// .Should(x => x.AssertResultIs<HeadResult>().StatusCode.ShouldBe(HttpStatusCode.OK))
/// .WhenCalling(x => x.Create());
/// }
/// </code>
/// </example>
/// </summary>
/// <param name="assertion">The assertion.</param>
/// <returns></returns>
public ActionExpectations<T> Should(Action<ActionResult> assertion)
{
if(assertion != null)
{
Expectations.Add(assertion);
}
return this;
}
/// <summary>
/// Shoulds the specified assertion.
/// This version also takes a reference to the mock controller for additional verifications
/// <example>
/// <code>
/// [TestClass]
/// public class UserControllerRedirectsTest
/// {
/// [TestMethod]
/// public void CreateReturnsOK()
/// {
/// GivenController.As<UserController>()
/// .Should((controller, actionResult) => actionResult.AssertResultIs<HeadResult>().StatusCode.ShouldBe(HttpStatusCode.OK))
/// .WhenCalling(x => x.Create());
/// }
/// </code>
/// </example>
/// </summary>
/// <param name="assertion"></param>
/// <returns></returns>
public ActionExpectations<T> ShouldController(Action<IController, ActionResult> assertion)
{
if(assertion != null)
{
Expectations.Add(actionResult => assertion(MockController, actionResult));
}
return this;
}
/// <summary>
/// Specifies setup on the mock controller. This should be used when setting
/// up the test case.
/// <example>
/// <code>
/// GivenController.As<UserController>()
/// .WithSetup(x => x.SessionRepository = new Mock<ISessionRepository>())
/// .WhenCalling(x => x.Get());
/// </code>
/// </example>
/// </summary>
/// <param name="setupAction">An action that is used to setup values on the mock controller. It is passed
/// an instance of the mock controller.</param>
/// <returns>An instance of this option to allow chaining.</returns>
public ActionExpectations<T> WithSetup(Action<IController> setupAction)
{
if(setupAction != null)
{
setupAction(MockController);
}
return this;
}
/// <summary>
/// Creates the setup conditions for a <see cref="GivenController"/>.As with the <see cref="RequestContext"/> to allow for mocking on the object.
/// This is the full version and there are shorter wrapper for specific headers <see cref="WithLocation"/>, <see cref="WithReferrer"/> and <see cref="WithUserAgent"/>.
/// <example>
/// <code>
/// GivenController.As<UserController>()
/// .Should(x => x.AssertResultIs<HeadResult>().StatusCode.ShouldBe(HttpStatusCode.OK))
/// .WhenCalling(x => x.Show());
/// </code>
/// </example>
/// </summary>
/// <param name="setupAction">The setup action.</param>
/// <returns></returns>
public ActionExpectations<T> WithRequest(Action<HttpRequestBase> setupAction)
{
if(setupAction != null)
{
if(MockRequest == null)
{
var fakeHttpContext = FakeHttpContext.Root();
MockRequest = MockRepository.GenerateMock<HttpRequestBase>();
var mockResponse = MockRepository.GenerateMock<HttpResponseBase>();
fakeHttpContext.SetResponse(mockResponse);
fakeHttpContext.SetRequest(MockRequest);
MockController.ControllerContext = new ControllerContext(new RequestContext(fakeHttpContext, new RouteData()),
MockController);
}
setupAction(MockRequest);
}
return this;
}
/// <summary>
/// Creates the Location Header on a Requestfor a <see cref="GivenController"/>.As with the <see cref="RequestContext"/>.
/// <example>
/// <code>
/// GivenController.As<UserController>()
/// .Should(x => x.WithLocation("http://from-somewhere.com"))
/// .WhenCalling(x => x.Show());
/// </code>
/// </example>
/// </summary>
/// <param name="headerLocation">The header location.</param>
/// <returns></returns>
public ActionExpectations<T> WithLocation(string headerLocation)
{
WithRequest(x => x.Stub(location => location.Url).Return(new Uri(headerLocation)));
return this;
}
/// <summary>
/// Creates the Referrer Header on a Requestfor a <see cref="GivenController"/>.As with the <see cref="RequestContext"/>.
/// <example>
/// <code>
/// GivenController.As<UserController>()
/// .Should(x => x.WithReferrer("http://referred-from-somewhereelse.org"))
/// .WhenCalling(x => x.Show());
/// </code>
/// </example>
/// </summary>
/// <returns></returns>
public ActionExpectations<T> WithReferrer(string headerReferrer)
{
WithRequest(x => x.Stub(location => location.UrlReferrer).Return(new Uri(headerReferrer)));
return this;
}
/// <summary>
/// Creates the UserAgent Header on a Requestfor a <see cref="GivenController"/>.As with the <see cref="RequestContext"/>.
/// <example>
/// <code>
/// GivenController.As<UserController>()
/// .Should(x => x.WithUserAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12 (.NET CLR 3.5.30729)"))
/// .WhenCalling(x => x.Show());
/// </code>
/// </example>
/// </summary>
/// <param name="headerUserAgent">The header location.</param>
/// <returns></returns>
public ActionExpectations<T> WithUserAgent(string headerUserAgent)
{
WithRequest(x => x.Stub(location => location.UserAgent).Return(headerUserAgent));
return this;
}
/// <summary>
/// Whens the calling. This returns void as it should be the last action in a chain of commands.
///
/// <example>
/// <code>
/// [TestClass]
/// public class UserControllerRedirectsTest
/// {
/// [TestMethod]
/// public void SuccessfulCreateRedirectsToIndex()
/// {
/// GivenController.As<UserController>()
/// .ShouldRedirectTo("Index")
/// .IfCallSucceeds()
/// .WhenCalling(x => x.Create(null));
/// }
///
/// [TestMethod]
/// public void UnsuccessfulCreateDisplaysNew()
/// {
/// GivenController.As<UserController>()
/// .ShouldRenderView("New")
/// .IfCallFails()
/// .WhenCalling(x => x.Create(null));
/// }
///
/// [TestMethod]
/// public void NewReturnsItself()
/// {
/// GivenController.As<UserController>()
/// .ShouldRenderItself("New")
/// .WhenCalling(x => x.New());
/// }
/// </code>
/// </example>
/// </summary>
/// <param name="action">The action.</param>
public void WhenCalling(Func<T, ActionResult> action)
{
ActionResult actionResult = action((T)MockController);
Expectations.ForEach(x => x(actionResult));
MockController.VerifyAllExpectations();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.Admin;
using OrchardCore.AdminMenu.Services;
using OrchardCore.AdminMenu.ViewModels;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.Routing;
using OrchardCore.Settings;
namespace OrchardCore.AdminMenu.Controllers
{
[Admin]
public class MenuController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly IAdminMenuService _adminMenuService;
private readonly ISiteService _siteService;
private readonly INotifier _notifier;
private readonly IStringLocalizer S;
private readonly IHtmlLocalizer H;
private readonly dynamic New;
private readonly ILogger _logger;
public MenuController(
IAuthorizationService authorizationService,
IAdminMenuService adminMenuService,
ISiteService siteService,
IShapeFactory shapeFactory,
INotifier notifier,
IStringLocalizer<MenuController> stringLocalizer,
IHtmlLocalizer<MenuController> htmlLocalizer,
ILogger<MenuController> logger)
{
_authorizationService = authorizationService;
_adminMenuService = adminMenuService;
_siteService = siteService;
New = shapeFactory;
_notifier = notifier;
S = stringLocalizer;
H = htmlLocalizer;
_logger = logger;
}
public async Task<IActionResult> List(ContentOptions options, PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
var adminMenuList = (await _adminMenuService.GetAdminMenuListAsync()).AdminMenu;
if (!string.IsNullOrWhiteSpace(options.Search))
{
adminMenuList = adminMenuList.Where(x => x.Name.Contains(options.Search, StringComparison.OrdinalIgnoreCase)).ToList();
}
var count = adminMenuList.Count();
var startIndex = pager.GetStartIndex();
var pageSize = pager.PageSize;
IEnumerable<Models.AdminMenu> results = new List<Models.AdminMenu>();
//todo: handle the case where there is a deserialization exception on some of the presets.
// load at least the ones without error. Provide a way to delete the ones on error.
try
{
results = adminMenuList
.Skip(startIndex)
.Take(pageSize)
.ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error when retrieving the list of admin menus.");
await _notifier.ErrorAsync(H["Error when retrieving the list of admin menus."]);
}
// Maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Search", options.Search);
var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData);
var model = new AdminMenuListViewModel
{
AdminMenu = results.Select(x => new AdminMenuEntry { AdminMenu = x }).ToList(),
Options = options,
Pager = pagerShape
};
model.Options.ContentsBulkAction = new List<SelectListItem>() {
new SelectListItem() { Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove) }
};
return View(model);
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(AdminMenuListViewModel model)
{
return RedirectToAction(nameof(List), new RouteValueDictionary {
{ "Options.Search", model.Options.Search }
});
}
public async Task<IActionResult> Create()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var model = new AdminMenuCreateViewModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(AdminMenuCreateViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
if (ModelState.IsValid)
{
var tree = new Models.AdminMenu { Name = model.Name };
await _adminMenuService.SaveAsync(tree);
return RedirectToAction(nameof(List));
}
return View(model);
}
public async Task<IActionResult> Edit(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.GetAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
return NotFound();
}
var model = new AdminMenuEditViewModel
{
Id = adminMenu.Id,
Name = adminMenu.Name
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(AdminMenuEditViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, model.Id);
if (adminMenu == null)
{
return NotFound();
}
if (ModelState.IsValid)
{
adminMenu.Name = model.Name;
await _adminMenuService.SaveAsync(adminMenu);
await _notifier.SuccessAsync(H["Admin menu updated successfully."]);
return RedirectToAction(nameof(List));
}
return View(model);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
await _notifier.ErrorAsync(H["Can't find the admin menu."]);
return RedirectToAction(nameof(List));
}
var removed = await _adminMenuService.DeleteAsync(adminMenu);
if (removed == 1)
{
await _notifier.SuccessAsync(H["Admin menu deleted successfully."]);
}
else
{
await _notifier.ErrorAsync(H["Can't delete the admin menu."]);
}
return RedirectToAction(nameof(List));
}
[HttpPost, ActionName("List")]
[FormValueRequired("submit.BulkAction")]
public async Task<ActionResult> IndexPost(ViewModels.ContentOptions options, IEnumerable<string> itemIds)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
if (itemIds?.Count() > 0)
{
var adminMenuList = (await _adminMenuService.GetAdminMenuListAsync()).AdminMenu;
var checkedContentItems = adminMenuList.Where(x => itemIds.Contains(x.Id));
switch (options.BulkAction)
{
case ContentsBulkAction.None:
break;
case ContentsBulkAction.Remove:
foreach (var item in checkedContentItems)
{
var adminMenu = adminMenuList.FirstOrDefault(x => String.Equals(x.Id, item.Id, StringComparison.OrdinalIgnoreCase));
await _adminMenuService.DeleteAsync(adminMenu);
}
await _notifier.SuccessAsync(H["Admin menus successfully removed."]);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return RedirectToAction(nameof(List));
}
[HttpPost]
public async Task<IActionResult> Toggle(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
return NotFound();
}
adminMenu.Enabled = !adminMenu.Enabled;
await _adminMenuService.SaveAsync(adminMenu);
await _notifier.SuccessAsync(H["Admin menu toggled successfully."]);
return RedirectToAction(nameof(List));
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Describes the result of a cluster resize operation.
/// </summary>
public partial class DescribeResizeResponse : AmazonWebServiceResponse
{
private double? _avgResizeRateInMegaBytesPerSecond;
private long? _elapsedTimeInSeconds;
private long? _estimatedTimeToCompletionInSeconds;
private List<string> _importTablesCompleted = new List<string>();
private List<string> _importTablesInProgress = new List<string>();
private List<string> _importTablesNotStarted = new List<string>();
private long? _progressInMegaBytes;
private string _status;
private string _targetClusterType;
private string _targetNodeType;
private int? _targetNumberOfNodes;
private long? _totalResizeDataInMegaBytes;
/// <summary>
/// Gets and sets the property AvgResizeRateInMegaBytesPerSecond.
/// <para>
/// The average rate of the resize operation over the last few minutes, measured in megabytes
/// per second. After the resize operation completes, this value shows the average rate
/// of the entire resize operation.
/// </para>
/// </summary>
public double AvgResizeRateInMegaBytesPerSecond
{
get { return this._avgResizeRateInMegaBytesPerSecond.GetValueOrDefault(); }
set { this._avgResizeRateInMegaBytesPerSecond = value; }
}
// Check to see if AvgResizeRateInMegaBytesPerSecond property is set
internal bool IsSetAvgResizeRateInMegaBytesPerSecond()
{
return this._avgResizeRateInMegaBytesPerSecond.HasValue;
}
/// <summary>
/// Gets and sets the property ElapsedTimeInSeconds.
/// <para>
/// The amount of seconds that have elapsed since the resize operation began. After the
/// resize operation completes, this value shows the total actual time, in seconds, for
/// the resize operation.
/// </para>
/// </summary>
public long ElapsedTimeInSeconds
{
get { return this._elapsedTimeInSeconds.GetValueOrDefault(); }
set { this._elapsedTimeInSeconds = value; }
}
// Check to see if ElapsedTimeInSeconds property is set
internal bool IsSetElapsedTimeInSeconds()
{
return this._elapsedTimeInSeconds.HasValue;
}
/// <summary>
/// Gets and sets the property EstimatedTimeToCompletionInSeconds.
/// <para>
/// The estimated time remaining, in seconds, until the resize operation is complete.
/// This value is calculated based on the average resize rate and the estimated amount
/// of data remaining to be processed. Once the resize operation is complete, this value
/// will be 0.
/// </para>
/// </summary>
public long EstimatedTimeToCompletionInSeconds
{
get { return this._estimatedTimeToCompletionInSeconds.GetValueOrDefault(); }
set { this._estimatedTimeToCompletionInSeconds = value; }
}
// Check to see if EstimatedTimeToCompletionInSeconds property is set
internal bool IsSetEstimatedTimeToCompletionInSeconds()
{
return this._estimatedTimeToCompletionInSeconds.HasValue;
}
/// <summary>
/// Gets and sets the property ImportTablesCompleted.
/// <para>
/// The names of tables that have been completely imported .
/// </para>
///
/// <para>
/// Valid Values: List of table names.
/// </para>
/// </summary>
public List<string> ImportTablesCompleted
{
get { return this._importTablesCompleted; }
set { this._importTablesCompleted = value; }
}
// Check to see if ImportTablesCompleted property is set
internal bool IsSetImportTablesCompleted()
{
return this._importTablesCompleted != null && this._importTablesCompleted.Count > 0;
}
/// <summary>
/// Gets and sets the property ImportTablesInProgress.
/// <para>
/// The names of tables that are being currently imported.
/// </para>
///
/// <para>
/// Valid Values: List of table names.
/// </para>
/// </summary>
public List<string> ImportTablesInProgress
{
get { return this._importTablesInProgress; }
set { this._importTablesInProgress = value; }
}
// Check to see if ImportTablesInProgress property is set
internal bool IsSetImportTablesInProgress()
{
return this._importTablesInProgress != null && this._importTablesInProgress.Count > 0;
}
/// <summary>
/// Gets and sets the property ImportTablesNotStarted.
/// <para>
/// The names of tables that have not been yet imported.
/// </para>
///
/// <para>
/// Valid Values: List of table names
/// </para>
/// </summary>
public List<string> ImportTablesNotStarted
{
get { return this._importTablesNotStarted; }
set { this._importTablesNotStarted = value; }
}
// Check to see if ImportTablesNotStarted property is set
internal bool IsSetImportTablesNotStarted()
{
return this._importTablesNotStarted != null && this._importTablesNotStarted.Count > 0;
}
/// <summary>
/// Gets and sets the property ProgressInMegaBytes.
/// <para>
/// While the resize operation is in progress, this value shows the current amount of
/// data, in megabytes, that has been processed so far. When the resize operation is complete,
/// this value shows the total amount of data, in megabytes, on the cluster, which may
/// be more or less than TotalResizeDataInMegaBytes (the estimated total amount of data
/// before resize).
/// </para>
/// </summary>
public long ProgressInMegaBytes
{
get { return this._progressInMegaBytes.GetValueOrDefault(); }
set { this._progressInMegaBytes = value; }
}
// Check to see if ProgressInMegaBytes property is set
internal bool IsSetProgressInMegaBytes()
{
return this._progressInMegaBytes.HasValue;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the resize operation.
/// </para>
///
/// <para>
/// Valid Values: <code>NONE</code> | <code>IN_PROGRESS</code> | <code>FAILED</code> |
/// <code>SUCCEEDED</code>
/// </para>
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property TargetClusterType.
/// <para>
/// The cluster type after the resize operation is complete.
/// </para>
///
/// <para>
/// Valid Values: <code>multi-node</code> | <code>single-node</code>
/// </para>
/// </summary>
public string TargetClusterType
{
get { return this._targetClusterType; }
set { this._targetClusterType = value; }
}
// Check to see if TargetClusterType property is set
internal bool IsSetTargetClusterType()
{
return this._targetClusterType != null;
}
/// <summary>
/// Gets and sets the property TargetNodeType.
/// <para>
/// The node type that the cluster will have after the resize operation is complete.
/// </para>
/// </summary>
public string TargetNodeType
{
get { return this._targetNodeType; }
set { this._targetNodeType = value; }
}
// Check to see if TargetNodeType property is set
internal bool IsSetTargetNodeType()
{
return this._targetNodeType != null;
}
/// <summary>
/// Gets and sets the property TargetNumberOfNodes.
/// <para>
/// The number of nodes that the cluster will have after the resize operation is complete.
/// </para>
/// </summary>
public int TargetNumberOfNodes
{
get { return this._targetNumberOfNodes.GetValueOrDefault(); }
set { this._targetNumberOfNodes = value; }
}
// Check to see if TargetNumberOfNodes property is set
internal bool IsSetTargetNumberOfNodes()
{
return this._targetNumberOfNodes.HasValue;
}
/// <summary>
/// Gets and sets the property TotalResizeDataInMegaBytes.
/// <para>
/// The estimated total amount of data, in megabytes, on the cluster before the resize
/// operation began.
/// </para>
/// </summary>
public long TotalResizeDataInMegaBytes
{
get { return this._totalResizeDataInMegaBytes.GetValueOrDefault(); }
set { this._totalResizeDataInMegaBytes = value; }
}
// Check to see if TotalResizeDataInMegaBytes property is set
internal bool IsSetTotalResizeDataInMegaBytes()
{
return this._totalResizeDataInMegaBytes.HasValue;
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LambdaModuloNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private enum ResultType
{
Success,
DivideByZero,
Overflow
}
#region Verify decimal?
private static void VerifyModuloNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
bool divideByZero;
decimal? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1");
// verify with parameters supplied
Expression<Func<decimal?>> e1 =
Expression.Lambda<Func<decimal?>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 =
Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>(
Expression.Lambda<Func<decimal?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?, decimal?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 =
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<decimal?, decimal?>>> e6 =
Expression.Lambda<Func<Func<decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal?)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify double?
private static void VerifyModuloNullableDouble(double? a, double? b, bool useInterpreter)
{
double? expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1");
// verify with parameters supplied
Expression<Func<double?>> e1 =
Expression.Lambda<Func<double?>>(
Expression.Invoke(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))
}),
Enumerable.Empty<ParameterExpression>());
Func<double?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<double?, double?, Func<double?>>> e2 =
Expression.Lambda<Func<double?, double?, Func<double?>>>(
Expression.Lambda<Func<double?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double?, double?, Func<double?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<double?, double?, double?>>> e3 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?, double?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<double?, double?, double?>>> e4 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double?, double?, double?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<double?, Func<double?, double?>>> e5 =
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double?, Func<double?, double?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<double?, double?>>> e6 =
Expression.Lambda<Func<Func<double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double?)) }),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify float?
private static void VerifyModuloNullableFloat(float? a, float? b, bool useInterpreter)
{
float? expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1");
// verify with parameters supplied
Expression<Func<float?>> e1 =
Expression.Lambda<Func<float?>>(
Expression.Invoke(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))
}),
Enumerable.Empty<ParameterExpression>());
Func<float?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<float?, float?, Func<float?>>> e2 =
Expression.Lambda<Func<float?, float?, Func<float?>>>(
Expression.Lambda<Func<float?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float?, float?, Func<float?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<float?, float?, float?>>> e3 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?, float?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<float?, float?, float?>>> e4 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float?, float?, float?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<float?, Func<float?, float?>>> e5 =
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float?, Func<float?, float?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<float?, float?>>> e6 =
Expression.Lambda<Func<Func<float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float?)) }),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify int?
private static void VerifyModuloNullableInt(int? a, int? b, bool useInterpreter)
{
ResultType outcome;
int? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == int.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1");
// verify with parameters supplied
Expression<Func<int?>> e1 =
Expression.Lambda<Func<int?>>(
Expression.Invoke(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))
}),
Enumerable.Empty<ParameterExpression>());
Func<int?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<int?, int?, Func<int?>>> e2 =
Expression.Lambda<Func<int?, int?, Func<int?>>>(
Expression.Lambda<Func<int?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int?, int?, Func<int?>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<int?, int?, int?>>> e3 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?, int?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<int?, int?, int?>>> e4 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int?, int?, int?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<int?, Func<int?, int?>>> e5 =
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int?, Func<int?, int?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<int?, int?>>> e6 =
Expression.Lambda<Func<Func<int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int?)) }),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify long?
private static void VerifyModuloNullableLong(long? a, long? b, bool useInterpreter)
{
ResultType outcome;
long? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == long.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1");
// verify with parameters supplied
Expression<Func<long?>> e1 =
Expression.Lambda<Func<long?>>(
Expression.Invoke(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))
}),
Enumerable.Empty<ParameterExpression>());
Func<long?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<long?, long?, Func<long?>>> e2 =
Expression.Lambda<Func<long?, long?, Func<long?>>>(
Expression.Lambda<Func<long?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long?, long?, Func<long?>> f2 = e2.Compile(useInterpreter);
long? f2Result = default(long?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<long?, long?, long?>>> e3 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?, long?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify as a function generator
Expression<Func<Func<long?, long?, long?>>> e4 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long?, long?, long?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify with currying
Expression<Func<long?, Func<long?, long?>>> e5 =
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long?, Func<long?, long?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with one parameter
Expression<Func<Func<long?, long?>>> e6 =
Expression.Lambda<Func<Func<long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long?)) }),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
}
#endregion
#region Verify short?
private static void VerifyModuloNullableShort(short? a, short? b, bool useInterpreter)
{
bool divideByZero;
short? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (short?)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1");
// verify with parameters supplied
Expression<Func<short?>> e1 =
Expression.Lambda<Func<short?>>(
Expression.Invoke(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))
}),
Enumerable.Empty<ParameterExpression>());
Func<short?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<short?, short?, Func<short?>>> e2 =
Expression.Lambda<Func<short?, short?, Func<short?>>>(
Expression.Lambda<Func<short?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short?, short?, Func<short?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<short?, short?, short?>>> e3 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?, short?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<short?, short?, short?>>> e4 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short?, short?, short?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<short?, Func<short?, short?>>> e5 =
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short?, Func<short?, short?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<short?, short?>>> e6 =
Expression.Lambda<Func<Func<short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short?)) }),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify uint?
private static void VerifyModuloNullableUInt(uint? a, uint? b, bool useInterpreter)
{
bool divideByZero;
uint? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1");
// verify with parameters supplied
Expression<Func<uint?>> e1 =
Expression.Lambda<Func<uint?>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<uint?, uint?, Func<uint?>>> e2 =
Expression.Lambda<Func<uint?, uint?, Func<uint?>>>(
Expression.Lambda<Func<uint?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint?, uint?, Func<uint?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<uint?, uint?, uint?>>> e3 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?, uint?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<uint?, uint?, uint?>>> e4 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint?, uint?, uint?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<uint?, Func<uint?, uint?>>> e5 =
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint?, Func<uint?, uint?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<uint?, uint?>>> e6 =
Expression.Lambda<Func<Func<uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint?)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ulong?
private static void VerifyModuloNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
bool divideByZero;
ulong? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1");
// verify with parameters supplied
Expression<Func<ulong?>> e1 =
Expression.Lambda<Func<ulong?>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 =
Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>(
Expression.Lambda<Func<ulong?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?, ulong?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 =
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ulong?, ulong?>>> e6 =
Expression.Lambda<Func<Func<ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ushort?
private static void VerifyModuloNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
bool divideByZero;
ushort? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (ushort?)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1");
// verify with parameters supplied
Expression<Func<ushort?>> e1 =
Expression.Lambda<Func<ushort?>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 =
Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>(
Expression.Lambda<Func<ushort?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?, ushort?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 =
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ushort?, ushort?>>> e6 =
Expression.Lambda<Func<Func<ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type SiteContentTypesCollectionRequest.
/// </summary>
public partial class SiteContentTypesCollectionRequest : BaseRequest, ISiteContentTypesCollectionRequest
{
/// <summary>
/// Constructs a new SiteContentTypesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public SiteContentTypesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified ContentType to the collection via POST.
/// </summary>
/// <param name="contentType">The ContentType to add.</param>
/// <returns>The created ContentType.</returns>
public System.Threading.Tasks.Task<ContentType> AddAsync(ContentType contentType)
{
return this.AddAsync(contentType, CancellationToken.None);
}
/// <summary>
/// Adds the specified ContentType to the collection via POST.
/// </summary>
/// <param name="contentType">The ContentType to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ContentType.</returns>
public System.Threading.Tasks.Task<ContentType> AddAsync(ContentType contentType, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<ContentType>(contentType, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<ISiteContentTypesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<ISiteContentTypesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<SiteContentTypesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest Expand(Expression<Func<ContentType, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest Select(Expression<Func<ContentType, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public ISiteContentTypesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
//
// Copyright (c) 2014 Piotr Fusik <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if DOTNET35
using NUnit.Framework;
using Sooda.UnitTests.BaseObjects;
using Sooda.UnitTests.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sooda.UnitTests.TestCases.Linq
{
[TestFixture]
public class GroupByTest
{
[Test]
public void Key()
{
using (new SoodaTransaction())
{
IEnumerable<string> se = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select g.Key;
CollectionAssert.AreEqual(new string[] { "Customer", "Employee", "Manager" }, se);
}
}
[Test]
public void KeyReference()
{
using (new SoodaTransaction())
{
IEnumerable<string> se = from c in Contact.Linq() group c by c.Type into g orderby g.Key.Description select g.Key.Code;
CollectionAssert.AreEqual(new string[] { "Customer", "Employee", "Manager" }, se);
}
}
[Test]
public void Multi()
{
using (new SoodaTransaction())
{
IEnumerable<string> se =
from c in Contact.Linq()
group c by new { c.Type.Code, c.Type.Description } into g
orderby g.Key.Code, g.Key.Description
select g.Key.Code;
CollectionAssert.AreEqual(new string[] { "Customer", "Employee", "Manager" }, se);
}
}
[Test]
public void MultiSelect()
{
using (new SoodaTransaction())
{
var ol =
(from c in Contact.Linq()
group c by new { c.Type.Code, c.Type.Description } into g
orderby g.Key.Code
select g.Key).ToList();
CollectionAssert.AreEqual(new string[] { "Customer", "Employee", "Manager" }, ol.Select(o => o.Code));
CollectionAssert.AreEqual(new string[] { "External Contact", "Internal Employee", "Internal Manager" }, ol.Select(o => o.Description.Value));
}
}
[Test]
public void Count()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select g.Count();
CollectionAssert.AreEqual(new int[] { 4, 2, 1 }, ie);
}
}
[Test]
public void CountFiltered()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select g.Count(c => c.LastSalary.Value >= 100);
CollectionAssert.AreEqual(new int[] { 1, 2, 1 }, ie);
}
}
[Test]
public void KeyCount()
{
using (new SoodaTransaction())
{
var ol = (from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select new { Type = g.Key, Count = g.Count() }).ToList();
CollectionAssert.AreEqual(new string[] { "Customer", "Employee", "Manager" }, ol.Select(o => o.Type));
CollectionAssert.AreEqual(new int[] { 4, 2, 1}, ol.Select(o => o.Count));
}
}
[Test]
public void KeyCountKeyValuePair()
{
using (new SoodaTransaction())
{
var pe = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select new KeyValuePair<string, int>(g.Key, g.Count());
CollectionAssert.AreEqual(new KeyValuePair<string, int>[] {
new KeyValuePair<string, int>("Customer", 4),
new KeyValuePair<string, int>("Employee", 2),
new KeyValuePair<string, int>("Manager", 1) }, pe);
}
}
#if DOTNET4 // Tuple
[Test]
public void MultiCount()
{
using (new SoodaTransaction())
{
var tq =
from c in Contact.Linq()
group c by new { c.Type.Code, c.Type.Description } into g
orderby g.Key.Code, g.Key.Description
select new Tuple<string, string, int>(g.Key.Code, g.Key.Description.Value, g.Count());
CollectionAssert.AreEqual(new Tuple<string, string, int>[] {
new Tuple<string, string, int>("Customer", "External Contact", 4),
new Tuple<string, string, int>("Employee", "Internal Employee", 2),
new Tuple<string, string, int>("Manager", "Internal Manager", 1) }, tq);
}
}
#endif
[Test]
public void Min()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select g.Min(c => c.ContactId);
CollectionAssert.AreEqual(new int[] { 50, 2, 1 }, ie);
}
}
[Test]
public void MinDateTime()
{
using (new SoodaTransaction())
{
IEnumerable<DateTime> de = from d in PKDateTime.Linq() group d by d.Id.Year into g select g.Min(d => d.Id);
CollectionAssert.AreEqual(new DateTime[] { new DateTime(2000, 1, 1) }, de);
}
}
[Test]
public void Max()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select g.Max(c => c.ContactId);
CollectionAssert.AreEqual(new int[] { 53, 3, 1 }, ie);
}
}
[Test]
public void MaxDateTime()
{
using (new SoodaTransaction())
{
IEnumerable<DateTime> de = from d in PKDateTime.Linq() group d by d.Id.Year into g select g.Max(d => d.Id);
CollectionAssert.AreEqual(new DateTime[] { new DateTime(2000, 1, 1, 2, 0, 0) }, de);
}
}
[Test]
public void Sum()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select g.Sum(c => c.ContactId);
CollectionAssert.AreEqual(new int[] { 50 + 51 + 52 + 53, 2 + 3, 1 }, ie);
}
}
[Test]
public void Average()
{
using (new SoodaTransaction())
{
IEnumerable<double> de = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key select g.Average(c => c.ContactId);
CollectionAssert.AreEqual(new double[] { (50 + 51 + 52 + 53) / 4.0, (2 + 3) / 2.0, 1 }, de);
}
}
[Test]
public void Having()
{
using (new SoodaTransaction())
{
IEnumerable<string> se = from c in Contact.Linq() group c by c.Type.Code into g where g.Count() > 1 orderby g.Key select g.Key;
CollectionAssert.AreEqual(new string[] { "Customer", "Employee" }, se);
}
}
[Test]
public void All()
{
using (new SoodaTransaction())
{
IEnumerable<string> se = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key where g.All(c => c.LastSalary.Value >= 100) select g.Key;
CollectionAssert.AreEqual(new string[] { "Employee", "Manager" }, se);
}
}
[Test]
public void Any()
{
using (new SoodaTransaction())
{
IEnumerable<string> se = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key where g.Any() select g.Key;
CollectionAssert.AreEqual(new string[] { "Customer", "Employee", "Manager" }, se);
}
}
[Test]
public void AnyFiltered()
{
using (new SoodaTransaction())
{
IEnumerable<string> se = from c in Contact.Linq() group c by c.Type.Code into g orderby g.Key where g.Any(c => c.LastSalary.Value < 100) select g.Key;
CollectionAssert.AreEqual(new string[] { "Customer" }, se);
}
}
[Test]
public void Bool()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = from c in Contact.Linq() group c by c.Name.StartsWith("C") into g orderby g.Key select g.Count();
CollectionAssert.AreEqual(new int[] { 3, 4 }, ie);
}
}
[Test]
public void Take()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = Contact.Linq().GroupBy(c => c.Type.Code).OrderBy(g => g.Key).Take(2).Select(g => g.Count());
CollectionAssert.AreEqual(new int[] { 4, 2 }, ie);
}
}
[Test]
public void Skip()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = Contact.Linq().GroupBy(c => c.Type.Code).OrderBy(g => g.Key).Skip(1).Select(g => g.Count());
CollectionAssert.AreEqual(new int[] { 2, 1 }, ie);
}
}
[Test]
public void SkipTake()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = Contact.Linq().GroupBy(c => c.Type.Code).OrderBy(g => g.Key).Skip(1).Take(1).Select(g => g.Count());
CollectionAssert.AreEqual(new int[] { 2 }, ie);
}
}
[Test]
public void TakeSkip()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = Contact.Linq().GroupBy(c => c.Type.Code).OrderBy(g => g.Key).Take(2).Skip(1).Select(g => g.Count());
CollectionAssert.AreEqual(new int[] { 2 }, ie);
}
}
[Test]
public void First()
{
using (new SoodaTransaction())
{
int i = Contact.Linq().GroupBy(c => c.Type.Code).OrderBy(g => g.Key).Select(g => g.Count()).First();
Assert.AreEqual(4, i);
}
}
[Test]
public void Distinct()
{
using (new SoodaTransaction())
{
IEnumerable<int> ie = (from c in Contact.Linq() group c by c.ContactId % 10 into g orderby g.Count() descending select g.Count()).Distinct();
CollectionAssert.AreEqual(new int[] { 2, 1 }, ie);
}
}
[Test]
public void NoSelect()
{
using (new SoodaTransaction())
{
var q = Contact.Linq().GroupBy(c => c.Type.Code);
Assert.AreEqual(3, q.Count());
}
}
}
}
#endif
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DSA2Test.cs">
// Copyright (c) 2014 Alexander Logger.
// Copyright (c) 2000 - 2013 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org).
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Text;
using NUnit.Framework;
using Raksha.Bcpg;
using Raksha.Bcpg.OpenPgp;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Bcpg.OpenPgp
{
/**
* GPG compatability test vectors
*/
[TestFixture]
public class Dsa2Test //extends TestCase
{
private const string OpenPgpDsaSigs = "OpenPgp.Dsa.Sigs.";
private const string OpenPgpDsaKeys = "OpenPgp.Dsa.Keys.";
private void doSigGenerateTest(string privateKeyFile, string publicKeyFile, HashAlgorithmTag digest)
{
PgpSecretKeyRing secRing = loadSecretKey(privateKeyFile);
PgpPublicKeyRing pubRing = loadPublicKey(publicKeyFile);
string data = "hello world!";
byte[] dataBytes = Encoding.ASCII.GetBytes(data);
var bOut = new MemoryStream();
var testIn = new MemoryStream(dataBytes, false);
var sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, digest);
sGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey("test".ToCharArray()));
var bcOut = new BcpgOutputStream(bOut);
sGen.GenerateOnePassVersion(false).Encode(bcOut);
var lGen = new PgpLiteralDataGenerator();
// Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000);
var testDate = new DateTime((DateTime.UtcNow.Ticks/TimeSpan.TicksPerSecond)*TimeSpan.TicksPerSecond);
Stream lOut = lGen.Open(new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDate);
int ch;
while ((ch = testIn.ReadByte()) >= 0)
{
lOut.WriteByte((byte) ch);
sGen.Update((byte) ch);
}
lGen.Close();
sGen.Generate().Encode(bcOut);
var pgpFact = new PgpObjectFactory(bOut.ToArray());
var p1 = (PgpOnePassSignatureList) pgpFact.NextPgpObject();
PgpOnePassSignature ops = p1[0];
Assert.AreEqual(digest, ops.HashAlgorithm);
Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, ops.KeyAlgorithm);
var p2 = (PgpLiteralData) pgpFact.NextPgpObject();
if (!p2.ModificationTime.Equals(testDate))
{
Assert.Fail("Modification time not preserved");
}
Stream dIn = p2.GetInputStream();
ops.InitVerify(pubRing.GetPublicKey());
while ((ch = dIn.ReadByte()) >= 0)
{
ops.Update((byte) ch);
}
var p3 = (PgpSignatureList) pgpFact.NextPgpObject();
PgpSignature sig = p3[0];
Assert.AreEqual(digest, sig.HashAlgorithm);
Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, sig.KeyAlgorithm);
Assert.IsTrue(ops.Verify(sig));
}
private void doSigVerifyTest(string publicKeyFile, string sigFile)
{
PgpPublicKeyRing publicKey = loadPublicKey(publicKeyFile);
PgpObjectFactory pgpFact = loadSig(sigFile);
var c1 = (PgpCompressedData) pgpFact.NextPgpObject();
pgpFact = new PgpObjectFactory(c1.GetDataStream());
var p1 = (PgpOnePassSignatureList) pgpFact.NextPgpObject();
PgpOnePassSignature ops = p1[0];
var p2 = (PgpLiteralData) pgpFact.NextPgpObject();
Stream dIn = p2.GetInputStream();
ops.InitVerify(publicKey.GetPublicKey());
int ch;
while ((ch = dIn.ReadByte()) >= 0)
{
ops.Update((byte) ch);
}
var p3 = (PgpSignatureList) pgpFact.NextPgpObject();
Assert.IsTrue(ops.Verify(p3[0]));
}
private PgpObjectFactory loadSig(string sigName)
{
Stream fIn = SimpleTest.GetTestDataAsStream(OpenPgpDsaSigs + sigName);
return new PgpObjectFactory(fIn);
}
private PgpPublicKeyRing loadPublicKey(string keyName)
{
Stream fIn = SimpleTest.GetTestDataAsStream(OpenPgpDsaKeys + keyName);
return new PgpPublicKeyRing(fIn);
}
private PgpSecretKeyRing loadSecretKey(string keyName)
{
Stream fIn = SimpleTest.GetTestDataAsStream(OpenPgpDsaKeys + keyName);
return new PgpSecretKeyRing(fIn);
}
[Test]
public void TestGenerateK1024H224()
{
doSigGenerateTest("DSA-1024-160.sec", "DSA-1024-160.pub", HashAlgorithmTag.Sha224);
}
[Test]
public void TestGenerateK1024H256()
{
doSigGenerateTest("DSA-1024-160.sec", "DSA-1024-160.pub", HashAlgorithmTag.Sha256);
}
[Test]
public void TestGenerateK1024H384()
{
doSigGenerateTest("DSA-1024-160.sec", "DSA-1024-160.pub", HashAlgorithmTag.Sha384);
}
[Test]
public void TestGenerateK1024H512()
{
doSigGenerateTest("DSA-1024-160.sec", "DSA-1024-160.pub", HashAlgorithmTag.Sha512);
}
[Test]
public void TestGenerateK2048H256()
{
doSigGenerateTest("DSA-2048-224.sec", "DSA-2048-224.pub", HashAlgorithmTag.Sha256);
}
[Test]
public void TestGenerateK2048H512()
{
doSigGenerateTest("DSA-2048-224.sec", "DSA-2048-224.pub", HashAlgorithmTag.Sha512);
}
[Test]
public void TestK1024H160()
{
doSigVerifyTest("DSA-1024-160.pub", "dsa-1024-160-sign.gpg");
}
[Test]
public void TestK1024H224()
{
doSigVerifyTest("DSA-1024-160.pub", "dsa-1024-224-sign.gpg");
}
[Test]
public void TestK1024H256()
{
doSigVerifyTest("DSA-1024-160.pub", "dsa-1024-256-sign.gpg");
}
[Test]
public void TestK1024H384()
{
doSigVerifyTest("DSA-1024-160.pub", "dsa-1024-384-sign.gpg");
}
[Test]
public void TestK1024H512()
{
doSigVerifyTest("DSA-1024-160.pub", "dsa-1024-512-sign.gpg");
}
[Test]
public void TestK15360H512()
{
doSigVerifyTest("DSA-15360-512.pub", "dsa-15360-512-sign.gpg");
}
[Test]
public void TestK2048H224()
{
doSigVerifyTest("DSA-2048-224.pub", "dsa-2048-224-sign.gpg");
}
[Test]
public void TestK3072H256()
{
doSigVerifyTest("DSA-3072-256.pub", "dsa-3072-256-sign.gpg");
}
[Test]
public void TestK7680H384()
{
doSigVerifyTest("DSA-7680-384.pub", "dsa-7680-384-sign.gpg");
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Utilities;
namespace Org.BouncyCastle.Crypto.Digests
{
/**
* implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
*
* It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
* is the "endienness" of the word processing!
*/
public class Sha1Digest
: GeneralDigest
{
private const int DigestLength = 20;
private uint H1, H2, H3, H4, H5;
private uint[] X = new uint[80];
private int xOff;
public Sha1Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha1Digest(Sha1Digest t)
: base(t)
{
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "SHA-1"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
if (++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE(H1, output, outOff);
Pack.UInt32_To_BE(H2, output, outOff + 4);
Pack.UInt32_To_BE(H3, output, outOff + 8);
Pack.UInt32_To_BE(H4, output, outOff + 12);
Pack.UInt32_To_BE(H5, output, outOff + 16);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
xOff = 0;
Array.Clear(X, 0, X.Length);
}
//
// Additive constants
//
private const uint Y1 = 0x5a827999;
private const uint Y2 = 0x6ed9eba1;
private const uint Y3 = 0x8f1bbcdc;
private const uint Y4 = 0xca62c1d6;
private static uint F(uint u, uint v, uint w)
{
return (u & v) | (~u & w);
}
private static uint H(uint u, uint v, uint w)
{
return u ^ v ^ w;
}
private static uint G(uint u, uint v, uint w)
{
return (u & v) | (u & w) | (v & w);
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 80 word block.
//
for (int i = 16; i < 80; i++)
{
uint t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >> 31;
}
//
// set up working variables.
//
uint A = H1;
uint B = H2;
uint C = H3;
uint D = H4;
uint E = H5;
//
// round 1
//
int idx = 0;
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1;
C = C << 30 | (C >> 2);
}
//
// round 2
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2;
C = C << 30 | (C >> 2);
}
//
// round 3
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3;
C = C << 30 | (C >> 2);
}
//
// round 4
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4;
C = C << 30 | (C >> 2);
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
}
}
}
| |
// 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.Account.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database table "account.reset_requests".
/// </summary>
public class ResetRequest : DbAccess, IResetRequestRepository
{
/// <summary>
/// The schema of this table. Returns literal "account".
/// </summary>
public override string _ObjectNamespace => "account";
/// <summary>
/// The schema unqualified name of this table. Returns literal "reset_requests".
/// </summary>
public override string _ObjectName => "reset_requests";
/// <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 "account.reset_requests".
/// </summary>
/// <returns>Returns the number of rows of the table "account.reset_requests".</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 \"ResetRequest\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM account.reset_requests;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.reset_requests" to return all instances of the "ResetRequest" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "ResetRequest" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.ResetRequest> 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 \"ResetRequest\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests ORDER BY request_id;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.reset_requests" to return all instances of the "ResetRequest" class to export.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "ResetRequest" 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 \"ResetRequest\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests ORDER BY request_id;";
return Factory.Get<dynamic>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the table "account.reset_requests" with a where filter on the column "request_id" to return a single instance of the "ResetRequest" class.
/// </summary>
/// <param name="requestId">The column "request_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped instance of "ResetRequest" 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.Account.Entities.ResetRequest Get(System.Guid requestId)
{
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 \"ResetRequest\" filtered by \"RequestId\" with value {RequestId} was denied to the user with Login ID {_LoginId}", requestId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests WHERE request_id=@0;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql, requestId).FirstOrDefault();
}
/// <summary>
/// Gets the first record of the table "account.reset_requests".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "ResetRequest" 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.Account.Entities.ResetRequest 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 \"ResetRequest\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests ORDER BY request_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Gets the previous record of the table "account.reset_requests" sorted by requestId.
/// </summary>
/// <param name="requestId">The column "request_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "ResetRequest" 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.Account.Entities.ResetRequest GetPrevious(System.Guid requestId)
{
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 \"ResetRequest\" by \"RequestId\" with value {RequestId} was denied to the user with Login ID {_LoginId}", requestId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests WHERE request_id < @0 ORDER BY request_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql, requestId).FirstOrDefault();
}
/// <summary>
/// Gets the next record of the table "account.reset_requests" sorted by requestId.
/// </summary>
/// <param name="requestId">The column "request_id" parameter used to find the next record.</param>
/// <returns>Returns a non-live, non-mapped instance of "ResetRequest" 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.Account.Entities.ResetRequest GetNext(System.Guid requestId)
{
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 \"ResetRequest\" by \"RequestId\" with value {RequestId} was denied to the user with Login ID {_LoginId}", requestId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests WHERE request_id > @0 ORDER BY request_id LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql, requestId).FirstOrDefault();
}
/// <summary>
/// Gets the last record of the table "account.reset_requests".
/// </summary>
/// <returns>Returns a non-live, non-mapped instance of "ResetRequest" 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.Account.Entities.ResetRequest 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 \"ResetRequest\" was denied to the user with Login ID {_LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests ORDER BY request_id DESC LIMIT 1;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql).FirstOrDefault();
}
/// <summary>
/// Executes a select query on the table "account.reset_requests" with a where filter on the column "request_id" to return a multiple instances of the "ResetRequest" class.
/// </summary>
/// <param name="requestIds">Array of column "request_id" parameter used on where filter.</param>
/// <returns>Returns a non-live, non-mapped collection of "ResetRequest" 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.Account.Entities.ResetRequest> Get(System.Guid[] requestIds)
{
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 \"ResetRequest\" was denied to the user with Login ID {LoginId}. requestIds: {requestIds}.", this._LoginId, requestIds);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests WHERE request_id IN (@0);";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql, requestIds);
}
/// <summary>
/// Custom fields are user defined form elements for account.reset_requests.
/// </summary>
/// <returns>Returns an enumerable custom field collection for the table account.reset_requests</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 \"ResetRequest\" 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='account.reset_requests' ORDER BY field_order;";
return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql);
}
sql = "SELECT * from config.get_custom_field_definition('account.reset_requests'::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 account.reset_requests.
/// </summary>
/// <returns>Returns an enumerable name and value collection for the table account.reset_requests</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 \"ResetRequest\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT request_id AS key, request_id as value FROM account.reset_requests;";
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 ResetRequest class on the database table "account.reset_requests".
/// </summary>
/// <param name="resetRequest">The instance of "ResetRequest" 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 resetRequest, List<Frapid.DataAccess.Models.CustomField> customFields)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
object primaryKeyValue = resetRequest.request_id;
if (resetRequest.request_id != null)
{
this.Update(resetRequest, resetRequest.request_id);
}
else
{
primaryKeyValue = this.Add(resetRequest);
}
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('account.reset_requests')" +
");";
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('account.reset_requests', @0::character varying(100)), " +
"@1, @2;";
Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
}
return primaryKeyValue;
}
/// <summary>
/// Inserts the instance of ResetRequest class on the database table "account.reset_requests".
/// </summary>
/// <param name="resetRequest">The instance of "ResetRequest" 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 resetRequest)
{
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 \"ResetRequest\" was denied to the user with Login ID {LoginId}. {ResetRequest}", this._LoginId, resetRequest);
throw new UnauthorizedException("Access is denied.");
}
}
return Factory.Insert(this._Catalog, resetRequest, "account.reset_requests", "request_id");
}
/// <summary>
/// Inserts or updates multiple instances of ResetRequest class on the database table "account.reset_requests";
/// </summary>
/// <param name="resetRequests">List of "ResetRequest" class to import.</param>
/// <returns></returns>
public List<object> BulkImport(List<ExpandoObject> resetRequests)
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to import entity \"ResetRequest\" was denied to the user with Login ID {LoginId}. {resetRequests}", this._LoginId, resetRequests);
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 resetRequest in resetRequests)
{
line++;
object primaryKeyValue = resetRequest.request_id;
if (resetRequest.request_id != null)
{
result.Add(resetRequest.request_id);
db.Update("account.reset_requests", "request_id", resetRequest, resetRequest.request_id);
}
else
{
result.Add(db.Insert("account.reset_requests", "request_id", resetRequest));
}
}
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 "account.reset_requests" with an instance of "ResetRequest" class against the primary key value.
/// </summary>
/// <param name="resetRequest">The instance of "ResetRequest" class to update.</param>
/// <param name="requestId">The value of the column "request_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 resetRequest, System.Guid requestId)
{
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 \"ResetRequest\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {ResetRequest}", requestId, this._LoginId, resetRequest);
throw new UnauthorizedException("Access is denied.");
}
}
Factory.Update(this._Catalog, resetRequest, requestId, "account.reset_requests", "request_id");
}
/// <summary>
/// Deletes the row of the table "account.reset_requests" against the primary key value.
/// </summary>
/// <param name="requestId">The value of the column "request_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(System.Guid requestId)
{
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 \"ResetRequest\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", requestId, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "DELETE FROM account.reset_requests WHERE request_id=@0;";
Factory.NonQuery(this._Catalog, sql, requestId);
}
/// <summary>
/// Performs a select statement on table "account.reset_requests" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "ResetRequest" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.ResetRequest> 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 \"ResetRequest\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM account.reset_requests ORDER BY request_id LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on table "account.reset_requests" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "ResetRequest" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.ResetRequest> 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 \"ResetRequest\" 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 account.reset_requests ORDER BY request_id LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.Account.Entities.ResetRequest>(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='account.reset_requests' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on table "account.reset_requests".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "ResetRequest" 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 \"ResetRequest\" 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 account.reset_requests WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.ResetRequest(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.reset_requests" 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 "ResetRequest" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.ResetRequest> 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 \"ResetRequest\" 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 account.reset_requests WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.ResetRequest(), filters);
sql.OrderBy("request_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on table "account.reset_requests".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "ResetRequest" 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 \"ResetRequest\" 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 account.reset_requests WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.ResetRequest(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on table "account.reset_requests" 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 "ResetRequest" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.Account.Entities.ResetRequest> 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 \"ResetRequest\" 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 account.reset_requests WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.ResetRequest(), filters);
sql.OrderBy("request_id");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.Account.Entities.ResetRequest>(this._Catalog, sql);
}
}
}
| |
/* ====================================================================
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 TestCases.SS.UserModel
{
using System;
using NUnit.Framework;
using TestCases.SS;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
/**
* Common superclass for testing implementatiosn of
* {@link NPOI.SS.usermodel.Cell}
*/
public class BaseTestCell
{
protected ITestDataProvider _testDataProvider;
public BaseTestCell()
: this(TestCases.HSSF.HSSFITestDataProvider.Instance)
{ }
/**
* @param testDataProvider an object that provides test data in HSSF / XSSF specific way
*/
protected BaseTestCell(ITestDataProvider testDataProvider)
{
// One or more test methods depends on the american culture.
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
_testDataProvider = testDataProvider;
}
[Test]
public void TestSetValues()
{
IWorkbook book = _testDataProvider.CreateWorkbook();
ISheet sheet = book.CreateSheet("test");
IRow row = sheet.CreateRow(0);
ICreationHelper factory = book.GetCreationHelper();
ICell cell = row.CreateCell(0);
cell.SetCellValue(1.2);
Assert.AreEqual(1.2, cell.NumericCellValue, 0.0001);
Assert.AreEqual(CellType.Numeric, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellValue(false);
Assert.AreEqual(false, cell.BooleanCellValue);
Assert.AreEqual(CellType.Boolean, cell.CellType);
cell.SetCellValue(true);
Assert.AreEqual(true, cell.BooleanCellValue);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellValue(factory.CreateRichTextString("Foo"));
Assert.AreEqual("Foo", cell.RichStringCellValue.String);
Assert.AreEqual("Foo", cell.StringCellValue);
Assert.AreEqual(CellType.String, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean,
CellType.Formula, CellType.Error);
cell.SetCellValue("345");
Assert.AreEqual("345", cell.RichStringCellValue.String);
Assert.AreEqual("345", cell.StringCellValue);
Assert.AreEqual(CellType.String, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean,
CellType.Formula, CellType.Error);
DateTime dt = DateTime.Now.AddMilliseconds(123456789);
cell.SetCellValue(dt);
Assert.IsTrue((dt.Ticks - cell.DateCellValue.Ticks) >= -20000);
Assert.AreEqual(CellType.Numeric, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellValue(dt);
Assert.IsTrue((dt.Ticks - cell.DateCellValue.Ticks) >= -20000);
Assert.AreEqual(CellType.Numeric, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String,
CellType.Formula, CellType.Error);
cell.SetCellErrorValue(FormulaError.NA.Code);
Assert.AreEqual(FormulaError.NA.Code, cell.ErrorCellValue);
Assert.AreEqual(CellType.Error, cell.CellType);
AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean,
CellType.Formula, CellType.String);
}
private static void AssertProhibitedValueAccess(ICell cell, params CellType[] types)
{
object a;
foreach (CellType type in types)
{
try
{
switch (type)
{
case CellType.Numeric:
a = cell.NumericCellValue;
break;
case CellType.String:
a = cell.StringCellValue;
break;
case CellType.Boolean:
a = cell.BooleanCellValue;
break;
case CellType.Formula:
a = cell.CellFormula;
break;
case CellType.Error:
a = cell.ErrorCellValue;
break;
}
Assert.Fail("Should get exception when Reading cell type (" + type + ").");
}
catch (InvalidOperationException e)
{
// expected during successful test
Assert.IsTrue(e.Message.StartsWith("Cannot get a"));
}
}
}
/**
* test that Boolean and Error types (BoolErrRecord) are supported properly.
*/
[Test]
public void TestBoolErr()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet s = wb.CreateSheet("testSheet1");
IRow r;
ICell c;
r = s.CreateRow(0);
c = r.CreateCell(1);
//c.SetCellType(HSSFCellType.Boolean);
c.SetCellValue(true);
c = r.CreateCell(2);
//c.SetCellType(HSSFCellType.Boolean);
c.SetCellValue(false);
r = s.CreateRow(1);
c = r.CreateCell(1);
//c.SetCellType(HSSFCellType.Error);
c.SetCellErrorValue((byte)0);
c = r.CreateCell(2);
//c.SetCellType(HSSFCellType.Error);
c.SetCellErrorValue((byte)7);
wb = _testDataProvider.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(1);
Assert.IsTrue(c.BooleanCellValue, "bool value 0,1 = true");
c = r.GetCell(2);
Assert.IsTrue(c.BooleanCellValue == false, "bool value 0,2 = false");
r = s.GetRow(1);
c = r.GetCell(1);
Assert.IsTrue(c.ErrorCellValue == 0, "bool value 0,1 = 0");
c = r.GetCell(2);
Assert.IsTrue(c.ErrorCellValue == 7, "bool value 0,2 = 7");
}
/**
* test that Cell Styles being applied to formulas remain intact
*/
[Test]
public void TestFormulaStyle()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet s = wb.CreateSheet("testSheet1");
IRow r = null;
ICell c = null;
ICellStyle cs = wb.CreateCellStyle();
IFont f = wb.CreateFont();
f.FontHeightInPoints = 20;
f.Color = (HSSFColor.Red.Index);
f.Boldweight = (int)FontBoldWeight.Bold;
f.FontName = "Arial Unicode MS";
cs.FillBackgroundColor = 3;
cs.SetFont(f);
cs.BorderTop = BorderStyle.Thin;
cs.BorderRight = BorderStyle.Thin;
cs.BorderLeft = BorderStyle.Thin;
cs.BorderBottom = BorderStyle.Thin;
r = s.CreateRow(0);
c = r.CreateCell(0);
c.CellStyle = cs;
c.CellFormula = ("2*3");
wb = _testDataProvider.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
c = r.GetCell(0);
Assert.IsTrue((c.CellType == CellType.Formula), "Formula Cell at 0,0");
cs = c.CellStyle;
Assert.IsNotNull(cs, "Formula Cell Style");
Assert.AreEqual(f.Index, cs.FontIndex, "Font Index Matches");
Assert.AreEqual(BorderStyle.Thin, cs.BorderTop , "Top Border");
Assert.AreEqual(BorderStyle.Thin, cs.BorderLeft, "Left Border");
Assert.AreEqual(BorderStyle.Thin, cs.BorderRight, "Right Border");
Assert.AreEqual(BorderStyle.Thin, cs.BorderBottom, "Bottom Border");
}
/**tests the ToString() method of HSSFCell*/
[Test]
public void TestToString()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
IRow r = wb.CreateSheet("Sheet1").CreateRow(0);
ICreationHelper factory = wb.GetCreationHelper();
r.CreateCell(0).SetCellValue(true);
r.CreateCell(1).SetCellValue(1.5);
r.CreateCell(2).SetCellValue(factory.CreateRichTextString("Astring"));
r.CreateCell(3).SetCellErrorValue((byte)ErrorConstants.ERROR_DIV_0);
r.CreateCell(4).CellFormula = ("A1+B1");
Assert.AreEqual("TRUE", r.GetCell(0).ToString(), "Boolean");
Assert.AreEqual("1.5", r.GetCell(1).ToString(), "Numeric");
Assert.AreEqual("Astring", r.GetCell(2).ToString(), "String");
Assert.AreEqual("#DIV/0!", r.GetCell(3).ToString(), "Error");
Assert.AreEqual("A1+B1", r.GetCell(4).ToString(), "Formula");
//Write out the file, read it in, and then check cell values
wb = _testDataProvider.WriteOutAndReadBack(wb);
r = wb.GetSheetAt(0).GetRow(0);
Assert.AreEqual("TRUE", r.GetCell(0).ToString(), "Boolean");
Assert.AreEqual("1.5", r.GetCell(1).ToString(), "Numeric");
Assert.AreEqual("Astring", r.GetCell(2).ToString(), "String");
Assert.AreEqual("#DIV/0!", r.GetCell(3).ToString(), "Error");
Assert.AreEqual("A1+B1", r.GetCell(4).ToString(), "Formula");
}
/**
* Test that Setting cached formula result keeps the cell type
*/
[Test]
public void TestSetFormulaValue()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet s = wb.CreateSheet();
IRow r = s.CreateRow(0);
ICell c1 = r.CreateCell(0);
c1.CellFormula = ("NA()");
Assert.AreEqual(0.0, c1.NumericCellValue, 0.0);
Assert.AreEqual(CellType.Numeric, c1.CachedFormulaResultType);
c1.SetCellValue(10);
Assert.AreEqual(10.0, c1.NumericCellValue, 0.0);
Assert.AreEqual(CellType.Formula, c1.CellType);
Assert.AreEqual(CellType.Numeric, c1.CachedFormulaResultType);
ICell c2 = r.CreateCell(1);
c2.CellFormula = ("NA()");
Assert.AreEqual(0.0, c2.NumericCellValue, 0.0);
Assert.AreEqual(CellType.Numeric, c2.CachedFormulaResultType);
c2.SetCellValue("I Changed!");
Assert.AreEqual("I Changed!", c2.StringCellValue);
Assert.AreEqual(CellType.Formula, c2.CellType);
Assert.AreEqual(CellType.String, c2.CachedFormulaResultType);
//calglin Cell.CellFormula = (null) for a non-formula cell
ICell c3 = r.CreateCell(2);
c3.CellFormula = (null);
Assert.AreEqual(CellType.Blank, c3.CellType);
}
private ICell CreateACell()
{
return _testDataProvider.CreateWorkbook().CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
}
[Test]
public void TestChangeTypeStringToBool()
{
ICell cell = CreateACell();
cell.SetCellValue("TRUE");
Assert.AreEqual(CellType.String, cell.CellType);
try
{
cell.SetCellType(CellType.Boolean);
}
catch (InvalidCastException)
{
throw new AssertionException(
"Identified bug in conversion of cell from text to bool");
}
Assert.AreEqual(CellType.Boolean, cell.CellType);
Assert.AreEqual(true, cell.BooleanCellValue);
cell.SetCellType(CellType.String);
Assert.AreEqual("TRUE", cell.RichStringCellValue.String);
// 'false' text to bool and back
cell.SetCellValue("FALSE");
cell.SetCellType(CellType.Boolean);
Assert.AreEqual(CellType.Boolean, cell.CellType);
Assert.AreEqual(false, cell.BooleanCellValue);
cell.SetCellType(CellType.String);
Assert.AreEqual("FALSE", cell.RichStringCellValue.String);
}
[Test]
public void TestChangeTypeBoolToString()
{
ICell cell = CreateACell();
cell.SetCellValue(true);
try
{
cell.SetCellType(CellType.String);
}
catch (InvalidOperationException e)
{
if (e.Message.Equals("Cannot get a text value from a bool cell"))
{
throw new AssertionException(
"Identified bug in conversion of cell from bool to text");
}
throw e;
}
Assert.AreEqual("TRUE", cell.RichStringCellValue.String);
}
[Test]
public void TestChangeTypeErrorToNumber()
{
ICell cell = CreateACell();
cell.SetCellErrorValue((byte)ErrorConstants.ERROR_NAME);
try
{
cell.SetCellValue(2.5);
}
catch (InvalidCastException)
{
throw new AssertionException("Identified bug 46479b");
}
Assert.AreEqual(2.5, cell.NumericCellValue, 0.0);
}
[Test]
public void TestChangeTypeErrorToBoolean()
{
ICell cell = CreateACell();
cell.SetCellErrorValue((byte)ErrorConstants.ERROR_NAME);
cell.SetCellValue(true);
try
{
object a = cell.BooleanCellValue;
}
catch (InvalidOperationException e)
{
if (e.Message.Equals("Cannot get a bool value from a error cell"))
{
throw new AssertionException("Identified bug 46479c");
}
throw e;
}
Assert.AreEqual(true, cell.BooleanCellValue);
}
/**
* Test for a bug observed around svn r886733 when using
* {@link FormulaEvaluator#EvaluateInCell(Cell)} with a
* string result type.
*/
[Test]
public void TestConvertStringFormulaCell()
{
ICell cellA1 = CreateACell();
cellA1.CellFormula = ("\"abc\"");
// default cached formula result is numeric zero
Assert.AreEqual(0.0, cellA1.NumericCellValue, 0.0);
IFormulaEvaluator fe = cellA1.Sheet.Workbook.GetCreationHelper().CreateFormulaEvaluator();
fe.EvaluateFormulaCell(cellA1);
Assert.AreEqual("abc", cellA1.StringCellValue);
fe.EvaluateInCell(cellA1);
if (cellA1.StringCellValue.Equals(""))
{
throw new AssertionException("Identified bug with writing back formula result of type string");
}
Assert.AreEqual("abc", cellA1.StringCellValue);
}
/**
* similar to {@link #testConvertStringFormulaCell()} but Checks at a
* lower level that {#link {@link Cell#SetCellType(int)} works properly
*/
[Test]
public void TestSetTypeStringOnFormulaCell()
{
ICell cellA1 = CreateACell();
IFormulaEvaluator fe = cellA1.Sheet.Workbook.GetCreationHelper().CreateFormulaEvaluator();
cellA1.CellFormula = ("\"DEF\"");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
Assert.AreEqual("DEF", cellA1.StringCellValue);
cellA1.SetCellType(CellType.String);
Assert.AreEqual("DEF", cellA1.StringCellValue);
cellA1.CellFormula = ("25.061");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
ConfirmCannotReadString(cellA1);
Assert.AreEqual(25.061, cellA1.NumericCellValue, 0.0);
cellA1.SetCellType(CellType.String);
Assert.AreEqual("25.061", cellA1.StringCellValue);
cellA1.CellFormula = ("TRUE");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
ConfirmCannotReadString(cellA1);
Assert.AreEqual(true, cellA1.BooleanCellValue);
cellA1.SetCellType(CellType.String);
Assert.AreEqual("TRUE", cellA1.StringCellValue);
cellA1.CellFormula = ("#NAME?");
fe.ClearAllCachedResultValues();
fe.EvaluateFormulaCell(cellA1);
ConfirmCannotReadString(cellA1);
Assert.AreEqual(ErrorConstants.ERROR_NAME, cellA1.ErrorCellValue);
cellA1.SetCellType(CellType.String);
Assert.AreEqual("#NAME?", cellA1.StringCellValue);
}
private static void ConfirmCannotReadString(ICell cell)
{
AssertProhibitedValueAccess(cell, CellType.String);
}
/**
* Test for bug in ConvertCellValueToBoolean to make sure that formula results get Converted
*/
[Test]
public void TestChangeTypeFormulaToBoolean()
{
ICell cell = CreateACell();
cell.CellFormula = ("1=1");
cell.SetCellValue(true);
cell.SetCellType(CellType.Boolean);
if (cell.BooleanCellValue == false)
{
throw new AssertionException("Identified bug 46479d");
}
Assert.AreEqual(true, cell.BooleanCellValue);
}
/**
* Bug 40296: HSSFCell.CellFormula = throws
* InvalidCastException if cell is Created using HSSFRow.CreateCell(short column, int type)
*/
[Test]
public void Test40296()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet workSheet = wb.CreateSheet("Sheet1");
ICell cell;
IRow row = workSheet.CreateRow(0);
cell = row.CreateCell(0, CellType.Numeric);
cell.SetCellValue(1.0);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(1.0, cell.NumericCellValue, 0.0);
cell = row.CreateCell(1, CellType.Numeric);
cell.SetCellValue(2.0);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(2.0, cell.NumericCellValue, 0.0);
cell = row.CreateCell(2, CellType.Formula);
cell.CellFormula = ("SUM(A1:B1)");
Assert.AreEqual(CellType.Formula, cell.CellType);
Assert.AreEqual("SUM(A1:B1)", cell.CellFormula);
//serialize and check again
wb = _testDataProvider.WriteOutAndReadBack(wb);
row = wb.GetSheetAt(0).GetRow(0);
cell = row.GetCell(0);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(1.0, cell.NumericCellValue, 0.0);
cell = row.GetCell(1);
Assert.AreEqual(CellType.Numeric, cell.CellType);
Assert.AreEqual(2.0, cell.NumericCellValue, 0.0);
cell = row.GetCell(2);
Assert.AreEqual(CellType.Formula, cell.CellType);
Assert.AreEqual("SUM(A1:B1)", cell.CellFormula);
}
[Test]
public void TestSetStringInFormulaCell_bug44606()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
cell.CellFormula = ("B1&C1");
try
{
cell.SetCellValue(wb.GetCreationHelper().CreateRichTextString("hello"));
}
catch (InvalidCastException)
{
throw new AssertionException("Identified bug 44606");
}
}
/**
* Make sure that cell.SetCellType(Cell.CELL_TYPE_BLANK) preserves the cell style
*/
[Test]
public void TestSetBlank_bug47028()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICellStyle style = wb.CreateCellStyle();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
cell.CellStyle = (style);
int i1 = cell.CellStyle.Index;
cell.SetCellType(CellType.Blank);
int i2 = cell.CellStyle.Index;
Assert.AreEqual(i1, i2);
}
/**
* Excel's implementation of floating number arithmetic does not fully adhere to IEEE 754:
*
* From http://support.microsoft.com/kb/78113:
*
* <ul>
* <li> Positive/Negative InfInities:
* InfInities occur when you divide by 0. Excel does not support infInities, rather,
* it gives a #DIV/0! error in these cases.
* </li>
* <li>
* Not-a-Number (NaN):
* NaN is used to represent invalid operations (such as infInity/infinity,
* infInity-infinity, or the square root of -1). NaNs allow a program to
* continue past an invalid operation. Excel instead immediately generates
* an error such as #NUM! or #DIV/0!.
* </li>
* </ul>
*/
[Test]
public void TestNanAndInfInity()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet workSheet = wb.CreateSheet("Sheet1");
IRow row = workSheet.CreateRow(0);
ICell cell0 = row.CreateCell(0);
cell0.SetCellValue(Double.NaN);
Assert.AreEqual(CellType.Error, cell0.CellType, "Double.NaN should change cell type to CELL_TYPE_ERROR");
Assert.AreEqual(ErrorConstants.ERROR_NUM, cell0.ErrorCellValue, "Double.NaN should change cell value to #NUM!");
ICell cell1 = row.CreateCell(1);
cell1.SetCellValue(Double.PositiveInfinity);
Assert.AreEqual(CellType.Error, cell1.CellType, "Double.PositiveInfinity should change cell type to CELL_TYPE_ERROR");
Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell1.ErrorCellValue, "Double.POSITIVE_INFINITY should change cell value to #DIV/0!");
ICell cell2 = row.CreateCell(2);
cell2.SetCellValue(Double.NegativeInfinity);
Assert.AreEqual(CellType.Error, cell2.CellType, "Double.NegativeInfinity should change cell type to CELL_TYPE_ERROR");
Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell2.ErrorCellValue, "Double.NEGATIVE_INFINITY should change cell value to #DIV/0!");
wb = _testDataProvider.WriteOutAndReadBack(wb);
row = wb.GetSheetAt(0).GetRow(0);
cell0 = row.GetCell(0);
Assert.AreEqual(CellType.Error, cell0.CellType);
Assert.AreEqual(ErrorConstants.ERROR_NUM, cell0.ErrorCellValue);
cell1 = row.GetCell(1);
Assert.AreEqual(CellType.Error, cell1.CellType);
Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell1.ErrorCellValue);
cell2 = row.GetCell(2);
Assert.AreEqual(CellType.Error, cell2.CellType);
Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell2.ErrorCellValue);
}
[Test]
public void TestDefaultStyleProperties()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);
ICellStyle style = cell.CellStyle;
Assert.IsTrue(style.IsLocked);
Assert.IsFalse(style.IsHidden);
Assert.AreEqual(0, style.Indention);
Assert.AreEqual(0, style.FontIndex);
Assert.AreEqual(0, (int)style.Alignment);
Assert.AreEqual(0, style.DataFormat);
Assert.AreEqual(false, style.WrapText);
ICellStyle style2 = wb.CreateCellStyle();
Assert.IsTrue(style2.IsLocked);
Assert.IsFalse(style2.IsHidden);
style2.IsLocked = (/*setter*/false);
style2.IsHidden = (/*setter*/true);
Assert.IsFalse(style2.IsLocked);
Assert.IsTrue(style2.IsHidden);
wb = _testDataProvider.WriteOutAndReadBack(wb);
cell = wb.GetSheetAt(0).GetRow(0).GetCell(0);
style = cell.CellStyle;
Assert.IsFalse(style2.IsLocked);
Assert.IsTrue(style2.IsHidden);
style2.IsLocked = (/*setter*/true);
style2.IsHidden = (/*setter*/false);
Assert.IsTrue(style2.IsLocked);
Assert.IsFalse(style2.IsHidden);
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Avalonia.Media
{
/// <summary>
/// Parses a path markup string.
/// </summary>
public class PathMarkupParser
{
private static readonly Dictionary<char, Command> Commands = new Dictionary<char, Command>
{
{ 'F', Command.FillRule },
{ 'f', Command.FillRule },
{ 'M', Command.Move },
{ 'm', Command.MoveRelative },
{ 'L', Command.Line },
{ 'l', Command.LineRelative },
{ 'H', Command.HorizontalLine },
{ 'h', Command.HorizontalLineRelative },
{ 'V', Command.VerticalLine },
{ 'v', Command.VerticalLineRelative },
{ 'C', Command.CubicBezierCurve },
{ 'c', Command.CubicBezierCurveRelative },
{ 'A', Command.Arc },
{ 'a', Command.Arc },
{ 'Z', Command.Close },
{ 'z', Command.Close },
};
private static readonly Dictionary<char, FillRule> FillRules = new Dictionary<char, FillRule>
{
{'0', FillRule.EvenOdd },
{'1', FillRule.NonZero }
};
private StreamGeometry _geometry;
private readonly StreamGeometryContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="PathMarkupParser"/> class.
/// </summary>
/// <param name="geometry">The geometry in which the path should be stored.</param>
/// <param name="context">The context for <paramref name="geometry"/>.</param>
public PathMarkupParser(StreamGeometry geometry, StreamGeometryContext context)
{
_geometry = geometry;
_context = context;
}
/// <summary>
/// Defines the command currently being processed.
/// </summary>
private enum Command
{
None,
FillRule,
Move,
MoveRelative,
Line,
LineRelative,
HorizontalLine,
HorizontalLineRelative,
VerticalLine,
VerticalLineRelative,
CubicBezierCurve,
CubicBezierCurveRelative,
Arc,
Close,
Eof,
}
/// <summary>
/// Parses the specified markup string.
/// </summary>
/// <param name="s">The markup string.</param>
public void Parse(string s)
{
bool openFigure = false;
using (StringReader reader = new StringReader(s))
{
Command lastCommand = Command.None;
Command command;
Point point = new Point();
while ((command = ReadCommand(reader, lastCommand)) != Command.Eof)
{
switch (command)
{
case Command.FillRule:
_context.SetFillRule(ReadFillRule(reader));
break;
case Command.Move:
case Command.MoveRelative:
if (openFigure)
{
_context.EndFigure(false);
}
point = command == Command.Move ?
ReadPoint(reader) :
ReadRelativePoint(reader, point);
_context.BeginFigure(point, true);
openFigure = true;
break;
case Command.Line:
point = ReadPoint(reader);
_context.LineTo(point);
break;
case Command.LineRelative:
point = ReadRelativePoint(reader, point);
_context.LineTo(point);
break;
case Command.HorizontalLine:
point = point.WithX(ReadDouble(reader));
_context.LineTo(point);
break;
case Command.HorizontalLineRelative:
point = new Point(point.X + ReadDouble(reader), point.Y);
_context.LineTo(point);
break;
case Command.VerticalLine:
point = point.WithY(ReadDouble(reader));
_context.LineTo(point);
break;
case Command.VerticalLineRelative:
point = new Point(point.X, point.Y + ReadDouble(reader));
_context.LineTo(point);
break;
case Command.CubicBezierCurve:
{
Point point1 = ReadPoint(reader);
Point point2 = ReadPoint(reader);
point = ReadPoint(reader);
_context.CubicBezierTo(point1, point2, point);
break;
}
case Command.CubicBezierCurveRelative:
{
Point point1 = ReadRelativePoint(reader, point);
Point point2 = ReadRelativePoint(reader, point);
_context.CubicBezierTo(point, point1, point2);
point = point2;
break;
}
case Command.Arc:
{
//example: A10,10 0 0,0 10,20
//format - size rotationAngle isLargeArcFlag sweepDirectionFlag endPoint
Size size = ReadSize(reader);
ReadSeparator(reader);
double rotationAngle = ReadDouble(reader);
ReadSeparator(reader);
bool isLargeArc = ReadBool(reader);
ReadSeparator(reader);
SweepDirection sweepDirection = ReadBool(reader) ? SweepDirection.Clockwise : SweepDirection.CounterClockwise;
point = ReadPoint(reader);
_context.ArcTo(point, size, rotationAngle, isLargeArc, sweepDirection);
break;
}
case Command.Close:
_context.EndFigure(true);
openFigure = false;
break;
default:
throw new NotSupportedException("Unsupported command");
}
lastCommand = command;
}
if (openFigure)
{
_context.EndFigure(false);
}
}
}
private static Command ReadCommand(StringReader reader, Command lastCommand)
{
ReadWhitespace(reader);
int i = reader.Peek();
if (i == -1)
{
return Command.Eof;
}
else
{
char c = (char)i;
Command command = Command.None;
if (!Commands.TryGetValue(c, out command))
{
if ((char.IsDigit(c) || c == '.' || c == '+' || c == '-') &&
(lastCommand != Command.None))
{
return lastCommand;
}
else
{
throw new InvalidDataException("Unexpected path command '" + c + "'.");
}
}
reader.Read();
return command;
}
}
private static FillRule ReadFillRule(StringReader reader)
{
int i = reader.Read();
if (i == -1)
{
throw new InvalidDataException("Invalid fill rule");
}
char c = (char)i;
FillRule rule;
if (!FillRules.TryGetValue(c, out rule))
{
throw new InvalidDataException("Invalid fill rule");
}
return rule;
}
private static double ReadDouble(StringReader reader)
{
ReadWhitespace(reader);
// TODO: Handle Infinity, NaN and scientific notation.
StringBuilder b = new StringBuilder();
bool readSign = false;
bool readPoint = false;
bool readExponent = false;
int i;
while ((i = reader.Peek()) != -1)
{
char c = char.ToUpperInvariant((char)i);
if (((c == '+' || c == '-') && !readSign) ||
(c == '.' && !readPoint) ||
(c == 'E' && !readExponent) ||
char.IsDigit(c))
{
b.Append(c);
reader.Read();
readSign = c == '+' || c == '-';
readPoint = c == '.';
if (c == 'E')
{
readSign = false;
readExponent = c == 'E';
}
}
else
{
break;
}
}
return double.Parse(b.ToString(), CultureInfo.InvariantCulture);
}
private static Point ReadPoint(StringReader reader)
{
ReadWhitespace(reader);
double x = ReadDouble(reader);
ReadSeparator(reader);
double y = ReadDouble(reader);
return new Point(x, y);
}
private static Size ReadSize(StringReader reader)
{
ReadWhitespace(reader);
double x = ReadDouble(reader);
ReadSeparator(reader);
double y = ReadDouble(reader);
return new Size(x, y);
}
private static bool ReadBool(StringReader reader)
{
return ReadDouble(reader) != 0;
}
private static Point ReadRelativePoint(StringReader reader, Point lastPoint)
{
ReadWhitespace(reader);
double x = ReadDouble(reader);
ReadSeparator(reader);
double y = ReadDouble(reader);
return new Point(lastPoint.X + x, lastPoint.Y + y);
}
private static void ReadSeparator(StringReader reader)
{
int i;
bool readComma = false;
while ((i = reader.Peek()) != -1)
{
char c = (char)i;
if (char.IsWhiteSpace(c))
{
reader.Read();
}
else if (c == ',')
{
if (readComma)
{
throw new InvalidDataException("Unexpected ','.");
}
readComma = true;
reader.Read();
}
else
{
break;
}
}
}
private static void ReadWhitespace(StringReader reader)
{
int i;
while ((i = reader.Peek()) != -1)
{
char c = (char)i;
if (char.IsWhiteSpace(c))
{
reader.Read();
}
else
{
break;
}
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Provides a way for an app to not start an operation unless
** there's a reasonable chance there's enough memory
** available for the operation to succeed.
**
**
===========================================================*/
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
/*
This class allows an application to fail before starting certain
activities. The idea is to fail early instead of failing in the middle
of some long-running operation to increase the survivability of the
application and ensure you don't have to write tricky code to handle an
OOM anywhere in your app's code (which implies state corruption, meaning you
should unload the appdomain, if you have a transacted environment to ensure
rollback of individual transactions). This is an incomplete tool to attempt
hoisting all your OOM failures from anywhere in your worker methods to one
particular point where it is easier to handle an OOM failure, and you can
optionally choose to not start a workitem if it will likely fail. This does
not help the performance of your code directly (other than helping to avoid
AD unloads). The point is to avoid starting work if it is likely to fail.
The Enterprise Services team has used these memory gates effectively in the
unmanaged world for a decade.
In Whidbey, we will simply check to see if there is enough memory available
in the OS's page file & attempt to ensure there might be enough space free
within the process's address space (checking for address space fragmentation
as well). We will not commit or reserve any memory. To avoid race conditions with
other threads using MemoryFailPoints, we'll also keep track of a
process-wide amount of memory "reserved" via all currently-active
MemoryFailPoints. This has two problems:
1) This can account for memory twice. If a thread creates a
MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB
less free memory and 100 MB less reserved memory. Yet, subtracting
off the 100 MB is necessary because the thread may not have started
allocating memory yet. Disposing of this class immediately after
front-loaded allocations have completed is a great idea.
2) This is still vulnerable to race conditions with other threads that don't use
MemoryFailPoints.
So this class is far from perfect. But it may be good enough to
meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps.
In Orcas or later, we might allocate some memory from the OS and add it
to a allocation context for this thread. Obviously, at that point we need
some way of conveying when we release this block of memory. So, we
implemented IDisposable on this type in Whidbey and expect all users to call
this from within a using block to provide lexical scope for their memory
usage. The call to Dispose (implicit with the using block) will give us an
opportunity to release this memory, perhaps. We anticipate this will give
us the possibility of a more effective design in a future version.
In Orcas, we may also need to differentiate between allocations that would
go into the normal managed heap vs. the large object heap, or we should
consider checking for enough free space in both locations (with any
appropriate adjustments to ensure the memory is contiguous).
*/
namespace System.Runtime
{
public sealed partial class MemoryFailPoint : CriticalFinalizerObject, IDisposable
{
// Find the top section of user mode memory. Avoid the last 64K.
// Windows reserves that block for the kernel, apparently, and doesn't
// let us ask about that memory. But since we ask for memory in 1 MB
// chunks, we don't have to special case this. Also, we need to
// deal with 32 bit machines in 3 GB mode.
// Using Win32's GetSystemInfo should handle all this for us.
private static readonly ulong s_topOfMemory = GetTopOfMemory();
// Walking the address space is somewhat expensive, taking around half
// a millisecond. Doing that per transaction limits us to a max of
// ~2000 transactions/second. Instead, let's do this address space
// walk once every 10 seconds, or when we will likely fail. This
// amortization scheme can reduce the cost of a memory gate by about
// a factor of 100.
private static long s_hiddenLastKnownFreeAddressSpace = 0;
private static long s_hiddenLastTimeCheckingAddressSpace = 0;
private const int CheckThreshold = 10 * 1000; // 10 seconds
private static long LastKnownFreeAddressSpace
{
get => Volatile.Read(ref s_hiddenLastKnownFreeAddressSpace);
set => Volatile.Write(ref s_hiddenLastKnownFreeAddressSpace, value);
}
private static void AddToLastKnownFreeAddressSpace(long addend) =>
Interlocked.Add(ref s_hiddenLastKnownFreeAddressSpace, addend);
private static long LastTimeCheckingAddressSpace
{
get => Volatile.Read(ref s_hiddenLastTimeCheckingAddressSpace);
set => Volatile.Write(ref s_hiddenLastTimeCheckingAddressSpace, value);
}
// When allocating memory segment by segment, we've hit some cases
// where there are only 22 MB of memory available on the machine,
// we need 1 16 MB segment, and the OS does not succeed in giving us
// that memory. Reasons for this could include:
// 1) The GC does allocate memory when doing a collection.
// 2) Another process on the machine could grab that memory.
// 3) Some other part of the runtime might grab this memory.
// If we build in a little padding, we can help protect
// ourselves against some of these cases, and we want to err on the
// conservative side with this class.
private const int LowMemoryFudgeFactor = 16 << 20;
// Round requested size to a 16MB multiple to have a better granularity
// when checking for available memory.
private const int MemoryCheckGranularity = 16;
// Note: This may become dynamically tunable in the future.
// Also note that we can have different segment sizes for the normal vs.
// large object heap. We currently use the max of the two.
private static readonly ulong s_GCSegmentSize = GC.GetSegmentSize();
// For multi-threaded workers, we want to ensure that if two workers
// use a MemoryFailPoint at the same time, and they both succeed, that
// they don't trample over each other's memory. Keep a process-wide
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer.
private static long s_failPointReservedMemory;
private readonly ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
// We can remove this link demand in a future version - we will
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum);
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
// Check to see that we both have enough memory on the system
// and that we have enough room within the user section of the
// process's address space. Also, we need to use the GC segment
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
ulong segmentSize = (ulong)(Math.Ceiling((double)size / s_GCSegmentSize) * s_GCSegmentSize);
if (segmentSize >= s_topOfMemory)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig);
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
// re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
ulong totalAddressSpaceFree = 0; // non-contiguous free address space
// Check for available memory, with 2 attempts at getting more
// memory.
// Stage 0: If we don't have enough, trigger a GC.
// Stage 1: If we don't have enough, try growing the swap file.
// Stage 2: Update memory state, then fail or leave loop.
//
// (In the future, we could consider adding another stage after
// Stage 0 to run finalizers. However, before doing that make sure
// that we could abort this constructor when we call
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
for (int stage = 0; stage < 3; stage++)
{
if (!CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree))
{
// _mustSubtractReservation == false
return;
}
// If we have enough room, then skip some stages.
// Note that multiple threads can still lead to a race condition for our free chunk
// of address space, which can't be easily solved.
ulong reserved = MemoryFailPointReservedMemory;
ulong segPlusReserved = segmentSize + reserved;
bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved;
bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow;
bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow;
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if (now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace ||
LastKnownFreeAddressSpace < (long)segmentSize)
{
CheckForFreeAddressSpace(segmentSize, false);
}
bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize;
#if false
Console.WriteLine($"MemoryFailPoint:" +
$"Checking for {(segmentSize >> 20)} MB, " +
$"for allocation size of {sizeInMegabytes} MB, " +
$"stage {stage}. " +
$"Need page file? {needPageFile} " +
$"Need Address Space? {needAddressSpace} " +
$"Need Contiguous address space? {needContiguousVASpace} " +
$"Avail page file: {(availPageFile >> 20)} MB " +
$"Total free VA space: {totalAddressSpaceFree >> 20} MB " +
$"Contiguous free address space (found): {LastKnownFreeAddressSpace >> 20} MB " +
$"Space reserved via process's MemoryFailPoints: {reserved} MB");
#endif
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
switch (stage)
{
case 0:
// The GC will release empty segments to the OS. This will
// relieve us from having to guess whether there's
// enough memory in either GC heap, and whether
// internal fragmentation will prevent those
// allocations from succeeding.
GC.Collect();
continue;
case 1:
// Do this step if and only if the page file is too small.
if (!needPageFile)
continue;
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
// This shouldn't overflow due to the if clauses above.
UIntPtr numBytes = new UIntPtr(segmentSize);
GrowPageFileIfNecessaryAndPossible(numBytes);
continue;
case 2:
// The call to CheckForAvailableMemory above updated our
// state.
if (needPageFile || needAddressSpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint);
#if DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
if (needContiguousVASpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
#if DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
break;
default:
Debug.Fail("Fell through switch statement!");
break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple race condition with other MemoryFailPoint instances.
AddToLastKnownFreeAddressSpace(-((long)size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
AddMemoryFailPointReservation((long)size);
_mustSubtractReservation = true;
}
~MemoryFailPoint()
{
Dispose(false);
}
// Applications must call Dispose, which conceptually "releases" the
// memory that was "reserved" by the MemoryFailPoint. This affects a
// global count of reserved memory in this version (helping to throttle
// future MemoryFailPoints) in this version. We may in the
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
if (_mustSubtractReservation)
{
RuntimeHelpers.PrepareConstrainedRegions();
AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
/*
// Prototype performance
// Let's pretend that we returned at least some free memory to
// the GC heap. We don't know this is true - the objects could
// have a longer lifetime, and the memory could be elsewhere in the
// GC heap. Additionally, we subtracted off the segment size, not
// this size. That's ok - we don't mind if this slowly degrades
// and requires us to refresh the value a little bit sooner.
// But releasing the memory here should help us avoid probing for
// free address space excessively with large workItem sizes.
Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory);
*/
}
internal static long AddMemoryFailPointReservation(long size) =>
// Size can legitimately be negative - see Dispose.
Interlocked.Add(ref s_failPointReservedMemory, (long)size);
internal static ulong MemoryFailPointReservedMemory
{
get
{
Debug.Assert(Volatile.Read(ref s_failPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
return (ulong)Volatile.Read(ref s_failPointReservedMemory);
}
}
#if DEBUG
[Serializable]
internal sealed class MemoryFailPointState
{
private readonly ulong _segmentSize;
private readonly int _allocationSizeInMB;
private readonly bool _needPageFile;
private readonly bool _needAddressSpace;
private readonly bool _needContiguousVASpace;
private readonly ulong _availPageFile;
private readonly ulong _totalFreeAddressSpace;
private readonly long _lastKnownFreeAddressSpace;
private readonly ulong _reservedMem;
private readonly string _stackTrace; // Where did we fail, for additional debugging.
internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem)
{
_allocationSizeInMB = allocationSizeInMB;
_segmentSize = segmentSize;
_needPageFile = needPageFile;
_needAddressSpace = needAddressSpace;
_needContiguousVASpace = needContiguousVASpace;
_availPageFile = availPageFile;
_totalFreeAddressSpace = totalFreeAddressSpace;
_lastKnownFreeAddressSpace = lastKnownFreeAddressSpace;
_reservedMem = reservedMem;
try
{
_stackTrace = Environment.StackTrace;
}
catch (System.Security.SecurityException)
{
_stackTrace = "no permission";
}
catch (OutOfMemoryException)
{
_stackTrace = "out of memory";
}
}
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
_segmentSize >> 20, _allocationSizeInMB, _needPageFile,
_needAddressSpace, _needContiguousVASpace,
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
}
#endif
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxTreeExtensions
{
public static ISet<SyntaxKind> GetPrecedingModifiers(
this SyntaxTree syntaxTree,
int position,
SyntaxToken tokenOnLeftOfPosition,
CancellationToken cancellationToken)
=> syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition, out var _);
public static ISet<SyntaxKind> GetPrecedingModifiers(
this SyntaxTree syntaxTree,
int position,
SyntaxToken tokenOnLeftOfPosition,
out int positionBeforeModifiers)
{
var token = tokenOnLeftOfPosition;
token = token.GetPreviousTokenIfTouchingWord(position);
var result = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer);
while (true)
{
switch (token.Kind())
{
case SyntaxKind.PublicKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.SealedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.VirtualKeyword:
case SyntaxKind.ExternKeyword:
case SyntaxKind.NewKeyword:
case SyntaxKind.OverrideKeyword:
case SyntaxKind.ReadOnlyKeyword:
case SyntaxKind.VolatileKeyword:
case SyntaxKind.UnsafeKeyword:
case SyntaxKind.AsyncKeyword:
result.Add(token.Kind());
token = token.GetPreviousToken(includeSkipped: true);
continue;
case SyntaxKind.IdentifierToken:
if (token.HasMatchingText(SyntaxKind.AsyncKeyword))
{
result.Add(SyntaxKind.AsyncKeyword);
token = token.GetPreviousToken(includeSkipped: true);
continue;
}
break;
}
break;
}
positionBeforeModifiers = token.FullSpan.End;
return result;
}
public static TypeDeclarationSyntax GetContainingTypeDeclaration(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.GetContainingTypeDeclarations(position, cancellationToken).FirstOrDefault();
}
public static BaseTypeDeclarationSyntax GetContainingTypeOrEnumDeclaration(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.GetContainingTypeOrEnumDeclarations(position, cancellationToken).FirstOrDefault();
}
public static IEnumerable<TypeDeclarationSyntax> GetContainingTypeDeclarations(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.GetAncestors<TypeDeclarationSyntax>().Where(t =>
{
return BaseTypeDeclarationContainsPosition(t, position);
});
}
private static bool BaseTypeDeclarationContainsPosition(BaseTypeDeclarationSyntax declaration, int position)
{
if (position <= declaration.OpenBraceToken.SpanStart)
{
return false;
}
if (declaration.CloseBraceToken.IsMissing)
{
return true;
}
return position <= declaration.CloseBraceToken.SpanStart;
}
public static IEnumerable<BaseTypeDeclarationSyntax> GetContainingTypeOrEnumDeclarations(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.GetAncestors<BaseTypeDeclarationSyntax>().Where(t => BaseTypeDeclarationContainsPosition(t, position));
}
private static readonly Func<SyntaxKind, bool> s_isDotOrArrow = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken;
private static readonly Func<SyntaxKind, bool> s_isDotOrArrowOrColonColon =
k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken || k == SyntaxKind.ColonColonToken;
public static bool IsRightOfDotOrArrowOrColonColon(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.IsRightOf(position, s_isDotOrArrowOrColonColon, cancellationToken);
}
public static bool IsRightOfDotOrArrow(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.IsRightOf(position, s_isDotOrArrow, cancellationToken);
}
private static bool IsRightOf(
this SyntaxTree syntaxTree, int position, Func<SyntaxKind, bool> predicate, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
return predicate(token.Kind());
}
public static bool IsRightOfNumericLiteral(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.Kind() == SyntaxKind.NumericLiteralToken;
}
public static bool IsPrimaryFunctionExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
{
return
syntaxTree.IsTypeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
syntaxTree.IsDefaultExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
syntaxTree.IsSizeOfExpressionContext(position, tokenOnLeftOfPosition, cancellationToken);
}
public static bool IsAfterKeyword(this SyntaxTree syntaxTree, int position, SyntaxKind kind, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
return token.Kind() == kind;
}
public static bool IsInNonUserCode(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return
syntaxTree.IsEntirelyWithinNonUserCodeComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken) ||
syntaxTree.IsInInactiveRegion(position, cancellationToken);
}
public static bool IsEntirelyWithinNonUserCodeComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var inNonUserSingleLineDocComment =
syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken) && !syntaxTree.IsEntirelyWithinCrefSyntax(position, cancellationToken);
return
syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) ||
inNonUserSingleLineDocComment;
}
public static bool IsEntirelyWithinComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return
syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken);
}
public static bool IsCrefContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true);
token = token.GetPreviousTokenIfTouchingWord(position);
if (token.Parent is XmlCrefAttributeSyntax)
{
var attribute = (XmlCrefAttributeSyntax)token.Parent;
return token == attribute.StartQuoteToken;
}
return false;
}
public static bool IsEntirelyWithinCrefSyntax(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree.IsCrefContext(position, cancellationToken))
{
return true;
}
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true);
return token.GetAncestor<CrefSyntax>() != null;
}
public static bool IsEntirelyWithinSingleLineDocComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
var trivia = root.FindTrivia(position);
// If we ask right at the end of the file, we'll get back nothing.
// So move back in that case and ask again.
var eofPosition = root.FullWidth();
if (position == eofPosition)
{
var eof = root.EndOfFileToken;
if (eof.HasLeadingTrivia)
{
trivia = eof.LeadingTrivia.Last();
}
}
if (trivia.IsSingleLineDocComment())
{
var span = trivia.Span;
var fullSpan = trivia.FullSpan;
var endsWithNewLine = trivia.GetStructure().GetLastToken(includeSkipped: true).Kind() == SyntaxKind.XmlTextLiteralNewLineToken;
if (endsWithNewLine)
{
if (position > fullSpan.Start && position < fullSpan.End)
{
return true;
}
}
else
{
if (position > fullSpan.Start && position <= fullSpan.End)
{
return true;
}
}
}
return false;
}
public static bool IsEntirelyWithinMultiLineDocComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position);
if (trivia.IsMultiLineDocComment())
{
var span = trivia.FullSpan;
if (position > span.Start && position < span.End)
{
return true;
}
}
return false;
}
public static bool IsEntirelyWithinMultiLineComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken);
if (trivia.IsMultiLineComment())
{
var span = trivia.FullSpan;
return trivia.IsCompleteMultiLineComment()
? position > span.Start && position < span.End
: position > span.Start && position <= span.End;
}
return false;
}
public static bool IsEntirelyWithinTopLevelSingleLineComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
// Check if we're on the newline right at the end of a comment
trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken);
}
if (trivia.IsSingleLineComment() || trivia.IsShebangDirective())
{
var span = trivia.FullSpan;
if (position > span.Start && position <= span.End)
{
return true;
}
}
return false;
}
public static bool IsEntirelyWithinPreProcessorSingleLineComment(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
// Search inside trivia for directives to ensure that we recognize
// single-line comments at the end of preprocessor directives.
var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken, findInsideTrivia: true);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
// Check if we're on the newline right at the end of a comment
trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken, findInsideTrivia: true);
}
if (trivia.IsSingleLineComment())
{
var span = trivia.FullSpan;
if (position > span.Start && position <= span.End)
{
return true;
}
}
return false;
}
private static bool AtEndOfIncompleteStringOrCharLiteral(SyntaxToken token, int position, char lastChar)
{
if (!token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken))
{
throw new ArgumentException(CSharpWorkspaceResources.Expected_string_or_char_literal, nameof(token));
}
int startLength = 1;
if (token.IsVerbatimStringLiteral())
{
startLength = 2;
}
return position == token.Span.End &&
(token.Span.Length == startLength || (token.Span.Length > startLength && token.ToString().Cast<char>().LastOrDefault() != lastChar));
}
public static bool IsEntirelyWithinStringOrCharLiteral(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return
syntaxTree.IsEntirelyWithinStringLiteral(position, cancellationToken) ||
syntaxTree.IsEntirelyWithinCharLiteral(position, cancellationToken);
}
public static bool IsEntirelyWithinStringLiteral(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true);
// If we ask right at the end of the file, we'll get back nothing. We handle that case
// specially for now, though SyntaxTree.FindToken should work at the end of a file.
if (token.IsKind(SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken))
{
token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true);
}
if (token.IsKind(SyntaxKind.StringLiteralToken))
{
var span = token.Span;
// cases:
// "|"
// "| (e.g. incomplete string literal)
return (position > span.Start && position < span.End)
|| AtEndOfIncompleteStringOrCharLiteral(token, position, '"');
}
if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.InterpolatedStringEndToken))
{
return token.SpanStart < position && token.Span.End > position;
}
return false;
}
public static bool IsEntirelyWithinCharLiteral(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax;
var token = root.FindToken(position, findInsideTrivia: true);
// If we ask right at the end of the file, we'll get back nothing.
// We handle that case specially for now, though SyntaxTree.FindToken should
// work at the end of a file.
if (position == root.FullWidth())
{
token = root.EndOfFileToken.GetPreviousToken(includeSkipped: true, includeDirectives: true);
}
if (token.Kind() == SyntaxKind.CharacterLiteralToken)
{
var span = token.Span;
// cases:
// '|'
// '| (e.g. incomplete char literal)
return (position > span.Start && position < span.End)
|| AtEndOfIncompleteStringOrCharLiteral(token, position, '\'');
}
return false;
}
public static bool IsInInactiveRegion(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(syntaxTree);
// cases:
// $ is EOF
// #if false
// |
// #if false
// |$
// #if false
// |
// #if false
// |$
if (syntaxTree.IsPreProcessorKeywordContext(position, cancellationToken))
{
return false;
}
// The latter two are the hard cases we don't actually have an
// DisabledTextTrivia yet.
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return true;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return false;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return false;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax)
{
var branch = (BranchingDirectiveTriviaSyntax)structure;
return !branch.IsActive || !branch.BranchTaken;
}
}
}
}
return false;
}
public static IList<MemberDeclarationSyntax> GetMembersInSpan(
this SyntaxTree syntaxTree,
TextSpan textSpan,
CancellationToken cancellationToken)
{
var token = syntaxTree.GetRoot(cancellationToken).FindToken(textSpan.Start);
var firstMember = token.GetAncestors<MemberDeclarationSyntax>().FirstOrDefault();
if (firstMember != null)
{
var containingType = firstMember.Parent as TypeDeclarationSyntax;
if (containingType != null)
{
var members = GetMembersInSpan(textSpan, containingType, firstMember);
if (members != null)
{
return members;
}
}
}
return SpecializedCollections.EmptyList<MemberDeclarationSyntax>();
}
private static List<MemberDeclarationSyntax> GetMembersInSpan(
TextSpan textSpan,
TypeDeclarationSyntax containingType,
MemberDeclarationSyntax firstMember)
{
List<MemberDeclarationSyntax> selectedMembers = null;
var members = containingType.Members;
var fieldIndex = members.IndexOf(firstMember);
if (fieldIndex < 0)
{
return null;
}
for (var i = fieldIndex; i < members.Count; i++)
{
var member = members[i];
if (textSpan.Contains(member.Span))
{
selectedMembers = selectedMembers ?? new List<MemberDeclarationSyntax>();
selectedMembers.Add(member);
}
else if (textSpan.OverlapsWith(member.Span))
{
return null;
}
else
{
break;
}
}
return selectedMembers;
}
public static bool IsInPartiallyWrittenGeneric(
this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out var genericIdentifier, out var lessThanToken);
}
public static bool IsInPartiallyWrittenGeneric(
this SyntaxTree syntaxTree,
int position,
CancellationToken cancellationToken,
out SyntaxToken genericIdentifier)
{
return syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out var lessThanToken);
}
public static bool IsInPartiallyWrittenGeneric(
this SyntaxTree syntaxTree,
int position,
CancellationToken cancellationToken,
out SyntaxToken genericIdentifier,
out SyntaxToken lessThanToken)
{
genericIdentifier = default(SyntaxToken);
lessThanToken = default(SyntaxToken);
int index = 0;
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
// check whether we are under type or member decl
if (token.GetAncestor<TypeParameterListSyntax>() != null)
{
return false;
}
int stack = 0;
while (true)
{
switch (token.Kind())
{
case SyntaxKind.LessThanToken:
if (stack == 0)
{
// got here so we read successfully up to a < now we have to read the
// name before that and we're done!
lessThanToken = token;
token = token.GetPreviousToken(includeSkipped: true);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
// ok
// so we've read something like:
// ~~~~~~~~~<a,b,...
// but we need to know the simple name that precedes the <
// it could be
// ~~~~~~foo<a,b,...
if (token.Kind() == SyntaxKind.IdentifierToken)
{
// okay now check whether it is actually partially written
if (IsFullyWrittenGeneric(token, lessThanToken))
{
return false;
}
genericIdentifier = token;
return true;
}
return false;
}
else
{
stack--;
break;
}
case SyntaxKind.GreaterThanGreaterThanToken:
stack++;
goto case SyntaxKind.GreaterThanToken;
// fall through
case SyntaxKind.GreaterThanToken:
stack++;
break;
case SyntaxKind.AsteriskToken: // for int*
case SyntaxKind.QuestionToken: // for int?
case SyntaxKind.ColonToken: // for global:: (so we don't dismiss help as you type the first :)
case SyntaxKind.ColonColonToken: // for global::
case SyntaxKind.CloseBracketToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.IdentifierToken:
break;
case SyntaxKind.CommaToken:
if (stack == 0)
{
index++;
}
break;
default:
// user might have typed "in" on the way to typing "int"
// don't want to disregard this genericname because of that
if (SyntaxFacts.IsKeywordKind(token.Kind()))
{
break;
}
// anything else and we're sunk.
return false;
}
// look backward one token, include skipped tokens, because the parser frequently
// does skip them in cases like: "Func<A, B", which get parsed as: expression
// statement "Func<A" with missing semicolon, expression statement "B" with missing
// semicolon, and the "," is skipped.
token = token.GetPreviousToken(includeSkipped: true);
if (token.Kind() == SyntaxKind.None)
{
return false;
}
}
}
private static bool IsFullyWrittenGeneric(SyntaxToken token, SyntaxToken lessThanToken)
{
var genericName = token.Parent as GenericNameSyntax;
return genericName != null && genericName.TypeArgumentList != null &&
genericName.TypeArgumentList.LessThanToken == lessThanToken && !genericName.TypeArgumentList.GreaterThanToken.IsMissing;
}
}
}
| |
// $Id$
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using Org.Apache.Etch.Bindings.Csharp.Msg;
using Org.Apache.Etch.Bindings.Csharp.Support;
using Org.Apache.Etch.Bindings.Csharp.Util;
namespace Org.Apache.Etch.Bindings.Csharp.Transport
{
public class DefaultDeliveryService : DeliveryService
{
public DefaultDeliveryService(MailboxManager transport, string uri, Resources resources)
: this(transport, new URL(uri), resources)
{
}
public DefaultDeliveryService(MailboxManager transport, URL uri, Resources resources)
{
this.transport = transport;
transport.SetSession(this);
disableTimeout = uri.GetBooleanTerm(DISABLE_TIMEOUT, false);
}
/// <summary>
/// Parameter to Globally Disable Timeout.
/// </summary>
public const string DISABLE_TIMEOUT = "DefaultDeliveryService.disableTimeout";
private bool disableTimeout = false;
private SessionMessage _stub;
private MailboxManager transport;
/// <summary>
/// Removes all the stubs in the set of stubs
/// </summary>
public void RemoveStub()
{
_stub = null;
}
public Object SessionQuery(object query)
{
if (_stub != null)
return _stub.SessionQuery(query);
throw new NotSupportedException("unknown query: " + query);
}
public void SessionControl(Object control, Object value)
{
if (_stub != null)
_stub.SessionControl(control, value);
throw new NotSupportedException("unknown control: " + control);
}
public void SessionNotify(Object eventObj)
{
if (eventObj is string)
{
string stringObj = (string) eventObj;
if (stringObj == SessionConsts.UP)
{
status.Set(SessionConsts.UP);
}
else if (stringObj == SessionConsts.DOWN)
{
status.Set(SessionConsts.DOWN);
}
}
_stub.SessionNotify(eventObj);
}
private Monitor<string> status = new Monitor<string>("session status");
public Object TransportQuery(Object query)
{
if(query.GetType() == typeof(TransportConsts.WaitUp))
{
waitUp(((TransportConsts.WaitUp) query)._maxDelay);
return null;
}
else if (query.GetType() == typeof(TransportConsts.WaitDown))
{
waitDown(((TransportConsts.WaitDown)query)._maxDelay);
return null;
}
else
{
return transport.TransportQuery(query);
}
}
private void waitUp(int maxDelay)
{
status.WaitUntilEq(SessionConsts.UP,maxDelay);
}
private void waitDown(int maxDelay)
{
status.WaitUntilEq(SessionConsts.DOWN, maxDelay);
}
public void TransportControl(Object control, Object value)
{
if (control is string)
{
string stringObj = (string) control;
if (stringObj == TransportConsts.START_AND_WAIT_UP)
{
transport.TransportControl(TransportConsts.START, null);
waitUp((int) value);
}
else if (stringObj == TransportConsts.STOP_AND_WAIT_DOWN)
{
transport.TransportControl(TransportConsts.STOP,null);
waitDown((int)value);
}
else
{
transport.TransportControl(control, value);
}
}
else
{
transport.TransportControl(control, value);
}
}
public void TransportNotify(Object eventObj)
{
transport.TransportNotify(eventObj);
}
public Mailbox BeginCall(Message msg)
{
return transport.TransportCall(null, msg);
}
public Object EndCall(Mailbox mb, XType responseType)
{
try
{
int timeout = disableTimeout ? 0 : responseType.Timeout;
Element mbe = mb.Read(timeout);
if (mbe == null)
throw new TimeoutException("timeout waiting for " + responseType);
Message rmsg = mbe.msg;
rmsg.CheckType(responseType);
Object r = rmsg.Get(responseType.ResponseField);
if (r is Exception)
{
Exception e = (Exception)r;
throw e;
}
return r;
}
finally
{
mb.CloseRead();
}
}
public override string ToString()
{
return transport.ToString();
}
#region SessionMessage Members
public bool SessionMessage(Who sender, Message msg)
{
return _stub.SessionMessage(sender, msg);
}
/// <summary>
/// Adds a stub to a list of stub
/// </summary>
/// <param name="stb"></param>
public void SetSession(SessionMessage stb)
{
if (_stub != null)
throw new Exception("Unsupported -- only one stub for now");
_stub = stb;
}
#endregion
#region TransportMessage Members
public void TransportMessage(Who recipient, Message msg)
{
transport.TransportMessage(recipient,msg);
}
#endregion
#region Transport<SessionMessage> Members
public SessionMessage GetSession()
{
return _stub;
}
#endregion
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_DynamicArgument()
{
string source = @"
class C
{
public C(int i)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C) (Syntax: 'new C(d)')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_MultipleApplicableSymbols()
{
string source = @"
class C
{
public C(int i)
{
}
public C(long i)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C) (Syntax: 'new C(d)')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_MultipleArgumentsAndApplicableSymbols()
{
string source = @"
class C
{
public C(int i, char c)
{
}
public C(long i, char c)
{
}
void M(dynamic d)
{
char c = 'c';
var x = /*<bind>*/new C(d, c)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C) (Syntax: 'new C(d, c)')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ILocalReferenceExpression: c (OperationKind.LocalReferenceExpression, Type: System.Char) (Syntax: 'c')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ArgumentNames()
{
string source = @"
class C
{
public C(int i, char c)
{
}
public C(long i, char c)
{
}
void M(dynamic d, dynamic e)
{
var x = /*<bind>*/new C(i: d, c: e)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C) (Syntax: 'new C(i: d, c: e)')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(2):
""i""
""c""
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ArgumentRefKinds()
{
string source = @"
class C
{
public C(ref object i, out int j, char c)
{
j = 0;
}
void M(object d, dynamic e)
{
int k;
var x = /*<bind>*/new C(ref d, out k, e)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C) (Syntax: 'new C(ref d, out k, e)')
Arguments(3):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'd')
ILocalReferenceExpression: k (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'k')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(0)
ArgumentRefKinds(3):
Ref
Out
None
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_Initializer()
{
string source = @"
class C
{
public int X;
public C(char c)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d) { X = 0 }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C) (Syntax: 'new C(d) { X = 0 }')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C) (Syntax: '{ X = 0 }')
Initializers(1):
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'X = 0')
Left:
IFieldReferenceExpression: System.Int32 C.X (OperationKind.FieldReferenceExpression, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_AllFields()
{
string source = @"
class C
{
public int X;
public C(ref int i, char c)
{
}
public C(ref int i, long c)
{
}
void M(dynamic d)
{
int i = 0;
var x = /*<bind>*/new C(ref i, c: d) { X = 0 }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C) (Syntax: 'new C(ref i ... ) { X = 0 }')
Arguments(2):
ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i')
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(2):
""null""
""c""
ArgumentRefKinds(2):
Ref
None
Initializer:
IObjectOrCollectionInitializerExpression (OperationKind.ObjectOrCollectionInitializerExpression, Type: C) (Syntax: '{ X = 0 }')
Initializers(1):
ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'X = 0')
Left:
IFieldReferenceExpression: System.Int32 C.X (OperationKind.FieldReferenceExpression, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_ErrorBadDynamicMethodArgLambda()
{
string source = @"
using System;
class C
{
static void Main()
{
dynamic y = null;
/*<bind>*/new C(delegate { }, y)/*</bind>*/;
}
public C(Action a, Action y)
{
}
}
";
string expectedOperationTree = @"
IDynamicObjectCreationExpression (OperationKind.DynamicObjectCreationExpression, Type: C, IsInvalid) (Syntax: 'new C(delegate { }, y)')
Arguments(2):
IAnonymousFunctionExpression (Symbol: lambda expression) (OperationKind.AnonymousFunctionExpression, Type: null, IsInvalid) (Syntax: 'delegate { }')
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: '{ }')
IReturnStatement (OperationKind.ReturnStatement, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
ILocalReferenceExpression: y (OperationKind.LocalReferenceExpression, Type: dynamic) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// /*<bind>*/new C(delegate { }, y)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicObjectCreation_OVerloadResolutionFailure()
{
string source = @"
class C
{
public C()
{
}
public C(int i, int j)
{
}
void M(dynamic d)
{
var x = /*<bind>*/new C(d)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidExpression (OperationKind.InvalidExpression, Type: C, IsInvalid) (Syntax: 'new C(d)')
Children(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.C(int, int)'
// var x = /*<bind>*/new C(d)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("j", "C.C(int, int)").WithLocation(14, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests
{
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
/// <summary>
/// Tests grid exceptions propagation.
/// </summary>
public class ExceptionsTest
{
/** */
private const string ExceptionTask = "org.apache.ignite.platform.PlatformExceptionTask";
/// <summary>
/// Before test.
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.KillProcesses();
}
/// <summary>
/// After test.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Tests exceptions.
/// </summary>
[Test]
public void TestExceptions()
{
var grid = StartGrid();
Assert.Throws<ArgumentException>(() => grid.GetCache<object, object>("invalidCacheName"));
var e = Assert.Throws<ClusterGroupEmptyException>(() => grid.GetCluster().ForRemotes().GetMetrics());
Assert.IsNotNull(e.InnerException);
Assert.IsTrue(e.InnerException.Message.StartsWith(
"class org.apache.ignite.cluster.ClusterGroupEmptyException: Cluster group is empty."));
// Check all exceptions mapping.
var comp = grid.GetCompute();
CheckException<BinaryObjectException>(comp, "BinaryObjectException");
CheckException<IgniteException>(comp, "IgniteException");
CheckException<BinaryObjectException>(comp, "BinaryObjectException");
CheckException<ClusterTopologyException>(comp, "ClusterTopologyException");
CheckException<ComputeExecutionRejectedException>(comp, "ComputeExecutionRejectedException");
CheckException<ComputeJobFailoverException>(comp, "ComputeJobFailoverException");
CheckException<ComputeTaskCancelledException>(comp, "ComputeTaskCancelledException");
CheckException<ComputeTaskTimeoutException>(comp, "ComputeTaskTimeoutException");
CheckException<ComputeUserUndeclaredException>(comp, "ComputeUserUndeclaredException");
CheckException<TransactionOptimisticException>(comp, "TransactionOptimisticException");
CheckException<TransactionTimeoutException>(comp, "TransactionTimeoutException");
CheckException<TransactionRollbackException>(comp, "TransactionRollbackException");
CheckException<TransactionHeuristicException>(comp, "TransactionHeuristicException");
CheckException<TransactionDeadlockException>(comp, "TransactionDeadlockException");
CheckException<IgniteFutureCancelledException>(comp, "IgniteFutureCancelledException");
CheckException<ServiceDeploymentException>(comp, "ServiceDeploymentException");
// Check stopped grid.
grid.Dispose();
Assert.Throws<InvalidOperationException>(() => grid.GetCache<object, object>("cache1"));
}
/// <summary>
/// Checks the exception.
/// </summary>
private static void CheckException<T>(ICompute comp, string name) where T : Exception
{
var ex = Assert.Throws<T>(() => comp.ExecuteJavaTask<string>(ExceptionTask, name));
var javaEx = ex.InnerException as JavaException;
Assert.IsNotNull(javaEx);
Assert.IsTrue(javaEx.Message.Contains("at " + ExceptionTask));
Assert.AreEqual(name, javaEx.JavaMessage);
Assert.IsTrue(javaEx.JavaClassName.EndsWith("." + name));
// Check serialization.
var formatter = new BinaryFormatter();
using (var ms = new MemoryStream())
{
formatter.Serialize(ms, ex);
ms.Seek(0, SeekOrigin.Begin);
var res = (T) formatter.Deserialize(ms);
Assert.AreEqual(ex.Message, res.Message);
Assert.AreEqual(ex.Source, res.Source);
Assert.AreEqual(ex.StackTrace, res.StackTrace);
Assert.AreEqual(ex.HelpLink, res.HelpLink);
var resJavaEx = res.InnerException as JavaException;
Assert.IsNotNull(resJavaEx);
Assert.AreEqual(javaEx.Message, resJavaEx.Message);
Assert.AreEqual(javaEx.JavaClassName, resJavaEx.JavaClassName);
Assert.AreEqual(javaEx.JavaMessage, resJavaEx.JavaMessage);
Assert.AreEqual(javaEx.StackTrace, resJavaEx.StackTrace);
Assert.AreEqual(javaEx.Source, resJavaEx.Source);
Assert.AreEqual(javaEx.HelpLink, resJavaEx.HelpLink);
}
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateException()
{
// Primitive type
TestPartialUpdateException(false, (x, g) => x);
// User type
TestPartialUpdateException(false, (x, g) => new BinarizableEntry(x));
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation in binary mode.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateExceptionBinarizable()
{
// User type
TestPartialUpdateException(false, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x)));
}
/// <summary>
/// Tests CachePartialUpdateException serialization.
/// </summary>
[Test]
public void TestPartialUpdateExceptionSerialization()
{
// Inner exception
TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg",
new IgniteException("Inner msg")));
// Primitive keys
TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg", new object[] {1, 2, 3}));
// User type keys
TestPartialUpdateExceptionSerialization(new CachePartialUpdateException("Msg",
new object[]
{
new SerializableEntry(1),
new SerializableEntry(2),
new SerializableEntry(3)
}));
}
/// <summary>
/// Tests that all exceptions have mandatory constructors and are serializable.
/// </summary>
[Test]
public void TestAllExceptionsConstructors()
{
var types = typeof(IIgnite).Assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Exception)));
foreach (var type in types)
{
Assert.IsTrue(type.IsSerializable, "Exception is not serializable: " + type);
// Default ctor.
var defCtor = type.GetConstructor(new Type[0]);
Assert.IsNotNull(defCtor);
var ex = (Exception) defCtor.Invoke(new object[0]);
Assert.AreEqual(string.Format("Exception of type '{0}' was thrown.", type.FullName), ex.Message);
// Message ctor.
var msgCtor = type.GetConstructor(new[] {typeof(string)});
Assert.IsNotNull(msgCtor);
ex = (Exception) msgCtor.Invoke(new object[] {"myMessage"});
Assert.AreEqual("myMessage", ex.Message);
// Serialization.
var stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, ex);
stream.Seek(0, SeekOrigin.Begin);
ex = (Exception) formatter.Deserialize(stream);
Assert.AreEqual("myMessage", ex.Message);
// Message+cause ctor.
var msgCauseCtor = type.GetConstructor(new[] { typeof(string), typeof(Exception) });
Assert.IsNotNull(msgCauseCtor);
ex = (Exception) msgCauseCtor.Invoke(new object[] {"myMessage", new Exception("innerEx")});
Assert.AreEqual("myMessage", ex.Message);
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("innerEx", ex.InnerException.Message);
}
}
/// <summary>
/// Tests CachePartialUpdateException serialization.
/// </summary>
private static void TestPartialUpdateExceptionSerialization(Exception ex)
{
var formatter = new BinaryFormatter();
var stream = new MemoryStream();
formatter.Serialize(stream, ex);
stream.Seek(0, SeekOrigin.Begin);
var ex0 = (Exception) formatter.Deserialize(stream);
var updateEx = ((CachePartialUpdateException) ex);
try
{
Assert.AreEqual(updateEx.GetFailedKeys<object>(),
((CachePartialUpdateException) ex0).GetFailedKeys<object>());
}
catch (Exception e)
{
if (typeof(IgniteException) != e.GetType())
throw;
}
while (ex != null && ex0 != null)
{
Assert.AreEqual(ex0.GetType(), ex.GetType());
Assert.AreEqual(ex.Message, ex0.Message);
ex = ex.InnerException;
ex0 = ex0.InnerException;
}
Assert.AreEqual(ex, ex0);
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateExceptionAsync()
{
// Primitive type
TestPartialUpdateException(true, (x, g) => x);
// User type
TestPartialUpdateException(true, (x, g) => new BinarizableEntry(x));
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation in binary mode.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestPartialUpdateExceptionAsyncBinarizable()
{
TestPartialUpdateException(true, (x, g) => g.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry(x)));
}
/// <summary>
/// Tests that invalid spring URL results in a meaningful exception.
/// </summary>
[Test]
public void TestInvalidSpringUrl()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = "z:\\invalid.xml"
};
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
Assert.IsTrue(ex.ToString().Contains("Spring XML configuration path is invalid: z:\\invalid.xml"));
}
/// <summary>
/// Tests that invalid configuration parameter results in a meaningful exception.
/// </summary>
[Test]
public void TestInvalidConfig()
{
var disco = TestUtils.GetStaticDiscovery();
disco.SocketTimeout = TimeSpan.FromSeconds(-1); // set invalid timeout
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi = disco
};
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
Assert.IsTrue(ex.ToString().Contains("SPI parameter failed condition check: sockTimeout > 0"));
}
/// <summary>
/// Tests CachePartialUpdateException keys propagation.
/// </summary>
private static void TestPartialUpdateException<TK>(bool async, Func<int, IIgnite, TK> keyFunc)
{
using (var grid = StartGrid())
{
var cache = grid.GetOrCreateCache<TK, int>("partitioned_atomic").WithNoRetries();
if (typeof (TK) == typeof (IBinaryObject))
cache = cache.WithKeepBinary<TK, int>();
// Do cache puts in parallel
var putTask = Task.Factory.StartNew(() =>
{
try
{
// Do a lot of puts so that one fails during Ignite stop
for (var i = 0; i < 1000000; i++)
{
// ReSharper disable once AccessToDisposedClosure
// ReSharper disable once AccessToModifiedClosure
var dict = Enumerable.Range(1, 100).ToDictionary(k => keyFunc(k, grid), k => i);
if (async)
cache.PutAllAsync(dict).Wait();
else
cache.PutAll(dict);
}
}
catch (AggregateException ex)
{
CheckPartialUpdateException<TK>((CachePartialUpdateException) ex.InnerException);
return;
}
catch (CachePartialUpdateException ex)
{
CheckPartialUpdateException<TK>(ex);
return;
}
Assert.Fail("CachePartialUpdateException has not been thrown.");
});
while (true)
{
Thread.Sleep(1000);
Ignition.Stop("grid_2", true);
StartGrid("grid_2");
Thread.Sleep(1000);
if (putTask.Exception != null)
throw putTask.Exception;
if (putTask.IsCompleted)
return;
}
}
}
/// <summary>
/// Checks the partial update exception.
/// </summary>
private static void CheckPartialUpdateException<TK>(CachePartialUpdateException ex)
{
var failedKeys = ex.GetFailedKeys<TK>();
Assert.IsTrue(failedKeys.Any());
var failedKeysObj = ex.GetFailedKeys<object>();
Assert.IsTrue(failedKeysObj.Any());
}
/// <summary>
/// Starts the grid.
/// </summary>
private static IIgnite StartGrid(string gridName = null)
{
return Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = gridName,
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new[]
{
new BinaryTypeConfiguration(typeof (BinarizableEntry))
}
}
});
}
/// <summary>
/// Binarizable entry.
/// </summary>
private class BinarizableEntry
{
/** Value. */
private readonly int _val;
/** <inheritDot /> */
public override int GetHashCode()
{
return _val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public BinarizableEntry(int val)
{
_val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
var entry = obj as BinarizableEntry;
return entry != null && entry._val == _val;
}
}
/// <summary>
/// Serializable entry.
/// </summary>
[Serializable]
private class SerializableEntry
{
/** Value. */
private readonly int _val;
/** <inheritDot /> */
public override int GetHashCode()
{
return _val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public SerializableEntry(int val)
{
_val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
var entry = obj as SerializableEntry;
return entry != null && entry._val == _val;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Settings/Master/EncounterSettings.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Settings.Master {
/// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/EncounterSettings.proto</summary>
public static partial class EncounterSettingsReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Settings/Master/EncounterSettings.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static EncounterSettingsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjJQT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9FbmNvdW50ZXJTZXR0aW5n",
"cy5wcm90bxIaUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXN0ZXIirgEKEUVuY291",
"bnRlclNldHRpbmdzEhwKFHNwaW5fYm9udXNfdGhyZXNob2xkGAEgASgCEiEK",
"GWV4Y2VsbGVudF90aHJvd190aHJlc2hvbGQYAiABKAISHQoVZ3JlYXRfdGhy",
"b3dfdGhyZXNob2xkGAMgASgCEhwKFG5pY2VfdGhyb3dfdGhyZXNob2xkGAQg",
"ASgCEhsKE21pbGVzdG9uZV90aHJlc2hvbGQYBSABKAViBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.EncounterSettings), global::POGOProtos.Settings.Master.EncounterSettings.Parser, new[]{ "SpinBonusThreshold", "ExcellentThrowThreshold", "GreatThrowThreshold", "NiceThrowThreshold", "MilestoneThreshold" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class EncounterSettings : pb::IMessage<EncounterSettings> {
private static readonly pb::MessageParser<EncounterSettings> _parser = new pb::MessageParser<EncounterSettings>(() => new EncounterSettings());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EncounterSettings> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Settings.Master.EncounterSettingsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EncounterSettings() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EncounterSettings(EncounterSettings other) : this() {
spinBonusThreshold_ = other.spinBonusThreshold_;
excellentThrowThreshold_ = other.excellentThrowThreshold_;
greatThrowThreshold_ = other.greatThrowThreshold_;
niceThrowThreshold_ = other.niceThrowThreshold_;
milestoneThreshold_ = other.milestoneThreshold_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EncounterSettings Clone() {
return new EncounterSettings(this);
}
/// <summary>Field number for the "spin_bonus_threshold" field.</summary>
public const int SpinBonusThresholdFieldNumber = 1;
private float spinBonusThreshold_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float SpinBonusThreshold {
get { return spinBonusThreshold_; }
set {
spinBonusThreshold_ = value;
}
}
/// <summary>Field number for the "excellent_throw_threshold" field.</summary>
public const int ExcellentThrowThresholdFieldNumber = 2;
private float excellentThrowThreshold_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float ExcellentThrowThreshold {
get { return excellentThrowThreshold_; }
set {
excellentThrowThreshold_ = value;
}
}
/// <summary>Field number for the "great_throw_threshold" field.</summary>
public const int GreatThrowThresholdFieldNumber = 3;
private float greatThrowThreshold_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float GreatThrowThreshold {
get { return greatThrowThreshold_; }
set {
greatThrowThreshold_ = value;
}
}
/// <summary>Field number for the "nice_throw_threshold" field.</summary>
public const int NiceThrowThresholdFieldNumber = 4;
private float niceThrowThreshold_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float NiceThrowThreshold {
get { return niceThrowThreshold_; }
set {
niceThrowThreshold_ = value;
}
}
/// <summary>Field number for the "milestone_threshold" field.</summary>
public const int MilestoneThresholdFieldNumber = 5;
private int milestoneThreshold_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int MilestoneThreshold {
get { return milestoneThreshold_; }
set {
milestoneThreshold_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EncounterSettings);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EncounterSettings other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (SpinBonusThreshold != other.SpinBonusThreshold) return false;
if (ExcellentThrowThreshold != other.ExcellentThrowThreshold) return false;
if (GreatThrowThreshold != other.GreatThrowThreshold) return false;
if (NiceThrowThreshold != other.NiceThrowThreshold) return false;
if (MilestoneThreshold != other.MilestoneThreshold) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (SpinBonusThreshold != 0F) hash ^= SpinBonusThreshold.GetHashCode();
if (ExcellentThrowThreshold != 0F) hash ^= ExcellentThrowThreshold.GetHashCode();
if (GreatThrowThreshold != 0F) hash ^= GreatThrowThreshold.GetHashCode();
if (NiceThrowThreshold != 0F) hash ^= NiceThrowThreshold.GetHashCode();
if (MilestoneThreshold != 0) hash ^= MilestoneThreshold.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (SpinBonusThreshold != 0F) {
output.WriteRawTag(13);
output.WriteFloat(SpinBonusThreshold);
}
if (ExcellentThrowThreshold != 0F) {
output.WriteRawTag(21);
output.WriteFloat(ExcellentThrowThreshold);
}
if (GreatThrowThreshold != 0F) {
output.WriteRawTag(29);
output.WriteFloat(GreatThrowThreshold);
}
if (NiceThrowThreshold != 0F) {
output.WriteRawTag(37);
output.WriteFloat(NiceThrowThreshold);
}
if (MilestoneThreshold != 0) {
output.WriteRawTag(40);
output.WriteInt32(MilestoneThreshold);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (SpinBonusThreshold != 0F) {
size += 1 + 4;
}
if (ExcellentThrowThreshold != 0F) {
size += 1 + 4;
}
if (GreatThrowThreshold != 0F) {
size += 1 + 4;
}
if (NiceThrowThreshold != 0F) {
size += 1 + 4;
}
if (MilestoneThreshold != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(MilestoneThreshold);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EncounterSettings other) {
if (other == null) {
return;
}
if (other.SpinBonusThreshold != 0F) {
SpinBonusThreshold = other.SpinBonusThreshold;
}
if (other.ExcellentThrowThreshold != 0F) {
ExcellentThrowThreshold = other.ExcellentThrowThreshold;
}
if (other.GreatThrowThreshold != 0F) {
GreatThrowThreshold = other.GreatThrowThreshold;
}
if (other.NiceThrowThreshold != 0F) {
NiceThrowThreshold = other.NiceThrowThreshold;
}
if (other.MilestoneThreshold != 0) {
MilestoneThreshold = other.MilestoneThreshold;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 13: {
SpinBonusThreshold = input.ReadFloat();
break;
}
case 21: {
ExcellentThrowThreshold = input.ReadFloat();
break;
}
case 29: {
GreatThrowThreshold = input.ReadFloat();
break;
}
case 37: {
NiceThrowThreshold = input.ReadFloat();
break;
}
case 40: {
MilestoneThreshold = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* 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>
/// TaxProviderUltraCartState
/// </summary>
[DataContract]
public partial class TaxProviderUltraCartState : IEquatable<TaxProviderUltraCartState>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="TaxProviderUltraCartState" /> class.
/// </summary>
/// <param name="enabled">True if this state taxes are managed by UltraCart.</param>
/// <param name="stateCode">State Code (2 digits).</param>
/// <param name="stateName">Fully spelled out state name.</param>
/// <param name="taxGiftCharge">True if gift charges should be taxed in this state..</param>
/// <param name="taxGiftWrap">True if gift wrap should be taxed in this state..</param>
/// <param name="taxRateFormatted">State tax rate formatted for display.</param>
/// <param name="taxShipping">True if shipping should be taxed in this state..</param>
public TaxProviderUltraCartState(bool? enabled = default(bool?), string stateCode = default(string), string stateName = default(string), bool? taxGiftCharge = default(bool?), bool? taxGiftWrap = default(bool?), string taxRateFormatted = default(string), bool? taxShipping = default(bool?))
{
this.Enabled = enabled;
this.StateCode = stateCode;
this.StateName = stateName;
this.TaxGiftCharge = taxGiftCharge;
this.TaxGiftWrap = taxGiftWrap;
this.TaxRateFormatted = taxRateFormatted;
this.TaxShipping = taxShipping;
}
/// <summary>
/// True if this state taxes are managed by UltraCart
/// </summary>
/// <value>True if this state taxes are managed by UltraCart</value>
[DataMember(Name="enabled", EmitDefaultValue=false)]
public bool? Enabled { get; set; }
/// <summary>
/// State Code (2 digits)
/// </summary>
/// <value>State Code (2 digits)</value>
[DataMember(Name="state_code", EmitDefaultValue=false)]
public string StateCode { get; set; }
/// <summary>
/// Fully spelled out state name
/// </summary>
/// <value>Fully spelled out state name</value>
[DataMember(Name="state_name", EmitDefaultValue=false)]
public string StateName { get; set; }
/// <summary>
/// True if gift charges should be taxed in this state.
/// </summary>
/// <value>True if gift charges should be taxed in this state.</value>
[DataMember(Name="tax_gift_charge", EmitDefaultValue=false)]
public bool? TaxGiftCharge { get; set; }
/// <summary>
/// True if gift wrap should be taxed in this state.
/// </summary>
/// <value>True if gift wrap should be taxed in this state.</value>
[DataMember(Name="tax_gift_wrap", EmitDefaultValue=false)]
public bool? TaxGiftWrap { get; set; }
/// <summary>
/// State tax rate formatted for display
/// </summary>
/// <value>State tax rate formatted for display</value>
[DataMember(Name="tax_rate_formatted", EmitDefaultValue=false)]
public string TaxRateFormatted { get; set; }
/// <summary>
/// True if shipping should be taxed in this state.
/// </summary>
/// <value>True if shipping should be taxed in this state.</value>
[DataMember(Name="tax_shipping", EmitDefaultValue=false)]
public bool? TaxShipping { 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 TaxProviderUltraCartState {\n");
sb.Append(" Enabled: ").Append(Enabled).Append("\n");
sb.Append(" StateCode: ").Append(StateCode).Append("\n");
sb.Append(" StateName: ").Append(StateName).Append("\n");
sb.Append(" TaxGiftCharge: ").Append(TaxGiftCharge).Append("\n");
sb.Append(" TaxGiftWrap: ").Append(TaxGiftWrap).Append("\n");
sb.Append(" TaxRateFormatted: ").Append(TaxRateFormatted).Append("\n");
sb.Append(" TaxShipping: ").Append(TaxShipping).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 TaxProviderUltraCartState);
}
/// <summary>
/// Returns true if TaxProviderUltraCartState instances are equal
/// </summary>
/// <param name="input">Instance of TaxProviderUltraCartState to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TaxProviderUltraCartState input)
{
if (input == null)
return false;
return
(
this.Enabled == input.Enabled ||
(this.Enabled != null &&
this.Enabled.Equals(input.Enabled))
) &&
(
this.StateCode == input.StateCode ||
(this.StateCode != null &&
this.StateCode.Equals(input.StateCode))
) &&
(
this.StateName == input.StateName ||
(this.StateName != null &&
this.StateName.Equals(input.StateName))
) &&
(
this.TaxGiftCharge == input.TaxGiftCharge ||
(this.TaxGiftCharge != null &&
this.TaxGiftCharge.Equals(input.TaxGiftCharge))
) &&
(
this.TaxGiftWrap == input.TaxGiftWrap ||
(this.TaxGiftWrap != null &&
this.TaxGiftWrap.Equals(input.TaxGiftWrap))
) &&
(
this.TaxRateFormatted == input.TaxRateFormatted ||
(this.TaxRateFormatted != null &&
this.TaxRateFormatted.Equals(input.TaxRateFormatted))
) &&
(
this.TaxShipping == input.TaxShipping ||
(this.TaxShipping != null &&
this.TaxShipping.Equals(input.TaxShipping))
);
}
/// <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.Enabled != null)
hashCode = hashCode * 59 + this.Enabled.GetHashCode();
if (this.StateCode != null)
hashCode = hashCode * 59 + this.StateCode.GetHashCode();
if (this.StateName != null)
hashCode = hashCode * 59 + this.StateName.GetHashCode();
if (this.TaxGiftCharge != null)
hashCode = hashCode * 59 + this.TaxGiftCharge.GetHashCode();
if (this.TaxGiftWrap != null)
hashCode = hashCode * 59 + this.TaxGiftWrap.GetHashCode();
if (this.TaxRateFormatted != null)
hashCode = hashCode * 59 + this.TaxRateFormatted.GetHashCode();
if (this.TaxShipping != null)
hashCode = hashCode * 59 + this.TaxShipping.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)
{
yield break;
}
}
}
| |
#region Usings
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Xml;
using Skahal.Logging;
using Skahal.Common;
using System.Collections.Generic;
using Buildron.Infrastructure;
using Skahal.Threading;
using Buildron.Infrastructure.BuildsProviders;
using System.Net;
#endregion
public class Requester : MonoBehaviour
{
#region Constants
public const float WaitForSecondsBetweenRequests = 0.1f;
#endregion
#region Events
public event EventHandler<RequestFailedEventArgs> GetFailed;
#endregion
#region Fields
private Queue<Action> m_requestsImmediatelyQueue = new Queue<Action>();
private Queue<Action> m_requestsQueue = new Queue<Action>();
#endregion
#region Constructors
static Requester ()
{
Instance = new GameObject ("BuildronRequester").AddComponent<Requester> ();
}
#endregion
#region Properties
public static Requester Instance { get; private set; }
public bool AcceptLanguageEnabled { get; set; }
#endregion
#region Methods
private void Awake ()
{
StartCoroutine (DequeueRequests ());
}
private IEnumerator DequeueRequests ()
{
while (true) {
if (m_requestsImmediatelyQueue.Count == 0) {
if (m_requestsQueue.Count > 0) {
m_requestsQueue.Dequeue () ();
}
} else {
m_requestsImmediatelyQueue.Dequeue () ();
}
// Be polite with the CI Server ;)
yield return new WaitForSeconds(WaitForSecondsBetweenRequests);
}
}
public void Get (string url, Action<XmlDocument> responseReceived, Action<RequestError> errorReceived = null)
{
m_requestsQueue.Enqueue (() =>
{
StartCoroutine (DoGet (url, responseReceived, errorReceived));
});
}
public void GetImmediately (string url, Action<XmlDocument> responseReceived, Action<RequestError> errorReceived = null)
{
m_requestsImmediatelyQueue.Enqueue (() =>
{
StartCoroutine (DoGet (url, responseReceived, errorReceived));
});
}
public void GetText (string url, Action<string> responseReceived, Action<RequestError> errorReceived = null)
{
m_requestsQueue.Enqueue (() =>
{
StartCoroutine (DoGet (url, responseReceived, errorReceived));
});
}
public void PostText (string url, Dictionary<string,string> fields, Action<string> responseReceived, Action<RequestError> errorReceived = null)
{
m_requestsQueue.Enqueue (() =>
{
StartCoroutine (DoPost (url, fields, responseReceived, errorReceived));
});
}
private IEnumerator DoPost (string url, Dictionary<string,string> fields, Action<string> responseReceived, Action<RequestError> errorReceived = null)
{
return DoBasicGet (url, (response) => {
responseReceived (response.text);
}, errorReceived, fields);
}
public void GetTextImmediately (string url, Action<string> responseReceived, Action<RequestError> errorReceived = null)
{
m_requestsImmediatelyQueue.Enqueue (() =>
{
StartCoroutine (DoGet (url, responseReceived, errorReceived));
});
}
public void Request (string url)
{
m_requestsQueue.Enqueue (() =>
{
StartCoroutine (DoBasicGet (url, null));
});
}
public void RequestImmediately (string url)
{
m_requestsImmediatelyQueue.Enqueue (() =>
{
StartCoroutine (DoBasicGet (url, null));
});
}
public void GetTexture (string url, Action<Texture2D> responseReceived, Action<RequestError> errorReceived = null)
{
m_requestsQueue.Enqueue (() =>
{
StartCoroutine (DoGet (url, responseReceived, errorReceived));
});
}
private IEnumerator DoGet (string url, Action<XmlDocument> responseReceived, Action<RequestError> errorReceived = null)
{
return DoBasicGet (url, (response) => {
var doc = new XmlDocument ();
doc.LoadXml (response.text);
responseReceived (doc);
}, errorReceived);
}
private IEnumerator DoGet (string url, Action<string> responseReceived, Action<RequestError> errorReceived = null)
{
return DoBasicGet (url, (response) => {
responseReceived (response.text);
}, errorReceived);
}
private IEnumerator DoGet (string url, Action<Texture2D> responseReceived, Action<RequestError> errorReceived = null)
{
return DoBasicGet (url, (response) => {
responseReceived (response.texture);
},
errorReceived);
}
private IEnumerator DoBasicGet (string url, Action<WWW> responseReceived)
{
return DoBasicGet(url, responseReceived, null, null);
}
private IEnumerator DoBasicGet (string url, Action<WWW> responseReceived, Action<RequestError> errorReceived, Dictionary<string, string> fields = null)
{
SHLog.Debug ("Requesting URL '{0}' on the server...", url);
WWW request;
if (AcceptLanguageEnabled) {
var form = new WWWForm ();
form.AddField ("Buildron", SHGameInfo.Version);
var headers = form.headers;
var rawData = form.data;
headers ["Accept-Language"] = "en-US";
request = new WWW (url, rawData, headers);
} if (fields != null) {
var form = new WWWForm ();
foreach(var f in fields)
{
form.AddField(f.Key, f.Value);
}
request = new WWW (url, form);
}
else {
request = new WWW (url);
}
// Timeout
bool hasTimeout = false;
SHCoroutine.Start(
60,
() =>
{
if(request != null && !request.isDone)
{
try
{
SHLog.Warning("Request timeout for url {0}.", url);
hasTimeout = true;
request.Dispose();
}
catch(ObjectDisposedException)
{
SHLog.Warning("Request already disposed.", url);
return;
}
}
});
yield return request;
if (hasTimeout)
{
if (errorReceived != null)
{
errorReceived(new RequestError
{
Message = "Timeout",
StatusCode = HttpStatusCode.RequestTimeout
});
}
else
{
GetFailed.Raise(this, new RequestFailedEventArgs(url));
}
}
else
{
var status = request.responseHeaders.ContainsKey("STATUS") ? request.responseHeaders["STATUS"] : "";
if (request.error == null
&& !status.Equals("HTTP/1.0 302 Found", StringComparison.InvariantCultureIgnoreCase)
&& !request.text.Contains("Status Code: 404"))
{
SHLog.Debug("Response from server to URL '{0}': {1}", url, request.text);
if (responseReceived != null)
{
try
{
responseReceived(request);
}
catch(Exception ex)
{
SHLog.Warning("Error calling responseReceived for url '{0}': {1}. {2}", url, ex.Message, ex.StackTrace);
GetFailed.Raise(this, new RequestFailedEventArgs(url));
}
}
}
else {
SHLog.Warning("Error from server to URL '{0}': {1}", url, request.error);
var errorMsg = request.error ?? request.text ?? string.Empty;
var statusCode = errorMsg.Contains("404 Not Found") || errorMsg.Contains("Status Code: 404")
? HttpStatusCode.NotFound
: HttpStatusCode.BadRequest;
if (errorReceived != null)
{
errorReceived(new RequestError
{
Message = errorMsg,
StatusCode = statusCode
});
}
else if (statusCode != HttpStatusCode.NotFound)
{
SHLog.Warning("Error requesting URL '{0}': {1}", url, request.error == null ? status : request.error);
GetFailed.Raise(this, new RequestFailedEventArgs(url));
}
}
}
}
#endregion
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace Multiverse.Interface
{
public interface IUIObject
{
/// <summary>
/// Get the alpha value for this widget. This does not
/// include the effect of the alpha values of the parent
/// widgets.
/// </summary>
/// <returns>the alpha value for this widget</returns>
float GetAlpha();
/// <summary>
/// Gets the name of the widget
/// </summary>
/// <returns>name of the widget</returns>
string GetName();
/// <summary>
/// Sets the alpha value of a widget.
/// </summary>
/// <param name="alpha">alpha value of this widget. A value of 0 corresponds to a transparent widget, while a value of 1 corresponds to an opaque widget</param>
void SetAlpha(float alpha);
}
/// <summary>
/// IRegion is the base interface for the various widgets.
/// </summary>
public interface IRegion : IUIObject
{
/// <summary>
/// Get the y coordinate of the top edge of this widget
/// </summary>
/// <returns>the y coordinate in pixels of the top edge where
/// higher values are higher on the screen</returns>
int GetTop();
/// <summary>
/// Get the y coordinate of the bottom edge of this widget
/// </summary>
/// <returns>the y coordinate in pixels of the bottom edge where
/// higher values are higher on the screen</returns>
int GetBottom();
/// <summary>
/// Get the x coordinate of the left edge of this widget
/// </summary>
/// <returns>the x coordinate in pixels of the left edge</returns>
int GetLeft();
/// <summary>
/// Get the x coordinate of the right edge of this widget
/// </summary>
/// <returns>the x coordinate in pixels of the right edge</returns>
int GetRight();
/// <summary>
/// Get this region's parent frame. This is the parent in layout,
/// rather than the parent in inheritance.
/// </summary>
/// <returns>this region's parent frame</returns>
IRegion GetParent();
/// <summary>
/// Clears all the anchors for this object
/// </summary>
void ClearAllPoints();
/// <summary>
/// Gets the height of this widget
/// </summary>
/// <returns>the height of the widget in pixels</returns>
int GetHeight();
/// <summary>
/// Sets the height of this widget
/// </summary>
/// <param name="height">the height in pixels</param>
void SetHeight(int height);
/// <summary>
/// Gets the width of this widget
/// </summary>
/// <returns>the width of the widget in pixels</returns>
int GetWidth();
/// <summary>
/// Sets the width of this widget
/// </summary>
/// <param name="width">the width in pixels</param>
void SetWidth(int width);
/// <summary>
/// Mark the widget as hidden. If the widget, or any of the
/// widget's parents are hidden, the widget will not be displayed.
/// </summary>
void Hide();
/// <summary>
/// Mark the widget as visible. If the widget, or any of the
/// widget's parents are hidden, the widget will not be displayed.
/// </summary>
void Show();
/// <summary>
/// Check to see if the widget is marked as visible. If the
/// widget, or any of the widget's parents are hidden,
/// the widget will not be displayed.
/// </summary>
/// <returns>Whether the widget is marked as visible</returns>
bool IsVisible();
/// <summary>
/// Set an anchor point for the widget.
/// </summary>
/// <param name="point">Which point of our widget that we are anchoring</param>
/// <param name="relativeTo">the name of the widget to which we are anchoring</param>
/// <param name="relativePoint">Which point of the target widget that we are anchoring to</param>
void SetPoint(string point, string relativeTo, string relativePoint);
/// <summary>
/// Set an anchor point for the widget.
/// </summary>
/// <param name="point">Which point of our widget that we are anchoring</param>
/// <param name="relativeTo">the name of the widget to which we are anchoring</param>
/// <param name="relativePoint">Which point of the target widget that we are anchoring to</param>
/// <param name="xOffset">Horizontal offset in pixels from the target</param>
/// <param name="yOffset">Vertical offset in pixels from the target. Higher points on the screen have a larger yOffset.</param>
void SetPoint(string point, string relativeTo, string relativePoint, int xOffset, int yOffset);
}
/// <summary>
/// Class used for display of text.
/// </summary>
public interface IFontString : ILayeredRegion
{
/// <summary>
/// Get the width of the text in the widget.
/// </summary>
/// <returns>the width in pixels of the string that is displayed</returns>
int GetStringWidth();
/// <summary>
/// Get the text of the widget
/// </summary>
/// <returns>the text that is displayed</returns>
string GetText();
/// <summary>
/// Set the text of the widget
/// </summary>
/// <param name="text">the text that will be displayed</param>
void SetText(string text);
/// <summary>
/// Sets the horizontal justification of a widget.
/// </summary>
/// <param name="justify">justification value'</param>
void SetJustifyH(string justify);
/// <summary>
/// Sets the vertical justification of a widget.
/// </summary>
/// <param name="justify">justification value'</param>
void SetJustifyV(string justify);
/// <summary>
/// Sets the color of the text
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
void SetTextColor(float r, float g, float b);
/// <summary>
/// Sets the color of the text
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
/// <param name="a">Alpha value (from 0 to 1)</param>
void SetTextColor(float r, float g, float b, float a);
/// <summary>
/// Sets the text height
/// </summary>
/// <param name="pixelHeight">the lineheight in pixels</param>
void SetTextHeight(int pixelHeight);
#region Unimplemented
//FontString:SetAlphaGradient(start,length)
#endregion
}
/// <summary>
/// Class used for displaying an image
/// </summary>
public interface ITexture : ILayeredRegion {
/// <summary>
/// Sets the texture coordinates for this widget. This allows for
/// the display of a portion of the base texture.
/// </summary>
/// <param name="x0">x coordinate of the left (from 0 to 1)</param>
/// <param name="y0">y coordinate of the top (from 0 to 1)</param>
/// <param name="x1">x coordinate of the right (from 0 to 1)</param>
/// <param name="y1">x coordinate of the bottom (from 0 to 1)</param>
void SetTexCoord(float x0, float y0, float x1, float y1);
/// <summary>
/// The complex way of setting up coordinates for situations
/// where the texture is either not being laid out with its
/// default orientation or not rectangular.
/// </summary>
/// <param name="ul_x">x coordinate of the upper left corner (from 0 to 1)</param>
/// <param name="ul_y">y coordinate of the upper left corner (from 0 to 1)</param>
/// <param name="ll_x">x coordinate of the lower left corner (from 0 to 1)</param>
/// <param name="ll_y">y coordinate of the lower left corner (from 0 to 1)</param>
/// <param name="ur_x">x coordinate of the upper right corner (from 0 to 1)</param>
/// <param name="ur_y">y coordinate of the upper right corner (from 0 to 1)</param>
/// <param name="lr_x">x coordinate of the lower right corner (from 0 to 1)</param>
/// <param name="lr_y">y coordinate of the lower right corner (from 0 to 1)</param>
void SetTexCoord(float ul_x, float ul_y, float ll_x, float ll_y, float ur_x, float ur_y, float lr_x, float lr_y);
/// <summary>
/// Sets the image texture to use. This should be a three part
/// string, like 'Interface\\ContainerFrame\\UI-Backpack-Background'.
/// The first portion is ignored, the second portion indicates
/// which imageset should be used, and the third portion indicates
/// which image within that imageset should be used.
/// </summary>
/// <param name="textureFile">texture to use</param>
void SetTexture(string textureFile);
#region Unimplemented
//Texture:GetBlendMode() - Return the blend mode set by SetBlendMode()
//Texture:GetTexCoord() - Gets the 8 texture coordinates that map to the Texture's corners - New in 1.11.
//Texture:GetTexCoordModifiesRect() - Get the SetTexCoordModifiesRect setting - New in 1.11
//Texture:GetTexture() - Gets this texture's current texture path.
//Texture:GetVertexColor() - Gets the vertex color for the Texture.
//Texture:IsDesaturated() - Gets the desaturation state of this Texture. - New in 1.11
//Texture:SetBlendMode("mode") - Set the alphaMode of the texture.
//Texture:SetDesaturated(flag) - Set whether this texture should be displayed with no saturation (Note: This has a return value)
//Texture:SetGradient("orientation", minR, minG, minB, maxR, maxG, maxB)
//Texture:SetGradientAlpha("orientation", minR, minG, minB, minA, maxR, maxG, maxB, maxA)
//Texture:SetTexCoordModifiesRect(enableFlag) - Set whether future SetTexCoord operations should modify the display rectangle rather than stretch the texture. - New in 1.11
//Texture:SetTexture(r, g, b[, a]) - Sets the texture to be displayed from a file or to a solid color.
#endregion
}
/// <summary>
/// This class is the base for widgets that can contain other widgets.
/// </summary>
public interface IFrame : IRegion {
/// <summary>
/// Get the id associated with this widget
/// </summary>
/// <returns>id associated with this widget</returns>
int GetID();
/// <summary>
/// Gets the FrameLevel of this frame. Generally, this is one more
/// than our UIParent's frame level.
/// </summary>
/// <returns>the frame level of this frame</returns>
int GetFrameLevel();
/// <summary>
/// Gets the FrameStrata of this frame.
/// </summary>
/// <returns>the frame strata of this frame</returns>
string GetFrameStrata();
/// <summary>
/// Register for callbacks for events with the given name
/// </summary>
/// <param name="eventName">name of the event we are interested in</param>
void RegisterEvent(string eventName);
/// <summary>
/// Unregister for callbacks for events with the given name
/// </summary>
/// <param name="eventName">name of the event we are no longer interested in</param>
void UnregisterEvent(string eventName);
/// <summary>
/// Sets the id associated with this widget
/// </summary>
/// <param name="id">id to be associated with this widget</param>
void SetID(int id);
/// <summary>
/// Sets the strata of the frame
/// </summary>
/// <param name="strata">the desired frame strata</param>
void SetFrameStrata(string strata);
void SetBackdropColor(float r, float g, float b);
void SetBackdropBorderColor(float r, float g, float b);
/// <summary>
/// Map of properties, keyed by string name.
/// This is so that scripts can associate arbitrary data with a
/// widget, and then look it up later.
/// </summary>
Dictionary<string, object> Properties { get; }
#region Unimplemented
//Frame:DisableDrawLayer
//Frame:EnableDrawLayer
//Frame:EnableKeyboard(enableFlag) - Set whether this frame will get keyboard input.
//Frame:EnableMouse(enableFlag) - Set whether this frame will get mouse input.
//Frame:GetCenter();
//Frame:GetScale() - Get the scale factor of this object relative to its parent.
//Frame:IsMovable() - Determine if the frame can be moved
//Frame:IsResizable() - Determine if the frame can be resized
//Frame:IsShown() - Determine if this frame is shown.
//Frame:IsUserPlaced() - Determine if this frame has been relocated by the user.
//Frame:Lower() - Lower this frame behind other frames.
//Frame:Raise() - Raise this frame above other frames.
//Frame:RegisterForDrag("buttonType"{,"buttonType"...}) - Inidicate that this frame should be notified of drag events for the specified buttons.
//Frame:SetAllPoints("frame")
//Frame:SetFrameLevel(level) - Set the level of this frame (determines which of overlapping frames shows on top).
//Frame:SetMaxResize(maxWidth,maxHeight) - Set the maximum dimensions this frame can be resized to.
//Frame:SetMinResize(minWidth,minHeight) - Set the minimum dimensions this frame can be resized to.
//Frame:SetMovable(isMovable) - Set whether frame can be moved.
//Frame:SetResizable(isResizable) - Set whether frame can be resized.
//Frame:SetScale(scale) - Set the scale factor of this frame relative to its parent.
//Frame:StartMoving() - Start moving this frame.
//Frame:StartSizing("point") - Start sizing this frame using the specified anchor point.
//Frame:StopMovingOrSizing() - Stop moving and/or sizing this frame.
#endregion
}
/// <summary>
/// Class for the button widget
/// </summary>
public interface IButton : IFrame
{
/// <summary>
/// Trigger a click event on the button.
/// </summary>
void Click();
/// <summary>
/// Disable the button. This will generally cause the button to
/// show up as disabled, and will prevent click events.
/// </summary>
void Disable();
/// <summary>
/// Enable the button. This will generally cause the button to
/// show up as normal, and will allow click events.
/// </summary>
void Enable();
/// <summary>
/// Gets the button state (NORMAL or PUSHED)
/// </summary>
/// <returns>the current button state</returns>
string GetButtonState();
/// <summary>
/// Get the text associated with the button.
/// </summary>
/// <returns>the text associated with the button</returns>
string GetText();
/// <summary>
/// Get the lineheight of the text associated with the button.
/// </summary>
/// <returns>the lineheight of the text associated with the button</returns>
int GetTextHeight();
/// <summary>
/// Get the width of the text associated with the button.
/// </summary>
/// <returns>the width of the current text associated with the button</returns>
int GetTextWidth();
/// <summary>
/// Determine whether the button is currently enabled.
/// </summary>
/// <returns>true if the button is enabled, or false if it is not</returns>
bool IsEnabled();
/// <summary>
/// Lock the highlight mode. This will generally cause the button to
/// show up as highlighted.
/// </summary>
void LockHighlight();
/// <summary>
/// Set the color of the text for when the button is disabled.
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
void SetDisabledTextColor(float r, float g, float b);
/// <summary>
/// Set the color of the text for when the button is disabled.
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
/// <param name="a">Alpha value (from 0 to 1)</param>
void SetDisabledTextColor(float r, float g, float b, float a);
/// <summary>
/// Set the texture to use when the button is disabled.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetDisabledTexture(string texture);
/// <summary>
/// Set the texture to use when the button is disabled.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetDisabledTexture(ITexture texture);
/// <summary>
/// Set the color of the text used when the button is highlighted
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
void SetHighlightTextColor(float r, float g, float b); /// <summary>
/// Set the color of the text used when the button is highlighted
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
/// <param name="a">Alpha value (from 0 to 1)</param>
void SetHighlightTextColor(float r, float g, float b, float a);
/// <summary>
/// Set the texture to use when the button is highlighted.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetHighlightTexture(string texture);
/// <summary>
/// Set the texture to use when the button is highlighted.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetHighlightTexture(ITexture texture);
/// <summary>
/// Set the texture to use when the button is in normal mode.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetNormalTexture(string texture); /// <summary>
/// Set the texture to use when the button is in normal mode.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetNormalTexture(ITexture texture);
/// <summary>
/// Set the texture to use when the button is pushed.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetPushedTexture(string texture); /// <summary>
/// Set the texture to use when the button is pushed.
/// </summary>
/// <param name="texture"></param>
/// <seealso cref="ITexture.SetTexture"/>
void SetPushedTexture(ITexture texture);
/// <summary>
/// Set the text to be displayed when the button is in normal mode
/// </summary>
/// <param name="text"></param>
void SetText(string text);
/// <summary>
/// Set the color of the text used when the button is in normal mode
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
void SetTextColor(float r, float g, float b);
/// <summary>
/// Unlock the highlight mode. This will generally cause the button to
/// show up as normal.
/// </summary>
void UnlockHighlight();
/// <summary>
/// Set the button state, but do not lock it
/// </summary>
/// <param name="state">the button state (NORMAL or PUSHED)</param>
void SetButtonState(string state);
/// <summary>
/// Set the button state, and optionally lock it
/// </summary>
/// <param name="state">the button state (NORMAL or PUSHED)</param>
/// <param name="locked">whether the state should be locked (0 for not locked)</param>
void SetButtonState(string state, int locked);
/// <summary>
/// Set the button state, and optionally lock it
/// </summary>
/// <param name="state">the button state (NORMAL or PUSHED)</param>
/// <param name="locked">whether the state should be locked (false for not locked)</param>
void SetButtonState(string state, bool locked);
#region Unimplemented
//Button:GetDisabledFontObject()
//Button:GetDisabledTextColor()
//Button:GetDisabledTexture()
//Button:GetFont()
//Button:GetFontString()
//Button:GetHighlightFontObject()
//Button:GetHighlightTextColor()
//Button:GetHighlightTexture()
//Button:GetNormalTexture()
//Button:GetPushedTextOffset()
//Button:GetPushedTexture()
//Button:GetTextColor()
//Button:GetTextFontObject()
//Button:RegisterForClicks("clickType"{,"clickType"...}) - Indicate which types of clicks this button should receive.
//Button:SetDisabledFontObject()
//Button:SetFont(...)
//Button:SetFontString(fontString)
//Button:SetHighlightFontObject()
//Button:SetPushedTextOffset()
//Button:SetTextFontObject()
#endregion
}
public interface IColorSelect : IFrame {
}
/// <summary>
/// Editable text frame. This is used for widgets like the chat input window.
/// </summary>
public interface IEditBox : IFrame {
/// <summary>
/// Store this text in the history for this widget
/// </summary>
/// <param name="text">the text that should be stored</param>
void AddHistoryLine(string text);
/// <summary>
/// Get the text that is currently entered in the edit box.
/// </summary>
/// <returns></returns>
string GetText();
/// <summary>
/// Set the text for the edit box
/// </summary>
/// <param name="text">text to put in the edit box</param>
void SetText(string text);
/// <summary>
/// Set the color of the text.
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
void SetTextColor(float r, float g, float b);
/// <summary>
/// This isn't really implemented yet, but should shift the text in from the outside of the widget.
/// </summary>
/// <param name="l">inset from the left (in pixels)</param>
/// <param name="r">inset from the right (in pixels)</param>
/// <param name="t">inset from the top (in pixels)</param>
/// <param name="b">inset from the bottom (in pixels)</param>
void SetTextInsets(int l, int r, int t, int b);
/// <summary>
/// Clear the focus (release input)
/// </summary>
void ClearFocus();
/// <summary>
/// Grab the focus
/// </summary>
void SetFocus();
#region Unimplemented
//EditBox:ToggleInputLanguage()
//EditBox:GetInputLanguage() - Get the input language (locale based not in-game)
//EditBox:GetNumLetters() - Gets the number of letters in the box.
//EditBox:GetNumber()
//EditBox:HighlightText({unknown1,unknown2})
//EditBox:Insert("text") - Inserts text at the cursor position
//EditBox:SetMaxBytes(maxBytes) - Set the maximum byte sizes allowed to be entered.
//EditBox:SetMaxLetters(maxLetters) - Set the maximum letter count allowed to be entered.
//EditBox:SetNumber(number)
#endregion
}
/// <summary>
/// This class is awkwardly placed. It is a game specific object.
/// </summary>
public interface IGameTooltip : IFrame {
/// <summary>
/// Set the text for the game tooltip
/// </summary>
/// <param name="text">text to put in the tooltip</param>
void SetText(string text);
/// <summary>
/// Move the game tooltip to a location based on the relative frame
/// and the anchor string. This is just a convenience method that
/// does the same thing as a call to SetPoint.
/// </summary>
/// <param name="frame">the frame to which we will anchor</param>
/// <param name="anchor">name of the anchor e.g. ANCHOR_TOPRIGHT</param>
void SetOwner(IRegion frame, string anchor);
#region Unimplemented
//GameTooltip:AddDoubleLine
//GameTooltip:AddLine
//GameTooltip:AppendText("text") - Append text to the end of the first line of the tooltip.
//GameTooltip:ClearLines
//GameTooltip:FadeOut
//GameTooltip:IsOwned
//GameTooltip:NumLines() - Get the number of lines in the tooltip.
//GameTooltip:SetAction(slot) - Shows the tooltip for the specified action button.
//GameTooltip:SetAuctionCompareItem("type",index{,offset})
//GameTooltip:SetAuctionItem("type",index) - Shows the tooltip for the specified auction item.
//GameTooltip:SetAuctionSellItem
//GameTooltip:SetBagItem
//GameTooltip:SetBuybackItem
//GameTooltip:SetCraftItem
//GameTooltip:SetCraftSpell
//GameTooltip:SetHyperlink(link) - Shows the tooltip for the specified hyperlink (usually item link).
//GameTooltip:SetInboxItem(index) - Shows the tooltip for the specified mail inbox item.
//GameTooltip:SetInventoryItem(unit,slot{,nameOnly})
//GameTooltip:SetLootItem
//GameTooltip:SetLootRollItem(id) - Shows the tooltip for the specified loot roll item.
//GameTooltip:SetMerchantCompareItem("slot"{,offset})
//GameTooltip:SetMerchantItem
//GameTooltip:SetMoneyWidth(width)
//GameTooltip:SetPadding
//GameTooltip:SetPetAction(slot) - Shows the tooltip for the specified pet action.
//GameTooltip:SetPlayerBuff(buffIndex) - Direct the tooltip to show information about a player's buff.
//GameTooltip:SetQuestItem
//GameTooltip:SetQuestLogItem
//GameTooltip:SetQuestLogRewardSpell
//GameTooltip:SetQuestRewardSpell
//GameTooltip:SetSendMailItem
//GameTooltip:SetShapeshift(slot) - Shows the tooltip for the specified shapeshift form.
//GameTooltip:SetSpell(spellId,spellbookTabNum) - Shows the tooltip for the specified spell.
//GameTooltip:SetTalent(tabIndex,talentIndex) - Shows the tooltip for the specified talent.
//GameTooltip:SetText("text",r,g,b{,alphaValue{,textWrap}}) - Set the text of the tooltip.
//GameTooltip:SetTrackingSpell
//GameTooltip:SetTradePlayerItem
//GameTooltip:SetTradeSkillItem
//GameTooltip:SetTradeTargetItem
//GameTooltip:SetTrainerService
//GameTooltip:SetUnit
//GameTooltip:SetUnitBuff("unit",buffIndex) - Shows the tooltip for a unit's buff.
//GameTooltip:SetUnitDebuff("unit",buffIndex) - Shows the tooltip for a unit's debuff.
#endregion
}
public interface ILayeredRegion : IRegion {
string GetDrawLayer();
void SetDrawLayer(string layer);
void SetVertexColor(float r, float g, float b);
void SetVertexColor(float r, float g, float b, float a);
}
public interface IMessageFrame : IFrame {
}
public interface IMinimap : IFrame {
}
public interface IModel : IFrame {
}
public interface IMovieFrame : IFrame {
}
public interface IScrollFrame : IFrame {
float GetHorizontalScroll();
float GetHorizontalScrollRange();
IFrame GetScrollChild();
float GetVerticalScroll();
float GetVerticalScrollRange();
void SetHorizontalScroll(float offset);
void SetScrollChild(IFrame frame);
void SetScrollChild(string frameName);
void SetVerticalScroll(float offset);
void UpdateScrollChildRect();
}
/// <summary>
/// Scrollable text frame. This is used for widgets like the chat window.
/// </summary>
public interface IScrollingMessageFrame : IFrame {
void AddMessage(string text, float r, float g, float b, int id);
int GetFontHeight(); // deprecated??
int GetNumLinesDisplayed();
void ScrollUp();
void ScrollDown();
void ScrollToTop();
void ScrollToBottom();
void SetFontHeight(int pixelHeight);
void SetScrollFromBottom(bool val);
#region Unimplemented
//ScrollingMessageFrame:AtBottom() - Return true if frame is at the bottom.
//ScrollingMessageFrame:AtTop() - Return true if frame is at the top.
//ScrollingMessageFrame:Clear()
//ScrollingMessageFrame:GetCurrentLine()
//ScrollingMessageFrame:GetCurrentScroll()
//ScrollingMessageFrame:GetFadeDuration()
//ScrollingMessageFrame:GetFading()
//ScrollingMessageFrame:GetMaxLines()
//ScrollingMessageFrame:GetNumMessages()
//ScrollingMessageFrame:GetTimeVisible()
//ScrollingMessageFrame:PageDown()
//ScrollingMessageFrame:PageUp()
//ScrollingMessageFrame:SetFadeDuration(seconds)
//ScrollingMessageFrame:SetFading()
//ScrollingMessageFrame:SetFading(isEnabled)
//ScrollingMessageFrame:SetMaxLines(lines)
//ScrollingMessageFrame:SetTimeVisible(seconds)
//ScrollingMessageFrame:UpdateColorByID(id,r,g,b)
#endregion
}
public interface ISimpleHTML : IFrame {
}
public interface ISlider : IFrame {
/// <summary>
/// Get the current value of the slider
/// </summary>
/// <returns>the current value for the slider</returns>
float GetValue();
/// <summary>
/// Get the minimum and maximum values of the slider
/// </summary>
/// <returns>Array of two floats, containing the minimum and maximum
/// values of the slider</returns>
float[] GetMinMaxValues();
/// <summary>
/// Gets the orientation for the slider
/// </summary>
/// <returns>one of HORIZONTAL or VERTICAL</returns>
string GetOrientation();
/// <summary>
/// Gets the value for a single step. This might be used for
/// things like the mouse wheel or arrow keys.
/// </summary>
/// <returns>the step size for the slider</returns>
float GetValueStep();
/// <summary>
/// Set the current value of the slider
/// </summary>
/// <param name="value">value for the slider</param>
void SetValue(float value);
/// <summary>
/// Set up the lower and upper limits of the slider
/// </summary>
/// <param name="min">the lower limit of the slider</param>
/// <param name="max">the upper limit of the slider</param>
void SetMinMaxValues(float min, float max);
/// <summary>
/// Sets the orientation for the slider
/// </summary>
/// <param name="orientation">one of HORIZONTAL or VERTICAL</param>
void SetOrientation(string orientation);
/// <summary>
/// Sets the value for a single step. This might be used for
/// things like the mouse wheel or arrow keys.
/// Currently, the value step is not used.
/// </summary>
/// <param name="val">the step size for the slider</param>
void SetValueStep(float val);
#region Unimplemented
//string GetThumbTexture();
//void SetThumbTexture(string texture);
#endregion
}
/// <summary>
/// Status bar widget.
/// </summary>
public interface IStatusBar : IFrame {
/// <summary>
/// Get the current value of the status bar
/// </summary>
/// <returns>the current value for the status bar</returns>
float GetValue();
/// <summary>
/// Set up the lower and upper limits of the status bar
/// </summary>
/// <param name="min">the lower limit of the status bar</param>
/// <param name="max">the upper limit of the status bar</param>
void SetMinMaxValues(float min, float max);
/// <summary>
/// Sets the orientation for the status bar
/// </summary>
/// <param name="orientation">one of HORIZONTAL or VERTICAL</param>
void SetOrientation(string orientation);
/// <summary>
/// Set the color of the status bar
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
void SetStatusBarColor(float r, float g, float b);
/// <summary>
/// Sets the color and alpha of the status bar
/// </summary>
/// <param name="r">Red value (from 0 to 1)</param>
/// <param name="g">Green value (from 0 to 1)</param>
/// <param name="b">Blue value (from 0 to 1)</param>
/// <param name="a">Alpha value (from 0 to 1)
/// where 0 is transparent and 1 is opaque</param>
void SetStatusBarColor(float r, float g, float b, float a);
/// <summary>
/// Set the current value of the status bar
/// </summary>
/// <param name="value">value for the status bar</param>
void SetValue(float value);
/// <summary>
/// Gets the orientation for the status bar
/// </summary>
/// <returns>one of HORIZONTAL or VERTICAL</returns>
string GetOrientation();
/// <summary>
/// Get the minimum and maximum values of the status bar
/// </summary>
/// <returns>Array of two floats, containing the minimum and maximum
/// values of the status bar</returns>
float[] GetMinMaxValues();
}
public interface ICheckButton : IButton {
bool GetChecked();
void SetChecked();
void SetChecked(bool state);
#region Unimplemented
//string GetCheckedTexture();
//string GetDisabledCheckedTexture();
//void SetCheckedTexture(string texture);
//void SetDisabledCheckedTexture(string texture);
#endregion
}
/// <summary>
/// Unlike the other classes, this class has no corresponding variant in
/// WoW.
/// </summary>
public interface IWebBrowser : IFrame {
// XXXMLM - BrowserLine
// XXXMLM - BrowserBorder
string GetURL();
void SetURL(string url);
bool GetScrollbarsEnabled();
void SetScrollbarsEnabled();
void SetScrollbarsEnabled(bool enabled);
bool GetBrowserErrors();
void SetBrowserErrors(bool enabled);
void SetObjectForScripting(object obj);
object GetObjectForScripting();
object InvokeScript(string method, IEnumerable<object> args);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Xml;
using System.Linq;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
// The interface is a perf optimization.
// Only KeyValuePairAdapter should implement the interface.
internal interface IKeyValuePairAdapter { }
//Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")]
internal class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter
{
private K _kvpKey;
private T _kvpValue;
public KeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
_kvpKey = kvPair.Key;
_kvpValue = kvPair.Value;
}
[DataMember(Name = "key")]
public K Key
{
get { return _kvpKey; }
set { _kvpKey = value; }
}
[DataMember(Name = "value")]
public T Value
{
get
{
return _kvpValue;
}
set
{
_kvpValue = value;
}
}
internal KeyValuePair<K, T> GetKeyValuePair()
{
return new KeyValuePair<K, T>(_kvpKey, _kvpValue);
}
internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
return new KeyValuePairAdapter<K, T>(kvPair);
}
}
#if USE_REFEMIT
public interface IKeyValue
#else
internal interface IKeyValue
#endif
{
object Key { get; set; }
object Value { get; set; }
}
[DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
#if USE_REFEMIT
public struct KeyValue<K, V> : IKeyValue
#else
internal struct KeyValue<K, V> : IKeyValue
#endif
{
private K _key;
private V _value;
internal KeyValue(K key, V value)
{
_key = key;
_value = value;
}
[DataMember(IsRequired = true)]
public K Key
{
get { return _key; }
set { _key = value; }
}
[DataMember(IsRequired = true)]
public V Value
{
get { return _value; }
set { _value = value; }
}
object IKeyValue.Key
{
get { return _key; }
set { _key = (K)value; }
}
object IKeyValue.Value
{
get { return _value; }
set { _value = (V)value; }
}
}
internal enum CollectionKind : byte
{
None,
GenericDictionary,
Dictionary,
GenericList,
GenericCollection,
List,
GenericEnumerable,
Collection,
Enumerable,
Array,
}
#if USE_REFEMIT
public sealed class CollectionDataContract : DataContract
#else
internal sealed class CollectionDataContract : DataContract
#endif
{
private XmlDictionaryString _collectionItemName;
private XmlDictionaryString _childElementNamespace;
private DataContract _itemContract;
private CollectionDataContractCriticalHelper _helper;
public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind))
{
InitCollectionDataContract(this);
}
internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type))
{
InitCollectionDataContract(this);
}
CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string deserializationExceptionMessage)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private void InitCollectionDataContract(DataContract sharedTypeContract)
{
_helper = base.Helper as CollectionDataContractCriticalHelper;
_collectionItemName = _helper.CollectionItemName;
if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary)
{
_itemContract = _helper.ItemContract;
}
_helper.SharedTypeContract = sharedTypeContract;
}
private static Type[] KnownInterfaces
{
get
{ return CollectionDataContractCriticalHelper.KnownInterfaces; }
}
internal CollectionKind Kind
{
get
{ return _helper.Kind; }
}
public Type ItemType
{
get
{ return _helper.ItemType; }
set { _helper.ItemType = value; }
}
public DataContract ItemContract
{
get
{
return _itemContract ?? _helper.ItemContract;
}
set
{
_itemContract = value;
_helper.ItemContract = value;
}
}
internal DataContract SharedTypeContract
{
get
{ return _helper.SharedTypeContract; }
}
public string ItemName
{
get
{ return _helper.ItemName; }
set
{ _helper.ItemName = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
set { _collectionItemName = value; }
}
public string KeyName
{
get
{ return _helper.KeyName; }
set
{ _helper.KeyName = value; }
}
public string ValueName
{
get
{ return _helper.ValueName; }
set
{ _helper.ValueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public XmlDictionaryString ChildElementNamespace
{
get
{
if (_childElementNamespace == null)
{
lock (this)
{
if (_childElementNamespace == null)
{
if (_helper.ChildElementNamespace == null && !IsDictionary)
{
XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
Interlocked.MemoryBarrier();
_helper.ChildElementNamespace = tempChildElementNamespace;
}
_childElementNamespace = _helper.ChildElementNamespace;
}
}
}
return _childElementNamespace;
}
}
internal bool IsItemTypeNullable
{
get { return _helper.IsItemTypeNullable; }
set { _helper.IsItemTypeNullable = value; }
}
internal bool IsConstructorCheckRequired
{
get
{ return _helper.IsConstructorCheckRequired; }
set
{ _helper.IsConstructorCheckRequired = value; }
}
internal MethodInfo GetEnumeratorMethod
{
get
{ return _helper.GetEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
get
{ return _helper.AddMethod; }
}
internal ConstructorInfo Constructor
{
get
{ return _helper.Constructor; }
}
public override DataContractDictionary KnownDataContracts
{
get
{ return _helper.KnownDataContracts; }
set
{ _helper.KnownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
get
{ return _helper.InvalidCollectionInSharedContractMessage; }
}
internal string DeserializationExceptionMessage
{
get { return _helper.DeserializationExceptionMessage; }
}
internal bool IsReadOnlyContract
{
get { return DeserializationExceptionMessage != null; }
}
private XmlFormatCollectionWriterDelegate CreateXmlFormatWriterDelegate()
{
return new XmlFormatWriterGenerator().GenerateCollectionWriter(this);
}
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
get
{
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatCollectionWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate();
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
set
{
}
}
private XmlFormatCollectionReaderDelegate CreateXmlFormatReaderDelegate()
{
return new XmlFormatReaderGenerator().GenerateCollectionReader(this);
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
get
{
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
if (IsReadOnlyContract)
{
ThrowInvalidDataContractException(_helper.DeserializationExceptionMessage, type: null);
}
XmlFormatCollectionReaderDelegate tempDelegate = CreateXmlFormatReaderDelegate();
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
set
{
}
}
private XmlFormatGetOnlyCollectionReaderDelegate CreateXmlFormatGetOnlyCollectionReaderDelegate()
{
return new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this);
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
get
{
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType))));
}
if (IsReadOnlyContract)
{
ThrowInvalidDataContractException(_helper.DeserializationExceptionMessage, type: null);
}
if (Kind != CollectionKind.Array && AddMethod == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType))));
}
XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = CreateXmlFormatGetOnlyCollectionReaderDelegate();
Interlocked.MemoryBarrier();
_helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatGetOnlyCollectionReaderDelegate;
}
set
{
}
}
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
_helper.IncrementCollectionCount(xmlWriter, obj, context);
}
internal IEnumerator GetEnumeratorForCollection(object obj)
{
return _helper.GetEnumeratorForCollection(obj);
}
internal Type GetCollectionElementType()
{
return _helper.GetCollectionElementType();
}
private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private static Type[] s_knownInterfaces;
private Type _itemType;
private bool _isItemTypeNullable;
private CollectionKind _kind;
private readonly MethodInfo _getEnumeratorMethod, _addMethod;
private readonly ConstructorInfo _constructor;
private readonly string _deserializationExceptionMessage;
private DataContract _itemContract;
private DataContract _sharedTypeContract;
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private string _itemName;
private bool _itemNameSetExplicit;
private XmlDictionaryString _collectionItemName;
private string _keyName;
private string _valueName;
private XmlDictionaryString _childElementNamespace;
private string _invalidCollectionInSharedContractMessage;
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
private bool _isConstructorCheckRequired = false;
internal static Type[] KnownInterfaces
{
get
{
if (s_knownInterfaces == null)
{
// Listed in priority order
s_knownInterfaces = new Type[]
{
Globals.TypeOfIDictionaryGeneric,
Globals.TypeOfIDictionary,
Globals.TypeOfIListGeneric,
Globals.TypeOfICollectionGeneric,
Globals.TypeOfIList,
Globals.TypeOfIEnumerableGeneric,
Globals.TypeOfICollection,
Globals.TypeOfIEnumerable
};
}
return s_knownInterfaces;
}
}
private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute)
{
_kind = kind;
if (itemType != null)
{
_itemType = itemType;
_isItemTypeNullable = DataContract.IsTypeNullable(itemType);
bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary);
string itemName = null, keyName = null, valueName = null;
if (collectionContractAttribute != null)
{
if (collectionContractAttribute.IsItemNameSetExplicitly)
{
if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType))));
itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName);
_itemNameSetExplicit = true;
}
if (collectionContractAttribute.IsKeyNameSetExplicitly)
{
if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName)));
keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName);
}
if (collectionContractAttribute.IsValueNameSetExplicitly)
{
if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName)));
valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName);
}
}
XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3);
this.Name = dictionary.Add(this.StableName.Name);
this.Namespace = dictionary.Add(this.StableName.Namespace);
_itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name;
_collectionItemName = dictionary.Add(_itemName);
if (isDictionary)
{
_keyName = keyName ?? Globals.KeyLocalName;
_valueName = valueName ?? Globals.ValueLocalName;
}
}
if (collectionContractAttribute != null)
{
this.IsReference = collectionContractAttribute.IsReference;
}
}
internal CollectionDataContractCriticalHelper(CollectionKind kind)
: base()
{
Init(kind, null, null);
}
// array
internal CollectionDataContractCriticalHelper(Type type) : base(type)
{
if (type == Globals.TypeOfArray)
type = Globals.TypeOfObjectArray;
if (type.GetArrayRank() > 1)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SupportForMultidimensionalArraysNotPresent));
this.StableName = DataContract.GetStableName(type);
Init(CollectionKind.Array, type.GetElementType(), null);
}
// read-only collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string deserializationExceptionMessage)
: base(type)
{
if (getEnumeratorMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, GetClrTypeFullName(type))));
if (itemType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, GetClrTypeFullName(type))));
CollectionDataContractAttribute collectionContractAttribute;
this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
Init(kind, itemType, collectionContractAttribute);
_getEnumeratorMethod = getEnumeratorMethod;
_deserializationExceptionMessage = deserializationExceptionMessage;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type)
{
if (getEnumeratorMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type))));
if (addMethod == null && !type.IsInterface)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type))));
if (itemType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type))));
CollectionDataContractAttribute collectionContractAttribute;
this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
Init(kind, itemType, collectionContractAttribute);
_getEnumeratorMethod = getEnumeratorMethod;
_addMethod = addMethod;
_constructor = constructor;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)
{
_isConstructorCheckRequired = isConstructorCheckRequired;
}
internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type)
{
Init(CollectionKind.Collection, null /*itemType*/, null);
_invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage;
}
internal CollectionKind Kind
{
get { return _kind; }
}
internal Type ItemType
{
get { return _itemType; }
set { _itemType = value; }
}
internal DataContract ItemContract
{
get
{
if (_itemContract == null && UnderlyingType != null)
{
if (IsDictionary)
{
if (string.CompareOrdinal(KeyName, ValueName) == 0)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName),
UnderlyingType);
}
_itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName });
// Ensure that DataContract gets added to the static DataContract cache for dictionary items
DataContract.GetDataContract(ItemType);
}
else
{
_itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType);
if (_itemContract == null)
{
_itemContract = DataContract.GetDataContract(ItemType);
}
}
}
return _itemContract;
}
set
{
_itemContract = value;
}
}
internal DataContract SharedTypeContract
{
get { return _sharedTypeContract; }
set { _sharedTypeContract = value; }
}
internal string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
internal bool IsConstructorCheckRequired
{
get { return _isConstructorCheckRequired; }
set { _isConstructorCheckRequired = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
}
internal string KeyName
{
get { return _keyName; }
set { _keyName = value; }
}
internal string ValueName
{
get { return _valueName; }
set { _valueName = value; }
}
internal bool IsDictionary => KeyName != null;
public string DeserializationExceptionMessage => _deserializationExceptionMessage;
public XmlDictionaryString ChildElementNamespace
{
get { return _childElementNamespace; }
set { _childElementNamespace = value; }
}
internal bool IsItemTypeNullable
{
get { return _isItemTypeNullable; }
set { _isItemTypeNullable = value; }
}
internal MethodInfo GetEnumeratorMethod => _getEnumeratorMethod;
internal MethodInfo AddMethod => _addMethod;
internal ConstructorInfo Constructor => _constructor;
internal override DataContractDictionary KnownDataContracts
{
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
set
{ _knownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage;
internal bool ItemNameSetExplicit => _itemNameSetExplicit;
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
get { return _xmlFormatGetOnlyCollectionReaderDelegate; }
set { _xmlFormatGetOnlyCollectionReaderDelegate = value; }
}
private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context);
private IncrementCollectionCountDelegate _incrementCollectionCountDelegate = null;
private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { }
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (_incrementCollectionCountDelegate == null)
{
switch (Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
{
_incrementCollectionCountDelegate = (x, o, c) =>
{
c.IncrementCollectionCount(x, (ICollection)o);
};
}
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType);
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
case CollectionKind.GenericDictionary:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments()));
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
default:
// Do nothing.
_incrementCollectionCountDelegate = DummyIncrementCollectionCount;
break;
}
}
_incrementCollectionCountDelegate(xmlWriter, obj, context);
}
private static MethodInfo s_buildIncrementCollectionCountDelegateMethod;
private static MethodInfo BuildIncrementCollectionCountDelegateMethod
{
get
{
if (s_buildIncrementCollectionCountDelegateMethod == null)
{
s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers);
}
return s_buildIncrementCollectionCountDelegateMethod;
}
}
private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>()
{
return (xmlwriter, obj, context) =>
{
context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj);
};
}
private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator);
private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate;
internal IEnumerator GetEnumeratorForCollection(object obj)
{
IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator();
if (Kind == CollectionKind.GenericDictionary)
{
if (_createGenericDictionaryEnumeratorDelegate == null)
{
var keyValueTypes = ItemType.GetGenericArguments();
var buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]);
_createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>());
}
enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator);
}
else if (Kind == CollectionKind.Dictionary)
{
enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator());
}
return enumerator;
}
internal Type GetCollectionElementType()
{
Type enumeratorType = null;
if (Kind == CollectionKind.GenericDictionary)
{
Type[] keyValueTypes = ItemType.GetGenericArguments();
enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
}
else if (Kind == CollectionKind.Dictionary)
{
enumeratorType = Globals.TypeOfDictionaryEnumerator;
}
else
{
enumeratorType = GetEnumeratorMethod.ReturnType;
}
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (getCurrentMethod == null)
{
if (enumeratorType.IsInterface)
{
getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
}
else
{
Type ienumeratorInterface = Globals.TypeOfIEnumerator;
if (Kind == CollectionKind.GenericDictionary || Kind == CollectionKind.GenericCollection || Kind == CollectionKind.GenericEnumerable)
{
Type[] interfaceTypes = enumeratorType.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
&& interfaceType.GetGenericArguments()[0] == ItemType)
{
ienumeratorInterface = interfaceType;
break;
}
}
}
getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
}
}
Type elementType = getCurrentMethod.ReturnType;
return elementType;
}
private static MethodInfo s_buildCreateGenericDictionaryEnumerator;
private static MethodInfo BuildCreateGenericDictionaryEnumerato
{
get
{
if (s_buildCreateGenericDictionaryEnumerator == null)
{
s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers);
}
return s_buildCreateGenericDictionaryEnumerator;
}
}
private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>()
{
return (enumerator) =>
{
return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator);
};
}
}
private DataContract GetSharedTypeContract(Type type)
{
if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
{
return this;
}
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return new ClassDataContract(type);
}
return null;
}
internal static bool IsCollectionInterface(Type type)
{
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
return ((IList<Type>)KnownInterfaces).Contains(type);
}
internal static bool IsCollection(Type type)
{
Type itemType;
return IsCollection(type, out itemType);
}
internal static bool IsCollection(Type type, out Type itemType)
{
return IsCollectionHelper(type, out itemType, true /*constructorRequired*/);
}
internal static bool IsCollection(Type type, bool constructorRequired)
{
Type itemType;
return IsCollectionHelper(type, out itemType, constructorRequired);
}
private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired)
{
if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null)
{
itemType = type.GetElementType();
return true;
}
DataContract dataContract;
return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired);
}
internal static bool TryCreate(Type type, out DataContract dataContract)
{
Type itemType;
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/);
}
internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract == null)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
else
{
if (dataContract is CollectionDataContract)
{
return true;
}
else
{
dataContract = null;
return false;
}
}
}
internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
return t?.GetMethod(name);
}
private static bool IsArraySegment(Type t)
{
return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired)
{
dataContract = null;
itemType = Globals.TypeOfObject;
if (DataContract.GetBuiltInDataContract(type) != null)
{
return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/,
SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract);
}
MethodInfo addMethod, getEnumeratorMethod;
bool hasCollectionDataContract = IsCollectionDataContract(type);
bool isReadOnlyContract = false;
string deserializationExceptionMessage = null;
Type baseType = type.BaseType;
bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject
&& baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false;
// Avoid creating an invalid collection contract for Serializable types since we can create a ClassDataContract instead
bool createContractWithException = isBaseTypeCollection && !type.IsSerializable;
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeCannotHaveDataContract, null, ref dataContract);
}
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type))
{
return false;
}
if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (type.IsInterface)
{
Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
addMethod = null;
if (type.IsGenericType)
{
Type[] genericArgs = type.GetGenericArguments();
if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric)
{
itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs);
addMethod = type.GetMethod(Globals.AddMethodName);
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName);
}
else
{
itemType = genericArgs[0];
if (interfaceTypeToCheck == Globals.TypeOfICollectionGeneric || interfaceTypeToCheck == Globals.TypeOfIListGeneric)
{
addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod(Globals.AddMethodName);
}
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName);
}
}
else
{
if (interfaceTypeToCheck == Globals.TypeOfIDictionary)
{
itemType = typeof(KeyValue<object, object>);
addMethod = type.GetMethod(Globals.AddMethodName);
}
else
{
itemType = Globals.TypeOfObject;
// IList has AddMethod
if (interfaceTypeToCheck == Globals.TypeOfIList)
{
addMethod = type.GetMethod(Globals.AddMethodName);
}
}
getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/);
return true;
}
}
}
ConstructorInfo defaultCtor = null;
if (!type.IsValueType)
{
defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Array.Empty<Type>(), null);
if (defaultCtor == null && constructorRequired)
{
// All collection types could be considered read-only collections except collection types that are marked [Serializable].
// Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons.
// DataContract types and POCO types cannot be collection types, so they don't need to be factored in
if (type.IsSerializable)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract);
}
else
{
isReadOnlyContract = true;
GetReadOnlyCollectionExceptionMessages(type, SR.CollectionTypeDoesNotHaveDefaultCtor, null, out deserializationExceptionMessage);
}
}
}
Type knownInterfaceType = null;
CollectionKind kind = CollectionKind.None;
bool multipleDefinitions = false;
Type[] interfaceTypes = type.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
CollectionKind currentKind = (CollectionKind)(i + 1);
if (kind == CollectionKind.None || currentKind < kind)
{
kind = currentKind;
knownInterfaceType = interfaceType;
multipleDefinitions = false;
}
else if ((kind & currentKind) == currentKind)
multipleDefinitions = true;
break;
}
}
}
if (kind == CollectionKind.None)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)
{
if (multipleDefinitions)
knownInterfaceType = Globals.TypeOfIEnumerable;
itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject;
GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType },
false /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
if (addMethod == null)
{
// All collection types could be considered read-only collections except collection types that are marked [Serializable].
// Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons.
// DataContract types and POCO types cannot be collection types, so they don't need to be factored in.
if (type.IsSerializable)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract);
}
else
{
isReadOnlyContract = true;
GetReadOnlyCollectionExceptionMessages(type, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), out deserializationExceptionMessage);
}
}
if (tryCreate)
{
dataContract = isReadOnlyContract ?
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) :
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
}
else
{
if (multipleDefinitions)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract);
}
Type[] addMethodTypeArray = null;
switch (kind)
{
case CollectionKind.GenericDictionary:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition
|| (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter);
itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.Dictionary:
addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.GenericList:
case CollectionKind.GenericCollection:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
itemType = addMethodTypeArray[0];
break;
case CollectionKind.List:
itemType = Globals.TypeOfObject;
addMethodTypeArray = new Type[] { itemType };
break;
}
if (tryCreate)
{
GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray,
true /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
dataContract = isReadOnlyContract ?
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) :
new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
}
return true;
}
internal static bool IsCollectionDataContract(Type type)
{
return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false);
}
private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract)
{
if (hasCollectionDataContract)
{
if (tryCreate)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param)));
return true;
}
if (createContractWithException)
{
if (tryCreate)
dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param));
return true;
}
return false;
}
static void GetReadOnlyCollectionExceptionMessages(Type type, string message, string param, out string deserializationExceptionMessage)
{
deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.Format(SR.ReadOnlyCollectionDeserialization, GetClrTypeFullName(type)), param);
}
private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param)
{
return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param);
}
private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
if (t != null)
{
addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod;
getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod;
}
}
private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod)
{
addMethod = getEnumeratorMethod = null;
if (addMethodOnInterface)
{
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, null, addMethodTypeArray, null);
if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0])
{
FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
Type[] parentInterfaceTypes = interfaceType.GetInterfaces();
// The for loop below depeneds on the order for the items in parentInterfaceTypes, which
// doesnt' seem right. But it's the behavior of DCS on the full framework.
// Sorting the array to make sure the behavior is consistent with Desktop's.
Array.Sort(parentInterfaceTypes, (x, y) => string.Compare(x.FullName, y.FullName));
foreach (Type parentInterfaceType in parentInterfaceTypes)
{
if (IsKnownInterface(parentInterfaceType))
{
FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
break;
}
}
}
}
}
}
else
{
// GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, addMethodTypeArray, null);
}
if (getEnumeratorMethod == null)
{
getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
{
Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
if (ienumerableInterface == null)
ienumerableInterface = Globals.TypeOfIEnumerable;
getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface);
}
}
}
private static bool IsKnownInterface(Type type)
{
Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
foreach (Type knownInterfaceType in KnownInterfaces)
{
if (typeToCheck == knownInterfaceType)
{
return true;
}
}
return false;
}
internal override DataContract GetValidContract(SerializationMode mode)
{
if (InvalidCollectionInSharedContractMessage != null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage));
return this;
}
internal override DataContract GetValidContract()
{
if (this.IsConstructorCheckRequired)
{
CheckConstructor();
}
return this;
}
private void CheckConstructor()
{
if (this.Constructor == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType))));
}
else
{
this.IsConstructorCheckRequired = false;
}
}
internal override bool IsValidContract(SerializationMode mode)
{
return (InvalidCollectionInSharedContractMessage == null);
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(Constructor))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.AddMethod))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractAddMethodNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.AddMethod.Name),
securityException));
}
return true;
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
return false;
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
xmlReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
else
{
o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
xmlReader.ReadEndElement();
return o;
}
internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>>
{
private IDictionaryEnumerator _enumerator;
public DictionaryEnumerator(IDictionaryEnumerator enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<object, object> Current
{
get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
internal class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>>
{
private IEnumerator<KeyValuePair<K, V>> _enumerator;
public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<K, V> Current
{
get
{
KeyValuePair<K, V> current = _enumerator.Current;
return new KeyValue<K, V>(current.Key, current.Value);
}
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Container for the parameters to the CreateLaunchConfiguration operation.
/// Creates a launch configuration.
///
///
/// <para>
/// If you exceed your maximum limit of launch configurations, which by default is 100
/// per region, the call fails. For information about viewing and updating this limit,
/// see <a>DescribeAccountLimits</a>.
/// </para>
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/LaunchConfiguration.html">Launch
/// Configurations</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public partial class CreateLaunchConfigurationRequest : AmazonAutoScalingRequest
{
private bool? _associatePublicIpAddress;
private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>();
private string _classicLinkVPCId;
private List<string> _classicLinkVPCSecurityGroups = new List<string>();
private bool? _ebsOptimized;
private string _iamInstanceProfile;
private string _imageId;
private string _instanceId;
private InstanceMonitoring _instanceMonitoring;
private string _instanceType;
private string _kernelId;
private string _keyName;
private string _launchConfigurationName;
private string _placementTenancy;
private string _ramdiskId;
private List<string> _securityGroups = new List<string>();
private string _spotPrice;
private string _userData;
/// <summary>
/// Gets and sets the property AssociatePublicIpAddress.
/// <para>
/// Used for groups that launch instances into a virtual private cloud (VPC). Specifies
/// whether to assign a public IP address to each instance. For more information, see
/// <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html">Auto
/// Scaling and Amazon Virtual Private Cloud</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
///
/// <para>
/// If you specify a value for this parameter, be sure to specify at least one subnet
/// using the <i>VPCZoneIdentifier</i> parameter when you create your group.
/// </para>
///
/// <para>
/// Default: If the instance is launched into a default subnet, the default is <code>true</code>.
/// If the instance is launched into a nondefault subnet, the default is <code>false</code>.
/// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html">Supported
/// Platforms</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public bool AssociatePublicIpAddress
{
get { return this._associatePublicIpAddress.GetValueOrDefault(); }
set { this._associatePublicIpAddress = value; }
}
// Check to see if AssociatePublicIpAddress property is set
internal bool IsSetAssociatePublicIpAddress()
{
return this._associatePublicIpAddress.HasValue;
}
/// <summary>
/// Gets and sets the property BlockDeviceMappings.
/// <para>
/// One or more mappings that specify how block devices are exposed to the instance. For
/// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block
/// Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get { return this._blockDeviceMappings; }
set { this._blockDeviceMappings = value; }
}
// Check to see if BlockDeviceMappings property is set
internal bool IsSetBlockDeviceMappings()
{
return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property ClassicLinkVPCId.
/// <para>
/// The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. This parameter
/// is supported only if you are launching EC2-Classic instances. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a>
/// in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string ClassicLinkVPCId
{
get { return this._classicLinkVPCId; }
set { this._classicLinkVPCId = value; }
}
// Check to see if ClassicLinkVPCId property is set
internal bool IsSetClassicLinkVPCId()
{
return this._classicLinkVPCId != null;
}
/// <summary>
/// Gets and sets the property ClassicLinkVPCSecurityGroups.
/// <para>
/// The IDs of one or more security groups for the VPC specified in <code>ClassicLinkVPCId</code>.
/// This parameter is required if <code>ClassicLinkVPCId</code> is specified, and is not
/// supported otherwise. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a>
/// in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public List<string> ClassicLinkVPCSecurityGroups
{
get { return this._classicLinkVPCSecurityGroups; }
set { this._classicLinkVPCSecurityGroups = value; }
}
// Check to see if ClassicLinkVPCSecurityGroups property is set
internal bool IsSetClassicLinkVPCSecurityGroups()
{
return this._classicLinkVPCSecurityGroups != null && this._classicLinkVPCSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property EbsOptimized.
/// <para>
/// Indicates whether the instance is optimized for Amazon EBS I/O. By default, the instance
/// is not optimized for EBS I/O. The optimization provides dedicated throughput to Amazon
/// EBS and an optimized configuration stack to provide optimal I/O performance. This
/// optimization is not available with all instance types. Additional usage charges apply.
/// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html">Amazon
/// EBS-Optimized Instances</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public bool EbsOptimized
{
get { return this._ebsOptimized.GetValueOrDefault(); }
set { this._ebsOptimized = value; }
}
// Check to see if EbsOptimized property is set
internal bool IsSetEbsOptimized()
{
return this._ebsOptimized.HasValue;
}
/// <summary>
/// Gets and sets the property IamInstanceProfile.
/// <para>
/// The name or the Amazon Resource Name (ARN) of the instance profile associated with
/// the IAM role for the instance.
/// </para>
///
/// <para>
/// EC2 instances launched with an IAM role will automatically have AWS security credentials
/// available. You can use IAM roles with Auto Scaling to automatically enable applications
/// running on your EC2 instances to securely access other AWS resources. For more information,
/// see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/us-iam-role.html">Launch
/// Auto Scaling Instances with an IAM Role</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public string IamInstanceProfile
{
get { return this._iamInstanceProfile; }
set { this._iamInstanceProfile = value; }
}
// Check to see if IamInstanceProfile property is set
internal bool IsSetIamInstanceProfile()
{
return this._iamInstanceProfile != null;
}
/// <summary>
/// Gets and sets the property ImageId.
/// <para>
/// The ID of the Amazon Machine Image (AMI) to use to launch your EC2 instances. For
/// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding
/// an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string ImageId
{
get { return this._imageId; }
set { this._imageId = value; }
}
// Check to see if ImageId property is set
internal bool IsSetImageId()
{
return this._imageId != null;
}
/// <summary>
/// Gets and sets the property InstanceId.
/// <para>
/// The ID of the EC2 instance to use to create the launch configuration.
/// </para>
///
/// <para>
/// The new launch configuration derives attributes from the instance, with the exception
/// of the block device mapping.
/// </para>
///
/// <para>
/// To create a launch configuration with a block device mapping or override any other
/// instance attributes, specify them as part of the same request.
/// </para>
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/create-lc-with-instanceID.html">Create
/// a Launch Configuration Using an EC2 Instance</a> in the <i>Auto Scaling Developer
/// Guide</i>.
/// </para>
/// </summary>
public string InstanceId
{
get { return this._instanceId; }
set { this._instanceId = value; }
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this._instanceId != null;
}
/// <summary>
/// Gets and sets the property InstanceMonitoring.
/// <para>
/// Enables detailed monitoring if it is disabled. Detailed monitoring is enabled by default.
/// </para>
///
/// <para>
/// When detailed monitoring is enabled, Amazon CloudWatch generates metrics every minute
/// and your account is charged a fee. When you disable detailed monitoring, by specifying
/// <code>False</code>, CloudWatch generates metrics every 5 minutes. For more information,
/// see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/as-instance-monitoring.html">Monitor
/// Your Auto Scaling Instances</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public InstanceMonitoring InstanceMonitoring
{
get { return this._instanceMonitoring; }
set { this._instanceMonitoring = value; }
}
// Check to see if InstanceMonitoring property is set
internal bool IsSetInstanceMonitoring()
{
return this._instanceMonitoring != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type of the EC2 instance. For information about available instance types,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">
/// Available Instance Types</a> in the <i>Amazon Elastic Compute Cloud User Guide.</i>
///
/// </para>
/// </summary>
public string InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property KernelId.
/// <para>
/// The ID of the kernel associated with the AMI.
/// </para>
/// </summary>
public string KernelId
{
get { return this._kernelId; }
set { this._kernelId = value; }
}
// Check to see if KernelId property is set
internal bool IsSetKernelId()
{
return this._kernelId != null;
}
/// <summary>
/// Gets and sets the property KeyName.
/// <para>
/// The name of the key pair. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon
/// EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string KeyName
{
get { return this._keyName; }
set { this._keyName = value; }
}
// Check to see if KeyName property is set
internal bool IsSetKeyName()
{
return this._keyName != null;
}
/// <summary>
/// Gets and sets the property LaunchConfigurationName.
/// <para>
/// The name of the launch configuration. This name must be unique within the scope of
/// your AWS account.
/// </para>
/// </summary>
public string LaunchConfigurationName
{
get { return this._launchConfigurationName; }
set { this._launchConfigurationName = value; }
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this._launchConfigurationName != null;
}
/// <summary>
/// Gets and sets the property PlacementTenancy.
/// <para>
/// The tenancy of the instance. An instance with a tenancy of <code>dedicated</code>
/// runs on single-tenant hardware and can only be launched into a VPC.
/// </para>
///
/// <para>
/// You must set the value of this parameter to <code>dedicated</code> if want to launch
/// Dedicated Instances into a shared tenancy VPC (VPC with instance placement tenancy
/// attribute set to <code>default</code>).
/// </para>
///
/// <para>
/// If you specify a value for this parameter, be sure to specify at least one subnet
/// using the <i>VPCZoneIdentifier</i> parameter when you create your group.
/// </para>
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html">Auto
/// Scaling and Amazon Virtual Private Cloud</a> in the <i>Auto Scaling Developer Guide</i>.
///
/// </para>
///
/// <para>
/// Valid values: <code>default</code> | <code>dedicated</code>
/// </para>
/// </summary>
public string PlacementTenancy
{
get { return this._placementTenancy; }
set { this._placementTenancy = value; }
}
// Check to see if PlacementTenancy property is set
internal bool IsSetPlacementTenancy()
{
return this._placementTenancy != null;
}
/// <summary>
/// Gets and sets the property RamdiskId.
/// <para>
/// The ID of the RAM disk associated with the AMI.
/// </para>
/// </summary>
public string RamdiskId
{
get { return this._ramdiskId; }
set { this._ramdiskId = value; }
}
// Check to see if RamdiskId property is set
internal bool IsSetRamdiskId()
{
return this._ramdiskId != null;
}
/// <summary>
/// Gets and sets the property SecurityGroups.
/// <para>
/// One or more security groups with which to associate the instances.
/// </para>
///
/// <para>
/// If your instances are launched in EC2-Classic, you can either specify security group
/// names or the security group IDs. For more information about security groups for EC2-Classic,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon
/// EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// If your instances are launched into a VPC, specify security group IDs. For more information,
/// see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security
/// Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User Guide</i>.
/// </para>
/// </summary>
public List<string> SecurityGroups
{
get { return this._securityGroups; }
set { this._securityGroups = value; }
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this._securityGroups != null && this._securityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The maximum hourly price to be paid for any Spot Instance launched to fulfill the
/// request. Spot Instances are launched when the price you specify exceeds the current
/// Spot market price. For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US-SpotInstances.html">Launch
/// Spot Instances in Your Auto Scaling Group</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property UserData.
/// <para>
/// The user data to make available to the launched EC2 instances. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance
/// Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// At this time, launch configurations don't support compressed (zipped) user data files.
/// </para>
/// </summary>
public string UserData
{
get { return this._userData; }
set { this._userData = value; }
}
// Check to see if UserData property is set
internal bool IsSetUserData()
{
return this._userData != null;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
/// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
/// a remote call so in general you should reuse a single channel for as many calls as possible.
/// </summary>
public class Channel
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
readonly object myLock = new object();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();
readonly string target;
readonly GrpcEnvironment environment;
readonly CompletionQueueSafeHandle completionQueue;
readonly ChannelSafeHandle handle;
readonly Dictionary<string, ChannelOption> options;
readonly Task connectivityWatcherTask;
bool shutdownRequested;
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
public Channel(string target, ChannelCredentials credentials) :
this(target, credentials, null)
{
}
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options)
{
this.target = GrpcPreconditions.CheckNotNull(target, "target");
this.options = CreateOptionsDictionary(options);
EnsureUserAgentChannelOption(this.options);
this.environment = GrpcEnvironment.AddRef();
this.completionQueue = this.environment.PickCompletionQueue();
using (var nativeCredentials = credentials.ToNativeCredentials())
using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
{
if (nativeCredentials != null)
{
this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
}
else
{
this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
}
}
// TODO(jtattermusch): Workaround for https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822.
// Remove once retries are supported in C core
this.connectivityWatcherTask = RunConnectivityWatcherAsync();
GrpcEnvironment.RegisterChannel(this);
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
public Channel(string host, int port, ChannelCredentials credentials) :
this(host, port, credentials, null)
{
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) :
this(string.Format("{0}:{1}", host, port), credentials, options)
{
}
/// <summary>
/// Gets current connectivity state of this channel.
/// After channel is has been shutdown, <c>ChannelState.Shutdown</c> will be returned.
/// </summary>
public ChannelState State
{
get
{
return GetConnectivityState(false);
}
}
// cached handler for watch connectivity state
static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) =>
{
var tcs = (TaskCompletionSource<bool>) state;
tcs.SetResult(success);
};
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState.
/// If deadline is reached or and error occurs, returned task is cancelled.
/// </summary>
public async Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
var result = await WaitForStateChangedInternalAsync(lastObservedState, deadline).ConfigureAwait(false);
if (!result)
{
throw new TaskCanceledException("Reached deadline.");
}
}
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState (<c>true</c> is returned) or if the wait has timed out (<c>false</c> is returned).
/// </summary>
internal Task<bool> WaitForStateChangedInternalAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
"Shutdown is a terminal state. No further state changes can occur.");
var tcs = new TaskCompletionSource<bool>();
var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
lock (myLock)
{
// pass "tcs" as "state" for WatchConnectivityStateHandler.
handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs);
}
return tcs.Task;
}
/// <summary>Resolved address of the remote endpoint in URI format.</summary>
public string ResolvedTarget
{
get
{
return handle.GetTarget();
}
}
/// <summary>The original target used to create the channel.</summary>
public string Target
{
get
{
return this.target;
}
}
/// <summary>
/// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
/// </summary>
public CancellationToken ShutdownToken
{
get
{
return this.shutdownTokenSource.Token;
}
}
/// <summary>
/// Allows explicitly requesting channel to connect without starting an RPC.
/// Returned task completes once state Ready was seen. If the deadline is reached,
/// or channel enters the Shutdown state, the task is cancelled.
/// There is no need to call this explicitly unless your use case requires that.
/// Starting an RPC on a new channel will request connection implicitly.
/// </summary>
/// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
public async Task ConnectAsync(DateTime? deadline = null)
{
var currentState = GetConnectivityState(true);
while (currentState != ChannelState.Ready)
{
if (currentState == ChannelState.Shutdown)
{
throw new OperationCanceledException("Channel has reached Shutdown state.");
}
await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
currentState = GetConnectivityState(false);
}
}
/// <summary>
/// Shuts down the channel cleanly. It is strongly recommended to shutdown
/// all previously created channels before exiting from the process.
/// </summary>
/// <remarks>
/// This method doesn't wait for all calls on this channel to finish (nor does
/// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
/// all the calls on this channel have finished (successfully or with an error)
/// before shutting down the channel to ensure channel shutdown won't impact
/// the outcome of those remote calls.
/// </remarks>
public async Task ShutdownAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
GrpcEnvironment.UnregisterChannel(this);
shutdownTokenSource.Cancel();
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
}
lock (myLock)
{
handle.Dispose();
}
await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
}
internal ChannelSafeHandle Handle
{
get
{
return this.handle;
}
}
internal GrpcEnvironment Environment
{
get
{
return this.environment;
}
}
internal CompletionQueueSafeHandle CompletionQueue
{
get
{
return this.completionQueue;
}
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
GrpcPreconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
private ChannelState GetConnectivityState(bool tryToConnect)
{
try
{
lock (myLock)
{
return handle.CheckConnectivityState(tryToConnect);
}
}
catch (ObjectDisposedException)
{
return ChannelState.Shutdown;
}
}
/// <summary>
/// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
/// </summary>
private async Task RunConnectivityWatcherAsync()
{
try
{
var lastState = State;
while (lastState != ChannelState.Shutdown)
{
lock (myLock)
{
if (shutdownRequested)
{
break;
}
}
// ignore the result
await WaitForStateChangedInternalAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
lastState = State;
}
}
catch (ObjectDisposedException) {
// during shutdown, channel is going to be disposed.
}
}
private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
{
var key = ChannelOptions.PrimaryUserAgentString;
var userAgentString = "";
ChannelOption option;
if (options.TryGetValue(key, out option))
{
// user-provided userAgentString needs to be at the beginning
userAgentString = option.StringValue + " ";
};
// TODO(jtattermusch): it would be useful to also provide .NET/mono version.
userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
}
private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
{
var dict = new Dictionary<string, ChannelOption>();
if (options == null)
{
return dict;
}
foreach (var option in options)
{
dict.Add(option.Name, option);
}
return dict;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Utils.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Client.Utils
{
/// <summary>
/// <para>A collection of utilities to workaround limitations of Java clone framework. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/utils/CloneUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/client/utils/CloneUtils", AccessFlags = 33)]
public partial class CloneUtils
/* scope: __dot42__ */
{
/// <summary>
/// <para>This class should not be instantiated. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal CloneUtils() /* MethodBuilder.Create */
{
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "(Ljava/lang/Object;)Ljava/lang/Object;", AccessFlags = 9)]
public static object Clone(object obj) /* MethodBuilder.Create */
{
return default(object);
}
}
/// <summary>
/// <para>A collection of utilities for URIs, to workaround bugs within the class or for ease-of-use features. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/utils/URIUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/client/utils/URIUtils", AccessFlags = 33)]
public partial class URIUtils
/* scope: __dot42__ */
{
/// <summary>
/// <para>This class should not be instantiated. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal URIUtils() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a URI using all the parameters. This should be used instead of URI#URI(String, String, String, int, String, String, String) or any of the other URI multi-argument URI constructors.</para><para>See for more information.</para><para></para>
/// </summary>
/// <java-name>
/// createURI
/// </java-name>
[Dot42.DexImport("createURI", "(Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/l" +
"ang/String;)Ljava/net/URI;", AccessFlags = 9)]
public static global::System.Uri CreateURI(string scheme, string host, int port, string path, string query, string fragment) /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
/// <summary>
/// <para>A convenience method for creating a new URI whose scheme, host and port are taken from the target host, but whose path, query and fragment are taken from the existing URI. The fragment is only used if dropFragment is false.</para><para></para>
/// </summary>
/// <java-name>
/// rewriteURI
/// </java-name>
[Dot42.DexImport("rewriteURI", "(Ljava/net/URI;Lorg/apache/http/HttpHost;Z)Ljava/net/URI;", AccessFlags = 9)]
public static global::System.Uri RewriteURI(global::System.Uri uri, global::Org.Apache.Http.HttpHost target, bool dropFragment) /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
/// <summary>
/// <para>A convenience method for URIUtils#rewriteURI(URI, HttpHost, boolean) that always keeps the fragment. </para>
/// </summary>
/// <java-name>
/// rewriteURI
/// </java-name>
[Dot42.DexImport("rewriteURI", "(Ljava/net/URI;Lorg/apache/http/HttpHost;)Ljava/net/URI;", AccessFlags = 9)]
public static global::System.Uri RewriteURI(global::System.Uri uri, global::Org.Apache.Http.HttpHost target) /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
/// <summary>
/// <para>Resolves a URI reference against a base URI. Work-around for bug in java.net.URI ()</para><para></para>
/// </summary>
/// <returns>
/// <para>the resulting URI </para>
/// </returns>
/// <java-name>
/// resolve
/// </java-name>
[Dot42.DexImport("resolve", "(Ljava/net/URI;Ljava/lang/String;)Ljava/net/URI;", AccessFlags = 9)]
public static global::System.Uri Resolve(global::System.Uri baseURI, string reference) /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
/// <summary>
/// <para>Resolves a URI reference against a base URI. Work-around for bug in java.net.URI ()</para><para></para>
/// </summary>
/// <returns>
/// <para>the resulting URI </para>
/// </returns>
/// <java-name>
/// resolve
/// </java-name>
[Dot42.DexImport("resolve", "(Ljava/net/URI;Ljava/net/URI;)Ljava/net/URI;", AccessFlags = 9)]
public static global::System.Uri Resolve(global::System.Uri baseURI, global::System.Uri reference) /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
}
/// <summary>
/// <para>A collection of utilities for encoding URLs. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/utils/URLEncodedUtils
/// </java-name>
[Dot42.DexImport("org/apache/http/client/utils/URLEncodedUtils", AccessFlags = 33)]
public partial class URLEncodedUtils
/* scope: __dot42__ */
{
/// <java-name>
/// CONTENT_TYPE
/// </java-name>
[Dot42.DexImport("CONTENT_TYPE", "Ljava/lang/String;", AccessFlags = 25)]
public const string CONTENT_TYPE = "application/x-www-form-urlencoded";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public URLEncodedUtils() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns a list of NameValuePairs as built from the URI's query portion. For example, a URI of would return a list of three NameValuePairs, one for a=1, one for b=2, and one for c=3. </para><para>This is typically useful while parsing an HTTP PUT.</para><para></para>
/// </summary>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Ljava/net/URI;Ljava/lang/String;)Ljava/util/List;", AccessFlags = 9, Signature = "(Ljava/net/URI;Ljava/lang/String;)Ljava/util/List<Lorg/apache/http/NameValuePair;" +
">;")]
public static global::Java.Util.IList<global::Org.Apache.Http.INameValuePair> Parse(global::System.Uri uri, string encoding) /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<global::Org.Apache.Http.INameValuePair>);
}
/// <summary>
/// <para>Returns a list of NameValuePairs as parsed from an HttpEntity. The encoding is taken from the entity's Content-Encoding header. </para><para>This is typically used while parsing an HTTP POST.</para><para></para>
/// </summary>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/HttpEntity;)Ljava/util/List;", AccessFlags = 9, Signature = "(Lorg/apache/http/HttpEntity;)Ljava/util/List<Lorg/apache/http/NameValuePair;>;")]
public static global::Java.Util.IList<global::Org.Apache.Http.INameValuePair> Parse(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<global::Org.Apache.Http.INameValuePair>);
}
/// <summary>
/// <para>Returns true if the entity's Content-Type header is <code>application/x-www-form-urlencoded</code>. </para>
/// </summary>
/// <java-name>
/// isEncoded
/// </java-name>
[Dot42.DexImport("isEncoded", "(Lorg/apache/http/HttpEntity;)Z", AccessFlags = 9)]
public static bool IsEncoded(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Adds all parameters within the Scanner to the list of <code>parameters</code>, as encoded by <code>encoding</code>. For example, a scanner containing the string <code>a=1&b=2&c=3</code> would add the NameValuePairs a=1, b=2, and c=3 to the list of parameters.</para><para></para>
/// </summary>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Ljava/util/List;Ljava/util/Scanner;Ljava/lang/String;)V", AccessFlags = 9, Signature = "(Ljava/util/List<Lorg/apache/http/NameValuePair;>;Ljava/util/Scanner;Ljava/lang/S" +
"tring;)V")]
public static void Parse(global::Java.Util.IList<global::Org.Apache.Http.INameValuePair> parameters, global::Java.Util.Scanner scanner, string encoding) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code> list of parameters in an HTTP PUT or HTTP POST.</para><para></para>
/// </summary>
/// <java-name>
/// format
/// </java-name>
[Dot42.DexImport("format", "(Ljava/util/List;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9, Signature = "(Ljava/util/List<+Lorg/apache/http/NameValuePair;>;Ljava/lang/String;)Ljava/lang/" +
"String;")]
public static string Format(global::Java.Util.IList<global::Org.Apache.Http.INameValuePair> parameters, string encoding) /* MethodBuilder.Create */
{
return default(string);
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_11_8_1 : EcmaTest
{
[Fact]
[Trait("Category", "11.8.1")]
public void WhiteSpaceAndLineTerminatorBetweenRelationalexpressionAndOrBetweenAndShiftexpressionAreAllowed()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void OperatorXYUsesGetvalue()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.1_T1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void OperatorXYUsesGetvalue2()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.1_T2.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void OperatorXYUsesGetvalue3()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.1_T3.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void OperatorXYUsesDefaultValue()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.2_T1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void TonumberFirstExpressionIsCalledFirstAndThenTonumberSecondExpression()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.3_T1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.4_T1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression2()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.4_T2.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression3()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A2.4_T3.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T1.1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY2()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T1.2.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY3()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T1.3.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY4()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY5()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.2.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY6()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.3.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY7()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.4.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY8()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.5.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY9()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.6.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY10()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.7.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY11()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.8.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfTypePrimitiveXIsNotStringOrTypePrimitiveYIsNotStringThenOperatorXYReturnsTonumberXTonumberY12()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.9.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void OperatorXYReturnsTostringXTostringYIfTypePrimitiveXIsStringAndTypePrimitiveYIsString()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.2_T1.1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void OperatorXYReturnsTostringXTostringYIfTypePrimitiveXIsStringAndTypePrimitiveYIsString2()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A3.2_T1.2.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfXIsNanReturnFalseIfResultIn1185IsUndefinedReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfYIsAPrefixOfXReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.10.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfXIsAPrefixOfYAndXYReturnTrue()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.11.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfNeitherXNorYIsAPrefixOfEachOtherReturnedResultOfStringsComparisonAppliesASimpleLexicographicOrderingToTheSequencesOfCodePointValueValues()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.12_T1.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfNeitherXNorYIsAPrefixOfEachOtherReturnedResultOfStringsComparisonAppliesASimpleLexicographicOrderingToTheSequencesOfCodePointValueValues2()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.12_T2.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfYIsNanReturnFalseIfResultIn1185IsUndefinedReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.2.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfXAndYAreTheSameNumberValueReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.3.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfXAndYAre0And0ReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.4.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfXIsInfinityReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.5.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfYIsInfinityAndXYReturnTrue()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.6.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfXIsInfinityAndXYReturnTrue()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.7.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfYIsInfinityReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.8.js", false);
}
[Fact]
[Trait("Category", "11.8.1")]
public void IfXIsLessThanYAndTheseValuesAreBothFiniteNonZeroReturnTrueOtherwiseReturnFalse()
{
RunTest(@"TestCases/ch11/11.8/11.8.1/S11.8.1_A4.9.js", false);
}
}
}
| |
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Callbacks;
using System;
#if UNITY_WEBPLAYER
/* Cut down version that compiles under restricted WebPlayer .NET runtime
and gives useful(hopefully) error message to the developer */
[InitializeOnLoad]
public class FMODEditorExtension : MonoBehaviour
{
static FMODEditorExtension()
{
Debug.LogError("FMOD Studio Integration: WebPlayer not supported. Please change your platform.");
}
[MenuItem ("FMOD/Import Banks")]
public static void ImportBanks()
{
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "WebPlayer not supported. Please change your platform.", "OK");
}
[MenuItem ("FMOD/Refresh Event List")]
static bool CheckRefreshEventList()
{
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "WebPlayer not supported. Please change your platform.", "OK");
return false;
}
[MenuItem ("FMOD/Refresh Event List")]
public static void RefreshEventList()
{
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "WebPlayer not supported. Please change your platform.", "OK");
}
[MenuItem ("FMOD/Online Manual")]
static void OnlineManual()
{
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "WebPlayer not supported. Please change your platform.", "OK");
}
[MenuItem ("FMOD/Online API Documentation")]
static void OnlineAPIDocs()
{
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "WebPlayer not supported. Please change your platform.", "OK");
}
[MenuItem ("FMOD/About Integration")]
static void AboutIntegration()
{
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "WebPlayer not supported. Please change your platform.", "OK");
}
/* Stubs so all the other scripts compile */
static void Update()
{
}
public static void AuditionEvent(FMODAsset asset)
{
}
public static void StopEvent()
{
}
public static void SetEventParameterValue(int index, float val)
{
}
public static FMOD.Studio.EventDescription GetEventDescription(string idString)
{
return null;
}
}
#else
/* Full version of editor extensions */
[InitializeOnLoad]
public class FMODEditorExtension : MonoBehaviour
{
public static FMOD.Studio.System sFMODSystem;
static Dictionary<string, FMOD.Studio.EventDescription> events = new Dictionary<string, FMOD.Studio.EventDescription>();
static FMOD.Studio.EventInstance currentInstance = null;
static List<FMOD.Studio.Bank> loadedBanks = new List<FMOD.Studio.Bank>();
const string AssetFolder = "FMODAssets";
static FMODEditorExtension()
{
EditorApplication.update += Update;
EditorApplication.playmodeStateChanged += HandleOnPlayModeChanged;
}
static void HandleOnPlayModeChanged()
{
if (EditorApplication.isPlayingOrWillChangePlaymode &&
!EditorApplication.isPaused)
{
UnloadAllBanks();
}
if (!EditorApplication.isPlaying && !EditorApplication.isPlayingOrWillChangePlaymode &&
!EditorApplication.isPaused)
{
//LoadAllBanks();
}
}
[PostProcessScene]
public static void OnPostprocessScene()
{
// Hack: clean up stale files from old versions of the integration that will mess
// with the build. DeleteAsset is a NoOp if the file doesn't exist
// moved in 1.05.10
AssetDatabase.DeleteAsset("Assets/Plugins/Android/libfmod.so");
AssetDatabase.DeleteAsset("Assets/Plugins/Android/libfmodstudio.so");
}
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
if (target == BuildTarget.StandaloneOSXIntel
|| target == BuildTarget.StandaloneOSXUniversal
#if !(UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1)
|| target == BuildTarget.StandaloneOSXIntel64
#endif
)
{
FMOD.Studio.UnityUtil.Log("Post build: copying FMOD DSP plugins to build directory");
var pluginLocation = Application.dataPath + "/Plugins";
// Assume all .dylibs are FMOD Studio DSP plugins
string[] files = System.IO.Directory.GetFiles(pluginLocation, "*.dylib");
foreach(var filePath in files)
{
var dest = pathToBuiltProject + "/Contents/Plugins/" + System.IO.Path.GetFileName(filePath);
FMOD.Studio.UnityUtil.Log("COPY: " + filePath + " TO " + dest);
System.IO.File.Copy(filePath, dest, true);
}
}
}
static void Update()
{
if (EditorApplication.isCompiling)
{
UnloadAllBanks();
}
if (sFMODSystem != null && sFMODSystem.isValid())
{
ERRCHECK(sFMODSystem.update());
}
}
public static void AuditionEvent(FMODAsset asset)
{
StopEvent();
var desc = GetEventDescription(asset.id);
if (desc == null)
{
FMOD.Studio.UnityUtil.LogError("Failed to retrieve EventDescription for event: " + asset.path);
}
if (!ERRCHECK(desc.createInstance(out currentInstance)))
{
return;
}
ERRCHECK(currentInstance.start());
}
public static void StopEvent()
{
if (currentInstance != null && currentInstance.isValid())
{
ERRCHECK(currentInstance.stop(FMOD.Studio.STOP_MODE.IMMEDIATE));
currentInstance = null;
}
}
public static void SetEventParameterValue(int index, float val)
{
if (currentInstance != null && currentInstance.isValid())
{
FMOD.Studio.ParameterInstance param;
currentInstance.getParameterByIndex(index, out param);
param.setValue(val);
}
}
public static FMOD.Studio.EventDescription GetEventDescription(string idString)
{
FMOD.Studio.EventDescription desc = null;
if (!events.TryGetValue(idString, out desc))
{
if (sFMODSystem == null)
{
if (!LoadAllBanks())
{
return null;
}
}
Guid id = new Guid();
if (!ERRCHECK(FMOD.Studio.Util.ParseID(idString, out id)))
{
return null;
}
FMOD.RESULT res = FMODEditorExtension.sFMODSystem.getEventByID(id, out desc);
if (res == FMOD.RESULT.ERR_EVENT_NOTFOUND || desc == null || !desc.isValid() || !ERRCHECK(res))
{
return null;
}
events[idString] = desc;
}
return desc;
}
[MenuItem ("FMOD/Import Banks")]
public static void ImportBanks()
{
if (PrepareIntegration())
{
string filePath = "";
if (!LocateProject(ref filePath))
{
return;
}
ImportAndRefresh(filePath + "/" + studioPlatformDirectoryName());
}
}
[MenuItem ("FMOD/Refresh Event List", true)]
static bool CheckRefreshEventList()
{
string guidPathKey = "FMODStudioProjectPath_" + Application.dataPath;
return EditorPrefs.HasKey(guidPathKey);
}
[MenuItem ("FMOD/Refresh Event List")]
public static void RefreshEventList()
{
string filePath = GetDefaultPath();
ImportAndRefresh(filePath + "/Build/" + studioPlatformDirectoryName());
}
static string studioPlatformDirectoryName()
{
var platDirFile = "Assets/Plugins/FMOD/PlatformDirectories.txt";
if (!System.IO.File.Exists(platDirFile))
{
FMOD.Studio.UnityUtil.Log("No PlatformDirectories.txt found in Assets/Plugins/FMOD defaulting to \"Desktop\"");
return "Desktop";
}
string platformName = UnityEditor.EditorUserBuildSettings.selectedBuildTargetGroup.ToString();
var stream = new System.IO.StreamReader(platDirFile);
while (!stream.EndOfStream)
{
var line = stream.ReadLine();
string[] s = line.Split(':');
if (string.Equals(s[0], platformName))
{
FMOD.Studio.UnityUtil.Log("target: " + platformName + ", directory: " + s[1]);
return s[1];
}
}
FMOD.Studio.UnityUtil.LogWarning("Current platform: " + platformName + " not found in PlatformDirectories.txt, defaulting to \"Desktop\"");
return "Desktop";
}
static bool CopyBanks(string path)
{
UnloadAllBanks();
var info = new System.IO.DirectoryInfo(path);
int bankCount = 0;
string copyBanksString = "";
var banksToCopy = new List<System.IO.FileInfo>();
bool hasNewStyleStringsBank = false; // PAS - hack fix for having two strings bank
foreach (var fileInfo in info.GetFiles())
{
var ex = fileInfo.Extension;
if (!ex.Equals(".bank", System.StringComparison.CurrentCultureIgnoreCase) &&
!ex.Equals(".strings", System.StringComparison.CurrentCultureIgnoreCase))
{
FMOD.Studio.UnityUtil.Log("Ignoring unexpected file: \"" + fileInfo.Name + "\": unknown file type: \"" + fileInfo.Extension + "\"");
continue;
}
hasNewStyleStringsBank = hasNewStyleStringsBank || fileInfo.FullName.Contains(".strings.bank");
++bankCount;
string bankMessage = "(added)";
var oldBankPath = Application.dataPath + "/StreamingAssets/" + fileInfo.Name;
if (System.IO.File.Exists(oldBankPath))
{
var oldFileInfo = new System.IO.FileInfo(oldBankPath);
if (oldFileInfo.LastWriteTime == fileInfo.LastWriteTime)
{
bankMessage = "(same)";
}
else if(oldFileInfo.LastWriteTime < fileInfo.LastWriteTime)
{
bankMessage = "(newer)";
}
else
{
bankMessage = "(older)";
}
}
copyBanksString += fileInfo.Name + " " + bankMessage + "\n";
banksToCopy.Add(fileInfo);
}
if (bankCount == 0)
{
EditorUtility.DisplayDialog("FMOD Studio Importer", "No .bank files found in the directory:\n" + path, "OK");
return false;
}
if (!EditorUtility.DisplayDialog("FMOD Studio Importer", "The import will modify the following files:\n" + copyBanksString, "Continue", "Cancel"))
{
return false;
}
string bankNames = "";
foreach (var fileInfo in banksToCopy)
{
if (hasNewStyleStringsBank && fileInfo.Extension.Equals(".strings"))
{
continue; // skip the stale strings bank
}
System.IO.Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");
var oldBankPath = Application.dataPath + "/StreamingAssets/" + fileInfo.Name;
fileInfo.CopyTo(oldBankPath, true);
bankNames += fileInfo.Name + "\n";
}
System.IO.File.WriteAllText(Application.dataPath + "/StreamingAssets/FMOD_bank_list.txt", bankNames);
return true;
}
static bool ImportAndRefresh(string filePath)
{
FMOD.Studio.UnityUtil.Log("import from path: " + filePath);
CopyBanks(filePath);
if (!LoadAllBanks())
{
return false;
}
List<FMODAsset> existingAssets = new List<FMODAsset>();
GatherExistingAssets(existingAssets);
List<FMODAsset> newAssets = new List<FMODAsset>();
GatherNewAssets(filePath, newAssets);
var assetsToDelete = existingAssets.Except(newAssets, new FMODAssetGUIDComparer());
var assetsToAdd = newAssets.Except(existingAssets, new FMODAssetGUIDComparer());
var assetsToMoveFrom = existingAssets.Intersect(newAssets, new FMODAssetGUIDComparer());
var assetsToMoveTo = newAssets.Intersect(existingAssets, new FMODAssetGUIDComparer());
var assetsToMove = assetsToMoveFrom.Except(assetsToMoveTo, new FMODAssetPathComparer());
if (!assetsToDelete.Any() && !assetsToAdd.Any() && !assetsToMove.Any())
{
Debug.Log("FMOD Studio Importer: Banks updated, events list unchanged " + System.DateTime.Now.ToString(@"[hh:mm tt]"));
}
else
{
string assetsToDeleteFormatted = "";
foreach (var asset in assetsToDelete)
{
assetsToDeleteFormatted += eventToAssetPath(asset.path) + "\n";
}
string assetsToAddFormatted = "";
foreach (var asset in assetsToAdd)
{
assetsToAddFormatted += eventToAssetPath(asset.path) + "\n";
}
string assetsToMoveFormatted = "";
foreach (var asset in assetsToMove)
{
var fromPath = assetsToMoveFrom.First( a => a.id == asset.id ).path;
var toPath = assetsToMoveTo.First( a => a.id == asset.id ).path;
assetsToMoveFormatted += fromPath + " moved to " + toPath + "\n";
}
string deletionMessage =
(assetsToDelete.Count() == 0 ? "No assets removed" : "Removed assets: " + assetsToDelete.Count()) + "\n" +
(assetsToAdd.Count() == 0 ? "No assets added" : "Added assets: " + assetsToAdd.Count()) + "\n" +
(assetsToMove.Count() == 0 ? "No assets moved" : "Moved assets: " + assetsToMove.Count()) + "\n" +
((assetsToDelete.Count() != 0 || assetsToAdd.Count() != 0 || assetsToMove.Count() != 0) ? "\nSee console for details" : "");
Debug.Log("FMOD import details " + System.DateTime.Now.ToString(@"[hh:mm tt]") + "\n\n" +
(assetsToDelete.Count() == 0 ? "No assets removed" : "Removed Assets:\n" + assetsToDeleteFormatted) + "\n" +
(assetsToAdd.Count() == 0 ? "No assets added" : "Added Assets:\n" + assetsToAddFormatted) + "\n" +
(assetsToMove.Count() == 0 ? "No assets moved" : "Moved Assets:\n" + assetsToMoveFormatted) + "\n" +
"________________________________");
if (!EditorUtility.DisplayDialog("FMOD Studio Importer", deletionMessage, "Continue", "Cancel"))
{
return false; // user clicked cancel
}
}
ImportAssets(assetsToAdd);
DeleteMissingAssets(assetsToDelete);
MoveExistingAssets(assetsToMove, assetsToMoveFrom, assetsToMoveTo);
AssetDatabase.Refresh();
return true;
}
static void CreateDirectories(string assetPath)
{
const string root = "Assets";
var currentDir = System.IO.Directory.GetParent(assetPath);
Stack<string> directories = new Stack<string>();
while (!currentDir.Name.Equals(root))
{
directories.Push(currentDir.Name);
currentDir = currentDir.Parent;
}
string path = root;
while (directories.Any())
{
var d = directories.Pop();
if (!System.IO.Directory.Exists(Application.dataPath + "/../" + path + "/" + d))
{
FMOD.Studio.UnityUtil.Log("Create folder: " + path + "/" + d);
AssetDatabase.CreateFolder(path, d);
}
path += "/" + d;
}
}
static void MoveExistingAssets(IEnumerable<FMODAsset> assetsToMove, IEnumerable<FMODAsset> assetsToMoveFrom, IEnumerable<FMODAsset> assetsToMoveTo)
{
foreach (var asset in assetsToMove)
{
var fromAsset = assetsToMoveFrom.First( a => a.id == asset.id );
var toAsset = assetsToMoveTo.First( a => a.id == asset.id );
var fromPath = "Assets/" + AssetFolder + eventToAssetPath(fromAsset.path) + ".asset";
var toPath = "Assets/" + AssetFolder + eventToAssetPath(toAsset.path) + ".asset";
CreateDirectories(toPath);
if (!AssetDatabase.Contains(fromAsset))
{
FMOD.Studio.UnityUtil.Log("$$ IMPORT ASSET $$");
AssetDatabase.ImportAsset(fromPath);
}
var result = AssetDatabase.MoveAsset(fromPath, toPath);
if (result != "")
{
FMOD.Studio.UnityUtil.Log("Asset move failed: " + result);
}
else
{
var dir = new System.IO.FileInfo(fromPath).Directory;
DeleteDirectoryIfEmpty(dir);
}
fromAsset.path = toAsset.path;
}
}
[MenuItem ("FMOD/Online Manual")]
static void OnlineManual()
{
Application.OpenURL("http://fmod.com/download/fmodstudio/integrations/Unity/Doc/UnityDocumentation.pdf");
}
[MenuItem ("FMOD/Online API Documentation")]
static void OnlineAPIDocs()
{
Application.OpenURL("http://fmod.com/documentation");
}
[MenuItem ("FMOD/About Integration")]
static void AboutIntegration()
{
if (PrepareIntegration())
{
if (sFMODSystem == null || !sFMODSystem.isValid())
{
CreateSystem();
if (sFMODSystem == null || !sFMODSystem.isValid())
{
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "Unable to retrieve version, check the version number in fmod.cs", "OK");
}
}
FMOD.System sys;
sFMODSystem.getLowLevelSystem(out sys);
uint version;
if (!ERRCHECK (sys.getVersion(out version)))
{
return;
}
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "Version: " + getVersionString(version), "OK");
}
}
static string getVersionString(uint version)
{
uint major = (version & 0x00FF0000) >> 16;
uint minor = (version & 0x0000FF00) >> 8;
uint patch = (version & 0x000000FF);
return major.ToString("X1") + "." +
minor.ToString("X2") + "." +
patch.ToString("X2");
}
static string guidPathKey
{
get { return "FMODStudioProjectPath_" + Application.dataPath; }
}
static string GetDefaultPath()
{
return EditorPrefs.GetString(guidPathKey, Application.dataPath);
}
static bool LocateProject(ref string filePath)
{
var defaultPath = GetDefaultPath();
{
var workDir = System.Environment.CurrentDirectory;
filePath = EditorUtility.OpenFolderPanel("Locate build directory", defaultPath, "Build");
System.Environment.CurrentDirectory = workDir; // HACK: fixes weird Unity bug that causes random crashes after using OpenFolderPanel
}
if (System.String.IsNullOrEmpty(filePath))
{
FMOD.Studio.UnityUtil.Log("No directory selected");
return false;
}
var directory = new System.IO.DirectoryInfo(filePath);
if (directory.Name.CompareTo("Build") != 0)
{
EditorUtility.DisplayDialog("Incorrect directory", "Incorrect directory selected, select the \"Build\" directory in the FMOD Studio project folder", "OK");
return false;
}
EditorPrefs.SetString(guidPathKey, directory.Parent.FullName);
var bankPath = filePath + "/" + studioPlatformDirectoryName();
var info = new System.IO.DirectoryInfo(bankPath);
if (info.GetFiles().Count() == 0)
{
EditorUtility.DisplayDialog("FMOD Studio Importer", "No bank files found in directory: " + bankPath +
"You must build the FMOD Studio project before importing", "OK");
return false;
}
return true;
}
static void GatherExistingAssets(List<FMODAsset> existingAssets)
{
var assetRoot = Application.dataPath + "/" + AssetFolder;
if (System.IO.Directory.Exists(assetRoot))
{
GatherAssetsFromDirectory(assetRoot, existingAssets);
}
}
static void GatherAssetsFromDirectory(string directory, List<FMODAsset> existingAssets)
{
var info = new System.IO.DirectoryInfo(directory);
foreach (var file in info.GetFiles())
{
var relativePath = new System.Uri(Application.dataPath).MakeRelativeUri(new System.Uri(file.FullName)).ToString();
var asset = (FMODAsset)AssetDatabase.LoadAssetAtPath(relativePath, typeof(FMODAsset));
if (asset != null)
{
existingAssets.Add(asset);
}
}
foreach (var dir in info.GetDirectories())
{
GatherAssetsFromDirectory(dir.FullName, existingAssets);
}
}
static void GatherNewAssets(string filePath, List<FMODAsset> newAssets)
{
if (System.String.IsNullOrEmpty(filePath))
{
FMOD.Studio.UnityUtil.LogError("No build folder specified");
return;
}
foreach (var bank in loadedBanks)
{
int count = 0;
ERRCHECK(bank.getEventCount(out count));
FMOD.Studio.EventDescription[] descriptions = new FMOD.Studio.EventDescription[count];
ERRCHECK(bank.getEventList(out descriptions));
foreach (var desc in descriptions)
{
string path;
FMOD.RESULT result = desc.getPath(out path);
if (result == FMOD.RESULT.ERR_EVENT_NOTFOUND || desc == null || !desc.isValid() || !ERRCHECK(result))
{
continue;
}
ERRCHECK(result);
Guid id;
ERRCHECK(desc.getID(out id));
var asset = ScriptableObject.CreateInstance<FMODAsset>();
asset.name = path.Substring(path.LastIndexOf('/') + 1);
asset.path = path;
asset.id = id.ToString("B");
//Debug.Log("name = " + asset.name + ", id = " + asset.id);
newAssets.Add(asset);
}
}
}
static string eventToAssetPath(string eventPath)
{
if (eventPath.StartsWith("event:"))
{
return eventPath.Substring(6); //trim "event:" from the start of the path
}
else if (eventPath.StartsWith("snapshot:"))
{
return eventPath.Substring(9); //trim "snapshot:" from the start of the path
}
else if (eventPath.StartsWith("/"))
{
// Assume 1.2 style paths
return eventPath;
}
throw new UnityException("Incorrectly formatted FMOD Studio event path: " + eventPath);
}
static void ImportAssets(IEnumerable<FMODAsset> assetsToAdd)
{
foreach (var asset in assetsToAdd)
{
var path = "Assets/" + AssetFolder + eventToAssetPath(asset.path) + ".asset";
CreateDirectories(path);
AssetDatabase.CreateAsset(asset, path);
}
}
static void DeleteMissingAssets(IEnumerable<FMODAsset> assetsToDelete)
{
foreach (var asset in assetsToDelete)
{
var path = AssetDatabase.GetAssetPath(asset);
AssetDatabase.DeleteAsset(path);
var dir = new System.IO.FileInfo(path).Directory;
DeleteDirectoryIfEmpty(dir);
}
}
static void DeleteDirectoryIfEmpty(System.IO.DirectoryInfo dir)
{
FMOD.Studio.UnityUtil.Log("Attempt delete directory: " + dir.FullName);
if (dir.GetFiles().Length == 0 && dir.GetDirectories().Length == 0 && dir.Name != AssetFolder)
{
dir.Delete();
DeleteDirectoryIfEmpty(dir.Parent);
}
}
static bool CreateSystem()
{
if (!FMOD.Studio.UnityUtil.ForceLoadLowLevelBinary())
{
return false;
}
if (!ERRCHECK(FMOD.Studio.System.create(out sFMODSystem)))
{
return false;
}
// Note plugins wont be used when auditioning inside the Unity editor
ERRCHECK(sFMODSystem.initialize(256, FMOD.Studio.INITFLAGS.ALLOW_MISSING_PLUGINS, FMOD.INITFLAGS.NORMAL, System.IntPtr.Zero));
return true;
}
static void UnloadAllBanks()
{
if (sFMODSystem != null)
{
foreach (var bank in loadedBanks)
{
ERRCHECK(bank.unload());
}
loadedBanks.Clear();
events.Clear();
sFMODSystem.release();
sFMODSystem = null;
}
else if (loadedBanks.Count != 0)
{
FMOD.Studio.UnityUtil.LogError("Banks not unloaded!");
}
}
static bool LoadAllBanks()
{
UnloadAllBanks();
if (!CreateSystem())
{
return false;
}
string bankPath = Application.dataPath + "/StreamingAssets";
FMOD.Studio.UnityUtil.Log("Loading banks in path: " + bankPath);
var info = new System.IO.DirectoryInfo(bankPath);
FMOD.Studio.UnityUtil.Log("Directory " + (info.Exists ? "exists" : "doesn't exist!!"));
if (info.Exists)
{
var fileInfo = info.GetFiles();
FMOD.Studio.UnityUtil.Log("Number of files: " + fileInfo.Length);
List<System.IO.FileInfo> bankFiles = new List<System.IO.FileInfo>();
foreach (var file in fileInfo)
{
bankFiles.Add(file);
}
int count = 0;
foreach (var file in bankFiles)
{
FMOD.Studio.UnityUtil.Log("file: " + file.Name);
var s = info.FullName + "/" + file.Name;
var ex = file.Extension;
if (ex.Equals(".bank", System.StringComparison.CurrentCultureIgnoreCase) ||
ex.Equals(".strings", System.StringComparison.CurrentCultureIgnoreCase))
{
FMOD.Studio.Bank bank = null;
FMOD.RESULT result = sFMODSystem.loadBankFile(s, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out bank);
if (result == FMOD.RESULT.ERR_VERSION)
{
//FMOD.Studio.UnityUtil.LogError("These banks were built with an incompatible version of FMOD Studio. Make sure the unity integration matches the FMOD Studio version. (current integration version = " + getVersionString(FMOD.VERSION.number) + ")" );
FMOD.Studio.UnityUtil.LogError("Bank " + s + " was built with an incompatible version of FMOD Studio. Make sure the unity integration matches the FMOD Studio version." );
return false;
}
if (result != FMOD.RESULT.OK)
{
FMOD.Studio.UnityUtil.LogError("An error occured while loading bank " + s + ": " + result.ToString() + "\n " + FMOD.Error.String(result));
return false;
}
loadedBanks.Add(bank);
}
++count;
}
}
return true;
}
static bool ERRCHECK(FMOD.RESULT result)
{
return FMOD.Studio.UnityUtil.ERRCHECK(result);
}
static bool PrepareIntegration()
{
// Cleanup stale DLL's from the old versions
if (Application.platform == RuntimePlatform.WindowsEditor)
{
var projectRoot = new System.IO.DirectoryInfo(Application.dataPath).Parent;
var lowLevelLib = projectRoot.FullName + "/fmod.dll";
DeleteBinaryFile(lowLevelLib);
var studioLib = projectRoot.FullName + "/fmodstudio.dll";
DeleteBinaryFile(studioLib);
}
else if (Application.platform == RuntimePlatform.OSXEditor)
{
var projectRoot = new System.IO.DirectoryInfo(Application.dataPath).Parent;
var lowLevelLib = projectRoot.FullName + "/fmod.dylib";
DeleteBinaryFile(lowLevelLib);
var studioLib = projectRoot.FullName + "/fmodstudio.dylib";
DeleteBinaryFile(studioLib);
}
#if !UNITY_5
if (!UnityEditorInternal.InternalEditorUtility.HasPro())
{
if (Application.platform == RuntimePlatform.WindowsEditor)
{
var projectRoot = new System.IO.DirectoryInfo(Application.dataPath).Parent;
var lowLevelLib = projectRoot.FullName + "/fmod.dll";
DeleteBinaryFile(lowLevelLib);
var studioLib = projectRoot.FullName + "/fmodstudio.dll";
DeleteBinaryFile(studioLib);
}
else if (Application.platform == RuntimePlatform.OSXEditor)
{
var projectRoot = new System.IO.DirectoryInfo(Application.dataPath).Parent;
var lowLevelLib = projectRoot.FullName + "/fmod.dylib";
DeleteBinaryFile(lowLevelLib);
var studioLib = projectRoot.FullName + "/fmodstudio.dylib";
DeleteBinaryFile(studioLib);
}
EditorUtility.DisplayDialog("FMOD Studio Unity Integration", "FMOD Studio Integration requires either Unity 4 Pro or Unity 5", "OK");
return false;
}
else
#endif
{
return true;
}
}
static void DeleteBinaryFile(string path)
{
if (System.IO.File.Exists(path))
{
try
{
System.IO.File.Delete(path);
}
catch (System.UnauthorizedAccessException e)
{
EditorUtility.DisplayDialog("Restart Unity",
"The following file is in use and cannot be overwritten, restart Unity and try again\n" + path, "OK");
throw e;
}
}
}
}
public class FMODAssetGUIDComparer : IEqualityComparer<FMODAsset>
{
public bool Equals(FMODAsset lhs, FMODAsset rhs)
{
return lhs.id.Equals(rhs.id, System.StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(FMODAsset asset)
{
return asset.id.GetHashCode();
}
}
public class FMODAssetPathComparer : IEqualityComparer<FMODAsset>
{
public bool Equals(FMODAsset lhs, FMODAsset rhs)
{
return lhs.path.Equals(rhs.path, System.StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(FMODAsset asset)
{
return asset.path.GetHashCode();
}
}
#endif
#endif
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using Quartz.Util;
namespace Quartz
{
/// <summary>
/// Holds state information for <see cref="IJob" /> instances.
/// </summary>
/// <remarks>
/// <see cref="JobDataMap" /> instances are stored once when the <see cref="IJob" />
/// is added to a scheduler. They are also re-persisted after every execution of
/// instances that have <see cref="PersistJobDataAfterExecutionAttribute" /> present.
/// <para>
/// <see cref="JobDataMap" /> instances can also be stored with a
/// <see cref="ITrigger" />. This can be useful in the case where you have a Job
/// that is stored in the scheduler for regular/repeated use by multiple
/// Triggers, yet with each independent triggering, you want to supply the
/// Job with different data inputs.
/// </para>
/// <para>
/// The <see cref="IJobExecutionContext" /> passed to a Job at execution time
/// also contains a convenience <see cref="JobDataMap" /> that is the result
/// of merging the contents of the trigger's JobDataMap (if any) over the
/// Job's JobDataMap (if any).
/// </para>
/// </remarks>
/// <seealso cref="IJob" />
/// <seealso cref="PersistJobDataAfterExecutionAttribute" />
/// <seealso cref="ITrigger" />
/// <seealso cref="IJobExecutionContext" />
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class JobDataMap : StringKeyDirtyFlagMap
{
/// <summary>
/// Create an empty <see cref="JobDataMap" />.
/// </summary>
public JobDataMap() : base(15)
{
}
/// <summary>
/// Create a <see cref="JobDataMap" /> with the given data.
/// </summary>
public JobDataMap(IDictionary<string, object> map) : this()
{
PutAll(map);
}
/// <summary>
/// Create a <see cref="JobDataMap" /> with the given data.
/// </summary>
public JobDataMap(IDictionary map) : this()
{
foreach (DictionaryEntry entry in map)
{
Put((string) entry.Key, entry.Value);
}
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected JobDataMap(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
/// <summary>
/// Adds the given <see cref="bool" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, bool value)
{
string strValue = value.ToString();
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="char" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, char value)
{
string strValue = value.ToString(CultureInfo.InvariantCulture);
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="double" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, double value)
{
string strValue = value.ToString(CultureInfo.InvariantCulture);
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="float" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, float value)
{
string strValue = value.ToString(CultureInfo.InvariantCulture);
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="int" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, int value)
{
string strValue = value.ToString(CultureInfo.InvariantCulture);
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="long" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, long value)
{
string strValue = value.ToString(CultureInfo.InvariantCulture);
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="DateTime" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, DateTime value)
{
string strValue = value.ToString(CultureInfo.InvariantCulture);
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="DateTimeOffset" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, DateTimeOffset value)
{
string strValue = value.ToString(CultureInfo.InvariantCulture);
base.Put(key, strValue);
}
/// <summary>
/// Adds the given <see cref="TimeSpan" /> value as a string version to the
/// <see cref="IJob" />'s data map.
/// </summary>
public virtual void PutAsString(string key, TimeSpan value)
{
string strValue = value.ToString();
base.Put(key, strValue);
}
/// <summary>
/// Retrieve the identified <see cref="int" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual int GetIntValueFromString(string key)
{
object obj = Get(key);
return Int32.Parse((string) obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Retrieve the identified <see cref="int" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual int GetIntValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetIntValueFromString(key);
}
return GetInt(key);
}
/// <summary>
/// Retrieve the identified <see cref="bool" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual bool GetBooleanValueFromString(string key)
{
object obj = Get(key);
return ((string) obj).ToUpper(CultureInfo.InvariantCulture).Equals("TRUE");
}
/// <summary>
/// Retrieve the identified <see cref="bool" /> value from the
/// <see cref="JobDataMap" />.
/// </summary>
public virtual bool GetBooleanValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetBooleanValueFromString(key);
}
return GetBoolean(key);
}
/// <summary>
/// Retrieve the identified <see cref="char" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual char GetCharFromString(string key)
{
object obj = Get(key);
return ((string) obj)[0];
}
/// <summary>
/// Retrieve the identified <see cref="double" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual double GetDoubleValueFromString(string key)
{
object obj = Get(key);
return Double.Parse((string) obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Retrieve the identified <see cref="double" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual double GetDoubleValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetDoubleValueFromString(key);
}
return GetDouble(key);
}
/// <summary>
/// Retrieve the identified <see cref="float" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual float GetFloatValueFromString(string key)
{
object obj = Get(key);
return Single.Parse((string) obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Retrieve the identified <see cref="float" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual float GetFloatValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetFloatValueFromString(key);
}
return GetFloat(key);
}
/// <summary>
/// Retrieve the identified <see cref="long" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual long GetLongValueFromString(string key)
{
object obj = Get(key);
return Int64.Parse((string) obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Retrieve the identified <see cref="DateTime" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual DateTime GetDateTimeValueFromString(string key)
{
object obj = Get(key);
return DateTime.Parse((string) obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Retrieve the identified <see cref="DateTimeOffset" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual DateTimeOffset GetDateTimeOffsetValueFromString(string key)
{
object obj = Get(key);
return DateTimeOffset.Parse((string) obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Retrieve the identified <see cref="TimeSpan" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual TimeSpan GetTimeSpanValueFromString(string key)
{
object obj = Get(key);
#if NET_40
return TimeSpan.Parse((string) obj, CultureInfo.InvariantCulture);
#else
return TimeSpan.Parse((string) obj);
#endif
}
/// <summary>
/// Retrieve the identified <see cref="long" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual long GetLongValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetLongValueFromString(key);
}
return GetLong(key);
}
/// <summary>
/// Gets the date time.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public virtual DateTime GetDateTimeValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetDateTimeValueFromString(key);
}
return GetDateTime(key);
}
/// <summary>
/// Gets the date time offset.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public virtual DateTimeOffset GetDateTimeOffsetValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetDateTimeOffsetValueFromString(key);
}
return GetDateTimeOffset(key);
}
/// <summary>
/// Retrieve the identified <see cref="TimeSpan" /> value from the <see cref="JobDataMap" />.
/// </summary>
public virtual TimeSpan GetTimeSpanValue(string key)
{
object obj = Get(key);
if (obj is string)
{
return GetTimeSpanValueFromString(key);
}
return GetTimeSpan(key);
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Event type: Sales event.
/// </summary>
public class SaleEvent_Core : TypeCore, IEvent
{
public SaleEvent_Core()
{
this._TypeId = 232;
this._Id = "SaleEvent";
this._Schema_Org_Url = "http://schema.org/SaleEvent";
string label = "";
GetLabel(out label, "SaleEvent", typeof(SaleEvent_Core));
this._Label = label;
this._Ancestors = new int[]{266,98};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{98};
this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218};
}
/// <summary>
/// A person attending the event.
/// </summary>
private Attendees_Core attendees;
public Attendees_Core Attendees
{
get
{
return attendees;
}
set
{
attendees = value;
SetPropertyInstance(attendees);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private EndDate_Core endDate;
public EndDate_Core EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
SetPropertyInstance(endDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// The main performer or performers of the event\u2014for example, a presenter, musician, or actor.
/// </summary>
private Performers_Core performers;
public Performers_Core Performers
{
get
{
return performers;
}
set
{
performers = value;
SetPropertyInstance(performers);
}
}
/// <summary>
/// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private StartDate_Core startDate;
public StartDate_Core StartDate
{
get
{
return startDate;
}
set
{
startDate = value;
SetPropertyInstance(startDate);
}
}
/// <summary>
/// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference.
/// </summary>
private SubEvents_Core subEvents;
public SubEvents_Core SubEvents
{
get
{
return subEvents;
}
set
{
subEvents = value;
SetPropertyInstance(subEvents);
}
}
/// <summary>
/// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent.
/// </summary>
private SuperEvent_Core superEvent;
public SuperEvent_Core SuperEvent
{
get
{
return superEvent;
}
set
{
superEvent = value;
SetPropertyInstance(superEvent);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_13 : EcmaTest
{
[Fact]
[Trait("Category", "13")]
public void XFunctionYStatementDoesNotStoreAReferenceToTheNewFunctionInTheVaraibleYIdentifier()
{
RunTest(@"TestCases/ch13/13.0/S13_A1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionIsAData()
{
RunTest(@"TestCases/ch13/13.0/S13_A10.js", false);
}
[Fact]
[Trait("Category", "13")]
public void SinceArgumentsPropertyHasAttributeDontdeleteOnlyItsElementsCanBeDeleted()
{
RunTest(@"TestCases/ch13/13.0/S13_A11_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void SinceArgumentsPropertyHasAttributeDontdeleteOnlyItsElementsCanBeDeleted2()
{
RunTest(@"TestCases/ch13/13.0/S13_A11_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void SinceArgumentsPropertyHasAttributeDontdeleteOnlyItsElementsCanBeDeleted3()
{
RunTest(@"TestCases/ch13/13.0/S13_A11_T3.js", false);
}
[Fact]
[Trait("Category", "13")]
public void SinceArgumentsPropertyHasAttributeDontdeleteOnlyItsElementsCanBeDeleted4()
{
RunTest(@"TestCases/ch13/13.0/S13_A11_T4.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionDeclarationsInGlobalOrFunctionScopeAreDontdelete()
{
RunTest(@"TestCases/ch13/13.0/S13_A12_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionDeclarationsInGlobalOrFunctionScopeAreDontdelete2()
{
RunTest(@"TestCases/ch13/13.0/S13_A12_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void DeletingArgumentsILeadsToBreakingTheConnectionToLocalReference()
{
RunTest(@"TestCases/ch13/13.0/S13_A13_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void DeletingArgumentsILeadsToBreakingTheConnectionToLocalReference2()
{
RunTest(@"TestCases/ch13/13.0/S13_A13_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void DeletingArgumentsILeadsToBreakingTheConnectionToLocalReference3()
{
RunTest(@"TestCases/ch13/13.0/S13_A13_T3.js", false);
}
[Fact]
[Trait("Category", "13")]
public void UnicodeSymbolsInFunctionNameAreAllowed()
{
RunTest(@"TestCases/ch13/13.0/S13_A14.js", false);
}
[Fact]
[Trait("Category", "13")]
public void ArgumentsVariableOverridesActivationobjectArguments()
{
RunTest(@"TestCases/ch13/13.0/S13_A15_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void ArgumentsVariableOverridesActivationobjectArguments2()
{
RunTest(@"TestCases/ch13/13.0/S13_A15_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void ArgumentsVariableOverridesActivationobjectArguments3()
{
RunTest(@"TestCases/ch13/13.0/S13_A15_T3.js", false);
}
[Fact]
[Trait("Category", "13")]
public void ArgumentsVariableOverridesActivationobjectArguments4()
{
RunTest(@"TestCases/ch13/13.0/S13_A15_T4.js", false);
}
[Fact]
[Trait("Category", "13")]
public void ArgumentsVariableOverridesActivationobjectArguments5()
{
RunTest(@"TestCases/ch13/13.0/S13_A15_T5.js", false);
}
[Fact]
[Trait("Category", "13")]
public void AnySeparatorsAreAdmittedBetweenDeclarationChunks()
{
RunTest(@"TestCases/ch13/13.0/S13_A16.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionCallCannotAppearInTheProgramBeforeTheFunctionexpressionAppears()
{
RunTest(@"TestCases/ch13/13.0/S13_A17_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionCallCannotAppearInTheProgramBeforeTheFunctionexpressionAppears2()
{
RunTest(@"TestCases/ch13/13.0/S13_A17_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void ClosuresAreAdmitted()
{
RunTest(@"TestCases/ch13/13.0/S13_A18.js", false);
}
[Fact]
[Trait("Category", "13")]
public void VarDoesNotOverrideFunctionDeclaration()
{
RunTest(@"TestCases/ch13/13.0/S13_A19_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void VarDoesNotOverrideFunctionDeclaration2()
{
RunTest(@"TestCases/ch13/13.0/S13_A19_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionMustBeEvaluatedInsideTheExpression()
{
RunTest(@"TestCases/ch13/13.0/S13_A2_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionMustBeEvaluatedInsideTheExpression2()
{
RunTest(@"TestCases/ch13/13.0/S13_A2_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionMustBeEvaluatedInsideTheExpression3()
{
RunTest(@"TestCases/ch13/13.0/S13_A2_T3.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheIdentifierInAFunctionexpressionCanBeReferencedFromInsideTheFunctionexpressionSFunctionbodyToAllowTheFunctionCallingItselfRecursively()
{
RunTest(@"TestCases/ch13/13.0/S13_A3_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheIdentifierInAFunctionexpressionCanBeReferencedFromInsideTheFunctionexpressionSFunctionbodyToAllowTheFunctionCallingItselfRecursively2()
{
RunTest(@"TestCases/ch13/13.0/S13_A3_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheIdentifierInAFunctionexpressionCanBeReferencedFromInsideTheFunctionexpressionSFunctionbodyToAllowTheFunctionCallingItselfRecursively3()
{
RunTest(@"TestCases/ch13/13.0/S13_A3_T3.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheProductionFunctiondeclarationFunctionIdentifierFormalparameterlistOptFunctionbodyIsProcessedByFunctionDeclarations()
{
RunTest(@"TestCases/ch13/13.0/S13_A4_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheProductionFunctiondeclarationFunctionIdentifierFormalparameterlistOptFunctionbodyIsProcessedByFunctionDeclarations2()
{
RunTest(@"TestCases/ch13/13.0/S13_A4_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheProductionFunctiondeclarationFunctionIdentifierFormalparameterlistOptFunctionbodyIsProcessedByFunctionDeclarations3()
{
RunTest(@"TestCases/ch13/13.0/S13_A4_T3.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheProductionFunctiondeclarationFunctionIdentifierFormalparameterlistOptFunctionbodyIsProcessedByFunctionDeclarations4()
{
RunTest(@"TestCases/ch13/13.0/S13_A4_T4.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctiondeclarationCanBeOverridedByOtherFunctiondeclarationWithTheSameIdentifier()
{
RunTest(@"TestCases/ch13/13.0/S13_A6_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctiondeclarationCanBeOverridedByOtherFunctiondeclarationWithTheSameIdentifier2()
{
RunTest(@"TestCases/ch13/13.0/S13_A6_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheFunctionbodyMustBeSourceelements()
{
RunTest(@"TestCases/ch13/13.0/S13_A7_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheFunctionbodyMustBeSourceelements2()
{
RunTest(@"TestCases/ch13/13.0/S13_A7_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void TheFunctionbodyMustBeSourceelements3()
{
RunTest(@"TestCases/ch13/13.0/S13_A7_T3.js", true);
}
[Fact]
[Trait("Category", "13")]
public void ArgumentsPropertyOfActivationObjectContainsRealParamsToBePassed()
{
RunTest(@"TestCases/ch13/13.0/S13_A8_T1.js", false);
}
[Fact]
[Trait("Category", "13")]
public void ArgumentsPropertyOfActivationObjectContainsRealParamsToBePassed2()
{
RunTest(@"TestCases/ch13/13.0/S13_A8_T2.js", false);
}
[Fact]
[Trait("Category", "13")]
public void FunctionCanBePassedAsArgument()
{
RunTest(@"TestCases/ch13/13.0/S13_A9.js", false);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Logging;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Rulesets;
namespace osu.Game.Screens.OnlinePlay.Components
{
public abstract class RoomManager : CompositeDrawable, IRoomManager
{
public event Action RoomsUpdated;
private readonly BindableList<Room> rooms = new BindableList<Room>();
public IBindable<bool> InitialRoomsReceived => initialRoomsReceived;
private readonly Bindable<bool> initialRoomsReceived = new Bindable<bool>();
public IBindableList<Room> Rooms => rooms;
protected IBindable<Room> JoinedRoom => joinedRoom;
private readonly Bindable<Room> joinedRoom = new Bindable<Room>();
[Resolved]
private RulesetStore rulesets { get; set; }
[Resolved]
private BeatmapManager beatmaps { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
protected RoomManager()
{
RelativeSizeAxes = Axes.Both;
InternalChildren = CreatePollingComponents().Select(p =>
{
p.RoomsReceived = onRoomsReceived;
return p;
}).ToList();
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
PartRoom();
}
public virtual void CreateRoom(Room room, Action<Room> onSuccess = null, Action<string> onError = null)
{
room.Host.Value = api.LocalUser.Value;
var req = new CreateRoomRequest(room);
req.Success += result =>
{
joinedRoom.Value = room;
update(room, result);
addRoom(room);
RoomsUpdated?.Invoke();
onSuccess?.Invoke(room);
};
req.Failure += exception =>
{
onError?.Invoke(req.Result?.Error ?? exception.Message);
};
api.Queue(req);
}
private JoinRoomRequest currentJoinRoomRequest;
public virtual void JoinRoom(Room room, string password = null, Action<Room> onSuccess = null, Action<string> onError = null)
{
currentJoinRoomRequest?.Cancel();
currentJoinRoomRequest = new JoinRoomRequest(room, password);
currentJoinRoomRequest.Success += () =>
{
joinedRoom.Value = room;
onSuccess?.Invoke(room);
};
currentJoinRoomRequest.Failure += exception =>
{
if (!(exception is OperationCanceledException))
Logger.Log($"Failed to join room: {exception}", level: LogLevel.Important);
onError?.Invoke(exception.ToString());
};
api.Queue(currentJoinRoomRequest);
}
public virtual void PartRoom()
{
currentJoinRoomRequest?.Cancel();
if (JoinedRoom.Value == null)
return;
api.Queue(new PartRoomRequest(joinedRoom.Value));
joinedRoom.Value = null;
}
private readonly HashSet<long> ignoredRooms = new HashSet<long>();
private void onRoomsReceived(List<Room> received)
{
if (received == null)
{
ClearRooms();
return;
}
// Remove past matches
foreach (var r in rooms.ToList())
{
if (received.All(e => e.RoomID.Value != r.RoomID.Value))
rooms.Remove(r);
}
for (int i = 0; i < received.Count; i++)
{
var room = received[i];
Debug.Assert(room.RoomID.Value != null);
if (ignoredRooms.Contains(room.RoomID.Value.Value))
continue;
room.Position.Value = i;
try
{
update(room, room);
addRoom(room);
}
catch (Exception ex)
{
Logger.Error(ex, $"Failed to update room: {room.Name.Value}.");
ignoredRooms.Add(room.RoomID.Value.Value);
rooms.Remove(room);
}
}
RoomsUpdated?.Invoke();
initialRoomsReceived.Value = true;
}
protected void RemoveRoom(Room room) => rooms.Remove(room);
protected void ClearRooms()
{
rooms.Clear();
initialRoomsReceived.Value = false;
}
/// <summary>
/// Updates a local <see cref="Room"/> with a remote copy.
/// </summary>
/// <param name="local">The local <see cref="Room"/> to update.</param>
/// <param name="remote">The remote <see cref="Room"/> to update with.</param>
private void update(Room local, Room remote)
{
foreach (var pi in remote.Playlist)
pi.MapObjects(beatmaps, rulesets);
local.CopyFrom(remote);
}
/// <summary>
/// Adds a <see cref="Room"/> to the list of available rooms.
/// </summary>
/// <param name="room">The <see cref="Room"/> to add.</param>
private void addRoom(Room room)
{
var existing = rooms.FirstOrDefault(e => e.RoomID.Value == room.RoomID.Value);
if (existing == null)
rooms.Add(room);
else
existing.CopyFrom(room);
}
protected abstract IEnumerable<RoomPollingComponent> CreatePollingComponents();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AnnuaireCertifies.WebServices.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/* ========================================================================
* Copyright (c) 2005-2016 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* 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.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Runtime.Serialization;
using ;
namespace ObjectTypeTest
{
#region Method Identifiers
/// <summary>
/// A class that declares constants for all Methods in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class Methods
{
/// <summary>
/// The identifier for the ComplexObjectType_ChildMethod Method.
/// </summary>
public const uint ComplexObjectType_ChildMethod = 10;
/// <summary>
/// The identifier for the DerivedFromComplexObjectType_ChildMethod Method.
/// </summary>
public const uint DerivedFromComplexObjectType_ChildMethod = 25;
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_ChildMethod Method.
/// </summary>
public const uint InstanceOfDerivedFromComplexObjectType_ChildMethod = 39;
}
#endregion
#region Object Identifiers
/// <summary>
/// A class that declares constants for all Objects in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class Objects
{
/// <summary>
/// The identifier for the ComplexObjectType_ChildObject Object.
/// </summary>
public const uint ComplexObjectType_ChildObject = 2;
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType Object.
/// </summary>
public const uint InstanceOfDerivedFromComplexObjectType = 30;
}
#endregion
#region ObjectType Identifiers
/// <summary>
/// A class that declares constants for all ObjectTypes in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class ObjectTypes
{
/// <summary>
/// The identifier for the ComplexObjectType ObjectType.
/// </summary>
public const uint ComplexObjectType = 1;
/// <summary>
/// The identifier for the DerivedFromComplexObjectType ObjectType.
/// </summary>
public const uint DerivedFromComplexObjectType = 16;
}
#endregion
#region Variable Identifiers
/// <summary>
/// A class that declares constants for all Variables in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class Variables
{
/// <summary>
/// The identifier for the ComplexObjectType_BrowseName4node66 Variable.
/// </summary>
public const uint ComplexObjectType_BrowseName4node66 = 3;
/// <summary>
/// The identifier for the ComplexObjectType_ChildVariable Variable.
/// </summary>
public const uint ComplexObjectType_ChildVariable = 43;
/// <summary>
/// The identifier for the ComplexObjectType_ChildVariable_EURange Variable.
/// </summary>
public const uint ComplexObjectType_ChildVariable_EURange = 47;
/// <summary>
/// The identifier for the ComplexObjectType_ChildMethod_InputArguments Variable.
/// </summary>
public const uint ComplexObjectType_ChildMethod_InputArguments = 11;
/// <summary>
/// The identifier for the ComplexObjectType_ChildMethod_OutputArguments Variable.
/// </summary>
public const uint ComplexObjectType_ChildMethod_OutputArguments = 12;
/// <summary>
/// The identifier for the DerivedFromComplexObjectType_BrowseName4node66 Variable.
/// </summary>
public const uint DerivedFromComplexObjectType_BrowseName4node66 = 18;
/// <summary>
/// The identifier for the DerivedFromComplexObjectType_ChildVariable_EURange Variable.
/// </summary>
public const uint DerivedFromComplexObjectType_ChildVariable_EURange = 53;
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_BrowseName4node66 Variable.
/// </summary>
public const uint InstanceOfDerivedFromComplexObjectType_BrowseName4node66 = 32;
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_ChildVariable Variable.
/// </summary>
public const uint InstanceOfDerivedFromComplexObjectType_ChildVariable = 55;
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_ChildVariable_EURange Variable.
/// </summary>
public const uint InstanceOfDerivedFromComplexObjectType_ChildVariable_EURange = 59;
}
#endregion
#region Method Node Identifiers
/// <summary>
/// A class that declares constants for all Methods in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class MethodIds
{
/// <summary>
/// The identifier for the ComplexObjectType_ChildMethod Method.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType_ChildMethod = new ExpandedNodeId(ObjectTypeTest.Methods.ComplexObjectType_ChildMethod, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the DerivedFromComplexObjectType_ChildMethod Method.
/// </summary>
public static readonly ExpandedNodeId DerivedFromComplexObjectType_ChildMethod = new ExpandedNodeId(ObjectTypeTest.Methods.DerivedFromComplexObjectType_ChildMethod, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_ChildMethod Method.
/// </summary>
public static readonly ExpandedNodeId InstanceOfDerivedFromComplexObjectType_ChildMethod = new ExpandedNodeId(ObjectTypeTest.Methods.InstanceOfDerivedFromComplexObjectType_ChildMethod, ObjectTypeTest.Namespaces.cas);
}
#endregion
#region Object Node Identifiers
/// <summary>
/// A class that declares constants for all Objects in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class ObjectIds
{
/// <summary>
/// The identifier for the ComplexObjectType_ChildObject Object.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType_ChildObject = new ExpandedNodeId(ObjectTypeTest.Objects.ComplexObjectType_ChildObject, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType Object.
/// </summary>
public static readonly ExpandedNodeId InstanceOfDerivedFromComplexObjectType = new ExpandedNodeId(ObjectTypeTest.Objects.InstanceOfDerivedFromComplexObjectType, ObjectTypeTest.Namespaces.cas);
}
#endregion
#region ObjectType Node Identifiers
/// <summary>
/// A class that declares constants for all ObjectTypes in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class ObjectTypeIds
{
/// <summary>
/// The identifier for the ComplexObjectType ObjectType.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType = new ExpandedNodeId(ObjectTypeTest.ObjectTypes.ComplexObjectType, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the DerivedFromComplexObjectType ObjectType.
/// </summary>
public static readonly ExpandedNodeId DerivedFromComplexObjectType = new ExpandedNodeId(ObjectTypeTest.ObjectTypes.DerivedFromComplexObjectType, ObjectTypeTest.Namespaces.cas);
}
#endregion
#region Variable Node Identifiers
/// <summary>
/// A class that declares constants for all Variables in the Model Design.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public static partial class VariableIds
{
/// <summary>
/// The identifier for the ComplexObjectType_BrowseName4node66 Variable.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType_BrowseName4node66 = new ExpandedNodeId(ObjectTypeTest.Variables.ComplexObjectType_BrowseName4node66, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the ComplexObjectType_ChildVariable Variable.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType_ChildVariable = new ExpandedNodeId(ObjectTypeTest.Variables.ComplexObjectType_ChildVariable, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the ComplexObjectType_ChildVariable_EURange Variable.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType_ChildVariable_EURange = new ExpandedNodeId(ObjectTypeTest.Variables.ComplexObjectType_ChildVariable_EURange, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the ComplexObjectType_ChildMethod_InputArguments Variable.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType_ChildMethod_InputArguments = new ExpandedNodeId(ObjectTypeTest.Variables.ComplexObjectType_ChildMethod_InputArguments, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the ComplexObjectType_ChildMethod_OutputArguments Variable.
/// </summary>
public static readonly ExpandedNodeId ComplexObjectType_ChildMethod_OutputArguments = new ExpandedNodeId(ObjectTypeTest.Variables.ComplexObjectType_ChildMethod_OutputArguments, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the DerivedFromComplexObjectType_BrowseName4node66 Variable.
/// </summary>
public static readonly ExpandedNodeId DerivedFromComplexObjectType_BrowseName4node66 = new ExpandedNodeId(ObjectTypeTest.Variables.DerivedFromComplexObjectType_BrowseName4node66, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the DerivedFromComplexObjectType_ChildVariable_EURange Variable.
/// </summary>
public static readonly ExpandedNodeId DerivedFromComplexObjectType_ChildVariable_EURange = new ExpandedNodeId(ObjectTypeTest.Variables.DerivedFromComplexObjectType_ChildVariable_EURange, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_BrowseName4node66 Variable.
/// </summary>
public static readonly ExpandedNodeId InstanceOfDerivedFromComplexObjectType_BrowseName4node66 = new ExpandedNodeId(ObjectTypeTest.Variables.InstanceOfDerivedFromComplexObjectType_BrowseName4node66, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_ChildVariable Variable.
/// </summary>
public static readonly ExpandedNodeId InstanceOfDerivedFromComplexObjectType_ChildVariable = new ExpandedNodeId(ObjectTypeTest.Variables.InstanceOfDerivedFromComplexObjectType_ChildVariable, ObjectTypeTest.Namespaces.cas);
/// <summary>
/// The identifier for the InstanceOfDerivedFromComplexObjectType_ChildVariable_EURange Variable.
/// </summary>
public static readonly ExpandedNodeId InstanceOfDerivedFromComplexObjectType_ChildVariable_EURange = new ExpandedNodeId(ObjectTypeTest.Variables.InstanceOfDerivedFromComplexObjectType_ChildVariable_EURange, ObjectTypeTest.Namespaces.cas);
}
#endregion
#region BrowseName Declarations
/// <summary>
/// Declares all of the BrowseNames used in the Model Design.
/// </summary>
public static partial class BrowseNames
{
/// <summary>
/// The BrowseName for the BrowseName4node66 component.
/// </summary>
public const string BrowseName4node66 = "ChildProperty";
/// <summary>
/// The BrowseName for the ChildMethod component.
/// </summary>
public const string ChildMethod = "ChildMethod";
/// <summary>
/// The BrowseName for the ChildObject component.
/// </summary>
public const string ChildObject = "ChildObject";
/// <summary>
/// The BrowseName for the ChildVariable component.
/// </summary>
public const string ChildVariable = "ChildVariable";
/// <summary>
/// The BrowseName for the ComplexObjectType component.
/// </summary>
public const string ComplexObjectType = "ComplexObjectType";
/// <summary>
/// The BrowseName for the DerivedFromComplexObjectType component.
/// </summary>
public const string DerivedFromComplexObjectType = "DerivedFromComplexObjectType";
/// <summary>
/// The BrowseName for the InstanceOfDerivedFromComplexObjectType component.
/// </summary>
public const string InstanceOfDerivedFromComplexObjectType = "InstanceOfDerivedFromComplexObjectType";
}
#endregion
#region Namespace Declarations
/// <summary>
/// Defines constants for all namespaces referenced by the model design.
/// </summary>
public static partial class Namespaces
{
/// <summary>
/// The URI for the cas namespace (.NET code namespace is 'ObjectTypeTest').
/// </summary>
public const string cas = "http://cas.eu/UA/CommServer/UnitTests/ObjectTypeTest";
/// <summary>
/// The URI for the ua namespace (.NET code namespace is '').
/// </summary>
public const string ua = "http://opcfoundation.org/UA/";
}
#endregion
#region ComplexObjectState Class
#if (!OPCUA_EXCLUDE_ComplexObjectState)
/// <summary>
/// Stores an instance of the ComplexObjectType ObjectType.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public partial class ComplexObjectState : BaseObjectState
{
#region Constructors
/// <summary>
/// Initializes the type with its default attribute values.
/// </summary>
public ComplexObjectState(NodeState parent) : base(parent)
{
}
/// <summary>
/// Returns the id of the default type definition node for the instance.
/// </summary>
protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
{
return Opc.Ua.NodeId.Create(ObjectTypeTest.ObjectTypes.ComplexObjectType, ObjectTypeTest.Namespaces.cas, namespaceUris);
}
#if (!OPCUA_EXCLUDE_InitializationStrings)
/// <summary>
/// Initializes the instance.
/// </summary>
protected override void Initialize(ISystemContext context)
{
Initialize(context, InitializationString);
InitializeOptionalChildren(context);
}
protected override void Initialize(ISystemContext context, NodeState source)
{
InitializeOptionalChildren(context);
base.Initialize(context, source);
}
/// <summary>
/// Initializes the any option children defined for the instance.
/// </summary>
protected override void InitializeOptionalChildren(ISystemContext context)
{
base.InitializeOptionalChildren(context);
}
#region Initialization String
private const string InitializationString =
"AQAAADQAAABodHRwOi8vY2FzLmV1L1VBL0NvbW1TZXJ2ZXIvVW5pdFRlc3RzL09iamVjdFR5cGVUZXN0" +
"/////wRggAABAAAAAQAZAAAAQ29tcGxleE9iamVjdFR5cGVJbnN0YW5jZQEBAQABAQEA/////wMAAAAV" +
"YMkKAgAAABEAAABCcm93c2VOYW1lNG5vZGU2NgEADQAAAENoaWxkUHJvcGVydHkBAQMAAC4ARAMAAAAA" +
"Ff////8BAf////8AAAAAFWCJCgIAAAABAA0AAABDaGlsZFZhcmlhYmxlAQErAAAvAQBACSsAAAAAGv//" +
"//8BAf////8BAAAAFWCJCgIAAAAAAAcAAABFVVJhbmdlAQEvAAAuAEQvAAAAAQB0A/////8BAf////8A" +
"AAAABGGCCgQAAAABAAsAAABDaGlsZE1ldGhvZAEBCgAALwEBCgAKAAAAAQH/////AAAAAA==";
#endregion
#endif
#endregion
#region Public Properties
/// <summary>
/// A description for the ChildProperty Property.
/// </summary>
public PropertyState<LocalizedText> BrowseName4node66
{
get
{
return m_browseName4node66;
}
set
{
if (!Object.ReferenceEquals(m_browseName4node66, value))
{
ChangeMasks |= NodeStateChangeMasks.Children;
}
m_browseName4node66 = value;
}
}
/// <summary>
/// A description for the ChildVariable Variable.
/// </summary>
public AnalogItemState ChildVariable
{
get
{
return m_childVariable;
}
set
{
if (!Object.ReferenceEquals(m_childVariable, value))
{
ChangeMasks |= NodeStateChangeMasks.Children;
}
m_childVariable = value;
}
}
/// <summary>
/// A description for the ChildMethod Method.
/// </summary>
public ChildMethodMethodState ChildMethod
{
get
{
return m_childMethodMethod;
}
set
{
if (!Object.ReferenceEquals(m_childMethodMethod, value))
{
ChangeMasks |= NodeStateChangeMasks.Children;
}
m_childMethodMethod = value;
}
}
#endregion
#region Overridden Methods
/// <summary>
/// Populates a list with the children that belong to the node.
/// </summary>
/// <param name="context">The context for the system being accessed.</param>
/// <param name="children">The list of children to populate.</param>
public override void GetChildren(
ISystemContext context,
IList<BaseInstanceState> children)
{
if (m_browseName4node66 != null)
{
children.Add(m_browseName4node66);
}
if (m_childVariable != null)
{
children.Add(m_childVariable);
}
if (m_childMethodMethod != null)
{
children.Add(m_childMethodMethod);
}
base.GetChildren(context, children);
}
/// <summary>
/// Finds the child with the specified browse name.
/// </summary>
protected override BaseInstanceState FindChild(
ISystemContext context,
QualifiedName browseName,
bool createOrReplace,
BaseInstanceState replacement)
{
if (QualifiedName.IsNull(browseName))
{
return null;
}
BaseInstanceState instance = null;
switch (browseName.Name)
{
case ObjectTypeTest.BrowseNames.BrowseName4node66:
{
if (createOrReplace)
{
if (BrowseName4node66 == null)
{
if (replacement == null)
{
BrowseName4node66 = new PropertyState<LocalizedText>(this);
}
else
{
BrowseName4node66 = (PropertyState<LocalizedText>)replacement;
}
}
}
instance = BrowseName4node66;
break;
}
case ObjectTypeTest.BrowseNames.ChildVariable:
{
if (createOrReplace)
{
if (ChildVariable == null)
{
if (replacement == null)
{
ChildVariable = new AnalogItemState(this);
}
else
{
ChildVariable = (AnalogItemState)replacement;
}
}
}
instance = ChildVariable;
break;
}
case ObjectTypeTest.BrowseNames.ChildMethod:
{
if (createOrReplace)
{
if (ChildMethod == null)
{
if (replacement == null)
{
ChildMethod = new ChildMethodMethodState(this);
}
else
{
ChildMethod = (ChildMethodMethodState)replacement;
}
}
}
instance = ChildMethod;
break;
}
}
if (instance != null)
{
return instance;
}
return base.FindChild(context, browseName, createOrReplace, replacement);
}
#endregion
#region Private Fields
private PropertyState<LocalizedText> m_browseName4node66;
private AnalogItemState m_childVariable;
private ChildMethodMethodState m_childMethodMethod;
#endregion
}
#endif
#endregion
#region DerivedFromComplexObjectState Class
#if (!OPCUA_EXCLUDE_DerivedFromComplexObjectState)
/// <summary>
/// Stores an instance of the DerivedFromComplexObjectType ObjectType.
/// </summary>
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
public partial class DerivedFromComplexObjectState : ComplexObjectState
{
#region Constructors
/// <summary>
/// Initializes the type with its default attribute values.
/// </summary>
public DerivedFromComplexObjectState(NodeState parent) : base(parent)
{
}
/// <summary>
/// Returns the id of the default type definition node for the instance.
/// </summary>
protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
{
return Opc.Ua.NodeId.Create(ObjectTypeTest.ObjectTypes.DerivedFromComplexObjectType, ObjectTypeTest.Namespaces.cas, namespaceUris);
}
#if (!OPCUA_EXCLUDE_InitializationStrings)
/// <summary>
/// Initializes the instance.
/// </summary>
protected override void Initialize(ISystemContext context)
{
Initialize(context, InitializationString);
InitializeOptionalChildren(context);
}
protected override void Initialize(ISystemContext context, NodeState source)
{
InitializeOptionalChildren(context);
base.Initialize(context, source);
}
/// <summary>
/// Initializes the any option children defined for the instance.
/// </summary>
protected override void InitializeOptionalChildren(ISystemContext context)
{
base.InitializeOptionalChildren(context);
}
#region Initialization String
private const string InitializationString =
"AQAAADQAAABodHRwOi8vY2FzLmV1L1VBL0NvbW1TZXJ2ZXIvVW5pdFRlc3RzL09iamVjdFR5cGVUZXN0" +
"/////wRggAABAAAAAQAkAAAARGVyaXZlZEZyb21Db21wbGV4T2JqZWN0VHlwZUluc3RhbmNlAQEQAAEB" +
"EAD/////AwAAABVgyQoCAAAAEQAAAEJyb3dzZU5hbWU0bm9kZTY2AQANAAAAQ2hpbGRQcm9wZXJ0eQEB" +
"EgAALgBEEgAAAAAV/////wEB/////wAAAAAVYIkKAgAAAAEADQAAAENoaWxkVmFyaWFibGUBATEAAC8B" +
"AEAJMQAAAAAa/////wEB/////wEAAAAVYIkKAgAAAAAABwAAAEVVUmFuZ2UBATUAAC4ARDUAAAABAHQD" +
"/////wEB/////wAAAABEYYIKBAAAAAEACwAAAENoaWxkTWV0aG9kAQEZAAMAAAAAEgAAAENoaWxkTWV0" +
"aG9kTmV3TmFtZQAvAQEKABkAAAABAf////8AAAAA";
#endregion
#endif
#endregion
#region Public Properties
#endregion
#region Overridden Methods
#endregion
#region Private Fields
#endregion
}
#endif
#endregion
}
| |
//
// MonoTests.System.Security.Policy.EvidenceTest
//
// Authors:
// Jackson Harper ([email protected])
// Sebastien Pouliot <[email protected]>
//
// (C) 2001 Jackson Harper, All rights reserved.
// Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
// 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;
using System.Collections;
using System.Security.Policy;
using NUnit.Framework;
namespace MonoTests.System.Security.Policy {
[TestFixture]
public class EvidenceTest : Assertion {
[Test]
public void DefaultConstructor ()
{
Evidence evidence = new Evidence ();
AssertEquals ("Default constructor count should be zero", evidence.Count, 0);
AssertEquals ("Default constructor host enumerator MoveNext() should be false",
evidence.GetHostEnumerator().MoveNext(), false);
AssertEquals ("Default constructor assembly enumerator MoveNext() should be false",
evidence.GetAssemblyEnumerator().MoveNext(), false);
AssertEquals ("Default constructor enumerator MoveNext() should be false",
evidence.GetEnumerator().MoveNext(), false);
}
[Test]
public void MultipleConstructor ()
{
object[] hostarray = new object[10];
object[] assemarray = new object[10];
Evidence evidence = new Evidence ( hostarray, assemarray );
AssertEquals ( "Count of multiple arg constructor should equal 20", evidence.Count, 20 );
}
[Test]
public void CopyConstructor ()
{
object[] hostlist = { "host-1", "host-2", "host-3", "host-4" };
object[] asmblist = { "asmb-1", "asmb-2", "asmb-3", "asmb-4" };
Evidence evidence1 = new Evidence (hostlist, asmblist);
Evidence evidence2 = new Evidence (evidence1);
AssertEquals("Copy constructor counts do not match", evidence1.Count, evidence2.Count);
}
[Test]
public void Constructor_Null ()
{
Evidence e = new Evidence (null);
AssertEquals ("Count-Empty", 0, e.Count);
}
[Test]
public void Constructor_NullNull ()
{
Evidence e = new Evidence (null, null);
AssertEquals ("Count-Empty", 0, e.Count);
}
[Test]
public void AddAssembly ()
{
Evidence evidence = new Evidence ();
object[] comparray = new object[100];
string obj;
for (int i=0; i<100; i++) {
obj = String.Format ("asmb-{0}", i+1);
comparray[i] = obj;
evidence.AddAssembly (obj);
AssertEquals (evidence.Count, i+1);
}
int index = 0;
foreach (object compobj in evidence) {
AssertEquals ("Comparison object does not equal evidence assembly object",
comparray[index++], compobj);
}
}
[Test]
public void AddHost ()
{
Evidence evidence = new Evidence ();
object[] comparray = new object[100];
string obj;
for (int i=0; i<100; i++) {
obj = String.Format ("asmb-{0}", i+1);
comparray[i] = obj;
evidence.AddAssembly ( obj );
AssertEquals (evidence.Count, i+1);
}
int index = 0;
foreach (object compobj in evidence) {
AssertEquals ("Comparison object does not equal evidence host object",
comparray[index++], compobj);
}
}
[Test]
public void MultiArgConstructorForEach ()
{
object[] hostarray = { "host-1", "host-2", "host-3", "host-4" };
object[] asmbarray = { "asmb-1", "asmb-2", "asmb-3", "asmb-4" };
ArrayList compare = new ArrayList ();
Evidence evidence = new Evidence (hostarray, asmbarray);
compare.AddRange (hostarray);
compare.AddRange (asmbarray);
int i = 0;
foreach (object obj in evidence) {
AssertEquals (obj, compare[i++]);
}
}
[Test]
public void EnumeratorReset ()
{
object[] hostarray = { "host-1", "host-2", "host-3", "host-4" };
object[] asmbarray = { "asmb-1", "asmb-2", "asmb-3", "asmb-4" };
ArrayList compare = new ArrayList ();
Evidence evidence = new Evidence (hostarray, asmbarray);
compare.AddRange (hostarray);
compare.AddRange (asmbarray);
int i = 0;
IEnumerator enumerator = evidence.GetEnumerator ();
while (enumerator.MoveNext ()) {
AssertEquals (enumerator.Current, compare[i++]);
}
enumerator.Reset ();
i = 0;
while (enumerator.MoveNext ()) {
AssertEquals (enumerator.Current, compare[i++]);
}
}
[Test]
public void GetHostEnumerator ()
{
object[] hostarray = { "host-1", "host-2", "host-3", "host-4" };
object[] asmbarray = { "asmb-1", "asmb-2" };
Evidence evidence = new Evidence (hostarray, asmbarray);
IEnumerator enumerator = evidence.GetHostEnumerator ();
int i = 0;
while (enumerator.MoveNext ()) {
AssertEquals (enumerator.Current, hostarray[i++]);
}
}
[Test]
public void GetHostAssemblyEnumerator ()
{
object[] hostarray = { "host-1", "host-2", "host-3", "host-4" };
object[] asmbarray = { "asmb-1", "asmb-2", "asmb-3", "asmb-4" };
Evidence evidence;
IEnumerator enumerator;
int i;
evidence = new Evidence (hostarray, asmbarray);
enumerator = evidence.GetAssemblyEnumerator ();
i = 0;
while (enumerator.MoveNext()) {
AssertEquals (enumerator.Current, asmbarray[i++]);
}
}
[Test]
public void Count ()
{
object[] hostarray = { "host-1", "host-2", "host-3", "host-4" };
object[] asmbarray = { "asmb-1", "asmb-2", "asmb-3", "asmb-4" };
Evidence evidence = new Evidence (hostarray, asmbarray);
Assertion.AssertEquals (evidence.Count, 8);
for( int i=0; i<100; i++ ) {
if ( 0 == i%2 ) {
evidence.AddHost (String.Format ("host-{0}", i + 5) );
} else {
evidence.AddAssembly (String.Format ("asmb-{0}", i + 5));
}
AssertEquals (evidence.Count, 9 + i);
}
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void NullCopyToException()
{
Evidence evidence = new Evidence ();
evidence.AddHost ("host-1");
evidence.CopyTo (null, 100);
}
/// <summary>
/// No Exception will be generated because the copy won't run because the evidence list is empty
/// </summary>
[Test]
public void CopyToNoException()
{
Evidence evidence = new Evidence ();
evidence.CopyTo (null, 100);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ArgOutOfRangeCopyToException()
{
Evidence evidence = new Evidence (new object[10], new object[10]);
evidence.CopyTo (new object[10], -100);
}
/// <summary>
/// No Exception will be generated because the copy won't run because the evidence list is empty
/// </summary>
[Test]
public void ArgOutOfRangeCopyToNoException()
{
Evidence evidence = new Evidence ();
evidence.CopyTo (new object[10], -100);
}
[Test]
public void BadMerge ()
{
Evidence evidence = new Evidence (null, null);
Evidence evidence2 = new Evidence ();
evidence2.Merge (evidence);
AssertEquals ("Count", evidence.Count, evidence2.Count);
}
[Test]
public void Merge ()
{
Evidence evidence = new Evidence (new object[10], new object[10]);
Evidence evidence2 = new Evidence ();
evidence2.Merge (evidence);
AssertEquals ("Count", evidence.Count, evidence2.Count);
}
[Test]
public void Merge_Null ()
{
Evidence evidence = new Evidence ();
evidence.Merge (null);
// no exception!
AssertEquals ("Count", 0, evidence.Count);
}
[Test]
public void DefaultProperties ()
{
Evidence e = new Evidence ();
AssertEquals ("Count", 0, e.Count);
Assert ("IsReadOnly", !e.IsReadOnly);
#if NET_2_0
Assert ("IsSynchronized", !e.IsSynchronized);
#else
// LAMESPEC: Always TRUE (not FALSE)
Assert ("IsSynchronized", e.IsSynchronized);
#endif
Assert ("Locked", !e.Locked);
AssertNotNull ("SyncRoot", e.SyncRoot);
}
#if NET_2_0
[Test]
public void Equals_GetHashCode ()
{
Evidence e1 = new Evidence ();
Evidence e2 = new Evidence ();
AssertEquals ("GetHashCode-1", e1.GetHashCode (), e2.GetHashCode ());
Assert ("e1.Equals(e2)", e1.Equals (e2));
e1.AddAssembly (String.Empty);
e2.AddAssembly (String.Empty);
AssertEquals ("GetHashCode-2", e1.GetHashCode (), e2.GetHashCode ());
e1.AddHost (String.Empty);
e2.AddHost (String.Empty);
AssertEquals ("GetHashCode-3", e1.GetHashCode (), e2.GetHashCode ());
Assert ("e2.Equals(e1)", e2.Equals (e1));
}
[Test]
public void Clear ()
{
Evidence e = new Evidence ();
AssertEquals ("Count-Empty", 0, e.Count);
e.AddAssembly (new object ());
AssertEquals ("Count+Assembly", 1, e.Count);
e.AddHost (new object ());
AssertEquals ("Count+Host", 2, e.Count);
e.Clear ();
AssertEquals ("Count-Cleared", 0, e.Count);
}
[Category ("NotWorking")]
[Test]
public void RemoveType ()
{
Evidence e = new Evidence ();
AssertEquals ("Count-Empty", 0, e.Count);
e.AddAssembly (new object ());
e.AddHost (new object ());
AssertEquals ("Count", 2, e.Count);
e.RemoveType (typeof (object));
AssertEquals ("Count-RemoveType(object)", 0, e.Count);
}
#else
[Test]
public void Equals_GetHashCode ()
{
Evidence e1 = new Evidence ();
Evidence e2 = new Evidence ();
Assert ("GetHashCode", e1.GetHashCode () != e2.GetHashCode ());
Assert ("!e1.Equals(e2)", !e1.Equals (e2));
Assert ("!e2.Equals(e1)", !e2.Equals (e1));
}
#endif
}
}
| |
//
// 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.IO;
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.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Product Policy.
/// </summary>
internal partial class ProductPolicyOperations : IServiceOperations<ApiManagementClient>, IProductPolicyOperations
{
/// <summary>
/// Initializes a new instance of the ProductPolicyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProductPolicyOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Deletes specific product policy of the Api Management service
/// instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string pid, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", 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(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
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.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// 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.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
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>
/// Gets specific product policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='format'>
/// Required. Format of the policy. Supported formats:
/// application/vnd.ms-azure-apim.policy+xml
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get policy output operation.
/// </returns>
public async Task<PolicyGetResponse> GetAsync(string resourceGroupName, string serviceName, string pid, string format, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("format", format);
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(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
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", format);
// 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
PolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new PolicyGetResponse();
result.PolicyBytes = Encoding.UTF8.GetBytes(responseContent);
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").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>
/// Sets policy for product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='format'>
/// Required. Format of the policy. Supported formats:
/// application/vnd.ms-azure-apim.policy+xml
/// </param>
/// <param name='policyStream'>
/// Required. Policy stream.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> SetAsync(string resourceGroupName, string serviceName, string pid, string format, Stream policyStream, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
if (policyStream == null)
{
throw new ArgumentNullException("policyStream");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("format", format);
tracingParameters.Add("policyStream", policyStream);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "SetAsync", 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(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/policy";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
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.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
Stream requestContent = policyStream;
httpRequest.Content = new StreamContent(requestContent);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(format);
// 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.Created && statusCode != HttpStatusCode.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
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();
}
}
}
}
}
| |
using System;
using System.IO;
using NUnit.Framework;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.OpenSsl.Tests
{
/**
* basic class for reading test.pem - the password is "secret"
*/
[TestFixture]
public class ReaderTest
: SimpleTest
{
private class Password
: IPasswordFinder
{
private readonly char[] password;
public Password(
char[] word)
{
this.password = (char[]) word.Clone();
}
public char[] GetPassword()
{
return (char[]) password.Clone();
}
}
public override string Name
{
get { return "PEMReaderTest"; }
}
public override void PerformTest()
{
IPasswordFinder pGet = new Password("secret".ToCharArray());
PemReader pemRd = OpenPemResource("test.pem", pGet);
IAsymmetricCipherKeyPair pair;
object o;
while ((o = pemRd.ReadObject()) != null)
{
// if (o is AsymmetricCipherKeyPair)
// {
// ackp = (AsymmetricCipherKeyPair)o;
//
// Console.WriteLine(ackp.Public);
// Console.WriteLine(ackp.Private);
// }
// else
// {
// Console.WriteLine(o.ToString());
// }
}
//
// pkcs 7 data
//
pemRd = OpenPemResource("pkcs7.pem", null);
ContentInfo d = (ContentInfo)pemRd.ReadObject();
if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
{
Fail("failed envelopedData check");
}
/*
{
//
// ECKey
//
pemRd = OpenPemResource("eckey.pem", null);
// TODO Resolve return type issue with EC keys and fix PemReader to return parameters
// ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject();
pair = (AsymmetricCipherKeyPair)pemRd.ReadObject();
ISigner sgr = SignerUtilities.GetSigner("ECDSA");
sgr.Init(true, pair.Private);
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.BlockUpdate(message, 0, message.Length);
byte[] sigBytes = sgr.GenerateSignature();
sgr.Init(false, pair.Public);
sgr.BlockUpdate(message, 0, message.Length);
if (!sgr.VerifySignature(sigBytes))
{
Fail("EC verification failed");
}
// TODO Resolve this issue with the algorithm name, study Java version
// if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA"))
// {
// Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName);
// }
//
// if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA"))
// {
// Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName);
// }
}
*/
//
// writer/parser test
//
IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
kpGen.Init(
new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x10001),
new SecureRandom(),
768,
25));
pair = kpGen.GenerateKeyPair();
keyPairTest("RSA", pair);
// kpGen = KeyPairGenerator.getInstance("DSA");
// kpGen.initialize(512, new SecureRandom());
DsaParametersGenerator pGen = new DsaParametersGenerator();
pGen.Init(512, 80, new SecureRandom());
kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA");
kpGen.Init(
new DsaKeyGenerationParameters(
new SecureRandom(),
pGen.GenerateParameters()));
pair = kpGen.GenerateKeyPair();
keyPairTest("DSA", pair);
//
// PKCS7
//
MemoryStream bOut = new MemoryStream();
PemWriter pWrt = new PemWriter(new StreamWriter(bOut));
pWrt.WriteObject(d);
pWrt.Writer.Close();
pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
d = (ContentInfo)pemRd.ReadObject();
if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
{
Fail("failed envelopedData recode check");
}
// OpenSSL test cases (as embedded resources)
doOpenSslDsaTest("unencrypted");
doOpenSslRsaTest("unencrypted");
doOpenSslTests("aes128");
doOpenSslTests("aes192");
doOpenSslTests("aes256");
doOpenSslTests("blowfish");
doOpenSslTests("des1");
doOpenSslTests("des2");
doOpenSslTests("des3");
doOpenSslTests("rc2_128");
doOpenSslDsaTest("rc2_40_cbc");
doOpenSslRsaTest("rc2_40_cbc");
doOpenSslDsaTest("rc2_64_cbc");
doOpenSslRsaTest("rc2_64_cbc");
// TODO Figure out why exceptions differ for commented out cases
doDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found");
doDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found");
// doDudPasswordTest("800ce", 2, "cannot recognise object in stream");
doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56");
doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28");
doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11");
doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35");
doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9");
doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14");
doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65");
doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57");
doDudPasswordTest("41af75", 11, "malformed sequence in DSA private key");
doDudPasswordTest("1704a5", 12, "corrupted stream detected");
// doDudPasswordTest("1c5822", 13, "corrupted stream detected");
// doDudPasswordTest("5a3d16", 14, "corrupted stream detected");
doDudPasswordTest("8d0c97", 15, "corrupted stream detected");
doDudPasswordTest("bc0daf", 16, "corrupted stream detected");
doDudPasswordTest("aaf9c4d",17, "Corrupted stream - out of bounds length found");
// encrypted private key test
pGet = new Password("password".ToCharArray());
pemRd = OpenPemResource("enckey.pem", pGet);
RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject();
if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
{
Fail("decryption of private key data check failed");
}
// general PKCS8 test
pGet = new Password("password".ToCharArray());
pemRd = OpenPemResource("pkcs8test.pem", pGet);
while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null)
{
if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
{
Fail("decryption of private key data check failed");
}
}
}
private void keyPairTest(
string name,
IAsymmetricCipherKeyPair pair)
{
MemoryStream bOut = new MemoryStream();
PemWriter pWrt = new PemWriter(new StreamWriter(bOut));
pWrt.WriteObject(pair.Public);
pWrt.Writer.Close();
PemReader pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
IAsymmetricKeyParameter pubK = (AsymmetricKeyParameter) pemRd.ReadObject();
if (!pubK.Equals(pair.Public))
{
Fail("Failed public key read: " + name);
}
bOut = new MemoryStream();
pWrt = new PemWriter(new StreamWriter(bOut));
pWrt.WriteObject(pair.Private);
pWrt.Writer.Close();
pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
IAsymmetricCipherKeyPair kPair = (AsymmetricCipherKeyPair) pemRd.ReadObject();
if (!kPair.Private.Equals(pair.Private))
{
Fail("Failed private key read: " + name);
}
if (!kPair.Public.Equals(pair.Public))
{
Fail("Failed private key public read: " + name);
}
}
private void doOpenSslTests(
string baseName)
{
doOpenSslDsaModesTest(baseName);
doOpenSslRsaModesTest(baseName);
}
private void doOpenSslDsaModesTest(
string baseName)
{
doOpenSslDsaTest(baseName + "_cbc");
doOpenSslDsaTest(baseName + "_cfb");
doOpenSslDsaTest(baseName + "_ecb");
doOpenSslDsaTest(baseName + "_ofb");
}
private void doOpenSslRsaModesTest(
string baseName)
{
doOpenSslRsaTest(baseName + "_cbc");
doOpenSslRsaTest(baseName + "_cfb");
doOpenSslRsaTest(baseName + "_ecb");
doOpenSslRsaTest(baseName + "_ofb");
}
private void doOpenSslDsaTest(
string name)
{
string fileName = "dsa.openssl_dsa_" + name + ".pem";
doOpenSslTestFile(fileName, typeof(DsaPrivateKeyParameters));
}
private void doOpenSslRsaTest(
string name)
{
string fileName = "rsa.openssl_rsa_" + name + ".pem";
doOpenSslTestFile(fileName, typeof(RsaPrivateCrtKeyParameters));
}
private void doOpenSslTestFile(
string fileName,
Type expectedPrivKeyType)
{
PemReader pr = OpenPemResource(fileName, new Password("changeit".ToCharArray()));
IAsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;
pr.Reader.Close();
if (kp == null)
{
Fail("Didn't find OpenSSL key");
}
if (!expectedPrivKeyType.IsInstanceOfType(kp.Private))
{
Fail("Returned key not of correct type");
}
}
private void doDudPasswordTest(string password, int index, string message)
{
// illegal state exception check - in this case the wrong password will
// cause an underlying class cast exception.
try
{
IPasswordFinder pGet = new Password(password.ToCharArray());
PemReader pemRd = OpenPemResource("test.pem", pGet);
Object o;
while ((o = pemRd.ReadObject()) != null)
{
}
Fail("issue not detected: " + index);
}
catch (IOException e)
{
if (e.Message.IndexOf(message) < 0)
{
Console.Error.WriteLine(message);
Console.Error.WriteLine(e.Message);
Fail("issue " + index + " exception thrown, but wrong message");
}
}
}
private static PemReader OpenPemResource(
string fileName,
IPasswordFinder pGet)
{
Stream data = GetTestDataAsStream("openssl." + fileName);
TextReader tr = new StreamReader(data);
return new PemReader(tr, pGet);
}
public static void Main(
string[] args)
{
RunTest(new ReaderTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Schema;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using System.Runtime.Serialization;
using System.Text;
#if !(NET20 || NET35)
using System.Threading.Tasks;
#endif
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class JsonConvertTest : TestFixtureBase
{
[Test]
public void ToStringEnsureEscapedArrayLength()
{
const char nonAsciiChar = (char)257;
const char escapableNonQuoteAsciiChar = '\0';
string value = nonAsciiChar + @"\" + escapableNonQuoteAsciiChar;
string convertedValue = JsonConvert.ToString((object)value);
Assert.AreEqual(@"""" + nonAsciiChar + @"\\\u0000""", convertedValue);
}
public class PopulateTestObject
{
public decimal Prop { get; set; }
}
[Test]
public void PopulateObjectWithHeaderComment()
{
string json = @"// file header
{
""prop"": 1.0
}";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
Assert.AreEqual(1m, o.Prop);
}
[Test]
public void PopulateObjectWithMultipleHeaderComment()
{
string json = @"// file header
// another file header?
{
""prop"": 1.0
}";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
Assert.AreEqual(1m, o.Prop);
}
[Test]
public void PopulateObjectWithNoContent()
{
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
string json = @"";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
}, "No JSON content found. Path '', line 0, position 0.");
}
[Test]
public void PopulateObjectWithOnlyComment()
{
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
string json = @"// file header";
PopulateTestObject o = new PopulateTestObject();
JsonConvert.PopulateObject(json, o);
}, "No JSON content found. Path '', line 1, position 14.");
}
[Test]
public void DefaultSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } });
StringAssert.AreEqual(@"{
""test"": [
1,
2,
3
]
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
public class NameTableTestClass
{
public string Value { get; set; }
}
public class NameTableTestClassConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
reader.Read();
reader.Read();
JsonTextReader jsonTextReader = (JsonTextReader)reader;
Assert.IsNotNull(jsonTextReader.NameTable);
string s = serializer.Deserialize<string>(reader);
Assert.AreEqual("hi", s);
Assert.IsNotNull(jsonTextReader.NameTable);
NameTableTestClass o = new NameTableTestClass
{
Value = s
};
return o;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(NameTableTestClass);
}
}
[Test]
public void NameTableTest()
{
StringReader sr = new StringReader("{'property':'hi'}");
JsonTextReader jsonTextReader = new JsonTextReader(sr);
Assert.IsNull(jsonTextReader.NameTable);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new NameTableTestClassConverter());
NameTableTestClass o = serializer.Deserialize<NameTableTestClass>(jsonTextReader);
Assert.IsNull(jsonTextReader.NameTable);
Assert.AreEqual("hi", o.Value);
}
[Test]
public void DefaultSettings_Example()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Employee e = new Employee
{
FirstName = "Eric",
LastName = "Example",
BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
Department = "IT",
JobTitle = "Web Dude"
};
string json = JsonConvert.SerializeObject(e);
// {
// "firstName": "Eric",
// "lastName": "Example",
// "birthDate": "1980-04-20T00:00:00Z",
// "department": "IT",
// "jobTitle": "Web Dude"
// }
StringAssert.AreEqual(@"{
""firstName"": ""Eric"",
""lastName"": ""Example"",
""birthDate"": ""1980-04-20T00:00:00Z"",
""department"": ""IT"",
""jobTitle"": ""Web Dude""
}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }, new JsonSerializerSettings
{
Formatting = Formatting.None
});
Assert.AreEqual(@"{""test"":[1,2,3]}", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Override_JsonConverterOrder()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy" } }
};
string json = JsonConvert.SerializeObject(new[] { new DateTime(2000, 12, 12, 4, 2, 4, DateTimeKind.Utc) }, new JsonSerializerSettings
{
Formatting = Formatting.None,
Converters =
{
// should take precedence
new JavaScriptDateTimeConverter(),
new IsoDateTimeConverter { DateTimeFormat = "dd" }
}
});
Assert.AreEqual(@"[new Date(976593724000)]", json);
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_Create()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault();
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer.Formatting = Formatting.None;
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = new JsonSerializer();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create();
serializer.Serialize(sw, l);
Assert.AreEqual(@"[1,2,3]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
[Test]
public void DefaultSettings_CreateWithSettings()
{
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
IList<int> l = new List<int> { 1, 2, 3 };
StringWriter sw = new StringWriter();
JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
{
Converters = { new IntConverter() }
});
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
2,
4,
6
]", sw.ToString());
sw = new StringWriter();
serializer.Converters.Clear();
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
sw = new StringWriter();
serializer = JsonSerializer.Create(new JsonSerializerSettings { Formatting = Formatting.Indented });
serializer.Serialize(sw, l);
StringAssert.AreEqual(@"[
1,
2,
3
]", sw.ToString());
}
finally
{
JsonConvert.DefaultSettings = null;
}
}
public class IntConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
int i = (int)value;
writer.WriteValue(i * 2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int);
}
}
[Test]
public void DeserializeObject_EmptyString()
{
object result = JsonConvert.DeserializeObject(string.Empty);
Assert.IsNull(result);
}
[Test]
public void DeserializeObject_Integer()
{
object result = JsonConvert.DeserializeObject("1");
Assert.AreEqual(1L, result);
}
[Test]
public void DeserializeObject_Integer_EmptyString()
{
int? value = JsonConvert.DeserializeObject<int?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_Decimal_EmptyString()
{
decimal? value = JsonConvert.DeserializeObject<decimal?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_DateTime_EmptyString()
{
DateTime? value = JsonConvert.DeserializeObject<DateTime?>("");
Assert.IsNull(value);
}
[Test]
public void EscapeJavaScriptString()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How now brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How now 'brown' cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How now <brown> cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How \r\nnow brown cow?", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""How \r\nnow brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result);
string data =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
string expected =
@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true, StringEscapeHandling.Default);
Assert.AreEqual(expected, result);
result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"'Fred\'s cat.'");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"'Fred\'s ""cat"".'");
result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(result, @"""\u001farray<address""");
}
[Test]
public void EscapeJavaScriptString_UnicodeLinefeeds()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""before\u0085after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""before\u2028after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true, StringEscapeHandling.Default);
Assert.AreEqual(@"""before\u2029after""", result);
}
[Test]
public void ToStringInvalid()
{
ExceptionAssert.Throws<ArgumentException>(() => { JsonConvert.ToString(new Version(1, 0)); }, "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.");
}
[Test]
public void GuidToString()
{
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
string json = JsonConvert.ToString(guid);
Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json);
}
[Test]
public void EnumToString()
{
string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase);
Assert.AreEqual("1", json);
}
[Test]
public void ObjectToString()
{
object value;
value = 1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = 1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = 1.1m;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (float)1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (short)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (long)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (byte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (uint)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ushort)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (sbyte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ulong)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value));
value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind));
#if !NET20
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value));
value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat));
#endif
value = null;
Assert.AreEqual("null", JsonConvert.ToString(value));
#if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40)
value = DBNull.Value;
Assert.AreEqual("null", JsonConvert.ToString(value));
#endif
value = "I am a string";
Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value));
value = true;
Assert.AreEqual("true", JsonConvert.ToString(value));
value = 'c';
Assert.AreEqual(@"""c""", JsonConvert.ToString(value));
}
[Test]
public void TestInvalidStrings()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string orig = @"this is a string ""that has quotes"" ";
string serialized = JsonConvert.SerializeObject(orig);
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
JsonConvert.DeserializeObject<string>(serialized);
}, "Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.");
}
[Test]
public void DeserializeValueObjects()
{
int i = JsonConvert.DeserializeObject<int>("1");
Assert.AreEqual(1, i);
#if !NET20
DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/""");
Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d);
#endif
bool b = JsonConvert.DeserializeObject<bool>("true");
Assert.AreEqual(true, b);
object n = JsonConvert.DeserializeObject<object>("null");
Assert.AreEqual(null, n);
object u = JsonConvert.DeserializeObject<object>("undefined");
Assert.AreEqual(null, u);
}
[Test]
public void FloatToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
Assert.AreEqual("1.0", JsonConvert.ToString(1d));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1d));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity));
Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity));
Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN));
}
[Test]
public void DecimalToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1m));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11m));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111m));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1m));
Assert.AreEqual("1.0", JsonConvert.ToString(1m));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01m));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001m));
Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue));
Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue));
}
[Test]
public void StringEscaping()
{
string v = "It's a good day\r\n\"sunshine\"";
string json = JsonConvert.ToString(v);
Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json);
}
[Test]
public void ToStringStringEscapeHandling()
{
string v = "<b>hi " + '\u20AC' + "</b>";
string json = JsonConvert.ToString(v, '"');
Assert.AreEqual(@"""<b>hi " + '\u20AC' + @"</b>""", json);
json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeHtml);
Assert.AreEqual(@"""\u003cb\u003ehi " + '\u20AC' + @"\u003c/b\u003e""", json);
json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeNonAscii);
Assert.AreEqual(@"""<b>hi \u20ac</b>""", json);
}
[Test]
public void WriteDateTime()
{
DateTimeResult result = null;
result = TestDateTime("DateTime Max", DateTime.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip);
Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified);
Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc);
DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local);
string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local", year2000local);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc);
DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local);
localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc);
DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local);
localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with ticks", ticksLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc);
DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);
result = TestDateTime("DateTime Unspecified", year2000Unspecified);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc);
DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Utc", year2000Utc);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc);
DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc);
utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Unix Epoc", unixEpoc);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc);
result = TestDateTime("DateTime Min", DateTime.MinValue);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
result = TestDateTime("DateTime Default", default(DateTime));
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
#if !NET20
result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1)));
Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5)));
Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)));
Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero));
Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue);
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset));
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
#endif
}
public class DateTimeResult
{
public string IsoDateRoundtrip { get; set; }
public string IsoDateLocal { get; set; }
public string IsoDateUnspecified { get; set; }
public string IsoDateUtc { get; set; }
public string MsDateRoundtrip { get; set; }
public string MsDateLocal { get; set; }
public string MsDateUnspecified { get; set; }
public string MsDateUtc { get; set; }
}
private DateTimeResult TestDateTime<T>(string name, T value)
{
Console.WriteLine(name);
DateTimeResult result = new DateTimeResult();
result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local);
result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified);
result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc);
}
result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local);
result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified);
result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc);
}
TestDateTimeFormat(value, new IsoDateTimeConverter());
#if !NETFX_CORE
if (value is DateTime)
{
Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind));
}
else
{
Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value));
}
#endif
#if !NET20
MemoryStream ms = new MemoryStream();
DataContractSerializer s = new DataContractSerializer(typeof(T));
s.WriteObject(ms, value);
string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
Console.WriteLine(json);
#endif
Console.WriteLine();
return result;
}
private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
string date = null;
if (value is DateTime)
{
date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling);
}
else
{
#if !NET20
date = JsonConvert.ToString((DateTimeOffset)(object)value, format);
#endif
}
Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date);
if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind)
{
T parsed = JsonConvert.DeserializeObject<T>(date);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception)
{
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
return date.Trim('"');
}
private static void TestDateTimeFormat<T>(T value, JsonConverter converter)
{
string date = Write(value, converter);
Console.WriteLine(converter.GetType().Name + ": " + date);
T parsed = Read<T>(date, converter);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception)
{
// JavaScript ticks aren't as precise, recheck after rounding
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
public static long GetTicks(object value)
{
return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks;
}
public static string Write(object value, JsonConverter converter)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
converter.WriteJson(writer, value, null);
writer.Flush();
return sw.ToString();
}
public static T Read<T>(string text, JsonConverter converter)
{
JsonTextReader reader = new JsonTextReader(new StringReader(text));
reader.ReadAsString();
return (T)converter.ReadJson(reader, typeof(T), null, null);
}
#if !(NET20 || NET35 || PORTABLE40)
[Test]
public void Async()
{
Task<string> task = null;
#pragma warning disable 612,618
task = JsonConvert.SerializeObjectAsync(42);
#pragma warning restore 612,618
task.Wait();
Assert.AreEqual("42", task.Result);
#pragma warning disable 612,618
task = JsonConvert.SerializeObjectAsync(new[] { 1, 2, 3, 4, 5 }, Formatting.Indented);
#pragma warning restore 612,618
task.Wait();
StringAssert.AreEqual(@"[
1,
2,
3,
4,
5
]", task.Result);
#pragma warning disable 612,618
task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
#pragma warning restore 612,618
task.Wait();
Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result);
#pragma warning disable 612,618
var taskObject = JsonConvert.DeserializeObjectAsync("[]");
#pragma warning restore 612,618
taskObject.Wait();
CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result);
#pragma warning disable 612,618
Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings
{
Converters = { new VersionConverter() }
});
#pragma warning restore 612,618
taskVersionArray.Wait();
Version[] versionArray = (Version[])taskVersionArray.Result;
Assert.AreEqual(1, versionArray.Length);
Assert.AreEqual(2, versionArray[0].Major);
#pragma warning disable 612,618
Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5");
#pragma warning restore 612,618
taskInt.Wait();
Assert.AreEqual(5, taskInt.Result);
#pragma warning disable 612,618
var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings
{
Converters = { new VersionConverter() }
});
#pragma warning restore 612,618
taskVersion.Wait();
Assert.AreEqual(2, taskVersion.Result.Major);
Movie p = new Movie();
p.Name = "Existing,";
#pragma warning disable 612,618
Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new StringAppenderConverter() }
});
#pragma warning restore 612,618
taskVoid.Wait();
Assert.AreEqual("Existing,Appended", p.Name);
}
#endif
[Test]
public void SerializeObjectDateTimeZoneHandling()
{
string json = JsonConvert.SerializeObject(
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
}
[Test]
public void DeserializeObject()
{
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
Assert.AreEqual("Bad Boys", m.Name);
}
#if !NET20
[Test]
public void TestJsonDateTimeOffsetRoundtrip()
{
var now = DateTimeOffset.Now;
var dict = new Dictionary<string, object> { { "foo", now } };
var settings = new JsonSerializerSettings();
settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
settings.DateParseHandling = DateParseHandling.DateTimeOffset;
settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
var json = JsonConvert.SerializeObject(dict, settings);
var newDict = new Dictionary<string, object>();
JsonConvert.PopulateObject(json, newDict, settings);
var date = newDict["foo"];
Assert.AreEqual(date, now);
}
[Test]
public void MaximumDateTimeOffsetLength()
{
DateTimeOffset dt = new DateTimeOffset(2000, 12, 31, 20, 59, 59, new TimeSpan(0, 11, 33, 0, 0));
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
Assert.AreEqual(@"""2000-12-31T20:59:59.9999999+11:33""", sw.ToString());
}
#endif
[Test]
public void MaximumDateTimeLength()
{
DateTime dt = new DateTime(2000, 12, 31, 20, 59, 59, DateTimeKind.Local);
dt = dt.AddTicks(9999999);
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(dt);
writer.Flush();
}
[Test]
public void MaximumDateTimeMicrosoftDateFormatLength()
{
DateTime dt = DateTime.MaxValue;
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
writer.WriteValue(dt);
writer.Flush();
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
[Test]
public void IntegerLengthOverflows()
{
// Maximum javascript number length (in characters) is 380
JObject o = JObject.Parse(@"{""biginteger"":" + new String('9', 380) + "}");
JValue v = (JValue)o["biginteger"];
Assert.AreEqual(JTokenType.Integer, v.Type);
Assert.AreEqual(typeof(BigInteger), v.Value.GetType());
Assert.AreEqual(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value);
ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"), "JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395.");
}
#endif
[Test]
public void ParseIsoDate()
{
StringReader sr = new StringReader(@"""2014-02-14T14:25:02-13:00""");
JsonReader jsonReader = new JsonTextReader(sr);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(typeof(DateTime), jsonReader.ValueType);
}
//[Test]
public void StackOverflowTest()
{
StringBuilder sb = new StringBuilder();
int depth = 900;
for (int i = 0; i < depth; i++)
{
sb.Append("{'A':");
}
// invalid json
sb.Append("{***}");
for (int i = 0; i < depth; i++)
{
sb.Append("}");
}
string json = sb.ToString();
JsonSerializer serializer = new JsonSerializer() { };
serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json)));
}
public class Nest
{
public Nest A { get; set; }
}
[Test]
public void ParametersPassedToJsonConverterConstructor()
{
ClobberMyProperties clobber = new ClobberMyProperties { One = "Red", Two = "Green", Three = "Yellow", Four = "Black" };
string json = JsonConvert.SerializeObject(clobber);
Assert.AreEqual("{\"One\":\"Uno-1-Red\",\"Two\":\"Dos-2-Green\",\"Three\":\"Tres-1337-Yellow\",\"Four\":\"Black\"}", json);
}
public class ClobberMyProperties
{
[JsonConverter(typeof(ClobberingJsonConverter), "Uno", 1)]
public string One { get; set; }
[JsonConverter(typeof(ClobberingJsonConverter), "Dos", 2)]
public string Two { get; set; }
[JsonConverter(typeof(ClobberingJsonConverter), "Tres")]
public string Three { get; set; }
public string Four { get; set; }
}
public class ClobberingJsonConverter : JsonConverter
{
public string ClobberValueString { get; private set; }
public int ClobberValueInt { get; private set; }
public ClobberingJsonConverter(string clobberValueString, int clobberValueInt)
{
ClobberValueString = clobberValueString;
ClobberValueInt = clobberValueInt;
}
public ClobberingJsonConverter(string clobberValueString)
: this(clobberValueString, 1337)
{
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(ClobberValueString + "-" + ClobberValueInt.ToString() + "-" + value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
}
[Test]
public void WrongParametersPassedToJsonConvertConstructorShouldThrow()
{
IncorrectJsonConvertParameters value = new IncorrectJsonConvertParameters { One = "Boom" };
ExceptionAssert.Throws<JsonException>(() => { JsonConvert.SerializeObject(value); });
}
public class IncorrectJsonConvertParameters
{
/// <summary>
/// We deliberately use the wrong number/type of arguments for ClobberingJsonConverter to ensure an
/// exception is thrown.
/// </summary>
[JsonConverter(typeof(ClobberingJsonConverter), "Uno", "Blammo")]
public string One { get; set; }
}
[Test]
public void CustomDoubleRounding()
{
var measurements = new Measurements
{
Loads = new List<double> { 23283.567554707258, 23224.849899771067, 23062.5, 22846.272519910868, 22594.281246368635 },
Positions = new List<double> { 57.724227689317019, 60.440934405753069, 63.444192925248643, 66.813119113482557, 70.4496501404433 },
Gain = 12345.67895111213
};
string json = JsonConvert.SerializeObject(measurements);
Assert.AreEqual("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json);
}
public class Measurements
{
[JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))]
public List<double> Positions { get; set; }
[JsonProperty(ItemConverterType = typeof(RoundingJsonConverter), ItemConverterParameters = new object[] { 0, MidpointRounding.ToEven })]
public List<double> Loads { get; set; }
[JsonConverter(typeof(RoundingJsonConverter), 4)]
public double Gain { get; set; }
}
public class RoundingJsonConverter : JsonConverter
{
int _precision;
MidpointRounding _rounding;
public RoundingJsonConverter()
: this(2)
{
}
public RoundingJsonConverter(int precision)
: this(precision, MidpointRounding.AwayFromZero)
{
}
public RoundingJsonConverter(int precision, MidpointRounding rounding)
{
_precision = precision;
_rounding = rounding;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(double);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(Math.Round((double)value, _precision, _rounding));
}
}
[Test]
public void GenericBaseClassSerialization()
{
string json = JsonConvert.SerializeObject(new NonGenericChildClass());
Assert.AreEqual("{\"Data\":null}", json);
}
public class GenericBaseClass<O, T>
{
public virtual T Data { get; set; }
}
public class GenericIntermediateClass<O> : GenericBaseClass<O, string>
{
public override string Data { get; set; }
}
public class NonGenericChildClass : GenericIntermediateClass<int>
{
}
}
}
| |
/*
-- =============================================
-- Author: Jonathan F. Minond
-- Create date: April 2006
-- Description: Database provider class
-- =============================================
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.OracleClient;
using System.IO;
namespace Content.API.Data
{
public class DatabaseHelper : IDisposable
{
private string strConnectionString;
private DbConnection objConnection;
private DbCommand objCommand;
private DbProviderFactory objFactory = null;
private bool boolHandleErrors;
private string strLastError;
private bool boolLogError;
private string strLogFile;
/// <summary>
/// Gets the connection.
/// </summary>
/// <value>The connection.</value>
public DbConnection Connection
{
get
{
return objConnection;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="T:DatabaseHelper"/> class.
/// </summary>
/// <param name="connectionstring">The connectionstring.</param>
/// <param name="provider">The provider.</param>
public DatabaseHelper(string connectionstring,Providers provider)
{
strConnectionString = connectionstring;
switch (provider)
{
case Providers.SqlServer:
objFactory = SqlClientFactory.Instance;
break;
case Providers.OleDb:
objFactory = OleDbFactory.Instance;
break;
case Providers.Oracle:
objFactory = OracleClientFactory.Instance;
break;
case Providers.ODBC:
objFactory = OdbcFactory.Instance;
break;
case Providers.ConfigDefined:
string providername=ConfigurationManager.ConnectionStrings["connectionstring"].ProviderName;
switch (providername)
{
case "System.Data.SqlClient":
objFactory = SqlClientFactory.Instance;
break;
case "System.Data.OleDb":
objFactory = OleDbFactory.Instance;
break;
case "System.Data.OracleClient":
objFactory = OracleClientFactory.Instance;
break;
case "System.Data.Odbc":
objFactory = OdbcFactory.Instance;
break;
}
break;
}
objConnection = objFactory.CreateConnection();
objCommand = objFactory.CreateCommand();
objConnection.ConnectionString = strConnectionString;
objCommand.Connection = objConnection;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:DatabaseHelper"/> class.
/// </summary>
/// <param name="provider">The provider.</param>
public DatabaseHelper(Providers provider):this(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString,provider)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:DatabaseHelper"/> class.
/// </summary>
/// <param name="connectionstring">The connectionstring.</param>
public DatabaseHelper(string connectionstring): this(connectionstring, Providers.SqlServer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:DatabaseHelper"/> class.
/// </summary>
public DatabaseHelper():this(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString,Providers.ConfigDefined)
{
}
/// <summary>
/// Gets or sets a value indicating whether [handle errors].
/// </summary>
/// <value><c>true</c> if [handle errors]; otherwise, <c>false</c>.</value>
public bool HandleErrors
{
get
{
return boolHandleErrors;
}
set
{
boolHandleErrors = value;
}
}
/// <summary>
/// Gets the last error.
/// </summary>
/// <value>The last error.</value>
public string LastError
{
get
{
return strLastError;
}
}
/// <summary>
/// Gets or sets a value indicating whether [log errors].
/// </summary>
/// <value><c>true</c> if [log errors]; otherwise, <c>false</c>.</value>
public bool LogErrors
{
get
{
return boolLogError;
}
set
{
boolLogError=value;
}
}
/// <summary>
/// Gets or sets the log file.
/// </summary>
/// <value>The log file.</value>
public string LogFile
{
get
{
return strLogFile;
}
set
{
strLogFile = value;
}
}
/// <summary>
/// Adds the parameter.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public int AddParameter(string name,object value)
{
DbParameter p = objFactory.CreateParameter();
p.ParameterName = name;
p.Value=value;
return objCommand.Parameters.Add(p);
}
/// <summary>
/// Adds the parameter.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <returns></returns>
public int AddParameter(DbParameter parameter)
{
return objCommand.Parameters.Add(parameter);
}
/// <summary>
/// Gets the command.
/// </summary>
/// <value>The command.</value>
public DbCommand Command
{
get
{
return objCommand;
}
}
/// <summary>
/// Begins the transaction.
/// </summary>
public void BeginTransaction()
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
objCommand.Transaction = objConnection.BeginTransaction();
}
/// <summary>
/// Commits the transaction.
/// </summary>
public void CommitTransaction()
{
objCommand.Transaction.Commit();
objConnection.Close();
}
/// <summary>
/// Rollbacks the transaction.
/// </summary>
public void RollbackTransaction()
{
objCommand.Transaction.Rollback();
objConnection.Close();
}
/// <summary>
/// Executes the non query.
/// </summary>
/// <param name="query">The query.</param>
/// <returns></returns>
public int ExecuteNonQuery(string query)
{
return ExecuteNonQuery(query, CommandType.Text, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the non query.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <returns></returns>
public int ExecuteNonQuery(string query,CommandType commandtype)
{
return ExecuteNonQuery(query, commandtype, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the non query.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public int ExecuteNonQuery(string query,ConnectionState connectionstate)
{
return ExecuteNonQuery(query,CommandType.Text,connectionstate);
}
/// <summary>
/// Executes the non query.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public int ExecuteNonQuery(string query,CommandType commandtype, ConnectionState connectionstate)
{
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
int i=-1;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
i = objCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
objConnection.Close();
}
}
return i;
}
/// <summary>
/// Executes the scalar.
/// </summary>
/// <param name="query">The query.</param>
/// <returns></returns>
public object ExecuteScalar(string query)
{
return ExecuteScalar(query, CommandType.Text, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the scalar.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <returns></returns>
public object ExecuteScalar(string query,CommandType commandtype)
{
return ExecuteScalar(query, commandtype, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the scalar.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public object ExecuteScalar(string query, ConnectionState connectionstate)
{
return ExecuteScalar(query, CommandType.Text, connectionstate);
}
/// <summary>
/// Executes the scalar.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public object ExecuteScalar(string query,CommandType commandtype, ConnectionState connectionstate)
{
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
object o = null;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
o = objCommand.ExecuteScalar();
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
objConnection.Close();
}
}
return o;
}
/// <summary>
/// Executes the reader.
/// </summary>
/// <param name="query">The query.</param>
/// <returns></returns>
public DbDataReader ExecuteReader(string query)
{
return ExecuteReader(query, CommandType.Text, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the reader.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <returns></returns>
public DbDataReader ExecuteReader(string query,CommandType commandtype)
{
return ExecuteReader(query, commandtype, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the reader.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public DbDataReader ExecuteReader(string query, ConnectionState connectionstate)
{
return ExecuteReader(query, CommandType.Text, connectionstate);
}
/// <summary>
/// Executes the reader.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public DbDataReader ExecuteReader(string query,CommandType commandtype, ConnectionState connectionstate)
{
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
DbDataReader reader=null;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
if (connectionstate == ConnectionState.CloseOnExit)
{
reader = objCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
else
{
reader = objCommand.ExecuteReader();
}
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
}
return reader;
}
/// <summary>
/// Executes the data set.
/// </summary>
/// <param name="query">The query.</param>
/// <returns></returns>
public DataSet ExecuteDataSet(string query)
{
return ExecuteDataSet(query, CommandType.Text, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the data set.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <returns></returns>
public DataSet ExecuteDataSet(string query,CommandType commandtype)
{
return ExecuteDataSet(query, commandtype, ConnectionState.CloseOnExit);
}
/// <summary>
/// Executes the data set.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public DataSet ExecuteDataSet(string query,ConnectionState connectionstate)
{
return ExecuteDataSet(query, CommandType.Text, connectionstate);
}
/// <summary>
/// Executes the data set.
/// </summary>
/// <param name="query">The query.</param>
/// <param name="commandtype">The commandtype.</param>
/// <param name="connectionstate">The connectionstate.</param>
/// <returns></returns>
public DataSet ExecuteDataSet(string query,CommandType commandtype, ConnectionState connectionstate)
{
DbDataAdapter adapter = objFactory.CreateDataAdapter();
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
adapter.SelectCommand = objCommand;
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
if (objConnection.State == System.Data.ConnectionState.Open)
{
objConnection.Close();
}
}
}
return ds;
}
/// <summary>
/// Handles the exceptions.
/// </summary>
/// <param name="ex">The ex.</param>
private void HandleExceptions(Exception ex)
{
if (LogErrors)
{
WriteToLog(ex.Message);
}
if (HandleErrors)
{
strLastError = ex.Message;
}
else
{
throw ex;
}
}
/// <summary>
/// Writes to log.
/// </summary>
/// <param name="msg">The MSG.</param>
private void WriteToLog(string msg)
{
StreamWriter writer= File.AppendText(LogFile);
writer.WriteLine(DateTime.Now.ToString() + " - " + msg);
writer.Close();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
objConnection.Close();
objConnection.Dispose();
objCommand.Dispose();
}
}
/// <summary>
/// Available DB Providers
/// </summary>
public enum Providers
{
/// <summary>
///
/// </summary>
SqlServer,
/// <summary>
///
/// </summary>
OleDb,
/// <summary>
///
/// </summary>
Oracle,
/// <summary>
///
/// </summary>
ODBC,
/// <summary>
///
/// </summary>
ConfigDefined
}
/// <summary>
/// State of connection
/// </summary>
public enum ConnectionState
{
KeepOpen,
CloseOnExit
}
}
| |
//
// Copyright (C) 2010 Jackson Harper ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using Manos.Http;
using Manos.Routing;
using Manos.Caching;
using Manos.Templates;
using Manos.Logging;
namespace Manos {
/// <summary>
/// A pre-packaged set of routes/actions that can be registered in the constructor of a ManoApp-derived class.
/// </summary>
public class ManosModule : IManosModule {
private RouteHandler routes = new RouteHandler ();
public ManosModule ()
{
//StartInternal ();
}
public RouteHandler Routes {
get { return routes; }
}
public IManosCache Cache {
get {
return AppHost.Cache;
}
}
public IManosLogger Log {
get {
return AppHost.Log;
}
}
public virtual string Get404Response()
{
return default404;
}
public virtual string Get500Response()
{
return default500;
}
private RouteHandler AddRouteHandler (IManosModule module, string [] patterns, HttpMethod [] methods)
{
if (module == null)
throw new ArgumentNullException ("module");
if (patterns == null)
throw new ArgumentNullException ("patterns");
if (methods == null)
throw new ArgumentNullException ("methods");
module.StartInternal ();
module.Routes.MatchOps = SimpleOpsForPatterns (patterns);
module.Routes.Methods = methods;
Routes.Children.Add (module.Routes);
return module.Routes;
}
private RouteHandler AddRouteHandler (ManosAction action, IMatchOperation[] matchOperations, HttpMethod [] methods)
{
return AddRouteHandler (new ActionTarget (action), matchOperations, methods);
}
private RouteHandler AddRouteHandler (ManosAction action, string [] patterns, HttpMethod [] methods)
{
return AddRouteHandler (new ActionTarget (action), patterns, methods);
}
private RouteHandler AddRouteHandler (IManosTarget target, IMatchOperation[] matchOperations, HttpMethod [] methods)
{
// TODO: Need to decide if this is a good or bad idea
// RemoveImplicitHandlers (action);
if (target == null)
throw new ArgumentNullException ("action");
if (matchOperations == null)
throw new ArgumentNullException ("matchOperations");
if (methods == null)
throw new ArgumentNullException ("methods");
RouteHandler res = new RouteHandler (matchOperations, methods, target);
Routes.Children.Add (res);
return res;
}
private RouteHandler AddRouteHandler (IManosTarget target, string [] patterns, HttpMethod [] methods)
{
// TODO: Need to decide if this is a good or bad idea
// RemoveImplicitHandlers (action);
if (target == null)
throw new ArgumentNullException ("action");
if (patterns == null)
throw new ArgumentNullException ("patterns");
if (methods == null)
throw new ArgumentNullException ("methods");
RouteHandler res = new RouteHandler (SimpleOpsForPatterns (patterns), methods, target);
Routes.Children.Add (res);
return res;
}
private RouteHandler AddImplicitRouteHandlerForModule (IManosModule module, string [] patterns, HttpMethod [] methods)
{
return AddImplicitRouteHandlerForModule (module, StringOpsForPatterns (patterns), methods);
}
private RouteHandler AddImplicitRouteHandlerForModule (IManosModule module, IMatchOperation [] ops, HttpMethod [] methods)
{
module.StartInternal ();
module.Routes.IsImplicit = true;
module.Routes.MatchOps = ops;
module.Routes.Methods = methods;
Routes.Children.Add (module.Routes);
return module.Routes;
}
private RouteHandler AddImplicitRouteHandlerForTarget (IManosTarget target, string[] patterns, HttpMethod[] methods, MatchType matchType)
{
return AddImplicitRouteHandlerForTarget (target, OpsForPatterns (patterns, matchType), methods);
//return AddImplicitRouteHandlerForTarget (target, StringOpsForPatterns (patterns), methods);
}
private RouteHandler AddImplicitRouteHandlerForTarget (IManosTarget target, IMatchOperation [] ops, HttpMethod [] methods)
{
RouteHandler res = new RouteHandler (ops, methods, target) {
IsImplicit = true,
};
Routes.Children.Add (res);
return res;
}
private IMatchOperation [] SimpleOpsForPatterns (string [] patterns)
{
return OpsForPatterns (patterns, MatchType.Simple);
}
private IMatchOperation [] StringOpsForPatterns (string [] patterns)
{
return OpsForPatterns (patterns, MatchType.String);
}
private IMatchOperation [] OpsForPatterns (string [] patterns, MatchType type)
{
var ops = new IMatchOperation [patterns.Length];
for (int i = 0; i < ops.Length; i++) {
ops [i] = MatchOperationFactory.Create (patterns [i], type);
}
return ops;
}
public RouteHandler Route (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.RouteMethods);
}
public RouteHandler Route (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.RouteMethods);
}
public RouteHandler Route (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Route (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.RouteMethods);
}
public RouteHandler Route (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.RouteMethods);
}
public RouteHandler Get (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.GetMethods);
}
public RouteHandler Get (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.GetMethods);
}
public RouteHandler Get (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.GetMethods);
}
public RouteHandler Get (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.GetMethods);
}
public RouteHandler Get (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.GetMethods);
}
//
public RouteHandler Put (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.PutMethods);
}
public RouteHandler Put (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.PutMethods);
}
public RouteHandler Put (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.PutMethods);
}
public RouteHandler Put (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.PutMethods);
}
public RouteHandler Put (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.PutMethods);
}
public RouteHandler Post (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.PostMethods);
}
public RouteHandler Post (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.PostMethods);
}
public RouteHandler Post (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.PostMethods);
}
public RouteHandler Post (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.PostMethods);
}
public RouteHandler Post (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.PostMethods);
}
//
public RouteHandler Delete (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.DeleteMethods);
}
public RouteHandler Delete (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.DeleteMethods);
}
public RouteHandler Delete (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.DeleteMethods);
}
public RouteHandler Delete (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.DeleteMethods);
}
public RouteHandler Delete (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.DeleteMethods);
}
//
public RouteHandler Head (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.HeadMethods);
}
public RouteHandler Head (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.HeadMethods);
}
public RouteHandler Head (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.HeadMethods);
}
public RouteHandler Head (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.HeadMethods);
}
public RouteHandler Head (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.HeadMethods);
}
//
public RouteHandler Options (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.OptionsMethods);
}
public RouteHandler Options (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.OptionsMethods);
}
public RouteHandler Options (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.OptionsMethods);
}
public RouteHandler Options (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.OptionsMethods);
}
public RouteHandler Options (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.OptionsMethods);
}
//
public RouteHandler Trace (string pattern, IManosModule module)
{
return AddRouteHandler (module, new string [] { pattern }, HttpMethods.TraceMethods);
}
public RouteHandler Trace (string pattern, ManosAction action)
{
return AddRouteHandler (action, new string [] { pattern }, HttpMethods.TraceMethods);
}
public RouteHandler Trace (string pattern, MatchType matchType, ManosAction action)
{
IMatchOperation [] ops = OpsForPatterns (new string [] { pattern }, matchType);
return AddRouteHandler (action, ops, HttpMethods.TraceMethods);
}
public RouteHandler Trace (ManosAction action, params string [] patterns)
{
return AddRouteHandler (action, patterns, HttpMethods.TraceMethods);
}
public RouteHandler Trace (IManosModule module, params string [] patterns)
{
return AddRouteHandler (module, patterns, HttpMethods.TraceMethods);
}
public static Timeout AddTimeout (TimeSpan timespan, TimeoutCallback callback)
{
return AddTimeout (timespan, RepeatBehavior.Single, null, callback);
}
public static Timeout AddTimeout (TimeSpan timespan, IRepeatBehavior repeat, TimeoutCallback callback)
{
return AddTimeout (timespan, repeat, null, callback);
}
public static Timeout AddTimeout (TimeSpan timespan, object data, TimeoutCallback callback)
{
return AddTimeout (timespan, RepeatBehavior.Single, data, callback);
}
public static Timeout AddTimeout (TimeSpan timespan, IRepeatBehavior repeat, object data, TimeoutCallback callback)
{
return AppHost.AddTimeout (timespan, repeat, data, callback);
}
public static void AddPipe (ManosPipe pipe)
{
AppHost.AddPipe (pipe);
}
public static void RenderTemplate (ManosContext ctx, string template, object data)
{
TemplateEngine.RenderToStream (template, ctx.Response.Writer, data);
}
public void StartInternal ()
{
AddImplicitRoutes ();
}
private void AddImplicitRoutes ()
{
MethodInfo[] methods = GetType ().GetMethods ();
foreach (MethodInfo meth in methods) {
if (meth.ReturnType != typeof(void))
continue;
if (IsIgnored (meth))
continue;
ParameterInfo [] parameters = meth.GetParameters ();
if (IsActionSignature (meth, parameters)) {
AddActionHandler (Routes, meth);
continue;
}
if (IsParameterizedActionSignature (meth, parameters)) {
AddParameterizedActionHandler (Routes, meth);
continue;
}
}
PropertyInfo [] properties = GetType ().GetProperties ();
foreach (PropertyInfo prop in properties) {
if (!typeof (ManosModule).IsAssignableFrom (prop.PropertyType))
continue;
if (IsIgnored (prop))
continue;
AddImplicitModule (prop);
}
}
private bool IsActionSignature (MethodInfo method, ParameterInfo [] parameters)
{
if (parameters.Length != 1)
return false;
if (method.DeclaringType.Assembly == typeof (ManosModule).Assembly)
return false;
if (parameters [0].ParameterType != typeof (IManosContext))
return false;
return true;
}
private bool IsParameterizedActionSignature (MethodInfo method, ParameterInfo [] parameters)
{
if (parameters.Length < 1) {
return false;
}
if (method.DeclaringType.Assembly == typeof (ManosModule).Assembly)
return false;
if (parameters [0].ParameterType != typeof (IManosContext))
return false;
return true;
}
private bool IsIgnored (MemberInfo info)
{
object [] atts = info.GetCustomAttributes (typeof (IgnoreHandlerAttribute), false);
return atts.Length > 0;
}
private void AddActionHandler (RouteHandler routes, MethodInfo info)
{
HttpMethodAttribute [] atts = (HttpMethodAttribute []) info.GetCustomAttributes (typeof (HttpMethodAttribute), false);
if (atts.Length == 0) {
AddDefaultHandlerForAction (routes, info);
return;
}
foreach (HttpMethodAttribute att in atts) {
AddHandlerForAction (routes, att, info);
}
}
private void AddDefaultHandlerForAction (RouteHandler routes, MethodInfo info)
{
ManosAction action = ActionForMethod (info);
ActionTarget target = new ActionTarget (action);
AddImplicitRouteHandlerForTarget (target, new string [] { "/" + info.Name }, HttpMethods.RouteMethods, MatchType.String);
}
private void AddHandlerForAction (RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
{
ManosAction action = ActionForMethod (info);
ActionTarget target = new ActionTarget (action);
string[] patterns = null == att.Patterns ? new string [] { "/" + info.Name } : att.Patterns;
AddImplicitRouteHandlerForTarget (target, OpsForPatterns (patterns, att.MatchType), att.Methods);
}
private ManosAction ActionForMethod (MethodInfo info)
{
ManosAction action;
if (info.IsStatic)
action = (ManosAction) Delegate.CreateDelegate (typeof (ManosAction), info);
else
action = (ManosAction) Delegate.CreateDelegate (typeof (ManosAction), this, info);
return action;
}
private void AddParameterizedActionHandler (RouteHandler routes, MethodInfo info)
{
HttpMethodAttribute [] atts = (HttpMethodAttribute []) info.GetCustomAttributes (typeof (HttpMethodAttribute), false);
if (atts.Length == 0) {
AddDefaultHandlerForParameterizedAction (routes, info);
return;
}
foreach (HttpMethodAttribute att in atts) {
AddHandlerForParameterizedAction (routes, att, info);
}
}
private void AddDefaultHandlerForParameterizedAction (RouteHandler routes, MethodInfo info)
{
ParameterizedAction action = ParameterizedActionFactory.CreateAction (info);
ParameterizedActionTarget target = new ParameterizedActionTarget (this, info, action);
AddImplicitRouteHandlerForTarget (target, new string [] { "/" + info.Name }, HttpMethods.RouteMethods, MatchType.String);
}
private void AddHandlerForParameterizedAction (RouteHandler routes, HttpMethodAttribute att, MethodInfo info)
{
ParameterizedAction action = ParameterizedActionFactory.CreateAction (info);
ParameterizedActionTarget target = new ParameterizedActionTarget (this, info, action);
AddImplicitRouteHandlerForTarget (target, att.Patterns, att.Methods, att.MatchType);
}
private void AddImplicitModule (PropertyInfo prop)
{
var value = (ManosModule) prop.GetValue (this, null);
if (value == null) {
try {
value = (ManosModule) Activator.CreateInstance (prop.PropertyType);
} catch (Exception e) {
throw new Exception (String.Format ("Unable to create default property value for '{0}'", prop), e);
}
prop.SetValue (this, value, null);
}
AddImplicitRouteHandlerForModule (value, new string [] { "/" + prop.Name }, HttpMethods.RouteMethods);
}
private static string default404 = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"" +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">" +
"<head>" +
" <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
" <title>The page you were looking for doesn't exist (404)</title>" +
"<style type=\"text/css\">" +
"body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }" +
"div.dialog {" +
"width: 25em;" +
"padding: 0 4em;" +
"margin: 4em auto 0 auto;" +
"border: 1px solid #ccc;" +
"border-right-color: #999;" +
"border-bottom-color: #999;" +
"}" +
"h1 { font-size: 100%; color: #f00; line-height: 1.5em; }" +
"</style>" +
"</head>" +
"<body>" +
" <div class=\"dialog\">" +
" <h1>404 - The page you were looking for doesn't exist.</h1>" +
" <p>You may have mistyped the address or the page may have moved.</p>" +
" <p><small>Powered by <a href=\"http://manosdemono.org\">manos</a></small></p>" +
" </div>" +
"</body>" +
"</html>";
private static string default500 = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"" +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">" +
"<head>" +
" <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
" <title>We're sorry, but something went wrong (500)</title>" +
"<style type=\"text/css\">" +
"body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }" +
"div.dialog {" +
"width: 25em;" +
"padding: 0 4em;" +
"margin: 4em auto 0 auto;" +
"border: 1px solid #ccc;" +
"border-right-color: #999;" +
"border-bottom-color: #999;" +
"}" +
"h1 { font-size: 100%; color: #f00; line-height: 1.5em; }" +
"</style>" +
"</head>" +
"<body>" +
" <div class=\"dialog\">" +
" <h1>500 - We're sorry, but something went wrong.</h1>" +
" <p><small>Powered by <a href=\"http://manosdemono.org\">manos</a></small></p>" +
" </div>" +
"</body>" +
"</html>";
}
}
| |
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.RegularExpressions;
namespace Facility.Core.Http;
/// <summary>
/// A service HTTP handler.
/// </summary>
public abstract class ServiceHttpHandler : DelegatingHandler
{
/// <summary>
/// Attempts to handle the HTTP request.
/// </summary>
public abstract Task<HttpResponseMessage?> TryHandleHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken);
/// <summary>
/// Creates an instance.
/// </summary>
protected ServiceHttpHandler(ServiceHttpHandlerSettings? settings, ServiceHttpHandlerDefaults defaults)
{
settings ??= new ServiceHttpHandlerSettings();
m_rootPath = (settings.RootPath ?? "").TrimEnd('/');
m_synchronous = settings.Synchronous;
m_contentSerializer = settings.ContentSerializer ?? defaults.ContentSerializer ?? HttpContentSerializer.Legacy;
m_bytesSerializer = settings.BytesSerializer ?? BytesHttpContentSerializer.Instance;
m_textSerializer = settings.TextSerializer ?? TextHttpContentSerializer.Instance;
m_aspects = settings.Aspects;
m_skipRequestValidation = settings.SkipRequestValidation;
m_skipResponseValidation = settings.SkipResponseValidation;
m_disableChunkedTransfer = settings.DisableChunkedTransfer;
}
/// <summary>
/// Creates an instance.
/// </summary>
[Obsolete("Regenerate code to use the new constructor.")]
protected ServiceHttpHandler(ServiceHttpHandlerSettings? settings)
: this(settings, new ServiceHttpHandlerDefaults())
{
}
/// <summary>
/// Attempts to handle a service method.
/// </summary>
protected async Task<HttpResponseMessage?> TryHandleServiceMethodAsync<TRequest, TResponse>(HttpMethodMapping<TRequest, TResponse> mapping, HttpRequestMessage httpRequest, Func<TRequest, CancellationToken, Task<ServiceResult<TResponse>>> invokeMethodAsync, CancellationToken cancellationToken)
where TRequest : ServiceDto, new()
where TResponse : ServiceDto, new()
{
if (mapping == null)
throw new ArgumentNullException(nameof(mapping));
if (httpRequest == null)
throw new ArgumentNullException(nameof(httpRequest));
if (invokeMethodAsync == null)
throw new ArgumentNullException(nameof(invokeMethodAsync));
if (httpRequest.RequestUri == null)
throw new ArgumentException("RequestUri must be specified.", nameof(httpRequest));
if (httpRequest.Method != mapping.HttpMethod)
return null;
var pathParameters = TryMatchHttpRoute(httpRequest.RequestUri, m_rootPath + mapping.Path);
if (pathParameters == null)
return null;
var context = new ServiceHttpContext();
ServiceHttpContext.SetContext(httpRequest, context);
var aspectHttpResponse = await AdaptTask(RequestReceivedAsync(httpRequest, cancellationToken)).ConfigureAwait(true);
if (aspectHttpResponse != null)
return aspectHttpResponse;
ServiceErrorDto? error = null;
object? requestBody = null;
if (mapping.RequestBodyType != null)
{
try
{
var serializer = GetHttpContentSerializer(mapping.RequestBodyType);
var requestResult = await AdaptTask(serializer.ReadHttpContentAsync(mapping.RequestBodyType, httpRequest.Content, cancellationToken)).ConfigureAwait(true);
if (requestResult.IsFailure)
error = requestResult.Error;
else
requestBody = requestResult.Value;
}
catch (Exception exception) when (ShouldCreateErrorFromException(exception))
{
// cancellation can cause the wrong exception
cancellationToken.ThrowIfCancellationRequested();
// error reading request body
error = CreateErrorFromException(exception);
}
}
TResponse? response = null;
if (error == null)
{
var request = mapping.CreateRequest(requestBody);
var uriParameters = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
foreach (var queryParameter in ParseQueryString(httpRequest.RequestUri.Query))
uriParameters[queryParameter.Key] = queryParameter.Value[0];
foreach (var pathParameter in pathParameters)
uriParameters[pathParameter.Key] = pathParameter.Value;
request = mapping.SetUriParameters(request, uriParameters);
request = mapping.SetRequestHeaders(request, HttpServiceUtility.CreateDictionaryFromHeaders(httpRequest.Headers, httpRequest.Content?.Headers)!);
context.Request = request;
if (!m_skipRequestValidation && !request.Validate(out var requestErrorMessage))
{
error = ServiceErrors.CreateInvalidRequest(requestErrorMessage);
}
else
{
var methodResult = await invokeMethodAsync(request, cancellationToken).ConfigureAwait(true);
if (methodResult.IsFailure)
{
error = methodResult.Error;
}
else
{
response = methodResult.Value;
if (!m_skipResponseValidation && !response.Validate(out var responseErrorMessage))
{
error = ServiceErrors.CreateInvalidResponse(responseErrorMessage);
response = null;
}
}
}
context.Result = error != null ? ServiceResult.Failure(error) : ServiceResult.Success<ServiceDto>(response!);
}
HttpResponseMessage httpResponse;
if (error == null)
{
var responseMappingGroups = mapping.ResponseMappings
.GroupBy(x => x.MatchesResponse(response!))
.Where(x => x.Key != false)
.OrderByDescending(x => x.Key)
.ToList();
if (responseMappingGroups.Count >= 1 && responseMappingGroups[0].Count() == 1)
{
var responseMapping = responseMappingGroups[0].Single();
httpResponse = new HttpResponseMessage(responseMapping.StatusCode);
var responseHeaders = mapping.GetResponseHeaders(response!);
var headersResult = HttpServiceUtility.TryAddNonContentHeaders(httpResponse.Headers, responseHeaders);
if (headersResult.IsFailure)
throw new InvalidOperationException(headersResult.Error!.Message);
if (responseMapping.ResponseBodyType != null)
{
var serializer = GetHttpContentSerializer(responseMapping.ResponseBodyType);
var mediaType = responseMapping.ResponseBodyContentType ?? responseHeaders?.GetContentType() ?? GetAcceptedMediaType(httpRequest, serializer);
httpResponse.Content = serializer.CreateHttpContent(responseMapping.GetResponseBody(response!)!, mediaType);
if (m_disableChunkedTransfer)
await httpResponse.Content.LoadIntoBufferAsync().ConfigureAwait(false);
}
}
else
{
throw new InvalidOperationException($"Found {responseMappingGroups.Sum(x => x.Count())} valid HTTP responses for {typeof(TResponse).Name}: {response}");
}
}
else
{
var statusCode = error.Code == null ? HttpStatusCode.InternalServerError :
(TryGetCustomHttpStatusCode(error.Code) ?? HttpServiceErrors.TryGetHttpStatusCode(error.Code) ?? HttpStatusCode.InternalServerError);
httpResponse = new HttpResponseMessage(statusCode);
if (statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotModified)
{
var mediaType = GetAcceptedMediaType(httpRequest, m_contentSerializer);
httpResponse.Content = m_contentSerializer.CreateHttpContent(error, mediaType);
if (m_disableChunkedTransfer)
await httpResponse.Content.LoadIntoBufferAsync().ConfigureAwait(false);
}
}
httpResponse.RequestMessage = httpRequest;
await AdaptTask(ResponseReadyAsync(httpResponse, cancellationToken)).ConfigureAwait(true);
return httpResponse;
}
/// <summary>
/// Returns the HTTP status code for a custom error code.
/// </summary>
protected virtual HttpStatusCode? TryGetCustomHttpStatusCode(string errorCode) => null;
/// <summary>
/// Handle or delegate the HTTP request.
/// </summary>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return await TryHandleHttpRequestAsync(request, cancellationToken).ConfigureAwait(true) ??
await base.SendAsync(request, cancellationToken).ConfigureAwait(true);
}
/// <summary>
/// Called to determine if an error object should be created from an unexpected exception.
/// </summary>
protected virtual bool ShouldCreateErrorFromException(Exception exception)
{
var exceptionTypeName = exception.GetType().FullName;
return exceptionTypeName != null && exceptionTypeName.StartsWith("System.Web.", StringComparison.Ordinal);
}
/// <summary>
/// Called to create an error object from an unexpected exception.
/// </summary>
protected virtual ServiceErrorDto CreateErrorFromException(Exception exception) =>
ServiceErrors.CreateInvalidRequest("Unexpected error while reading request body.");
/// <summary>
/// Makes a task synchronous if necessary.
/// </summary>
[SuppressMessage("Performance", "CA1849:Call async methods when in an async method", Justification = "Task is completed.")]
protected Task AdaptTask(Task task)
{
if (!m_synchronous)
return task;
#pragma warning disable CA1849
task.GetAwaiter().GetResult();
#pragma warning restore CA1849
return Task.CompletedTask;
}
/// <summary>
/// Makes a task synchronous if necessary.
/// </summary>
protected Task<T> AdaptTask<T>(Task<T> task)
{
if (!m_synchronous)
return task;
return Task.FromResult(task.GetAwaiter().GetResult());
}
private static IReadOnlyDictionary<string, string>? TryMatchHttpRoute(Uri requestUri, string routePath)
{
var requestPath = requestUri.AbsolutePath.Trim('/');
routePath = routePath.Trim('/');
if (routePath.IndexOfOrdinal('{') != -1)
{
// ReSharper disable once RedundantEnumerableCastCall (needed for .NET Standard 2.0)
var names = s_regexPathParameterRegex.Matches(routePath).Cast<Match>().Select(x => x.Groups[1].ToString()).ToList();
var regexPattern = Regex.Escape(routePath);
foreach (var name in names)
regexPattern = regexPattern.ReplaceOrdinal("\\{" + name + "}", "(?'" + name + "'[^/]+)");
regexPattern = "^(?:" + regexPattern + ")$";
var match = new Regex(regexPattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase).Match(requestPath);
return match.Success ? names.ToDictionary(name => name, name => Uri.UnescapeDataString(match.Groups[name].ToString())) : null;
}
if (string.Equals(requestPath, routePath, StringComparison.OrdinalIgnoreCase))
return s_emptyDictionary;
return null;
}
private static IReadOnlyDictionary<string, IReadOnlyList<string>> ParseQueryString(string query)
{
if (query.Length != 0 && query[0] == '?')
query = query.Substring(1);
return query.Split('&')
.Select(x => x.Split(new[] { '=' }, 2))
.GroupBy(x => Uri.UnescapeDataString(x[0]), x => Uri.UnescapeDataString(x.Length == 1 ? "" : x[1]), StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => (IReadOnlyList<string>) x.ToList());
}
private string? GetAcceptedMediaType(HttpRequestMessage httpRequest, HttpContentSerializer serializer) =>
httpRequest.Headers.Accept
.OrderByDescending(x => x.Quality)
.Select(x => x.MediaType)
.Where(x => x is not null)
.Select(x => x!)
.FirstOrDefault(serializer.IsAcceptedMediaType);
private async Task<HttpResponseMessage?> RequestReceivedAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken)
{
if (m_aspects != null)
{
foreach (var aspect in m_aspects)
{
var httpResponse = await aspect.RequestReceivedAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (httpResponse != null)
return httpResponse;
}
}
return null;
}
private async Task ResponseReadyAsync(HttpResponseMessage httpResponse, CancellationToken cancellationToken)
{
if (m_aspects != null)
{
foreach (var aspect in m_aspects)
await aspect.ResponseReadyAsync(httpResponse, cancellationToken).ConfigureAwait(false);
}
}
private HttpContentSerializer GetHttpContentSerializer(Type objectType) =>
HttpServiceUtility.UsesBytesSerializer(objectType) ? m_bytesSerializer :
HttpServiceUtility.UsesTextSerializer(objectType) ? m_textSerializer :
m_contentSerializer;
private static readonly IReadOnlyDictionary<string, string> s_emptyDictionary = new Dictionary<string, string>();
private static readonly Regex s_regexPathParameterRegex = new(@"\{([a-zA-Z][a-zA-Z0-9]*)\}", RegexOptions.CultureInvariant);
private readonly string m_rootPath;
private readonly bool m_synchronous;
private readonly HttpContentSerializer m_contentSerializer;
private readonly HttpContentSerializer m_bytesSerializer;
private readonly HttpContentSerializer m_textSerializer;
private readonly IReadOnlyList<ServiceHttpHandlerAspect>? m_aspects;
private readonly bool m_skipRequestValidation;
private readonly bool m_skipResponseValidation;
private readonly bool m_disableChunkedTransfer;
}
| |
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 AccessTokenMvcApiService.Areas.HelpPage.ModelDescriptions;
using AccessTokenMvcApiService.Areas.HelpPage.Models;
namespace AccessTokenMvcApiService.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace MyNatsClient.Internals
{
internal sealed class NatsConnection : INatsConnection
{
private readonly ILogger<NatsConnection> _logger = LoggerManager.CreateLogger<NatsConnection>();
private readonly CancellationToken _cancellationToken;
private Socket _socket;
private Stream _stream;
private BufferedStream _writeStream;
private BufferedStream _readStream;
private SemaphoreSlim _writeStreamSync;
private NatsOpStreamReader _reader;
private NatsStreamWriter _writer;
private bool _isDisposed;
public INatsServerInfo ServerInfo { get; }
public bool IsConnected => _socket.Connected;
private bool CanRead =>
_socket.Connected &&
_stream.CanRead &&
!_cancellationToken.IsCancellationRequested;
internal NatsConnection(
NatsServerInfo serverInfo,
Socket socket,
Stream stream,
CancellationToken cancellationToken)
{
ServerInfo = serverInfo ?? throw new ArgumentNullException(nameof(serverInfo));
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
if (!socket.Connected)
throw new ArgumentException("Socket is not connected.", nameof(socket));
_stream = stream ?? throw new ArgumentNullException(nameof(stream));
_writeStream = new BufferedStream(_stream, socket.SendBufferSize);
_readStream = new BufferedStream(_stream, socket.ReceiveBufferSize);
_cancellationToken = cancellationToken;
_writeStreamSync = new SemaphoreSlim(1, 1);
_writer = new NatsStreamWriter(_writeStream, _cancellationToken);
_reader = NatsOpStreamReader.Use(_readStream);
}
public void Dispose()
{
ThrowIfDisposed();
_isDisposed = true;
var exs = new List<Exception>();
void TryDispose(IDisposable disposable)
{
try
{
disposable.Dispose();
}
catch (Exception ex)
{
exs.Add(ex);
}
}
TryDispose(_reader);
TryDispose(_writeStream);
TryDispose(_readStream);
TryDispose(_stream);
try
{
_socket.Shutdown(SocketShutdown.Both);
}
catch (Exception ex)
{
exs.Add(ex);
}
TryDispose(_socket);
TryDispose(_writeStreamSync);
_reader = null;
_writeStream = null;
_readStream = null;
_stream = null;
_socket = null;
_writeStreamSync = null;
_reader = null;
_writer = null;
if (exs.Any())
throw new AggregateException("Failed while disposing connection. See inner exception(s) for more details.", exs);
}
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(GetType().Name);
}
private void ThrowIfNotConnected()
{
if (!IsConnected)
throw NatsException.NotConnected();
}
public IEnumerable<IOp> ReadOps()
{
ThrowIfDisposed();
ThrowIfNotConnected();
_logger.LogDebug("Starting OPs read loop");
while (CanRead)
{
#if Debug
_logger.LogDebug("Reading OP");
#endif
yield return _reader.ReadOp();
}
}
public void WithWriteLock(Action<INatsStreamWriter> a)
{
ThrowIfDisposed();
ThrowIfNotConnected();
_writeStreamSync.Wait(_cancellationToken);
try
{
a(_writer);
}
finally
{
_writeStreamSync.Release();
}
}
public void WithWriteLock<TArg>(Action<INatsStreamWriter, TArg> a, TArg arg)
{
ThrowIfDisposed();
ThrowIfNotConnected();
_writeStreamSync.Wait(_cancellationToken);
try
{
a(_writer, arg);
}
finally
{
_writeStreamSync.Release();
}
}
public async Task WithWriteLockAsync(Func<INatsStreamWriter, Task> a)
{
ThrowIfDisposed();
ThrowIfNotConnected();
await _writeStreamSync.WaitAsync(_cancellationToken).ConfigureAwait(false);
try
{
await a(_writer).ConfigureAwait(false);
}
finally
{
_writeStreamSync.Release();
}
}
public async Task WithWriteLockAsync<TArg>(Func<INatsStreamWriter, TArg, Task> a, TArg arg)
{
ThrowIfDisposed();
ThrowIfNotConnected();
await _writeStreamSync.WaitAsync(_cancellationToken).ConfigureAwait(false);
try
{
await a(_writer, arg).ConfigureAwait(false);
}
finally
{
_writeStreamSync.Release();
}
}
}
}
| |
// Copyright (C) AS Sertifitseerimiskeskus
// This software is released under the BSD License (see LICENSE.BSD)
using System;
using System.IO;
namespace NDigiDoc.Ionic.Zlib
{
internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 }
internal class ZlibBaseStream : System.IO.Stream
{
protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec();
protected internal StreamMode _streamMode = StreamMode.Undefined;
protected internal FlushType _flushMode;
protected internal ZlibStreamFlavor _flavor;
protected internal CompressionMode _compressionMode;
protected internal CompressionLevel _level;
protected internal bool _leaveOpen;
protected internal byte[] _workingBuffer;
protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault;
protected internal byte[] _buf1 = new byte[1];
protected internal System.IO.Stream _stream;
protected internal CompressionStrategy Strategy = CompressionStrategy.Default;
// workitem 7159
Ionic.Crc.CRC32 crc;
protected internal string _GzipFileName;
protected internal string _GzipComment;
protected internal DateTime _GzipMtime;
protected internal int _gzipHeaderByteCount;
internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } }
public ZlibBaseStream(System.IO.Stream stream,
CompressionMode compressionMode,
CompressionLevel level,
ZlibStreamFlavor flavor,
bool leaveOpen)
: base()
{
this._flushMode = FlushType.None;
//this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT];
this._stream = stream;
this._leaveOpen = leaveOpen;
this._compressionMode = compressionMode;
this._flavor = flavor;
this._level = level;
// workitem 7159
if (flavor == ZlibStreamFlavor.GZIP)
{
this.crc = new Ionic.Crc.CRC32();
}
}
protected internal bool _wantCompress
{
get
{
return (this._compressionMode == CompressionMode.Compress);
}
}
private ZlibCodec z
{
get
{
if (_z == null)
{
bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB);
_z = new ZlibCodec();
if (this._compressionMode == CompressionMode.Decompress)
{
_z.InitializeInflate(wantRfc1950Header);
}
else
{
_z.Strategy = Strategy;
_z.InitializeDeflate(this._level, wantRfc1950Header);
}
}
return _z;
}
}
private byte[] workingBuffer
{
get
{
if (_workingBuffer == null)
_workingBuffer = new byte[_bufferSize];
return _workingBuffer;
}
}
public override void Write(System.Byte[] buffer, int offset, int count)
{
// workitem 7159
// calculate the CRC on the unccompressed data (before writing)
if (crc != null)
crc.SlurpBlock(buffer, offset, count);
if (_streamMode == StreamMode.Undefined)
_streamMode = StreamMode.Writer;
else if (_streamMode != StreamMode.Writer)
throw new ZlibException("Cannot Write after Reading.");
if (count == 0)
return;
// first reference of z property will initialize the private var _z
z.InputBuffer = buffer;
_z.NextIn = offset;
_z.AvailableBytesIn = count;
bool done = false;
do
{
_z.OutputBuffer = workingBuffer;
_z.NextOut = 0;
_z.AvailableBytesOut = _workingBuffer.Length;
int rc = (_wantCompress)
? _z.Deflate(_flushMode)
: _z.Inflate(_flushMode);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message);
//if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
// If GZIP and de-compress, we're done when 8 bytes remain.
if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
}
while (!done);
}
private void finish()
{
if (_z == null) return;
if (_streamMode == StreamMode.Writer)
{
bool done = false;
do
{
_z.OutputBuffer = workingBuffer;
_z.NextOut = 0;
_z.AvailableBytesOut = _workingBuffer.Length;
int rc = (_wantCompress)
? _z.Deflate(FlushType.Finish)
: _z.Inflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
{
string verb = (_wantCompress ? "de" : "in") + "flating";
if (_z.Message == null)
throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc));
else
throw new ZlibException(verb + ": " + _z.Message);
}
if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
{
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
}
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
// If GZIP and de-compress, we're done when 8 bytes remain.
if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
}
while (!done);
Flush();
// workitem 7159
if (_flavor == ZlibStreamFlavor.GZIP)
{
if (_wantCompress)
{
// Emit the GZIP trailer: CRC32 and size mod 2^32
int c1 = crc.Crc32Result;
_stream.Write(BitConverter.GetBytes(c1), 0, 4);
int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF);
_stream.Write(BitConverter.GetBytes(c2), 0, 4);
}
else
{
throw new ZlibException("Writing with decompression is not supported.");
}
}
}
// workitem 7159
else if (_streamMode == StreamMode.Reader)
{
if (_flavor == ZlibStreamFlavor.GZIP)
{
if (!_wantCompress)
{
// workitem 8501: handle edge case (decompress empty stream)
if (_z.TotalBytesOut == 0L)
return;
// Read and potentially verify the GZIP trailer:
// CRC32 and size mod 2^32
byte[] trailer = new byte[8];
// workitems 8679 & 12554
if (_z.AvailableBytesIn < 8)
{
// Make sure we have read to the end of the stream
Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn);
int bytesNeeded = 8 - _z.AvailableBytesIn;
int bytesRead = _stream.Read(trailer,
_z.AvailableBytesIn,
bytesNeeded);
if (bytesNeeded != bytesRead)
{
throw new ZlibException(String.Format("Missing or incomplete GZIP trailer. Expected 8 bytes, got {0}.",
_z.AvailableBytesIn + bytesRead));
}
}
else
{
Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length);
}
Int32 crc32_expected = BitConverter.ToInt32(trailer, 0);
Int32 crc32_actual = crc.Crc32Result;
Int32 isize_expected = BitConverter.ToInt32(trailer, 4);
Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF);
if (crc32_actual != crc32_expected)
throw new ZlibException(String.Format("Bad CRC32 in GZIP trailer. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected));
if (isize_actual != isize_expected)
throw new ZlibException(String.Format("Bad size in GZIP trailer. (actual({0})!=expected({1}))", isize_actual, isize_expected));
}
else
{
throw new ZlibException("Reading with compression is not supported.");
}
}
}
}
private void end()
{
if (z == null)
return;
if (_wantCompress)
{
_z.EndDeflate();
}
else
{
_z.EndInflate();
}
_z = null;
}
public override void Close()
{
if (_stream == null) return;
try
{
finish();
}
finally
{
end();
if (!_leaveOpen) _stream.Close();
_stream = null;
}
}
public override void Flush()
{
_stream.Flush();
}
public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
//_outStream.Seek(offset, origin);
}
public override void SetLength(System.Int64 value)
{
_stream.SetLength(value);
}
#if NOT
public int Read()
{
if (Read(_buf1, 0, 1) == 0)
return 0;
// calculate CRC after reading
if (crc!=null)
crc.SlurpBlock(_buf1,0,1);
return (_buf1[0] & 0xFF);
}
#endif
private bool nomoreinput = false;
private string ReadZeroTerminatedString()
{
var list = new System.Collections.Generic.List<byte>();
bool done = false;
do
{
// workitem 7740
int n = _stream.Read(_buf1, 0, 1);
if (n != 1)
throw new ZlibException("Unexpected EOF reading GZIP header.");
else
{
if (_buf1[0] == 0)
done = true;
else
list.Add(_buf1[0]);
}
} while (!done);
byte[] a = list.ToArray();
return GZipStream.iso8859dash1.GetString(a, 0, a.Length);
}
private int _ReadAndValidateGzipHeader()
{
int totalBytesRead = 0;
// read the header on the first read
byte[] header = new byte[10];
int n = _stream.Read(header, 0, header.Length);
// workitem 8501: handle edge case (decompress empty stream)
if (n == 0)
return 0;
if (n != 10)
throw new ZlibException("Not a valid GZIP stream.");
if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8)
throw new ZlibException("Bad GZIP header.");
Int32 timet = BitConverter.ToInt32(header, 4);
_GzipMtime = GZipStream._unixEpoch.AddSeconds(timet);
totalBytesRead += n;
if ((header[3] & 0x04) == 0x04)
{
// read and discard extra field
n = _stream.Read(header, 0, 2); // 2-byte length field
totalBytesRead += n;
Int16 extraLength = (Int16)(header[0] + header[1] * 256);
byte[] extra = new byte[extraLength];
n = _stream.Read(extra, 0, extra.Length);
if (n != extraLength)
throw new ZlibException("Unexpected end-of-file reading GZIP header.");
totalBytesRead += n;
}
if ((header[3] & 0x08) == 0x08)
_GzipFileName = ReadZeroTerminatedString();
if ((header[3] & 0x10) == 0x010)
_GzipComment = ReadZeroTerminatedString();
if ((header[3] & 0x02) == 0x02)
Read(_buf1, 0, 1); // CRC16, ignore
return totalBytesRead;
}
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
{
// According to MS documentation, any implementation of the IO.Stream.Read function must:
// (a) throw an exception if offset & count reference an invalid part of the buffer,
// or if count < 0, or if buffer is null
// (b) return 0 only upon EOF, or if count = 0
// (c) if not EOF, then return at least 1 byte, up to <count> bytes
if (_streamMode == StreamMode.Undefined)
{
if (!this._stream.CanRead) throw new ZlibException("The stream is not readable.");
// for the first read, set up some controls.
_streamMode = StreamMode.Reader;
// (The first reference to _z goes through the private accessor which
// may initialize it.)
z.AvailableBytesIn = 0;
if (_flavor == ZlibStreamFlavor.GZIP)
{
_gzipHeaderByteCount = _ReadAndValidateGzipHeader();
// workitem 8501: handle edge case (decompress empty stream)
if (_gzipHeaderByteCount == 0)
return 0;
}
}
if (_streamMode != StreamMode.Reader)
throw new ZlibException("Cannot Read after Writing.");
if (count == 0) return 0;
if (nomoreinput && _wantCompress) return 0; // workitem 8557
if (buffer == null) throw new ArgumentNullException("buffer");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset");
if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count");
int rc = 0;
// set up the output of the deflate/inflate codec:
_z.OutputBuffer = buffer;
_z.NextOut = offset;
_z.AvailableBytesOut = count;
// This is necessary in case _workingBuffer has been resized. (new byte[])
// (The first reference to _workingBuffer goes through the private accessor which
// may initialize it.)
_z.InputBuffer = workingBuffer;
do
{
// need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any.
if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
{
// No data available, so try to Read data from the captive stream.
_z.NextIn = 0;
_z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
if (_z.AvailableBytesIn == 0)
nomoreinput = true;
}
// we have data in InputBuffer; now compress or decompress as appropriate
rc = (_wantCompress)
? _z.Deflate(_flushMode)
: _z.Inflate(_flushMode);
if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
return 0;
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message));
if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
break; // nothing more to read
}
//while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);
// workitem 8557
// is there more room in output?
if (_z.AvailableBytesOut > 0)
{
if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
{
// deferred
}
// are we completely done reading?
if (nomoreinput)
{
// and in compression?
if (_wantCompress)
{
// no more input data available; therefore we flush to
// try to complete the read
rc = _z.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message));
}
}
}
rc = (count - _z.AvailableBytesOut);
// calculate CRC after reading
if (crc != null)
crc.SlurpBlock(buffer, offset, rc);
return rc;
}
public override System.Boolean CanRead
{
get { return this._stream.CanRead; }
}
public override System.Boolean CanSeek
{
get { return this._stream.CanSeek; }
}
public override System.Boolean CanWrite
{
get { return this._stream.CanWrite; }
}
public override System.Int64 Length
{
get { return _stream.Length; }
}
public override long Position
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
internal enum StreamMode
{
Writer,
Reader,
Undefined,
}
public static void CompressString(String s, Stream compressor)
{
byte[] uncompressed = System.Text.Encoding.UTF8.GetBytes(s);
using (compressor)
{
compressor.Write(uncompressed, 0, uncompressed.Length);
}
}
public static void CompressBuffer(byte[] b, Stream compressor)
{
// workitem 8460
using (compressor)
{
compressor.Write(b, 0, b.Length);
}
}
public static String UncompressString(byte[] compressed, Stream decompressor)
{
// workitem 8460
byte[] working = new byte[1024];
var encoding = System.Text.Encoding.UTF8;
using (var output = new MemoryStream())
{
using (decompressor)
{
int n;
while ((n = decompressor.Read(working, 0, working.Length)) != 0)
{
output.Write(working, 0, n);
}
}
// reset to allow read from start
output.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(output, encoding);
return sr.ReadToEnd();
}
}
public static byte[] UncompressBuffer(byte[] compressed, Stream decompressor)
{
// workitem 8460
byte[] working = new byte[1024];
using (var output = new MemoryStream())
{
using (decompressor)
{
int n;
while ((n = decompressor.Read(working, 0, working.Length)) != 0)
{
output.Write(working, 0, n);
}
}
return output.ToArray();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using Xunit;
public partial class CompareInfoTests
{
[Theory]
[InlineData("")]
[InlineData("en")]
[InlineData("en-US")]
public static void GetCompareInfo(string localeName)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(localeName, ci.Name);
}
[Fact]
public static void GetCompareInfoBadCompareType()
{
Assert.Throws<ArgumentNullException>(() => CompareInfo.GetCompareInfo(null));
}
[Theory]
[MemberData("CompareToData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void Compare(string localeName, string left, string right, int expected, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expected, Math.Sign(ci.Compare(left, right, options)));
if (options == CompareOptions.None)
{
Assert.Equal(expected, Math.Sign(ci.Compare(left, right)));
}
}
[Theory]
[InlineData(null, -1)]
[InlineData("", -1)]
[InlineData("abc", -1)]
[InlineData("abc", 4)]
public static void CompareArgumentOutOfRangeIndex(string badString, int badOffset)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, badString, badOffset));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, "good", 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, badString, badOffset, CompareOptions.None));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, "good", 0, CompareOptions.None));
}
[Theory]
[InlineData(null, 0, -1)]
[InlineData(null, -1, 0)]
[InlineData(null, -1, -1)]
[InlineData("", 0, -1)]
[InlineData("", -1, 0)]
[InlineData("", -1, -1)]
[InlineData("abc", 0, 4)]
[InlineData("abc", 4, 0)]
[InlineData("abc", 0, -1)]
[InlineData("abc", -1, 3)]
[InlineData("abc", 2, 2)]
public static void CompareArgumentOutOfRangeIndexAndCount(string badString, int badOffset, int badCount)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, 4, badString, badOffset, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, badCount, "good", 0, 4));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare("good", 0, 4, badString, badOffset, badCount, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.Compare(badString, badOffset, badCount, "good", 0, 4, CompareOptions.Ordinal));
}
[Fact]
public static void CompareBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.Compare("a", "b", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.Compare("a", "b", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.Compare("a", "b", (CompareOptions)(-1)));
}
[Theory]
[MemberData("IndexOfData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IndexOf(string localeName, string source, string value, int expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.IndexOf(source, value, options));
if (value.Length == 1)
{
Assert.Equal(expectedResult, ci.IndexOf(source, value[0], options));
}
if (options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.IndexOf(source, value));
}
if (value.Length == 1 && options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.IndexOf(source, value[0]));
}
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IndexOfMinusOneCompatability()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
// This behavior was for .NET Framework 1.1 compatability. We early outed for empty source strings
// even with invalid offsets.
Assert.Equal(0, ci.IndexOf("", "", -1, CompareOptions.None));
Assert.Equal(-1, ci.IndexOf("", "a", -1, CompareOptions.None));
}
[Theory]
[InlineData("", 'a', 1)]
[InlineData("abc", 'a', -1)]
[InlineData("abc", 'a', 4)]
public static void IndexOfArgumentOutOfRangeIndex(string source, char value, int badStartIndex)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, value, badStartIndex, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, valueAsString, badStartIndex, CompareOptions.Ordinal));
}
[Theory]
[InlineData("abc", 'a', 0, -1)]
[InlineData("abc", 'a', 0, 4)]
[InlineData("abc", 'a', 2, 2)]
[InlineData("abc", 'a', 4, 0)]
[InlineData("abc", 'a', 4, -1)]
public static void IndexOfArgumentOutOfRangeIndexAndCount(string source, char value, int badStartIndex, int badCount)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, value, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, value, badStartIndex, badCount, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, valueAsString, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.IndexOf(source, valueAsString, badStartIndex, badCount, CompareOptions.Ordinal));
}
[Fact]
public static void IndexOfArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a'));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a"));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', 0, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", 0, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, 0, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', 0, 1));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", 0, 1));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, 0, 1));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, 'a', 0, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf(null, "a", 0, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IndexOf("a", null, 0, 1, CompareOptions.Ordinal));
}
[Fact]
public static void IndexOfBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", (CompareOptions)(-1)));
Assert.Throws<ArgumentException>(() => ci.IndexOf("abc", "a", CompareOptions.StringSort));
}
[Theory]
[MemberData("LastIndexOfData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void LastIndexOf(string localeName, string source, string value, int expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.LastIndexOf(source, value, options));
if (value.Length == 1)
{
Assert.Equal(expectedResult, ci.LastIndexOf(source, value[0], options));
}
if (options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.LastIndexOf(source, value));
}
if (value.Length == 1 && options == CompareOptions.None)
{
Assert.Equal(expectedResult, ci.LastIndexOf(source, value[0]));
}
}
[Theory]
[InlineData("", 'a', 1)]
[InlineData("abc", 'a', -1)]
[InlineData("abc", 'a', 4)]
public static void LastIndexOfArgumentOutOfRangeIndex(string source, char value, int badStartIndex)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, value, badStartIndex, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, valueAsString, badStartIndex, CompareOptions.Ordinal));
}
[Theory]
[InlineData("abc", 'a', 2, -1)]
[InlineData("abc", 'a', 2, 4)]
[InlineData("abc", 'a', 1, 3)]
[InlineData("abc", 'a', 4, 0)]
[InlineData("abc", 'a', 4, -1)]
public static void LastIndexOfArgumentOutOfRangeIndexAndCount(string source, char value, int badStartIndex, int badCount)
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
string valueAsString = value.ToString();
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, value, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, value, badStartIndex, badCount, CompareOptions.Ordinal));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, valueAsString, badStartIndex, badCount));
Assert.Throws<ArgumentOutOfRangeException>(() => ci.LastIndexOf(source, valueAsString, badStartIndex, badCount, CompareOptions.Ordinal));
}
[Fact]
public static void LastIndexOfArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a'));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a"));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', 1, 1));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", 1, 1));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, 1, 1));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, 'a', 1, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf(null, "a", 1, 1, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.LastIndexOf("a", null, 1, 1, CompareOptions.Ordinal));
}
[Fact]
public static void LastIndexOfBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", (CompareOptions)(-1)));
Assert.Throws<ArgumentException>(() => ci.LastIndexOf("abc", "a", CompareOptions.StringSort));
}
[Theory]
[MemberData("IsPrefixData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IsPrefix(string localeName, string source, string prefix, bool expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.IsPrefix(source, prefix, options));
}
[Fact]
public static void IsPrefixBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", CompareOptions.StringSort));
Assert.Throws<ArgumentException>(() => ci.IsPrefix("aaa", "a", (CompareOptions)(-1)));
}
[Fact]
public static void IsPrefixArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, ""));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, "", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix("", null));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix("", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, null));
Assert.Throws<ArgumentNullException>(() => ci.IsPrefix(null, null, CompareOptions.Ordinal));
}
[Theory]
[MemberData("IsSuffixData")]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void IsSuffix(string localeName, string source, string suffix, bool expectedResult, CompareOptions options)
{
CompareInfo ci = CompareInfo.GetCompareInfo(localeName);
Assert.Equal(expectedResult, ci.IsSuffix(source, suffix, options));
}
[Fact]
public static void IsSuffixBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", CompareOptions.Ordinal | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreWidth));
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", CompareOptions.StringSort));
Assert.Throws<ArgumentException>(() => ci.IsSuffix("aaa", "a", (CompareOptions)(-1)));
}
[Fact]
public static void IsSuffixArgumentNullException()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, ""));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, "", CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix("", null));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix("", null, CompareOptions.Ordinal));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, null));
Assert.Throws<ArgumentNullException>(() => ci.IsSuffix(null, null, CompareOptions.Ordinal));
}
[Fact]
public static void EqualsAndHashCode()
{
CompareInfo ciInvariantFromCultureInfo = CultureInfo.InvariantCulture.CompareInfo;
CompareInfo ciInvariantFromFactory = CompareInfo.GetCompareInfo("");
CompareInfo ciEnUs = CompareInfo.GetCompareInfo("en-US");
Assert.True(ciInvariantFromCultureInfo.Equals(ciInvariantFromFactory));
Assert.False(ciEnUs.Equals(ciInvariantFromCultureInfo));
Assert.False(ciEnUs.Equals(new object()));
Assert.Equal(ciInvariantFromCultureInfo.GetHashCode(), ciInvariantFromFactory.GetHashCode());
}
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void GetHashCodeOfString()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Equal("abc".GetHashCode(), ci.GetHashCode("abc", CompareOptions.Ordinal));
Assert.Equal(ci.GetHashCode("abc", CompareOptions.OrdinalIgnoreCase), ci.GetHashCode("ABC", CompareOptions.OrdinalIgnoreCase));
// This behavior of the empty string is specical cased today.
Assert.Equal(0, ci.GetHashCode("", CompareOptions.None));
// Not much we can assert about the hashcode of a string itself, but we can assume that computing it twice yeilds the same value.
int hashCode1 = ci.GetHashCode("abc", CompareOptions.None);
int hashCode2 = ci.GetHashCode("abc", CompareOptions.None);
Assert.Equal(hashCode1, hashCode2);
}
[Fact]
public static void GetHashCodeOfStringNullSource()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentNullException>(() => ci.GetHashCode(null, CompareOptions.None));
}
[Fact]
public static void GetHashCodeOfStringBadCompareOptions()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.Throws<ArgumentException>(() => ci.GetHashCode("", CompareOptions.StringSort));
Assert.Throws<ArgumentException>(() => ci.GetHashCode("", CompareOptions.Ordinal | CompareOptions.IgnoreSymbols));
Assert.Throws<ArgumentException>(() => ci.GetHashCode("", (CompareOptions)(-1)));
}
[Fact]
public static void ToStringReturnsNonNullNonEmpty()
{
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Assert.NotNull(ci.ToString());
Assert.NotEqual("", ci.ToString());
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Collections.ObjectModel
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
[Serializable]
////[DebuggerTypeProxy( typeof( Mscorlib_CollectionDebugView<> ) )]
////[DebuggerDisplay( "Count = {Count}" )]
public class ReadOnlyCollection<T> : IList<T>, IList
{
IList<T> list;
[NonSerialized]
private Object _syncRoot;
public ReadOnlyCollection( IList<T> list )
{
if(list == null)
{
ThrowHelper.ThrowArgumentNullException( ExceptionArgument.list );
}
this.list = list;
}
public int Count
{
get
{
return list.Count;
}
}
public T this[int index]
{
get
{
return list[index];
}
}
public bool Contains( T value )
{
return list.Contains( value );
}
public void CopyTo( T[] array, int index )
{
list.CopyTo( array, index );
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
public int IndexOf( T value )
{
return list.IndexOf( value );
}
protected IList<T> Items
{
get
{
return list;
}
}
bool ICollection<T>.IsReadOnly
{
get
{
return true;
}
}
T IList<T>.this[int index]
{
get
{
return list[index];
}
set
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
}
void ICollection<T>.Add( T value )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
void ICollection<T>.Clear()
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
void IList<T>.Insert( int index, T value )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
bool ICollection<T>.Remove( T value )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
return false;
}
void IList<T>.RemoveAt( int index )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)list).GetEnumerator();
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
if(_syncRoot == null)
{
ICollection c = list as ICollection;
if(c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange( ref _syncRoot, new Object(), null );
}
}
return _syncRoot;
}
}
void ICollection.CopyTo( Array array, int index )
{
if(array == null)
{
ThrowHelper.ThrowArgumentNullException( ExceptionArgument.array );
}
if(array.Rank != 1)
{
ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_RankMultiDimNotSupported );
}
if(array.GetLowerBound( 0 ) != 0)
{
ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_NonZeroLowerBound );
}
if(index < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException( ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum );
}
if(array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException( ExceptionResource.Arg_ArrayPlusOffTooSmall );
}
T[] items = array as T[];
if(items != null)
{
list.CopyTo( items, index );
}
else
{
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof( T );
if(!(targetType.IsAssignableFrom( sourceType ) || sourceType.IsAssignableFrom( targetType )))
{
ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType );
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if(objects == null)
{
ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType );
}
int count = list.Count;
try
{
for(int i = 0; i < count; i++)
{
objects[index++] = list[i];
}
}
catch(ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArrayType );
}
}
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
bool IList.IsReadOnly
{
get
{
return true;
}
}
object IList.this[int index]
{
get
{
return list[index];
}
set
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
}
int IList.Add( object value )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
return -1;
}
void IList.Clear()
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
private static bool IsCompatibleObject( object value )
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default( T ) == null));
}
bool IList.Contains( object value )
{
if(IsCompatibleObject( value ))
{
return Contains( (T)value );
}
return false;
}
int IList.IndexOf( object value )
{
if(IsCompatibleObject( value ))
{
return IndexOf( (T)value );
}
return -1;
}
void IList.Insert( int index, object value )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
void IList.Remove( object value )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
void IList.RemoveAt( int index )
{
ThrowHelper.ThrowNotSupportedException( ExceptionResource.NotSupported_ReadOnlyCollection );
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using SocketHttpListener.Net;
using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse;
using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
namespace SocketHttpListener
{
/// <summary>
/// Provides a set of static methods for the websocket-sharp.
/// </summary>
public static class Ext
{
#region Private Const Fields
private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
#endregion
#region Private Methods
private static MemoryStream compress(this Stream stream)
{
var output = new MemoryStream();
if (stream.Length == 0)
return output;
stream.Position = 0;
using (var ds = new DeflateStream(output, CompressionMode.Compress, true))
{
stream.CopyTo(ds);
//ds.Close(); // "BFINAL" set to 1.
output.Position = 0;
return output;
}
}
private static byte[] decompress(this byte[] value)
{
if (value.Length == 0)
return value;
using (var input = new MemoryStream(value))
{
return input.decompressToArray();
}
}
private static MemoryStream decompress(this Stream stream)
{
var output = new MemoryStream();
if (stream.Length == 0)
return output;
stream.Position = 0;
using (var ds = new DeflateStream(stream, CompressionMode.Decompress, true))
{
ds.CopyTo(output, true);
return output;
}
}
private static byte[] decompressToArray(this Stream stream)
{
using (var decomp = stream.decompress())
{
return decomp.ToArray();
}
}
private static byte[] readBytes(this Stream stream, byte[] buffer, int offset, int length)
{
var len = stream.Read(buffer, offset, length);
if (len < 1)
return buffer.SubArray(0, offset);
var tmp = 0;
while (len < length)
{
tmp = stream.Read(buffer, offset + len, length - len);
if (tmp < 1)
break;
len += tmp;
}
return len < length
? buffer.SubArray(0, offset + len)
: buffer;
}
private static bool readBytes(
this Stream stream, byte[] buffer, int offset, int length, Stream dest)
{
var bytes = stream.readBytes(buffer, offset, length);
var len = bytes.Length;
dest.Write(bytes, 0, len);
return len == offset + length;
}
#endregion
#region Internal Methods
internal static byte[] Append(this ushort code, string reason)
{
using (var buffer = new MemoryStream())
{
var tmp = code.ToByteArrayInternally(ByteOrder.Big);
buffer.Write(tmp, 0, 2);
if (reason != null && reason.Length > 0)
{
tmp = Encoding.UTF8.GetBytes(reason);
buffer.Write(tmp, 0, tmp.Length);
}
return buffer.ToArray();
}
}
internal static string CheckIfClosable(this WebSocketState state)
{
return state == WebSocketState.Closing
? "While closing the WebSocket connection."
: state == WebSocketState.Closed
? "The WebSocket connection has already been closed."
: null;
}
internal static string CheckIfOpen(this WebSocketState state)
{
return state == WebSocketState.Connecting
? "A WebSocket connection isn't established."
: state == WebSocketState.Closing
? "While closing the WebSocket connection."
: state == WebSocketState.Closed
? "The WebSocket connection has already been closed."
: null;
}
internal static string CheckIfValidControlData(this byte[] data, string paramName)
{
return data.Length > 125
? String.Format("'{0}' length must be less.", paramName)
: null;
}
internal static string CheckIfValidSendData(this byte[] data)
{
return data == null
? "'data' must not be null."
: null;
}
internal static string CheckIfValidSendData(this string data)
{
return data == null
? "'data' must not be null."
: null;
}
internal static void Close(this HttpListenerResponse response, HttpStatusCode code)
{
response.StatusCode = (int)code;
response.OutputStream.Close();
}
internal static Stream Compress(this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? stream.compress()
: stream;
}
internal static bool Contains<T>(this IEnumerable<T> source, Func<T, bool> condition)
{
foreach (T elm in source)
if (condition(elm))
return true;
return false;
}
internal static void CopyTo(this Stream src, Stream dest, bool setDefaultPosition)
{
var readLen = 0;
var bufferLen = 256;
var buffer = new byte[bufferLen];
while ((readLen = src.Read(buffer, 0, bufferLen)) > 0)
{
dest.Write(buffer, 0, readLen);
}
if (setDefaultPosition)
dest.Position = 0;
}
internal static byte[] Decompress(this byte[] value, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? value.decompress()
: value;
}
internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? stream.decompressToArray()
: stream.ToByteArray();
}
/// <summary>
/// Determines whether the specified <see cref="int"/> equals the specified <see cref="char"/>,
/// and invokes the specified Action<int> delegate at the same time.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> equals <paramref name="c"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// An <see cref="int"/> to compare.
/// </param>
/// <param name="c">
/// A <see cref="char"/> to compare.
/// </param>
/// <param name="action">
/// An Action<int> delegate that references the method(s) called at
/// the same time as comparing. An <see cref="int"/> parameter to pass to
/// the method(s) is <paramref name="value"/>.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> isn't between 0 and 255.
/// </exception>
internal static bool EqualsWith(this int value, char c, Action<int> action)
{
if (value < 0 || value > 255)
throw new ArgumentOutOfRangeException("value");
action(value);
return value == c - 0;
}
internal static string GetMessage(this CloseStatusCode code)
{
return code == CloseStatusCode.ProtocolError
? "A WebSocket protocol error has occurred."
: code == CloseStatusCode.IncorrectData
? "An incorrect data has been received."
: code == CloseStatusCode.Abnormal
? "An exception has occurred."
: code == CloseStatusCode.InconsistentData
? "An inconsistent data has been received."
: code == CloseStatusCode.PolicyViolation
? "A policy violation has occurred."
: code == CloseStatusCode.TooBig
? "A too big data has been received."
: code == CloseStatusCode.IgnoreExtension
? "WebSocket client did not receive expected extension(s)."
: code == CloseStatusCode.ServerError
? "WebSocket server got an internal error."
: code == CloseStatusCode.TlsHandshakeFailure
? "An error has occurred while handshaking."
: String.Empty;
}
internal static string GetNameInternal(this string nameAndValue, string separator)
{
var i = nameAndValue.IndexOf(separator);
return i > 0
? nameAndValue.Substring(0, i).Trim()
: null;
}
internal static string GetValueInternal(this string nameAndValue, string separator)
{
var i = nameAndValue.IndexOf(separator);
return i >= 0 && i < nameAndValue.Length - 1
? nameAndValue.Substring(i + 1).Trim()
: null;
}
internal static bool IsCompressionExtension(this string value, CompressionMethod method)
{
return value.StartsWith(method.ToExtensionString());
}
internal static bool IsPortNumber(this int value)
{
return value > 0 && value < 65536;
}
internal static bool IsReserved(this ushort code)
{
return code == (ushort)CloseStatusCode.Undefined ||
code == (ushort)CloseStatusCode.NoStatusCode ||
code == (ushort)CloseStatusCode.Abnormal ||
code == (ushort)CloseStatusCode.TlsHandshakeFailure;
}
internal static bool IsReserved(this CloseStatusCode code)
{
return code == CloseStatusCode.Undefined ||
code == CloseStatusCode.NoStatusCode ||
code == CloseStatusCode.Abnormal ||
code == CloseStatusCode.TlsHandshakeFailure;
}
internal static bool IsText(this string value)
{
var len = value.Length;
for (var i = 0; i < len; i++)
{
char c = value[i];
if (c < 0x20 && !"\r\n\t".Contains(c))
return false;
if (c == 0x7f)
return false;
if (c == '\n' && ++i < len)
{
c = value[i];
if (!" \t".Contains(c))
return false;
}
}
return true;
}
internal static bool IsToken(this string value)
{
foreach (char c in value)
if (c < 0x20 || c >= 0x7f || _tspecials.Contains(c))
return false;
return true;
}
internal static string Quote(this string value)
{
return value.IsToken()
? value
: String.Format("\"{0}\"", value.Replace("\"", "\\\""));
}
internal static byte[] ReadBytes(this Stream stream, int length)
{
return stream.readBytes(new byte[length], 0, length);
}
internal static byte[] ReadBytes(this Stream stream, long length, int bufferLength)
{
using (var result = new MemoryStream())
{
var count = length / bufferLength;
var rem = (int)(length % bufferLength);
var buffer = new byte[bufferLength];
var end = false;
for (long i = 0; i < count; i++)
{
if (!stream.readBytes(buffer, 0, bufferLength, result))
{
end = true;
break;
}
}
if (!end && rem > 0)
stream.readBytes(new byte[rem], 0, rem, result);
return result.ToArray();
}
}
internal static async Task<byte[]> ReadBytesAsync(this Stream stream, int length)
{
var buffer = new byte[length];
var len = await stream.ReadAsync(buffer, 0, length).ConfigureAwait(false);
var bytes = len < 1
? new byte[0]
: len < length
? stream.readBytes(buffer, len, length - len)
: buffer;
return bytes;
}
internal static string RemovePrefix(this string value, params string[] prefixes)
{
var i = 0;
foreach (var prefix in prefixes)
{
if (value.StartsWith(prefix))
{
i = prefix.Length;
break;
}
}
return i > 0
? value.Substring(i)
: value;
}
internal static T[] Reverse<T>(this T[] array)
{
var len = array.Length;
T[] reverse = new T[len];
var end = len - 1;
for (var i = 0; i <= end; i++)
reverse[i] = array[end - i];
return reverse;
}
internal static IEnumerable<string> SplitHeaderValue(
this string value, params char[] separator)
{
var len = value.Length;
var separators = new string(separator);
var buffer = new StringBuilder(32);
var quoted = false;
var escaped = false;
char c;
for (var i = 0; i < len; i++)
{
c = value[i];
if (c == '"')
{
if (escaped)
escaped = !escaped;
else
quoted = !quoted;
}
else if (c == '\\')
{
if (i < len - 1 && value[i + 1] == '"')
escaped = true;
}
else if (separators.Contains(c))
{
if (!quoted)
{
yield return buffer.ToString();
buffer.Length = 0;
continue;
}
}
else {
}
buffer.Append(c);
}
if (buffer.Length > 0)
yield return buffer.ToString();
}
internal static byte[] ToByteArray(this Stream stream)
{
using (var output = new MemoryStream())
{
stream.Position = 0;
stream.CopyTo(output);
return output.ToArray();
}
}
internal static byte[] ToByteArrayInternally(this ushort value, ByteOrder order)
{
var bytes = BitConverter.GetBytes(value);
if (!order.IsHostOrder())
Array.Reverse(bytes);
return bytes;
}
internal static byte[] ToByteArrayInternally(this ulong value, ByteOrder order)
{
var bytes = BitConverter.GetBytes(value);
if (!order.IsHostOrder())
Array.Reverse(bytes);
return bytes;
}
internal static string ToExtensionString(
this CompressionMethod method, params string[] parameters)
{
if (method == CompressionMethod.None)
return String.Empty;
var m = String.Format("permessage-{0}", method.ToString().ToLower());
if (parameters == null || parameters.Length == 0)
return m;
return String.Format("{0}; {1}", m, parameters.ToString("; "));
}
internal static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
return new List<TSource>(source);
}
internal static ushort ToUInt16(this byte[] src, ByteOrder srcOrder)
{
return BitConverter.ToUInt16(src.ToHostOrder(srcOrder), 0);
}
internal static ulong ToUInt64(this byte[] src, ByteOrder srcOrder)
{
return BitConverter.ToUInt64(src.ToHostOrder(srcOrder), 0);
}
internal static string TrimEndSlash(this string value)
{
value = value.TrimEnd('/');
return value.Length > 0
? value
: "/";
}
internal static string Unquote(this string value)
{
var start = value.IndexOf('\"');
var end = value.LastIndexOf('\"');
if (start < end)
value = value.Substring(start + 1, end - start - 1).Replace("\\\"", "\"");
return value.Trim();
}
internal static void WriteBytes(this Stream stream, byte[] value)
{
using (var src = new MemoryStream(value))
{
src.CopyTo(stream);
}
}
#endregion
#region Public Methods
/// <summary>
/// Determines whether the specified <see cref="string"/> contains any of characters
/// in the specified array of <see cref="char"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> contains any of <paramref name="chars"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to test.
/// </param>
/// <param name="chars">
/// An array of <see cref="char"/> that contains characters to find.
/// </param>
public static bool Contains(this string value, params char[] chars)
{
return chars == null || chars.Length == 0
? true
: value == null || value.Length == 0
? false
: value.IndexOfAny(chars) != -1;
}
/// <summary>
/// Determines whether the specified <see cref="NameValueCollection"/> contains the entry
/// with the specified <paramref name="name"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="collection"/> contains the entry
/// with <paramref name="name"/>; otherwise, <c>false</c>.
/// </returns>
/// <param name="collection">
/// A <see cref="NameValueCollection"/> to test.
/// </param>
/// <param name="name">
/// A <see cref="string"/> that represents the key of the entry to find.
/// </param>
public static bool Contains(this NameValueCollection collection, string name)
{
return collection == null || collection.Count == 0
? false
: collection[name] != null;
}
/// <summary>
/// Determines whether the specified <see cref="NameValueCollection"/> contains the entry
/// with the specified both <paramref name="name"/> and <paramref name="value"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="collection"/> contains the entry
/// with both <paramref name="name"/> and <paramref name="value"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="collection">
/// A <see cref="NameValueCollection"/> to test.
/// </param>
/// <param name="name">
/// A <see cref="string"/> that represents the key of the entry to find.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the entry to find.
/// </param>
public static bool Contains(this NameValueCollection collection, string name, string value)
{
if (collection == null || collection.Count == 0)
return false;
var values = collection[name];
if (values == null)
return false;
foreach (var v in values.Split(','))
if (v.Trim().Equals(value, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>
/// Emits the specified <see cref="EventHandler"/> delegate if it isn't <see langword="null"/>.
/// </summary>
/// <param name="eventHandler">
/// A <see cref="EventHandler"/> to emit.
/// </param>
/// <param name="sender">
/// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
/// </param>
/// <param name="e">
/// A <see cref="EventArgs"/> that contains no event data.
/// </param>
public static void Emit(this EventHandler eventHandler, object sender, EventArgs e)
{
if (eventHandler != null)
eventHandler(sender, e);
}
/// <summary>
/// Emits the specified <c>EventHandler<TEventArgs></c> delegate
/// if it isn't <see langword="null"/>.
/// </summary>
/// <param name="eventHandler">
/// An <c>EventHandler<TEventArgs></c> to emit.
/// </param>
/// <param name="sender">
/// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
/// </param>
/// <param name="e">
/// A <c>TEventArgs</c> that represents the event data.
/// </param>
/// <typeparam name="TEventArgs">
/// The type of the event data generated by the event.
/// </typeparam>
public static void Emit<TEventArgs>(
this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e)
where TEventArgs : EventArgs
{
if (eventHandler != null)
eventHandler(sender, e);
}
/// <summary>
/// Gets the collection of the HTTP cookies from the specified HTTP <paramref name="headers"/>.
/// </summary>
/// <returns>
/// A <see cref="CookieCollection"/> that receives a collection of the HTTP cookies.
/// </returns>
/// <param name="headers">
/// A <see cref="NameValueCollection"/> that contains a collection of the HTTP headers.
/// </param>
/// <param name="response">
/// <c>true</c> if <paramref name="headers"/> is a collection of the response headers;
/// otherwise, <c>false</c>.
/// </param>
public static CookieCollection GetCookies(this NameValueCollection headers, bool response)
{
var name = response ? "Set-Cookie" : "Cookie";
return headers == null || !headers.Contains(name)
? new CookieCollection()
: CookieHelper.Parse(headers[name], response);
}
/// <summary>
/// Gets the description of the specified HTTP status <paramref name="code"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the description of the HTTP status code.
/// </returns>
/// <param name="code">
/// One of <see cref="HttpStatusCode"/> enum values, indicates the HTTP status codes.
/// </param>
public static string GetDescription(this HttpStatusCode code)
{
return ((int)code).GetStatusDescription();
}
/// <summary>
/// Gets the name from the specified <see cref="string"/> that contains a pair of name and
/// value separated by a separator string.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the name if any; otherwise, <c>null</c>.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// string.
/// </param>
/// <param name="separator">
/// A <see cref="string"/> that represents a separator string.
/// </param>
public static string GetName(this string nameAndValue, string separator)
{
return (nameAndValue != null && nameAndValue.Length > 0) &&
(separator != null && separator.Length > 0)
? nameAndValue.GetNameInternal(separator)
: null;
}
/// <summary>
/// Gets the name and value from the specified <see cref="string"/> that contains a pair of
/// name and value separated by a separator string.
/// </summary>
/// <returns>
/// A <c>KeyValuePair<string, string></c> that represents the name and value if any.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// string.
/// </param>
/// <param name="separator">
/// A <see cref="string"/> that represents a separator string.
/// </param>
public static KeyValuePair<string, string> GetNameAndValue(
this string nameAndValue, string separator)
{
var name = nameAndValue.GetName(separator);
var value = nameAndValue.GetValue(separator);
return name != null
? new KeyValuePair<string, string>(name, value)
: new KeyValuePair<string, string>(null, null);
}
/// <summary>
/// Gets the description of the specified HTTP status <paramref name="code"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the description of the HTTP status code.
/// </returns>
/// <param name="code">
/// An <see cref="int"/> that represents the HTTP status code.
/// </param>
public static string GetStatusDescription(this int code)
{
switch (code)
{
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status";
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 409: return "Conflict";
case 410: return "Gone";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Request Entity Too Large";
case 414: return "Request-Uri Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Requested Range Not Satisfiable";
case 417: return "Expectation Failed";
case 422: return "Unprocessable Entity";
case 423: return "Locked";
case 424: return "Failed Dependency";
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "Http Version Not Supported";
case 507: return "Insufficient Storage";
}
return String.Empty;
}
/// <summary>
/// Gets the value from the specified <see cref="string"/> that contains a pair of name and
/// value separated by a separator string.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the value if any; otherwise, <c>null</c>.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// string.
/// </param>
/// <param name="separator">
/// A <see cref="string"/> that represents a separator string.
/// </param>
public static string GetValue(this string nameAndValue, string separator)
{
return (nameAndValue != null && nameAndValue.Length > 0) &&
(separator != null && separator.Length > 0)
? nameAndValue.GetValueInternal(separator)
: null;
}
/// <summary>
/// Determines whether the specified <see cref="ByteOrder"/> is host
/// (this computer architecture) byte order.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="order"/> is host byte order;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="order">
/// One of the <see cref="ByteOrder"/> enum values, to test.
/// </param>
public static bool IsHostOrder(this ByteOrder order)
{
// true : !(true ^ true) or !(false ^ false)
// false: !(true ^ false) or !(false ^ true)
return !(BitConverter.IsLittleEndian ^ (order == ByteOrder.Little));
}
/// <summary>
/// Determines whether the specified <see cref="string"/> is a predefined scheme.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> is a predefined scheme; otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to test.
/// </param>
public static bool IsPredefinedScheme(this string value)
{
if (value == null || value.Length < 2)
return false;
var c = value[0];
if (c == 'h')
return value == "http" || value == "https";
if (c == 'w')
return value == "ws" || value == "wss";
if (c == 'f')
return value == "file" || value == "ftp";
if (c == 'n')
{
c = value[1];
return c == 'e'
? value == "news" || value == "net.pipe" || value == "net.tcp"
: value == "nntp";
}
return (c == 'g' && value == "gopher") || (c == 'm' && value == "mailto");
}
/// <summary>
/// Determines whether the specified <see cref="string"/> is a URI string.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> may be a URI string; otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to test.
/// </param>
public static bool MaybeUri(this string value)
{
if (value == null || value.Length == 0)
return false;
var i = value.IndexOf(':');
if (i == -1)
return false;
if (i >= 10)
return false;
return value.Substring(0, i).IsPredefinedScheme();
}
/// <summary>
/// Retrieves a sub-array from the specified <paramref name="array"/>.
/// A sub-array starts at the specified element position.
/// </summary>
/// <returns>
/// An array of T that receives a sub-array, or an empty array of T if any problems
/// with the parameters.
/// </returns>
/// <param name="array">
/// An array of T that contains the data to retrieve a sub-array.
/// </param>
/// <param name="startIndex">
/// An <see cref="int"/> that contains the zero-based starting position of a sub-array
/// in <paramref name="array"/>.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of elements to retrieve a sub-array.
/// </param>
/// <typeparam name="T">
/// The type of elements in the <paramref name="array"/>.
/// </typeparam>
public static T[] SubArray<T>(this T[] array, int startIndex, int length)
{
if (array == null || array.Length == 0)
return new T[0];
if (startIndex < 0 || length <= 0)
return new T[0];
if (startIndex + length > array.Length)
return new T[0];
if (startIndex == 0 && array.Length == length)
return array;
T[] subArray = new T[length];
Array.Copy(array, startIndex, subArray, 0, length);
return subArray;
}
/// <summary>
/// Converts the order of the specified array of <see cref="byte"/> to the host byte order.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> converted from <paramref name="src"/>.
/// </returns>
/// <param name="src">
/// An array of <see cref="byte"/> to convert.
/// </param>
/// <param name="srcOrder">
/// One of the <see cref="ByteOrder"/> enum values, indicates the byte order of
/// <paramref name="src"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="src"/> is <see langword="null"/>.
/// </exception>
public static byte[] ToHostOrder(this byte[] src, ByteOrder srcOrder)
{
if (src == null)
throw new ArgumentNullException("src");
return src.Length > 1 && !srcOrder.IsHostOrder()
? src.Reverse()
: src;
}
/// <summary>
/// Converts the specified <paramref name="array"/> to a <see cref="string"/> that
/// concatenates the each element of <paramref name="array"/> across the specified
/// <paramref name="separator"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> converted from <paramref name="array"/>,
/// or <see cref="String.Empty"/> if <paramref name="array"/> is empty.
/// </returns>
/// <param name="array">
/// An array of T to convert.
/// </param>
/// <param name="separator">
/// A <see cref="string"/> that represents the separator string.
/// </param>
/// <typeparam name="T">
/// The type of elements in <paramref name="array"/>.
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
public static string ToString<T>(this T[] array, string separator)
{
if (array == null)
throw new ArgumentNullException("array");
var len = array.Length;
if (len == 0)
return String.Empty;
if (separator == null)
separator = String.Empty;
var buff = new StringBuilder(64);
(len - 1).Times(i => buff.AppendFormat("{0}{1}", array[i].ToString(), separator));
buff.Append(array[len - 1].ToString());
return buff.ToString();
}
/// <summary>
/// Executes the specified <c>Action<int></c> delegate <paramref name="n"/> times.
/// </summary>
/// <param name="n">
/// An <see cref="int"/> is the number of times to execute.
/// </param>
/// <param name="action">
/// An <c>Action<int></c> delegate that references the method(s) to execute.
/// An <see cref="int"/> parameter to pass to the method(s) is the zero-based count of
/// iteration.
/// </param>
public static void Times(this int n, Action<int> action)
{
if (n > 0 && action != null)
for (int i = 0; i < n; i++)
action(i);
}
/// <summary>
/// Converts the specified <see cref="string"/> to a <see cref="Uri"/>.
/// </summary>
/// <returns>
/// A <see cref="Uri"/> converted from <paramref name="uriString"/>, or <see langword="null"/>
/// if <paramref name="uriString"/> isn't successfully converted.
/// </returns>
/// <param name="uriString">
/// A <see cref="string"/> to convert.
/// </param>
public static Uri ToUri(this string uriString)
{
Uri res;
return Uri.TryCreate(
uriString, uriString.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out res)
? res
: null;
}
/// <summary>
/// URL-decodes the specified <see cref="string"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the decoded string, or the <paramref name="value"/>
/// if it's <see langword="null"/> or empty.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to decode.
/// </param>
public static string UrlDecode(this string value)
{
return value == null || value.Length == 0
? value
: WebUtility.UrlDecode(value);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Manatee.Trello.Internal.Caching;
using Manatee.Trello.Internal.DataAccess;
using Manatee.Trello.Internal.Validation;
using Manatee.Trello.Json;
namespace Manatee.Trello.Internal.Synchronization
{
internal class OrganizationContext : DeletableSynchronizationContext<IJsonOrganization>
{
private static readonly Dictionary<string, object> Parameters;
private static readonly Organization.Fields MemberFields;
public static Dictionary<string, object> CurrentParameters
{
get
{
lock (Parameters)
{
if (!Parameters.Any())
GenerateParameters();
return new Dictionary<string, object>(Parameters);
}
}
}
public ReadOnlyActionCollection Actions { get; }
public BoardCollection Boards { get; }
public ReadOnlyMemberCollection Members { get; }
public OrganizationMembershipCollection Memberships { get; }
public ReadOnlyPowerUpDataCollection PowerUpData { get; }
public OrganizationPreferencesContext OrganizationPreferencesContext { get; }
public virtual bool HasValidId => IdRule.Instance.Validate(Data.Id, null) == null;
static OrganizationContext()
{
Parameters = new Dictionary<string, object>();
MemberFields = Organization.Fields.Description |
Organization.Fields.DisplayName |
Organization.Fields.LogoHash |
Organization.Fields.Name |
Organization.Fields.Preferences |
Organization.Fields.Url |
Organization.Fields.Website;
Properties = new Dictionary<string, Property<IJsonOrganization>>
{
{
nameof(Organization.Description),
new Property<IJsonOrganization, string>((d, a) => d.Desc, (d, o) => d.Desc = o)
},
{
nameof(Organization.DisplayName),
new Property<IJsonOrganization, string>((d, a) => d.DisplayName, (d, o) => d.DisplayName = o)
},
{
nameof(Organization.Id),
new Property<IJsonOrganization, string>((d, a) => d.Id, (d, o) => d.Id = o)
},
{
nameof(Organization.IsBusinessClass),
new Property<IJsonOrganization, bool?>((d, a) => d.PaidAccount, (d, o) => d.PaidAccount = o)
},
{
nameof(Organization.Name),
new Property<IJsonOrganization, string>((d, a) => d.Name, (d, o) => d.Name = o)
},
{
nameof(Organization.Preferences),
new Property<IJsonOrganization, IJsonOrganizationPreferences>((d, a) => d.Prefs, (d, o) => d.Prefs = o)
},
{
nameof(Organization.Url),
new Property<IJsonOrganization, string>((d, a) => d.Url, (d, o) => d.Url = o)
},
{
nameof(Organization.Website),
new Property<IJsonOrganization, string>((d, a) => d.Website, (d, o) => d.Website = o)
},
{
nameof(IJsonOrganization.ValidForMerge),
new Property<IJsonOrganization, bool>((d, a) => d.ValidForMerge, (d, o) => d.ValidForMerge = o, true)
},
};
}
public OrganizationContext(string id, TrelloAuthorization auth)
: base(auth)
{
Data.Id = id;
Actions = new ReadOnlyActionCollection(typeof(Organization), () => Data.Id, auth);
Actions.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Actions)});
Boards = new BoardCollection(typeof(Organization), () => Data.Id, auth);
Boards.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Boards)});
Members = new ReadOnlyMemberCollection(EntityRequestType.Organization_Read_Members, () => Data.Id, auth);
Members.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Members)});
Memberships = new OrganizationMembershipCollection(() => Data.Id, auth);
Memberships.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Memberships)});
PowerUpData = new ReadOnlyPowerUpDataCollection(EntityRequestType.Organization_Read_PowerUpData, () => Data.Id, auth);
PowerUpData.Refreshed += (s, e) => OnMerged(new List<string> {nameof(PowerUpData)});
OrganizationPreferencesContext = new OrganizationPreferencesContext(Auth);
OrganizationPreferencesContext.SubmitRequested += ct => HandleSubmitRequested("Preferences", ct);
Data.Prefs = OrganizationPreferencesContext.Data;
}
public static void UpdateParameters()
{
lock (Parameters)
{
Parameters.Clear();
}
}
private static void GenerateParameters()
{
lock (Parameters)
{
Parameters.Clear();
var flags = Enum.GetValues(typeof(Organization.Fields)).Cast<Organization.Fields>().ToList();
var availableFields = (Organization.Fields)flags.Cast<int>().Sum();
var memberFields = availableFields & MemberFields & Organization.DownloadedFields;
Parameters["fields"] = memberFields.GetDescription();
var parameterFields = availableFields & Organization.DownloadedFields & (~MemberFields);
if (parameterFields.HasFlag(Organization.Fields.Actions))
{
Parameters["actions"] = "all";
Parameters["actions_format"] = "list";
}
if (parameterFields.HasFlag(Organization.Fields.Boards))
{
Parameters["boards"] = "open";
Parameters["board_fields"] = BoardContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Organization.Fields.Members))
{
Parameters["members"] = "all";
Parameters["member_fields"] = MemberContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Organization.Fields.Memberships))
{
Parameters["memberships"] = "all";
Parameters["memberships_member"] = "true";
Parameters["membership_member_fields"] = MemberContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Organization.Fields.PowerUpData))
Parameters["pluginData"] = "true";
}
}
public override Endpoint GetRefreshEndpoint()
{
return EndpointFactory.Build(EntityRequestType.Organization_Read_Refresh,
new Dictionary<string, object> {{"_id", Data.Id}});
}
protected override Dictionary<string, object> GetParameters()
{
return CurrentParameters;
}
protected override Endpoint GetDeleteEndpoint()
{
return EndpointFactory.Build(EntityRequestType.Organization_Write_Delete,
new Dictionary<string, object> {{"_id", Data.Id}});
}
protected override async Task SubmitData(IJsonOrganization json, CancellationToken ct)
{
var endpoint = EndpointFactory.Build(EntityRequestType.Organization_Write_Update, new Dictionary<string, object> {{"_id", Data.Id}});
var newData = await JsonRepository.Execute(Auth, endpoint, json, ct);
Merge(newData);
}
protected override void ApplyDependentChanges(IJsonOrganization json)
{
if (OrganizationPreferencesContext.HasChanges)
{
json.Prefs = OrganizationPreferencesContext.GetChanges();
OrganizationPreferencesContext.ClearChanges();
}
}
protected override IEnumerable<string> MergeDependencies(IJsonOrganization json, bool overwrite)
{
var properties = OrganizationPreferencesContext.Merge(json.Prefs, overwrite)
.Select(p => $"{nameof(Organization.Preferences)}.{p}")
.ToList();
if (json.Actions != null)
{
Actions.Update(json.Actions.Select(a => a.GetFromCache<Action, IJsonAction>(Auth, overwrite)));
properties.Add(nameof(Organization.Actions));
}
if (json.Boards != null)
{
Boards.Update(json.Boards.Select(a => a.GetFromCache<Board, IJsonBoard>(Auth, overwrite)));
properties.Add(nameof(Organization.Boards));
}
if (json.Members != null)
{
Members.Update(json.Members.Select(a => a.GetFromCache<Member, IJsonMember>(Auth, overwrite)));
properties.Add(nameof(Organization.Members));
}
if (json.Memberships != null)
{
Memberships.Update(json.Memberships.Select(a => a.TryGetFromCache<OrganizationMembership, IJsonOrganizationMembership>(overwrite) ??
new OrganizationMembership(a, Data.Id, Auth)));
properties.Add(nameof(Organization.Memberships));
}
if (json.PowerUpData != null)
{
PowerUpData.Update(json.PowerUpData.Select(a => a.GetFromCache<PowerUpData, IJsonPowerUpData>(Auth, overwrite)));
properties.Add(nameof(Organization.PowerUpData));
}
return properties;
}
}
}
| |
using System;
using KabMan.Data;
using DevExpress.XtraGrid.Views.Grid;
using System.Windows.Forms;
using System.Data;
using DevExpress.XtraEditors;
namespace KabMan.Forms
{
public partial class DasdDetailManagerForm : DevExpress.XtraEditors.XtraForm
{
#region Properties
private object _DasdID = null;
/// <summary>
/// Gets Rack ID which associated to this form
/// </summary>
public long DasdID
{
get
{
if (_DasdID != null)
{
return Convert.ToInt64(this._DasdID);
}
return 0;
}
}
private object _SanGroupId;
public long SanGroupId
{
get
{
if (_SanGroupId != null)
{
return Convert.ToInt64(this._SanGroupId);
}
return 0;
}
}
#endregion
#region Constructor
public DasdDetailManagerForm()
{
InitializeComponent();
}
public DasdDetailManagerForm(object argRackID, Int64 sanGroupId)
{
this._DasdID = argRackID;
this._SanGroupId = sanGroupId;
InitializeComponent();
}
public DasdDetailManagerForm(object argRackID, string text, Int64 sanGroupId)
{
this._DasdID = argRackID;
this._SanGroupId = sanGroupId;
InitializeComponent();
this.Text = text;
}
#endregion
private void setVTPortRepositoryDataSource()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.VTPort_For_Dasd_BySanGroupId, new object[] { "@SanGroupId", SanGroupId });
repVtPortSan1.DataSource = ds.Tables[0];
repVtPortSan2.DataSource = ds.Tables[1];
}
private void setBlechRepositoryDataSource()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.Blech_For_Dasd, new object[] { });
repBlechSan1.DataSource = ds.Tables[0];
repBlechSan2.DataSource = ds.Tables[0];
}
private void setLcUrmRepositoryDataSource()
{
DataSet ds = DBAssistant.ExecProcedure(sproc.Cable_Select_Available_LcUrm_For_Dasd_BySanGroupId, new object[] { "@DasdID", this.DasdID, "@SanGroupId", this.SanGroupId });
repLcUrmSan1.DataSource = ds.Tables[0];
repLcUrmSan2.DataSource = ds.Tables[1];
}
private void DasdDetailManagerForm_Load(object sender, EventArgs e)
{
if (this.DasdID > 0)
{
DataSet dsMain = DBAssistant.ExecProcedure(sproc.DASDDetail_Select_BySanGroupId, new object[] { "@DASDID", this.DasdID, "@SanGroupId", this.SanGroupId });
CSan1Grid.DataSource = dsMain.Tables[0];
CSan2Grid.DataSource = dsMain.Tables[1];
setVTPortRepositoryDataSource();
setBlechRepositoryDataSource();
setLcUrmRepositoryDataSource();
}
}
private void CSan1View_ShownEditor(object sender, EventArgs e)
{
GridView gridView = sender as GridView;
if (gridView.FocusedColumn == gridColumn2 || gridView.FocusedColumn == gridColumn4 || gridView.FocusedColumn == gridColumn7)
if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.No)
gridView.CloseEditor();
else
{
if (gridView.ActiveEditor != null)
gridView.ActiveEditor.SelectAll();
}
}
private void CSan2View_ShownEditor(object sender, EventArgs e)
{
GridView gridView = sender as GridView;
if (gridView.FocusedColumn == gridColumn9 || gridView.FocusedColumn == gridColumn12 || gridView.FocusedColumn == gridColumn10)
if (XtraMessageBox.Show("Do you wish to edit this row?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.No)
gridView.CloseEditor();
else
{
if (gridView.ActiveEditor != null)
gridView.ActiveEditor.SelectAll();
}
}
private void repVtPortSan1_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repVtPortSan1.DataSource).DefaultView;
view.RowFilter = "VTPortId=" + CSan1View.GetFocusedRowCellValue("VTPortId").ToString();
}
private void repVtPortSan1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repVtPortSan1.DataSource).DefaultView;
view.RowFilter = "" ;
}
private void repVtPortSan2_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repVtPortSan2.DataSource).DefaultView;
view.RowFilter = "VTPortId=" + CSan2View.GetFocusedRowCellValue("VTPortId").ToString();
}
private void repVtPortSan2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repVtPortSan2.DataSource).DefaultView;
view.RowFilter = "" ;
}
private void repBlechSan1_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repBlechSan1.DataSource).DefaultView;
view.RowFilter = "BlechId=" + CSan1View.GetFocusedRowCellValue("BlechId").ToString();
}
private void repBlechSan1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repBlechSan1.DataSource).DefaultView;
view.RowFilter = "";
}
private void repBlechSan2_Popup(object sender, EventArgs e)
{
DataView view = ((DataTable)repBlechSan2.DataSource).DefaultView;
view.RowFilter = "BlechId=" + CSan2View.GetFocusedRowCellValue("BlechId").ToString();
}
private void repBlechSan2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView view = ((DataTable)repBlechSan2.DataSource).DefaultView;
view.RowFilter = "";
}
private void repLcUrmSan1_Popup(object sender, EventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan1.DataSource).DefaultView;
dv.RowFilter = "Connected = 'False'";
}
private void repLcUrmSan1_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan1.DataSource).DefaultView;
dv.RowFilter = "";
}
private void repLcUrmSan2_Popup(object sender, EventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan2.DataSource).DefaultView;
dv.RowFilter = "Connected = 'False'";
}
private void repLcUrmSan2_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
{
DataView dv = ((DataTable)repLcUrmSan2.DataSource).DefaultView;
dv.RowFilter = "";
}
private void CSan1View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column == gridColumn2)
{
DBAssistant.ExecProcedure(sproc.DasdDetail_Update_LcUrm, new object[] { "@LcUrmID", e.Value, "@ID", CSan1View.GetRowCellValue(e.RowHandle, "ID") });
setLcUrmRepositoryDataSource();
}
else if (e.Column == gridColumn4)
{
string typeName = "VTPort";
object dasdDetailId = CSan1View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
DBAssistant.ExecProcedure(sproc.DasdDetail_Blech_VTPort_Update, new object[] { "@DasdDetailID", dasdDetailId, "@TypeName", typeName, "@NewObjectId", newVtPortId });
setVTPortRepositoryDataSource();
}
else if (e.Column == gridColumn7)
{
string typeName = "Blech";
object dasdDetailId = CSan1View.GetRowCellValue(e.RowHandle, "ID");
object newBlechId = e.Value;
DBAssistant.ExecProcedure(sproc.DasdDetail_Blech_VTPort_Update, new object[] { "@DasdDetailID", dasdDetailId, "@TypeName", typeName, "@NewObjectId", newBlechId });
setBlechRepositoryDataSource();
}
}
private void CSan2View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column == gridColumn9)
{
DBAssistant.ExecProcedure(sproc.DasdDetail_Update_LcUrm, new object[] { "@LcUrmID", e.Value, "@ID", CSan2View.GetRowCellValue(e.RowHandle, "ID") });
setLcUrmRepositoryDataSource();
}
else if (e.Column == gridColumn12)
{
string typeName = "VTPort";
object dasdDetailId = CSan2View.GetRowCellValue(e.RowHandle, "ID");
object newVtPortId = e.Value;
DBAssistant.ExecProcedure(sproc.DasdDetail_Blech_VTPort_Update, new object[] { "@DasdDetailID", dasdDetailId, "@TypeName", typeName, "@NewObjectId", newVtPortId });
setVTPortRepositoryDataSource();
}
else if (e.Column == gridColumn10)
{
string typeName = "Blech";
object dasdDetailId = CSan2View.GetRowCellValue(e.RowHandle, "ID");
object newBlechId = e.Value;
DBAssistant.ExecProcedure(sproc.DasdDetail_Blech_VTPort_Update, new object[] { "@DasdDetailID", dasdDetailId, "@TypeName", typeName, "@NewObjectId", newBlechId });
setBlechRepositoryDataSource();
}
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Text;
using Xunit;
public partial class ConsoleEncoding : RemoteExecutorTestBase
{
public static IEnumerable<object[]> InputData()
{
yield return new object[] { "This is Ascii string" };
yield return new object[] { "This is string have surrogates \uD800\uDC00" };
yield return new object[] { "This string has non ascii characters \u03b1\u00df\u0393\u03c0\u03a3\u03c3\u00b5" };
yield return new object[] { "This string has invalid surrogates \uD800\uD800\uD800\uD800\uD800\uD800" };
yield return new object[] { "\uD800" };
}
[Theory]
[ActiveIssue("https://github.com/dotnet/corefx/issues/18220", TargetFrameworkMonikers.UapAot)]
[MemberData(nameof(InputData))]
public void TestEncoding(string inputString)
{
TextWriter outConsoleStream = Console.Out;
TextReader inConsoleStream = Console.In;
try
{
byte [] inputBytes;
byte [] inputBytesNoBom = Console.OutputEncoding.GetBytes(inputString);
byte [] bom = Console.OutputEncoding.GetPreamble();
if (bom.Length > 0)
{
inputBytes = new byte[inputBytesNoBom.Length + bom.Length];
Array.Copy(bom, inputBytes, bom.Length);
Array.Copy(inputBytesNoBom, 0, inputBytes, bom.Length, inputBytesNoBom.Length);
}
else
{
inputBytes = inputBytesNoBom;
}
byte[] outBytes = new byte[inputBytes.Length];
using (MemoryStream ms = new MemoryStream(outBytes, true))
{
using (StreamWriter sw = new StreamWriter(ms, Console.OutputEncoding))
{
Console.SetOut(sw);
Console.Write(inputString);
}
}
Assert.Equal(inputBytes, outBytes);
string inString = new String(Console.InputEncoding.GetChars(inputBytesNoBom));
string outString;
using (MemoryStream ms = new MemoryStream(inputBytesNoBom, false))
{
using (StreamReader sr = new StreamReader(ms, Console.InputEncoding))
{
Console.SetIn(sr);
outString = Console.In.ReadToEnd();
}
}
Assert.True(inString.Equals(outString), $"Encoding: {Console.InputEncoding}, Codepage: {Console.InputEncoding.CodePage}, Expected: {inString}, Actual: {outString} ");
}
finally
{
Console.SetOut(outConsoleStream);
Console.SetIn(inConsoleStream);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "https://github.com/dotnet/corefx/issues/21483")]
public void TestValidEncodings()
{
Action<Encoding> check = encoding =>
{
Console.OutputEncoding = encoding;
Assert.Equal(encoding, Console.OutputEncoding);
Console.InputEncoding = encoding;
Assert.Equal(encoding, Console.InputEncoding);
};
// These seem to always be available
check(Encoding.UTF8);
check(Encoding.Unicode);
// On full Windows, ASCII is available also
if (!PlatformDetection.IsWindowsNanoServer)
{
check(Encoding.ASCII);
}
}
public class NonexistentCodePageEncoding : Encoding
{
public override int CodePage => int.MinValue;
public override int GetByteCount(char[] chars, int index, int count) => 0;
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => 0;
public override int GetCharCount(byte[] bytes, int index, int count) => 0;
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => 0;
public override int GetMaxByteCount(int charCount) => 0;
public override int GetMaxCharCount(int byteCount) => 0;
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corefx/issues/18220", TargetFrameworkMonikers.UapAot)]
public void InputEncoding_SetWithInInitialized_ResetsIn()
{
RemoteInvoke(() =>
{
// Initialize Console.In
TextReader inReader = Console.In;
Assert.NotNull(inReader);
Assert.Same(inReader, Console.In);
// Change the InputEncoding
Console.InputEncoding = Encoding.Unicode; // Not ASCII: not supported by Windows Nano
Assert.Equal(Encoding.Unicode, Console.InputEncoding);
if (PlatformDetection.IsWindows)
{
// Console.set_InputEncoding is effectively a nop on Unix,
// so although the reader accessed by Console.In will be reset,
// it'll be re-initialized on re-access to the same singleton,
// (assuming input isn't redirected).
Assert.NotSame(inReader, Console.In);
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void InputEncoding_SetNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Console.InputEncoding = null);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void InputEncoding_SetEncodingWithInvalidCodePage_ThrowsIOException()
{
NonexistentCodePageEncoding invalidEncoding = new NonexistentCodePageEncoding();
Assert.Throws<IOException>(() => Console.InputEncoding = invalidEncoding);
Assert.NotSame(invalidEncoding, Console.InputEncoding);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corefx/issues/18220", TargetFrameworkMonikers.UapAot)]
public void OutputEncoding_SetWithErrorAndOutputInitialized_ResetsErrorAndOutput()
{
RemoteInvoke(() =>
{
// Initialize Console.Error
TextWriter errorWriter = Console.Error;
Assert.NotNull(errorWriter);
Assert.Same(errorWriter, Console.Error);
// Initialize Console.Out
TextWriter outWriter = Console.Out;
Assert.NotNull(outWriter);
Assert.Same(outWriter, Console.Out);
// Change the OutputEncoding
Console.OutputEncoding = Encoding.Unicode; // Not ASCII: not supported by Windows Nano
Assert.Equal(Encoding.Unicode, Console.OutputEncoding);
Assert.NotSame(errorWriter, Console.Error);
Assert.NotSame(outWriter, Console.Out);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void OutputEncoding_SetNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Console.OutputEncoding = null);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/corefx/issues/18220", TargetFrameworkMonikers.UapAot)]
[PlatformSpecific(TestPlatforms.Windows)]
public void OutputEncoding_SetEncodingWithInvalidCodePage_ThrowsIOException()
{
NonexistentCodePageEncoding invalidEncoding = new NonexistentCodePageEncoding();
Assert.Throws<IOException>(() => Console.OutputEncoding = invalidEncoding);
Assert.NotSame(invalidEncoding, Console.OutputEncoding);
}
}
| |
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MessagePack.LZ4;
using Nerdbank.Streams;
namespace MessagePack
{
/// <summary>
/// High-Level API of MessagePack for C#.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Each overload has sufficiently unique required parameters.")]
public static partial class MessagePackSerializer
{
private const int LZ4NotCompressionSizeInLz4BlockType = 64;
private const int MaxHintSize = 1024 * 1024;
/// <summary>
/// Gets or sets the default set of options to use when not explicitly specified for a method call.
/// </summary>
/// <value>The default value is <see cref="MessagePackSerializerOptions.Standard"/>.</value>
/// <remarks>
/// This is an AppDomain or process-wide setting.
/// If you're writing a library, you should NOT set or rely on this property but should instead pass
/// in <see cref="MessagePackSerializerOptions.Standard"/> (or the required options) explicitly to every method call
/// to guarantee appropriate behavior in any application.
/// If you are an app author, realize that setting this property impacts the entire application so it should only be
/// set once, and before any use of <see cref="MessagePackSerializer"/> occurs.
/// </remarks>
public static MessagePackSerializerOptions DefaultOptions { get; set; } = MessagePackSerializerOptions.Standard;
/// <summary>
/// A thread-local, recyclable array that may be used for short bursts of code.
/// </summary>
[ThreadStatic]
private static byte[] scratchArray;
/// <summary>
/// Serializes a given value with the specified buffer writer.
/// </summary>
/// <param name="writer">The buffer writer to serialize with.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static void Serialize<T>(IBufferWriter<byte> writer, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
var fastWriter = new MessagePackWriter(writer)
{
CancellationToken = cancellationToken,
};
Serialize(ref fastWriter, value, options);
fastWriter.Flush();
}
/// <summary>
/// Serializes a given value with the specified buffer writer.
/// </summary>
/// <param name="writer">The buffer writer to serialize with.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static void Serialize<T>(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options = null)
{
options = options ?? DefaultOptions;
bool originalOldSpecValue = writer.OldSpec;
if (options.OldSpec.HasValue)
{
writer.OldSpec = options.OldSpec.Value;
}
try
{
if (options.Compression.IsCompression() && !PrimitiveChecker<T>.IsMessagePackFixedSizePrimitive)
{
using (var scratchRental = SequencePool.Shared.Rent())
{
var scratch = scratchRental.Value;
MessagePackWriter scratchWriter = writer.Clone(scratch);
options.Resolver.GetFormatterWithVerify<T>().Serialize(ref scratchWriter, value, options);
scratchWriter.Flush();
ToLZ4BinaryCore(scratch, ref writer, options.Compression);
}
}
else
{
options.Resolver.GetFormatterWithVerify<T>().Serialize(ref writer, value, options);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException($"Failed to serialize {typeof(T).FullName} value.", ex);
}
finally
{
writer.OldSpec = originalOldSpecValue;
}
}
/// <summary>
/// Serializes a given value with the specified buffer writer.
/// </summary>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A byte array with the serialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static byte[] Serialize<T>(T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
byte[] array = scratchArray;
if (array == null)
{
scratchArray = array = new byte[65536];
}
var msgpackWriter = new MessagePackWriter(SequencePool.Shared, array)
{
CancellationToken = cancellationToken,
};
Serialize(ref msgpackWriter, value, options);
return msgpackWriter.FlushAndGetArray();
}
/// <summary>
/// Serializes a given value to the specified stream.
/// </summary>
/// <param name="stream">The stream to serialize to.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static void Serialize<T>(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent())
{
Serialize<T>(sequenceRental.Value, value, options, cancellationToken);
try
{
foreach (ReadOnlyMemory<byte> segment in sequenceRental.Value.AsReadOnlySequence)
{
cancellationToken.ThrowIfCancellationRequested();
stream.Write(segment.Span);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex);
}
}
}
/// <summary>
/// Serializes a given value to the specified stream.
/// </summary>
/// <param name="stream">The stream to serialize to.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A task that completes with the result of the async serialization operation.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static async Task SerializeAsync<T>(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent())
{
Serialize<T>(sequenceRental.Value, value, options, cancellationToken);
try
{
foreach (ReadOnlyMemory<byte> segment in sequenceRental.Value.AsReadOnlySequence)
{
cancellationToken.ThrowIfCancellationRequested();
await stream.WriteAsync(segment, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex);
}
}
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="byteSequence">The sequence to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(in ReadOnlySequence<byte> byteSequence, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
var reader = new MessagePackReader(byteSequence)
{
CancellationToken = cancellationToken,
};
return Deserialize<T>(ref reader, options);
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="reader">The reader to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ref MessagePackReader reader, MessagePackSerializerOptions options = null)
{
options = options ?? DefaultOptions;
try
{
if (options.Compression.IsCompression())
{
using (var msgPackUncompressedRental = SequencePool.Shared.Rent())
{
var msgPackUncompressed = msgPackUncompressedRental.Value;
if (TryDecompress(ref reader, msgPackUncompressed))
{
MessagePackReader uncompressedReader = reader.Clone(msgPackUncompressed.AsReadOnlySequence);
return options.Resolver.GetFormatterWithVerify<T>().Deserialize(ref uncompressedReader, options);
}
else
{
return options.Resolver.GetFormatterWithVerify<T>().Deserialize(ref reader, options);
}
}
}
else
{
return options.Resolver.GetFormatterWithVerify<T>().Deserialize(ref reader, options);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException($"Failed to deserialize {typeof(T).FullName} value.", ex);
}
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="buffer">The buffer to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ReadOnlyMemory<byte> buffer, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
var reader = new MessagePackReader(buffer)
{
CancellationToken = cancellationToken,
};
return Deserialize<T>(ref reader, options);
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="buffer">The memory to deserialize from.</param>
/// <param name="bytesRead">The number of bytes read.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ReadOnlyMemory<byte> buffer, out int bytesRead, CancellationToken cancellationToken = default) => Deserialize<T>(buffer, options: null, out bytesRead, cancellationToken);
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="buffer">The memory to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="bytesRead">The number of bytes read.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ReadOnlyMemory<byte> buffer, MessagePackSerializerOptions options, out int bytesRead, CancellationToken cancellationToken = default)
{
var reader = new MessagePackReader(buffer)
{
CancellationToken = cancellationToken,
};
T result = Deserialize<T>(ref reader, options);
bytesRead = buffer.Slice(0, (int)reader.Consumed).Length;
return result;
}
/// <summary>
/// Deserializes the entire content of a <see cref="Stream"/>.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="stream">
/// The stream to deserialize from.
/// The entire stream will be read, and the first msgpack token deserialized will be returned.
/// If <see cref="Stream.CanSeek"/> is true on the stream, its position will be set to just after the last deserialized byte.
/// </param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
/// <remarks>
/// If multiple top-level msgpack data structures are expected on the stream, use <see cref="MessagePackStreamReader"/> instead.
/// </remarks>
public static T Deserialize<T>(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result))
{
return result;
}
using (var sequenceRental = SequencePool.Shared.Rent())
{
var sequence = sequenceRental.Value;
try
{
int bytesRead;
do
{
cancellationToken.ThrowIfCancellationRequested();
Span<byte> span = sequence.GetSpan(stream.CanSeek ? (int)Math.Min(MaxHintSize, stream.Length - stream.Position) : 0);
bytesRead = stream.Read(span);
sequence.Advance(bytesRead);
}
while (bytesRead > 0);
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex);
}
return DeserializeFromSequenceAndRewindStreamIfPossible<T>(stream, options, sequence, cancellationToken);
}
}
/// <summary>
/// Deserializes the entire content of a <see cref="Stream"/>.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="stream">
/// The stream to deserialize from.
/// The entire stream will be read, and the first msgpack token deserialized will be returned.
/// If <see cref="Stream.CanSeek"/> is true on the stream, its position will be set to just after the last deserialized byte.
/// </param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
/// <remarks>
/// If multiple top-level msgpack data structures are expected on the stream, use <see cref="MessagePackStreamReader"/> instead.
/// </remarks>
public static async ValueTask<T> DeserializeAsync<T>(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result))
{
return result;
}
using (var sequenceRental = SequencePool.Shared.Rent())
{
var sequence = sequenceRental.Value;
try
{
int bytesRead;
do
{
Memory<byte> memory = sequence.GetMemory(stream.CanSeek ? (int)Math.Min(MaxHintSize, stream.Length - stream.Position) : 0);
bytesRead = await stream.ReadAsync(memory, cancellationToken).ConfigureAwait(false);
sequence.Advance(bytesRead);
}
while (bytesRead > 0);
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex);
}
return DeserializeFromSequenceAndRewindStreamIfPossible<T>(stream, options, sequence, cancellationToken);
}
}
private delegate int LZ4Transform(ReadOnlySpan<byte> input, Span<byte> output);
private static readonly LZ4Transform LZ4CodecEncode = LZ4Codec.Encode;
private static readonly LZ4Transform LZ4CodecDecode = LZ4Codec.Decode;
private static bool TryDeserializeFromMemoryStream<T>(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken, out T result)
{
cancellationToken.ThrowIfCancellationRequested();
if (stream is MemoryStream ms && ms.TryGetBuffer(out ArraySegment<byte> streamBuffer))
{
result = Deserialize<T>(streamBuffer.AsMemory(checked((int)ms.Position)), options, out int bytesRead, cancellationToken);
// Emulate that we had actually "read" from the stream.
ms.Seek(bytesRead, SeekOrigin.Current);
return true;
}
result = default;
return false;
}
private static T DeserializeFromSequenceAndRewindStreamIfPossible<T>(Stream streamToRewind, MessagePackSerializerOptions options, ReadOnlySequence<byte> sequence, CancellationToken cancellationToken)
{
if (streamToRewind is null)
{
throw new ArgumentNullException(nameof(streamToRewind));
}
var reader = new MessagePackReader(sequence)
{
CancellationToken = cancellationToken,
};
T result = Deserialize<T>(ref reader, options);
if (streamToRewind.CanSeek && !reader.End)
{
// Reverse the stream as many bytes as we left unread.
int bytesNotRead = checked((int)reader.Sequence.Slice(reader.Position).Length);
streamToRewind.Seek(-bytesNotRead, SeekOrigin.Current);
}
return result;
}
/// <summary>
/// Performs LZ4 compression or decompression.
/// </summary>
/// <param name="input">The input for the operation.</param>
/// <param name="output">The buffer to write the result of the operation.</param>
/// <param name="lz4Operation">The LZ4 codec transformation.</param>
/// <returns>The number of bytes written to the <paramref name="output"/>.</returns>
private static int LZ4Operation(in ReadOnlySequence<byte> input, Span<byte> output, LZ4Transform lz4Operation)
{
ReadOnlySpan<byte> inputSpan;
byte[] rentedInputArray = null;
if (input.IsSingleSegment)
{
inputSpan = input.First.Span;
}
else
{
rentedInputArray = ArrayPool<byte>.Shared.Rent((int)input.Length);
input.CopyTo(rentedInputArray);
inputSpan = rentedInputArray.AsSpan(0, (int)input.Length);
}
try
{
return lz4Operation(inputSpan, output);
}
finally
{
if (rentedInputArray != null)
{
ArrayPool<byte>.Shared.Return(rentedInputArray);
}
}
}
private static bool TryDecompress(ref MessagePackReader reader, IBufferWriter<byte> writer)
{
if (!reader.End)
{
// Try to find LZ4Block
if (reader.NextMessagePackType == MessagePackType.Extension)
{
MessagePackReader peekReader = reader.CreatePeekReader();
ExtensionHeader header = peekReader.ReadExtensionFormatHeader();
if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4Block)
{
// Read the extension using the original reader, so we "consume" it.
ExtensionResult extension = reader.ReadExtensionFormat();
var extReader = new MessagePackReader(extension.Data);
// The first part of the extension payload is a MessagePack-encoded Int32 that
// tells us the length the data will be AFTER decompression.
int uncompressedLength = extReader.ReadInt32();
// The rest of the payload is the compressed data itself.
ReadOnlySequence<byte> compressedData = extReader.Sequence.Slice(extReader.Position);
Span<byte> uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength);
int actualUncompressedLength = LZ4Operation(compressedData, uncompressedSpan, LZ4CodecDecode);
Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data.");
writer.Advance(actualUncompressedLength);
return true;
}
}
// Try to find LZ4BlockArray
if (reader.NextMessagePackType == MessagePackType.Array)
{
MessagePackReader peekReader = reader.CreatePeekReader();
var arrayLength = peekReader.ReadArrayHeader();
if (arrayLength != 0 && peekReader.NextMessagePackType == MessagePackType.Extension)
{
ExtensionHeader header = peekReader.ReadExtensionFormatHeader();
if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4BlockArray)
{
// switch peekReader as original reader.
reader = peekReader;
// Read from [Ext(98:int,int...), bin,bin,bin...]
var sequenceCount = arrayLength - 1;
var uncompressedLengths = ArrayPool<int>.Shared.Rent(sequenceCount);
try
{
for (int i = 0; i < sequenceCount; i++)
{
uncompressedLengths[i] = reader.ReadInt32();
}
for (int i = 0; i < sequenceCount; i++)
{
var uncompressedLength = uncompressedLengths[i];
var lz4Block = reader.ReadBytes();
Span<byte> uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength);
var actualUncompressedLength = LZ4Operation(lz4Block.Value, uncompressedSpan, LZ4CodecDecode);
Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data.");
writer.Advance(actualUncompressedLength);
}
return true;
}
finally
{
ArrayPool<int>.Shared.Return(uncompressedLengths);
}
}
}
}
}
return false;
}
private static void ToLZ4BinaryCore(in ReadOnlySequence<byte> msgpackUncompressedData, ref MessagePackWriter writer, MessagePackCompression compression)
{
if (compression == MessagePackCompression.Lz4Block)
{
if (msgpackUncompressedData.Length < LZ4NotCompressionSizeInLz4BlockType)
{
writer.WriteRaw(msgpackUncompressedData);
return;
}
var maxCompressedLength = LZ4Codec.MaximumOutputLength((int)msgpackUncompressedData.Length);
var lz4Span = ArrayPool<byte>.Shared.Rent(maxCompressedLength);
try
{
int lz4Length = LZ4Operation(msgpackUncompressedData, lz4Span, LZ4CodecEncode);
const int LengthOfUncompressedDataSizeHeader = 5;
writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4Block, LengthOfUncompressedDataSizeHeader + (uint)lz4Length));
writer.WriteInt32((int)msgpackUncompressedData.Length);
writer.WriteRaw(lz4Span.AsSpan(0, lz4Length));
}
finally
{
ArrayPool<byte>.Shared.Return(lz4Span);
}
}
else if (compression == MessagePackCompression.Lz4BlockArray)
{
// Write to [Ext(98:int,int...), bin,bin,bin...]
var sequenceCount = 0;
var extHeaderSize = 0;
foreach (var item in msgpackUncompressedData)
{
sequenceCount++;
extHeaderSize += GetUInt32WriteSize((uint)item.Length);
}
writer.WriteArrayHeader(sequenceCount + 1);
writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4BlockArray, extHeaderSize));
{
foreach (var item in msgpackUncompressedData)
{
writer.Write(item.Length);
}
}
foreach (var item in msgpackUncompressedData)
{
var maxCompressedLength = LZ4Codec.MaximumOutputLength(item.Length);
var lz4Span = writer.GetSpan(maxCompressedLength + 5);
int lz4Length = LZ4Codec.Encode(item.Span, lz4Span.Slice(5, lz4Span.Length - 5));
WriteBin32Header((uint)lz4Length, lz4Span);
writer.Advance(lz4Length + 5);
}
}
else
{
throw new ArgumentException("Invalid MessagePackCompression Code. Code:" + compression);
}
}
private static int GetUInt32WriteSize(uint value)
{
if (value <= MessagePackRange.MaxFixPositiveInt)
{
return 1;
}
else if (value <= byte.MaxValue)
{
return 2;
}
else if (value <= ushort.MaxValue)
{
return 3;
}
else
{
return 5;
}
}
private static void WriteBin32Header(uint value, Span<byte> span)
{
unchecked
{
span[0] = MessagePackCode.Bin32;
// Write to highest index first so the JIT skips bounds checks on subsequent writes.
span[4] = (byte)value;
span[3] = (byte)(value >> 8);
span[2] = (byte)(value >> 16);
span[1] = (byte)(value >> 24);
}
}
private static class PrimitiveChecker<T>
{
public static readonly bool IsMessagePackFixedSizePrimitive;
static PrimitiveChecker()
{
IsMessagePackFixedSizePrimitive = IsMessagePackFixedSizePrimitiveTypeHelper(typeof(T));
}
}
private static bool IsMessagePackFixedSizePrimitiveTypeHelper(Type type)
{
return type == typeof(short)
|| type == typeof(int)
|| type == typeof(long)
|| type == typeof(ushort)
|| type == typeof(uint)
|| type == typeof(ulong)
|| type == typeof(float)
|| type == typeof(double)
|| type == typeof(bool)
|| type == typeof(byte)
|| type == typeof(sbyte)
|| type == typeof(char)
;
}
}
}
| |
//#define USE_GENERICS
//#define DELETE_AFTER_TEST
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.Runtime;
using Orleans.TestingHost;
using Tester;
using Tester.AzureUtils.Streaming;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using UnitTests.StreamingTests;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable ConvertToConstant.Local
// ReSharper disable CheckNamespace
namespace UnitTests.Streaming.Reliability
{
[TestCategory("Streaming"), TestCategory("Reliability")]
public class StreamReliabilityTests : TestClusterPerTest
{
private readonly ITestOutputHelper output;
public const string SMS_STREAM_PROVIDER_NAME = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
public const string AZURE_QUEUE_STREAM_PROVIDER_NAME = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
private const int queueCount = 8;
private Guid _streamId;
private string _streamProviderName;
private int numExpectedSilos;
#if DELETE_AFTER_TEST
private HashSet<IStreamReliabilityTestGrain> _usedGrains;
#endif
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
TestUtils.CheckForAzureStorage();
this.numExpectedSilos = 2;
builder.CreateSiloAsync = AppDomainSiloHandle.Create;
builder.Options.InitialSilosCount = (short) this.numExpectedSilos;
builder.Options.UseTestClusterMembership = false;
builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>();
builder.AddClientBuilderConfigurator<ClientBuilderConfigurator>();
}
public class ClientBuilderConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.UseAzureStorageClustering(gatewayOptions =>
{
gatewayOptions.ConnectionString = TestDefaultConfiguration.DataConnectionString;
})
.AddAzureQueueStreams(AZURE_QUEUE_STREAM_PROVIDER_NAME, ob => ob.Configure<IOptions<ClusterOptions>>(
(options, dep) =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount);
}))
.AddSimpleMessageStreamProvider(SMS_STREAM_PROVIDER_NAME)
.Configure<GatewayOptions>(options => options.GatewayListRefreshPeriod = TimeSpan.FromSeconds(5));
}
}
public class SiloBuilderConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.UseAzureStorageClustering(options =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.MaxStorageBusyRetries = 3;
})
.AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.DeleteStateOnClear = true;
}))
.AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1)
.AddSimpleMessageStreamProvider(SMS_STREAM_PROVIDER_NAME)
.AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.DeleteStateOnClear = true;
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
}))
.AddAzureQueueStreams(AZURE_QUEUE_STREAM_PROVIDER_NAME, ob => ob.Configure<IOptions<ClusterOptions>>(
(options, dep) =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount);
}))
.AddAzureQueueStreams("AzureQueueProvider2", ob => ob.Configure<IOptions<ClusterOptions>>(
(options, dep) =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.QueueNames = AzureQueueUtilities.GenerateQueueNames($"{dep.Value.ClusterId}2", queueCount);
}));
}
}
public StreamReliabilityTests(ITestOutputHelper output)
{
this.output = output;
CheckSilosRunning("Initially", numExpectedSilos);
#if DELETE_AFTER_TEST
_usedGrains = new HashSet<IStreamReliabilityTestGrain>();
#endif
}
public override void Dispose()
{
#if DELETE_AFTER_TEST
List<Task> promises = new List<Task>();
foreach (var g in _usedGrains)
{
promises.Add(g.ClearGrain());
}
Task.WhenAll(promises).Wait();
#endif
base.Dispose();
if (this.HostedCluster != null)
{
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance,
AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount),
TestDefaultConfiguration.DataConnectionString).Wait();
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance,
AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount),
TestDefaultConfiguration.DataConnectionString).Wait();
}
}
[SkippableFact, TestCategory("Functional")]
public void Baseline_StreamRel()
{
// This test case is just a sanity-check that the silo test config is OK.
const string testName = "Baseline_StreamRel";
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
StreamTestUtils.LogEndTest(testName, logger);
}
[SkippableFact, TestCategory("Functional")]
public async Task Baseline_StreamRel_RestartSilos()
{
// This test case is just a sanity-check that the silo test config is OK.
const string testName = "Baseline_StreamRel_RestartSilos";
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
CheckSilosRunning("Before Restart", numExpectedSilos);
var silos = this.HostedCluster.Silos;
await RestartAllSilos();
CheckSilosRunning("After Restart", numExpectedSilos);
Assert.NotEqual(silos, this.HostedCluster.Silos); // Should be different silos after restart
StreamTestUtils.LogEndTest(testName, logger);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_Baseline_StreamRel()
{
// This test case is just a sanity-check that the SMS test config is OK.
const string testName = "SMS_Baseline_StreamRel";
_streamId = Guid.NewGuid();
_streamProviderName = SMS_STREAM_PROVIDER_NAME;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
// Grain Producer -> Grain Consumer
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
await Do_BaselineTest(consumerGrainId, producerGrainId);
StreamTestUtils.LogEndTest(testName, logger);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure")]
public async Task AQ_Baseline_StreamRel()
{
// This test case is just a sanity-check that the AzureQueue test config is OK.
const string testName = "AQ_Baseline_StreamRel";
_streamId = Guid.NewGuid();
_streamProviderName = AZURE_QUEUE_STREAM_PROVIDER_NAME;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
await Do_BaselineTest(consumerGrainId, producerGrainId);
StreamTestUtils.LogEndTest(testName, logger);
}
[SkippableFact(Skip ="Ignore"), TestCategory("Failures"), TestCategory("Streaming"), TestCategory("Reliability")]
public async Task SMS_AddMany_Consumers()
{
const string testName = "SMS_AddMany_Consumers";
await Test_AddMany_Consumers(testName, SMS_STREAM_PROVIDER_NAME);
}
[SkippableFact(Skip = "Ignore"), TestCategory("Failures"), TestCategory("Streaming"), TestCategory("Reliability"), TestCategory("Azure")]
public async Task AQ_AddMany_Consumers()
{
const string testName = "AQ_AddMany_Consumers";
await Test_AddMany_Consumers(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_PubSub_MultiConsumerSameGrain()
{
const string testName = "SMS_PubSub_MultiConsumerSameGrain";
await Test_PubSub_MultiConsumerSameGrain(testName, SMS_STREAM_PROVIDER_NAME);
}
// AQ_PubSub_MultiConsumerSameGrain not required - does not use PubSub
[SkippableFact, TestCategory("Functional")]
public async Task SMS_PubSub_MultiProducerSameGrain()
{
const string testName = "SMS_PubSub_MultiProducerSameGrain";
await Test_PubSub_MultiProducerSameGrain(testName, SMS_STREAM_PROVIDER_NAME);
}
// AQ_PubSub_MultiProducerSameGrain not required - does not use PubSub
[SkippableFact, TestCategory("Functional")]
public async Task SMS_PubSub_Unsubscribe()
{
const string testName = "SMS_PubSub_Unsubscribe";
await Test_PubSub_Unsubscribe(testName, SMS_STREAM_PROVIDER_NAME);
}
// AQ_PubSub_Unsubscribe not required - does not use PubSub
//TODO: This test fails because the resubscribe to streams after restart creates a new subscription, losing the events on the previous subscription. Should be fixed when 'renew' subscription feature is added. - jbragg
[SkippableFact, TestCategory("Functional"), TestCategory("Failures")]
public async Task SMS_StreamRel_AllSilosRestart_PubSubCounts()
{
const string testName = "SMS_StreamRel_AllSilosRestart_PubSubCounts";
await Test_AllSilosRestart_PubSubCounts(testName, SMS_STREAM_PROVIDER_NAME);
}
// AQ_StreamRel_AllSilosRestart_PubSubCounts not required - does not use PubSub
[SkippableFact, TestCategory("Functional")]
public async Task SMS_StreamRel_AllSilosRestart()
{
const string testName = "SMS_StreamRel_AllSilosRestart";
await Test_AllSilosRestart(testName, SMS_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")]
public async Task AQ_StreamRel_AllSilosRestart()
{
const string testName = "AQ_StreamRel_AllSilosRestart";
await Test_AllSilosRestart(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_StreamRel_SiloJoins()
{
const string testName = "SMS_StreamRel_SiloJoins";
await Test_SiloJoins(testName, SMS_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")]
public async Task AQ_StreamRel_SiloJoins()
{
const string testName = "AQ_StreamRel_SiloJoins";
await Test_SiloJoins(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_StreamRel_SiloDies_Consumer()
{
const string testName = "SMS_StreamRel_SiloDies_Consumer";
await Test_SiloDies_Consumer(testName, SMS_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")]
public async Task AQ_StreamRel_SiloDies_Consumer()
{
const string testName = "AQ_StreamRel_SiloDies_Consumer";
await Test_SiloDies_Consumer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_StreamRel_SiloDies_Producer()
{
const string testName = "SMS_StreamRel_SiloDies_Producer";
await Test_SiloDies_Producer(testName, SMS_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")]
public async Task AQ_StreamRel_SiloDies_Producer()
{
const string testName = "AQ_StreamRel_SiloDies_Producer";
await Test_SiloDies_Producer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_StreamRel_SiloRestarts_Consumer()
{
const string testName = "SMS_StreamRel_SiloRestarts_Consumer";
await Test_SiloRestarts_Consumer(testName, SMS_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")]
public async Task AQ_StreamRel_SiloRestarts_Consumer()
{
const string testName = "AQ_StreamRel_SiloRestarts_Consumer";
await Test_SiloRestarts_Consumer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_StreamRel_SiloRestarts_Producer()
{
const string testName = "SMS_StreamRel_SiloRestarts_Producer";
await Test_SiloRestarts_Producer(testName, SMS_STREAM_PROVIDER_NAME);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("AzureQueue")]
public async Task AQ_StreamRel_SiloRestarts_Producer()
{
const string testName = "AQ_StreamRel_SiloRestarts_Producer";
await Test_SiloRestarts_Producer(testName, AZURE_QUEUE_STREAM_PROVIDER_NAME);
}
// -------------------
// Test helper methods
#if USE_GENERICS
private async Task<IStreamReliabilityTestGrain<int>> Do_BaselineTest(long consumerGrainId, long producerGrainId)
#else
private async Task<IStreamReliabilityTestGrain> Do_BaselineTest(long consumerGrainId, long producerGrainId)
#endif
{
logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId);
var consumerGrain = GetGrain(consumerGrainId);
var producerGrain = GetGrain(producerGrainId);
#if DELETE_AFTER_TEST
_usedGrains.Add(producerGrain);
_usedGrains.Add(producerGrain);
#endif
await producerGrain.Ping();
string when = "Before subscribe";
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, false, false);
logger.Info("AddConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await consumerGrain.AddConsumer(_streamId, _streamProviderName);
logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await producerGrain.BecomeProducer(_streamId, _streamProviderName);
when = "After subscribe";
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
when = "Ping";
await producerGrain.Ping();
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
when = "SendItem";
await producerGrain.SendItem(1);
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
return producerGrain;
}
#if USE_GENERICS
private async Task<IStreamReliabilityTestGrain<int>[]> Do_AddConsumerGrains(long baseId, int numGrains)
#else
private async Task<IStreamReliabilityTestGrain[]> Do_AddConsumerGrains(long baseId, int numGrains)
#endif
{
logger.Info("Initializing: BaseId={0} NumGrains={1}", baseId, numGrains);
#if USE_GENERICS
var grains = new IStreamReliabilityTestGrain<int>[numGrains];
#else
var grains = new IStreamReliabilityTestGrain[numGrains];
#endif
List<Task> promises = new List<Task>(numGrains);
for (int i = 0; i < numGrains; i++)
{
grains[i] = GetGrain(i + baseId);
promises.Add(grains[i].Ping());
#if DELETE_AFTER_TEST
_usedGrains.Add(grains[i]);
#endif
}
await Task.WhenAll(promises);
logger.Info("AddConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await Task.WhenAll(grains.Select(g => g.AddConsumer(_streamId, _streamProviderName)));
return grains;
}
private static int baseConsumerId = 0;
private async Task Test_AddMany_Consumers(string testName, string streamProviderName)
{
const int numLoops = 100;
const int numGrains = 10;
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
var producerGrain = GetGrain(producerGrainId);
var consumerGrain = GetGrain(consumerGrainId);
#if DELETE_AFTER_TEST
_usedGrains.Add(producerGrain);
_usedGrains.Add(consumerGrain);
#endif
// Note: This does first SendItem
await Do_BaselineTest(consumerGrainId, producerGrainId);
int baseId = 10000 * ++baseConsumerId;
var grains1 = await Do_AddConsumerGrains(baseId, numGrains);
for (int i = 0; i < numLoops; i++)
{
await producerGrain.SendItem(2);
}
string when1 = "AddConsumers-Send-2";
// Messages received by original consumer grain
await CheckReceivedCounts(when1, consumerGrain, numLoops + 1, 0);
// Messages received by new consumer grains
// ReSharper disable once AccessToModifiedClosure
await Task.WhenAll(grains1.Select(async g =>
{
await CheckReceivedCounts(when1, g, numLoops, 0);
#if DELETE_AFTER_TEST
_usedGrains.Add(g);
#endif
}));
string when2 = "AddConsumers-Send-3";
baseId = 10000 * ++baseConsumerId;
var grains2 = await Do_AddConsumerGrains(baseId, numGrains);
for (int i = 0; i < numLoops; i++)
{
await producerGrain.SendItem(3);
}
////Thread.Sleep(TimeSpan.FromSeconds(2));
// Messages received by original consumer grain
await CheckReceivedCounts(when2, consumerGrain, numLoops*2 + 1, 0);
// Messages received by new consumer grains
await Task.WhenAll(grains2.Select(g => CheckReceivedCounts(when2, g, numLoops, 0)));
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_PubSub_MultiConsumerSameGrain(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
// Grain Producer -> Grain 2 x Consumer
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
string when;
logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId);
var consumerGrain = GetGrain(consumerGrainId);
var producerGrain = GetGrain(producerGrainId);
logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await producerGrain.BecomeProducer(_streamId, _streamProviderName);
when = "After BecomeProducer";
// Note: Only semantics guarenteed for producer is that they will have been registered by time that first msg is sent.
await producerGrain.SendItem(0);
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
logger.Info("AddConsumer x 2 : StreamId={0} Provider={1}", _streamId, _streamProviderName);
await consumerGrain.AddConsumer(_streamId, _streamProviderName);
when = "After first AddConsumer";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
await consumerGrain.AddConsumer(_streamId, _streamProviderName);
when = "After second AddConsumer";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 2, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_PubSub_MultiProducerSameGrain(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
// Grain Producer -> Grain 2 x Consumer
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
string when;
logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId);
var consumerGrain = GetGrain(consumerGrainId);
var producerGrain = GetGrain(producerGrainId);
logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await producerGrain.BecomeProducer(_streamId, _streamProviderName);
when = "After first BecomeProducer";
// Note: Only semantics guarenteed for producer is that they will have been registered by time that first msg is sent.
await producerGrain.SendItem(0);
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
await producerGrain.BecomeProducer(_streamId, _streamProviderName);
when = "After second BecomeProducer";
await producerGrain.SendItem(0);
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
logger.Info("AddConsumer x 2 : StreamId={0} Provider={1}", _streamId, _streamProviderName);
await consumerGrain.AddConsumer(_streamId, _streamProviderName);
when = "After first AddConsumer";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
await consumerGrain.AddConsumer(_streamId, _streamProviderName);
when = "After second AddConsumer";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 2, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_PubSub_Unsubscribe(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
// Grain Producer -> Grain 2 x Consumer
// Note: PubSub should only count distinct grains, even if a grain has multiple consumer handles
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
string when;
logger.Info("Initializing: ConsumerGrain={0} ProducerGrain={1}", consumerGrainId, producerGrainId);
var consumerGrain = GetGrain(consumerGrainId);
var producerGrain = GetGrain(producerGrainId);
logger.Info("BecomeProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await producerGrain.BecomeProducer(_streamId, _streamProviderName);
await producerGrain.BecomeProducer(_streamId, _streamProviderName);
when = "After BecomeProducer";
// Note: Only semantics guarenteed are that producer will have been registered by time that first msg is sent.
await producerGrain.SendItem(0);
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
logger.Info("AddConsumer x 2 : StreamId={0} Provider={1}", _streamId, _streamProviderName);
var c1 = await consumerGrain.AddConsumer(_streamId, _streamProviderName);
when = "After first AddConsumer";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
await CheckConsumerCounts(when, consumerGrain, 1);
var c2 = await consumerGrain.AddConsumer(_streamId, _streamProviderName);
when = "After second AddConsumer";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 2, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
await CheckConsumerCounts(when, consumerGrain, 2);
logger.Info("RemoveConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await consumerGrain.RemoveConsumer(_streamId, _streamProviderName, c1);
when = "After first RemoveConsumer";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
await CheckConsumerCounts(when, consumerGrain, 1);
#if REMOVE_PRODUCER
logger.Info("RemoveProducer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await producerGrain.RemoveProducer(_streamId, _streamProviderName);
when = "After RemoveProducer";
await CheckPubSubCounts(when, 0, 1);
await CheckConsumerCounts(when, consumerGrain, 1);
#endif
logger.Info("RemoveConsumer: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await consumerGrain.RemoveConsumer(_streamId, _streamProviderName, c2);
when = "After second RemoveConsumer";
#if REMOVE_PRODUCER
await CheckPubSubCounts(when, 0, 0);
#else
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 0, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
#endif
await CheckConsumerCounts(when, consumerGrain, 0);
StreamTestUtils.LogEndTest(testName, logger);
}
[SkippableFact, TestCategory("Functional")]
public async Task SMS_AllSilosRestart_UnsubscribeConsumer()
{
const string testName = "SMS_AllSilosRestart_UnsubscribeConsumer";
_streamId = Guid.NewGuid();
_streamProviderName = SMS_STREAM_PROVIDER_NAME;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
var consumerGrain = this.GrainFactory.GetGrain<IStreamUnsubscribeTestGrain>(consumerGrainId);
logger.Info("Subscribe: StreamId={0} Provider={1}", _streamId, _streamProviderName);
await consumerGrain.Subscribe(_streamId, _streamProviderName);
// Restart silos
await RestartAllSilos();
string when = "After restart all silos";
CheckSilosRunning(when, numExpectedSilos);
// Since we restart all silos, the client might not haave had enough
// time to reconnect to the new gateways. Let's retry the call if it
// is the case
for (int i = 0; i < 3; i++)
{
try
{
await consumerGrain.UnSubscribeFromAllStreams();
break;
}
catch (OrleansMessageRejectionException ex)
{
if (!ex.Message.Contains("No gateways available"))
throw;
}
await Task.Delay(100);
}
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_AllSilosRestart(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
await Do_BaselineTest(consumerGrainId, producerGrainId);
// Restart silos
await RestartAllSilos();
string when = "After restart all silos";
CheckSilosRunning(when, numExpectedSilos);
when = "SendItem";
var producerGrain = GetGrain(producerGrainId);
await producerGrain.SendItem(1);
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_AllSilosRestart_PubSubCounts(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
#if USE_GENERICS
IStreamReliabilityTestGrain<int> producerGrain =
#else
IStreamReliabilityTestGrain producerGrain =
#endif
await Do_BaselineTest(consumerGrainId, producerGrainId);
string when = "Before restart all silos";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
// Restart silos
//RestartDefaultSilosButKeepCurrentClient(testName);
await RestartAllSilos();
when = "After restart all silos";
CheckSilosRunning(when, numExpectedSilos);
// Note: It is not guaranteed that the list of producers will not get modified / cleaned up during silo shutdown, so can't assume count will be 1 here.
// Expected == -1 means don't care.
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, -1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
await producerGrain.SendItem(1);
when = "After SendItem";
await StreamTestUtils.CheckPubSubCounts(this.InternalClient, output, when, 1, 1, _streamId, _streamProviderName, StreamTestsConstants.StreamReliabilityNamespace);
var consumerGrain = GetGrain(consumerGrainId);
await CheckReceivedCounts(when, consumerGrain, 1, 0);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_SiloDies_Consumer(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
string when;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId);
when = "Before kill one silo";
CheckSilosRunning(when, numExpectedSilos);
bool sameSilo = await CheckGrainCounts();
// Find which silo the consumer grain is located on
var consumerGrain = GetGrain(consumerGrainId);
SiloAddress siloAddress = await consumerGrain.GetLocation();
output.WriteLine("Consumer grain is located on silo {0} ; Producer on same silo = {1}", siloAddress, sameSilo);
// Kill the silo containing the consumer grain
SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress));
await StopSilo(siloToKill, true, false);
// Note: Don't restart failed silo for this test case
// Note: Don't reinitialize client
when = "After kill one silo";
CheckSilosRunning(when, numExpectedSilos - 1);
when = "SendItem";
await producerGrain.SendItem(1);
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_SiloDies_Producer(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
string when;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId);
when = "Before kill one silo";
CheckSilosRunning(when, numExpectedSilos);
bool sameSilo = await CheckGrainCounts();
// Find which silo the producer grain is located on
SiloAddress siloAddress = await producerGrain.GetLocation();
output.WriteLine("Producer grain is located on silo {0} ; Consumer on same silo = {1}", siloAddress, sameSilo);
// Kill the silo containing the producer grain
SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress));
await StopSilo(siloToKill, true, false);
// Note: Don't restart failed silo for this test case
// Note: Don't reinitialize client
when = "After kill one silo";
CheckSilosRunning(when, numExpectedSilos - 1);
when = "SendItem";
await producerGrain.SendItem(1);
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_SiloRestarts_Consumer(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
string when;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId);
when = "Before restart one silo";
CheckSilosRunning(when, numExpectedSilos);
bool sameSilo = await CheckGrainCounts();
// Find which silo the consumer grain is located on
var consumerGrain = GetGrain(consumerGrainId);
SiloAddress siloAddress = await consumerGrain.GetLocation();
output.WriteLine("Consumer grain is located on silo {0} ; Producer on same silo = {1}", siloAddress, sameSilo);
// Restart the silo containing the consumer grain
SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress));
await StopSilo(siloToKill, true, true);
// Note: Don't reinitialize client
when = "After restart one silo";
CheckSilosRunning(when, numExpectedSilos);
when = "SendItem";
await producerGrain.SendItem(1);
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_SiloRestarts_Producer(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
string when;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
var producerGrain = await Do_BaselineTest(consumerGrainId, producerGrainId);
when = "Before restart one silo";
CheckSilosRunning(when, numExpectedSilos);
bool sameSilo = await CheckGrainCounts();
// Find which silo the producer grain is located on
SiloAddress siloAddress = await producerGrain.GetLocation();
output.WriteLine("Producer grain is located on silo {0} ; Consumer on same silo = {1}", siloAddress, sameSilo);
// Restart the silo containing the consumer grain
SiloHandle siloToKill = this.HostedCluster.Silos.First(s => s.SiloAddress.Equals(siloAddress));
await StopSilo(siloToKill, true, true);
// Note: Don't reinitialize client
when = "After restart one silo";
CheckSilosRunning(when, numExpectedSilos);
when = "SendItem";
await producerGrain.SendItem(1);
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
StreamTestUtils.LogEndTest(testName, logger);
}
private async Task Test_SiloJoins(string testName, string streamProviderName)
{
_streamId = Guid.NewGuid();
_streamProviderName = streamProviderName;
const int numLoops = 3;
StreamTestUtils.LogStartTest(testName, _streamId, _streamProviderName, logger, HostedCluster);
long consumerGrainId = random.Next();
long producerGrainId = random.Next();
var producerGrain = GetGrain(producerGrainId);
SiloAddress producerLocation = await producerGrain.GetLocation();
var consumerGrain = GetGrain(consumerGrainId);
SiloAddress consumerLocation = await consumerGrain.GetLocation();
output.WriteLine("Grain silo locations: Producer={0} Consumer={1}", producerLocation, consumerLocation);
// Note: This does first SendItem
await Do_BaselineTest(consumerGrainId, producerGrainId);
int expectedReceived = 1;
string when = "SendItem-2";
for (int i = 0; i < numLoops; i++)
{
await producerGrain.SendItem(2);
}
expectedReceived += numLoops;
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
await CheckReceivedCounts(when, consumerGrain, expectedReceived, 0);
// Add new silo
//SiloHandle newSilo = StartAdditionalOrleans();
//WaitForLivenessToStabilize();
SiloHandle newSilo = await this.HostedCluster.StartAdditionalSiloAsync();
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
when = "After starting additional silo " + newSilo;
output.WriteLine(when);
CheckSilosRunning(when, numExpectedSilos + 1);
//when = "SendItem-3";
//output.WriteLine(when);
//for (int i = 0; i < numLoops; i++)
//{
// await producerGrain.SendItem(3);
//}
//expectedReceived += numLoops;
//await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId, true, true);
//await CheckReceivedCounts(when, consumerGrain, expectedReceived, 0);
// Find a Consumer Grain on the new silo
IStreamReliabilityTestGrain newConsumer = CreateGrainOnSilo(newSilo.SiloAddress);
await newConsumer.AddConsumer(_streamId, _streamProviderName);
output.WriteLine("Grain silo locations: Producer={0} OldConsumer={1} NewConsumer={2}", producerLocation, consumerLocation, newSilo.SiloAddress);
////Thread.Sleep(TimeSpan.FromSeconds(2));
when = "SendItem-4";
output.WriteLine(when);
for (int i = 0; i < numLoops; i++)
{
await producerGrain.SendItem(4);
}
expectedReceived += numLoops;
// Old consumer received the newly published messages
await CheckReceivedCounts(when+"-Old", consumerGrain, expectedReceived, 0);
// New consumer received the newly published messages
await CheckReceivedCounts(when+"-New", newConsumer, numLoops, 0);
StreamTestUtils.LogEndTest(testName, logger);
}
// ---------- Utility Functions ----------
private async Task RestartAllSilos()
{
output.WriteLine("\n\n\n\n-----------------------------------------------------\n" +
"Restarting all silos - Old Primary={0} Secondary={1}" +
"\n-----------------------------------------------------\n\n\n",
this.HostedCluster.Primary?.SiloAddress, this.HostedCluster.SecondarySilos.FirstOrDefault()?.SiloAddress);
foreach (var silo in this.HostedCluster.GetActiveSilos().ToList())
{
await this.HostedCluster.RestartSiloAsync(silo);
}
// Note: Needed to reinitialize client in this test case to connect to new silos
// this.HostedCluster.InitializeClient();
output.WriteLine("\n\n\n\n-----------------------------------------------------\n" +
"Restarted new silos - New Primary={0} Secondary={1}" +
"\n-----------------------------------------------------\n\n\n",
this.HostedCluster.Primary?.SiloAddress, this.HostedCluster.SecondarySilos.FirstOrDefault()?.SiloAddress);
}
private async Task StopSilo(SiloHandle silo, bool kill, bool restart)
{
SiloAddress oldSilo = silo.SiloAddress;
bool isPrimary = oldSilo.Equals(this.HostedCluster.Primary?.SiloAddress);
string siloType = isPrimary ? "Primary" : "Secondary";
string action;
if (restart) action = kill ? "Kill+Restart" : "Stop+Restart";
else action = kill ? "Kill" : "Stop";
logger.Warn(2, "{0} {1} silo {2}", action, siloType, oldSilo);
if (restart)
{
//RestartRuntime(silo, kill);
SiloHandle newSilo = await this.HostedCluster.RestartSiloAsync(silo);
logger.Info("Restarted new {0} silo {1}", siloType, newSilo.SiloAddress);
Assert.NotEqual(oldSilo, newSilo.SiloAddress); //"Should be different silo address after Restart"
}
else if (kill)
{
await this.HostedCluster.KillSiloAsync(silo);
Assert.False(silo.IsActive);
}
else
{
await this.HostedCluster.StopSiloAsync(silo);
Assert.False(silo.IsActive);
}
// WaitForLivenessToStabilize(!kill);
this.HostedCluster.WaitForLivenessToStabilizeAsync(kill).Wait();
}
#if USE_GENERICS
protected IStreamReliabilityTestGrain<int> GetGrain(long grainId)
#else
protected IStreamReliabilityTestGrain GetGrain(long grainId)
#endif
{
#if USE_GENERICS
return StreamReliabilityTestGrainFactory<int>.GetGrain(grainId);
#else
return this.GrainFactory.GetGrain<IStreamReliabilityTestGrain>(grainId);
#endif
}
#if USE_GENERICS
private IStreamReliabilityTestGrain<int> CreateGrainOnSilo(SiloHandle silo)
#else
private IStreamReliabilityTestGrain CreateGrainOnSilo(SiloAddress silo)
#endif
{
// Find a Grain to use which is located on the specified silo
IStreamReliabilityTestGrain newGrain;
long kp = random.Next();
while (true)
{
newGrain = GetGrain(++kp);
SiloAddress loc = newGrain.GetLocation().Result;
if (loc.Equals(silo))
break;
}
output.WriteLine("Using Grain {0} located on silo {1}", kp, silo);
return newGrain;
}
protected async Task CheckConsumerProducerStatus(string when, long producerGrainId, long consumerGrainId, bool expectIsProducer, bool expectIsConsumer)
{
await CheckConsumerProducerStatus(when, producerGrainId, consumerGrainId,
expectIsProducer ? 1 : 0,
expectIsConsumer ? 1 : 0);
}
protected async Task CheckConsumerProducerStatus(string when, long producerGrainId, long consumerGrainId, int expectedNumProducers, int expectedNumConsumers)
{
var producerGrain = GetGrain(producerGrainId);
var consumerGrain = GetGrain(consumerGrainId);
bool isProducer = await producerGrain.IsProducer();
output.WriteLine("Grain {0} IsProducer={1}", producerGrainId, isProducer);
Assert.Equal(expectedNumProducers > 0, isProducer);
bool isConsumer = await consumerGrain.IsConsumer();
output.WriteLine("Grain {0} IsConsumer={1}", consumerGrainId, isConsumer);
Assert.Equal(expectedNumConsumers > 0, isConsumer);
int consumerHandleCount = await consumerGrain.GetConsumerHandlesCount();
int consumerObserverCount = await consumerGrain.GetConsumerHandlesCount();
output.WriteLine("Grain {0} HandleCount={1} ObserverCount={2}", consumerGrainId, consumerHandleCount, consumerObserverCount);
Assert.Equal(expectedNumConsumers, consumerHandleCount);
Assert.Equal(expectedNumConsumers, consumerObserverCount);
}
private void CheckSilosRunning(string when, int expectedNumSilos)
{
Assert.Equal(expectedNumSilos, this.HostedCluster.GetActiveSilos().Count());
}
protected async Task<bool> CheckGrainCounts()
{
#if USE_GENERICS
string grainType = typeof(StreamReliabilityTestGrain<int>).FullName;
#else
string grainType = typeof(StreamReliabilityTestGrain).FullName;
#endif
IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0);
SimpleGrainStatistic[] grainStats = await mgmtGrain.GetSimpleGrainStatistics();
output.WriteLine("Found grains " + Utils.EnumerableToString(grainStats));
var grainLocs = grainStats.Where(gs => gs.GrainType == grainType).ToArray();
Assert.True(grainLocs.Length > 0, "Found too few grains");
Assert.True(grainLocs.Length <= 2, "Found too many grains " + grainLocs.Length);
bool sameSilo = grainLocs.Length == 1;
if (sameSilo)
{
StreamTestUtils.Assert_AreEqual(output, 2, grainLocs[0].ActivationCount, "Num grains on same Silo " + grainLocs[0].SiloAddress);
}
else
{
StreamTestUtils.Assert_AreEqual(output, 1, grainLocs[0].ActivationCount, "Num grains on Silo " + grainLocs[0].SiloAddress);
StreamTestUtils.Assert_AreEqual(output, 1, grainLocs[1].ActivationCount, "Num grains on Silo " + grainLocs[1].SiloAddress);
}
return sameSilo;
}
#if USE_GENERICS
protected async Task CheckReceivedCounts<T>(string when, IStreamReliabilityTestGrain<T> consumerGrain, int expectedReceivedCount, int expectedErrorsCount)
#else
protected async Task CheckReceivedCounts(string when, IStreamReliabilityTestGrain consumerGrain, int expectedReceivedCount, int expectedErrorsCount)
#endif
{
long pk = consumerGrain.GetPrimaryKeyLong();
int receivedCount = 0;
for (int i = 0; i < 20; i++)
{
receivedCount = await consumerGrain.GetReceivedCount();
output.WriteLine("After {0}s ReceivedCount={1} for grain {2}", i, receivedCount, pk);
if (receivedCount == expectedReceivedCount)
break;
Thread.Sleep(TimeSpan.FromSeconds(1));
}
StreamTestUtils.Assert_AreEqual(output, expectedReceivedCount, receivedCount,
"ReceivedCount for stream {0} for grain {1} {2}", _streamId, pk, when);
int errorsCount = await consumerGrain.GetErrorsCount();
StreamTestUtils.Assert_AreEqual(output, expectedErrorsCount, errorsCount, "ErrorsCount for stream {0} for grain {1} {2}", _streamId, pk, when);
}
#if USE_GENERICS
protected async Task CheckConsumerCounts<T>(string when, IStreamReliabilityTestGrain<T> consumerGrain, int expectedConsumerCount)
#else
protected async Task CheckConsumerCounts(string when, IStreamReliabilityTestGrain consumerGrain, int expectedConsumerCount)
#endif
{
int consumerCount = await consumerGrain.GetConsumerCount();
StreamTestUtils.Assert_AreEqual(output, expectedConsumerCount, consumerCount, "ConsumerCount for stream {0} {1}", _streamId, when);
}
}
}
// ReSharper restore ConvertToConstant.Local
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using Bloom.Api;
using Bloom.MiscUI;
using Bloom.ToPalaso;
using Bloom.web.controllers;
using SIL.IO;
using SIL.Reporting;
using SIL.Windows.Forms.Reporting;
namespace Bloom.ErrorReporter
{
/// <summary>
/// An Error Reporter designed to be used with libpalaso's ErrorReport.
/// Unlike WinFormsErrorReporter, which uses WinForms to display the UI, this utilizes a browser to display the UI
/// </summary>
public class HtmlErrorReporter: IErrorReporter
{
private HtmlErrorReporter()
{
ResetToDefaults();
DefaultReportLabel = L10NSharp.LocalizationManager.GetString("ErrorReportDialog.Report", "Report");
}
private static HtmlErrorReporter _instance;
public static HtmlErrorReporter Instance
{
get
{
if (_instance == null)
{
_instance = new HtmlErrorReporter();
}
return _instance;
}
}
internal string DefaultReportLabel { get; private set; }
static object _lock = new object();
#region Dependencies exposed for unit tests to mock
internal IReactDialogFactory BrowserDialogFactory = new ReactDialogFactory();
internal Control Control { get; set; }
private IBloomServer _bloomServer = null;
internal IBloomServer BloomServer
{
// This property allows the unit tests to set the Bloom Server to a mocked value.
// However, if it hasn't been set at the time the value is read, then it lazily sets it
// to the default singleton instance.
// We can't do the simple/eager instantiation at construction time of this object
// because the Bloom Server is still null when this object is constructed.
get
{
if (_bloomServer == null)
_bloomServer = Api.BloomServer._theOneInstance;
return _bloomServer;
}
set
{
_bloomServer = value;
}
}
#endregion
#region Additional NotifyUserOfProblem parameters saved as instance vars
protected string ReportButtonLabel { get; set; }
protected string SecondaryActionButtonLabel { get; set; }
protected Action<Exception, string> OnSecondaryActionPressed { get; set; } = null;
protected ErrorResult? SecondaryActionResult { get; set; }
#endregion
private void ResetToDefaults()
{
ReportButtonLabel = null;
SecondaryActionButtonLabel = null;
OnSecondaryActionPressed = null;
SecondaryActionResult = null;
Control = null;
}
/// <summary>
/// Sets all the extra parameters required for the auto-invoke versions of NotifyUserOfProblem to work correctly.
/// They can't be directly added to NotifyUserOfProblem because it needs to match the IErrorReporter interface.
/// As a result, we work around that by having class instance variables that you set before invoking NotifyUserOfProblem.
/// This function exposes only the class instance variables that are necessary for Auto-Invoke versions to work.
/// Auto-invoke means the overloads that want an Action, which will be automatically invoked by ErrorReport when the corresponding button is pressed.
/// (as opposed to the overloads that use return codes to accomplish that)
/// </summary>
/// <param name="reportButtonLabel">The localized text for the Report button (aka alternateButton1 in libpalaso)</param>
/// <param name="secondaryActionButtonLabel">The localized text for the Secondary Action button. For example, you might offer a "Retry" button</param>
/// <param name="onSecondaryActionPressed">The Action that will be invoked after the Secondary Action button is pressed. Note: the action is invoked after the dialog is closed.</param>
protected void SetExtraParamsForCustomNotifyAuto(string reportButtonLabel, string secondaryActionButtonLabel, Action<Exception, string> onSecondaryActionPressed)
{
this.ReportButtonLabel = reportButtonLabel;
this.SecondaryActionButtonLabel = secondaryActionButtonLabel;
this.OnSecondaryActionPressed = onSecondaryActionPressed;
this.SecondaryActionResult = null;
}
/// <summary>
/// Sets all the extra parameters required for the manual-invoke versions of NotifyUserOfProblem to work correctly.
/// They can't be directly added to NotifyUserOfProblem because it needs to match the IErrorReporter interface.
/// As a result, we work around that by having class instance variables that you set beofre invoking NotifyUserOfProblem.
/// This function exposes only the class instance variables that are necessary for Manual-Invoke versions to work.
/// Manual-invoke means the overloads that utilize return codes to tell the caller which button was pressed.
/// Then the caller manually invokes the code that should happen for that button.
/// (as opposed to the overloads that ask for an action to invoke for you)
/// </summary>
/// <param name="reportButtonLabel">The localized text for the Report button (aka alternateButton1 in libpalaso)</param>
/// <param name="secondaryActionButtonLabel">The localized text for the Secondary Action button. For example, you might offer a "Retry" button</param>
/// <param name="resultIfSecondaryActionPressed">The return code that the caller would like this function to return to indicate that the secondary action button was pressed</param>
protected void SetExtraParamsForCustomNotifyManual(string reportButtonLabel, string secondaryActionButtonLabel, ErrorResult resultIfSecondaryActionPressed)
{
this.ReportButtonLabel = reportButtonLabel;
this.SecondaryActionButtonLabel = secondaryActionButtonLabel;
this.SecondaryActionResult = resultIfSecondaryActionPressed;
}
/// <summary>
/// Notifies the user of a problem, using a browser-based dialog.
/// A Report and a secondary action button are potentially available. This method
/// will automatically invoke the corresponding Action for each button that is clicked.
/// </summary>
/// <param name="reportButtonLabel">The localized text that goes on the Report button. null means Use Default ("Report"). Empty string means disable the button</param>
/// <param name="secondaryActionButtonLabel">The localized text that goes on the Report button. Either null or empty string means disable the button</param>
/// <param name="onSecondaryActionPressed">Optional - The action which will be invoked if secondary action button is clicked. You may pass null, but that will invoke the ErrorReport default (which is to report a non-fatal exception). ErrorReport.cs will pass the Action an exception ({error}) and a string (the {message} formatted with {args}, which you will probably ignore.</param>
/// <param name="error">Optional - Any exception that was encountered that should be included in the notification/report. May be null</param>
/// <param name="message">The message to show to the user. May be a format string.</param>
/// <param name="args">The args to pass to the {message} format string</param>
public void CustomNotifyUserAuto(string reportButtonLabel, string secondaryActionButtonLabel, Action<Exception, string> onSecondaryActionPressed,
Exception error, string message, params object[] args)
{
Debug.Assert(!System.Threading.Monitor.IsEntered(_lock), "Expected object not to have been locked yet, but the current thread already aquired it earlier. Bug?");
// Block until lock acquired
System.Threading.Monitor.Enter(_lock);
try
{
SetExtraParamsForCustomNotifyAuto(reportButtonLabel, secondaryActionButtonLabel, onSecondaryActionPressed);
// Note: It's more right to go through ErrorReport than to invoke
// our NotifyUserOfProblem directly. ErrorReport has some logic,
// and it's also necessary if we have a CompositeErrorReporter
ErrorReport.NotifyUserOfProblem(error, message, args);
}
finally
{
System.Threading.Monitor.Exit(_lock);
}
}
/// <summary>
/// Notifies the user of a problem, using a browser-based dialog.
/// A Report and a secondary action button are potentially available. This method
/// will automatically invoke the corresponding Action for each button that is clicked.
/// </summary>
/// <param name="reportButtonLabel">The localized text that goes on the Report button. null means Use Default ("Report"). Empty string means disable the button</param>
/// <param name="secondaryActionButtonLabel">The localized text that goes on the Report button. Either null or empty string means disable the button</param>
/// <param name="onSecondaryActionPressed">Optional - The action which will be invoked if secondary action button is clicked. You may pass null, but that will invoke the ErrorReport default (which is to report a non-fatal exception). ErrorReport.cs will pass the Action an exception ({error}) and a string (the {message} formatted with {args}, which you will probably ignore.</param>
/// <param name="policy">Checks if we should notify the user, based on the contents of {message}</param>
/// <param name="error">Optional - Any exception that was encountered that should be included in the notification/report. May be null</param>
/// <param name="message">The message to show to the user. May be a format string.</param>
/// <param name="args">The args to pass to the {message} format string</param>
public void CustomNotifyUserAuto(string reportButtonLabel, string secondaryActionButtonLabel, Action<Exception, string> onSecondaryActionPressed,
IRepeatNoticePolicy policy, Exception error, string message, params object[] args)
{
Debug.Assert(!System.Threading.Monitor.IsEntered(_lock), "Expected object not to have been locked yet, but the current thread already aquired it earlier. Bug?");
// Block until lock acquired
System.Threading.Monitor.Enter(_lock);
try
{
SetExtraParamsForCustomNotifyAuto(reportButtonLabel, secondaryActionButtonLabel, onSecondaryActionPressed);
// Note: It's more right to go through ErrorReport than to invoke
// our NotifyUserOfProblem directly. ErrorReport has some logic,
// and it's also necessary if we have a CompositeErrorReporter
ErrorReport.NotifyUserOfProblem(policy, error, message, args);
}
finally
{
System.Threading.Monitor.Exit(_lock);
}
}
/// <summary>
/// Notifies the user of a problem, using a browser-based dialog.
/// A Report and a secondary action button are potentially available. This method
/// will return a return code to the caller to indicate which button was pressed.
/// It is the caller's responsibility to perform any appropriate actions based on the button click.
/// </summary>
/// <param name="policy">Checks if we should notify the user, based on the contents of {message}</param>
/// <param name="reportButtonLabel">The localized text that goes on the Report button. null means Use Default ("Report"). Empty string means disable the button</param>
/// <param name="resultIfReportButtonPressed">This is the value that this method should return so that the caller
/// can know if the Report button was pressed, and if so, the caller can invoke whatever actions are desired.</param>
/// <param name="secondaryActionButtonLabel">The localized text that goes on the Report button. Either null or empty string means disable the button</param>
/// <param name="resultIfSecondaryPressed">This is the value that this method should return so that the caller
/// can know if the secondary action button was pressed, and if so, the caller can invoke whatever actions are desired.</param>
/// <param name="messageFmt">The message to show to the user</param>
/// <param name="args">The args to pass to the {messageFmt} format string</param>
/// <returns>If closed normally, returns ErrorResult.OK
/// If the report button was pressed, returns {resultIfAlternateButtonPressed}.
/// If the secondary action button was pressed, returns {this.SecondaryActionResult} if that is non-null; otherwise falls back to {resultIfAlternateButtonPressed}
/// If an exception is thrown while executing this function, returns ErrorResult.Abort.
/// </returns>
public ErrorResult CustomNotifyUserManual(
IRepeatNoticePolicy policy,
string reportButtonLabel, /* The Report button is equivalent to the Details button in libpalaso's WinFormsErrorReporter of {alternateButton1} in libpalaso's ErrorReport */
ErrorResult resultIfReportButtonPressed,
string secondaryActionButtonLabel, /* An additional action such as Retry / etc */
ErrorResult resultIfSecondaryPressed,
string messageFmt,
params object[] args)
{
Debug.Assert(!System.Threading.Monitor.IsEntered(_lock), "Expected object not to have been locked yet, but the current thread already aquired it earlier. Bug?");
// Block until lock acquired
System.Threading.Monitor.Enter(_lock);
try
{
SetExtraParamsForCustomNotifyManual(reportButtonLabel, secondaryActionButtonLabel, resultIfSecondaryPressed);
// Note: It's more right to go through ErrorReport than to invoke
// our NotifyUserOfProblem directly. ErrorReport has some logic,
// and it's also necessary if we have a CompositeErrorReporter
return ErrorReport.NotifyUserOfProblem(policy, reportButtonLabel, resultIfReportButtonPressed, messageFmt, args);
}
finally
{
System.Threading.Monitor.Exit(_lock);
}
}
#region IErrorReporter interface
/// <summary>
/// Notifies the user of a problem, using a browser-based dialog.
/// Note: This is designed to be called by LibPalaso's ErrorReport class.
/// </summary>
/// <param name="policy">Checks if we should notify the user, based on the contents of {message}</param>
/// <param name="alternateButton1Label">The text that goes on the Report button. However, if speicfied, this.ReportButtonLabel takes precedence over this parameter</param>
/// <param name="resultIfAlternateButtonPressed">This is the value that this method should return so that the caller (mainly LibPalaso ErrorReport)
/// can know if the alternate button was pressed, and if so, invoke whatever actions are desired.</param>
/// <param name="message">The message to show to the user</param>
/// <returns>If closed normally, returns ErrorResult.OK
/// If the report button was pressed, returns {resultIfAlternateButtonPressed}.
/// If the secondary action button was pressed, returns {this.SecondaryActionResult} if that is non-null; otherwise falls back to {resultIfAlternateButtonPressed}
/// If an exception is throw while executing this function, returns ErrorResult.Abort.
/// </returns>
public ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string message)
{
// Let this thread try to acquire the lock, if necessary
// Note: It is expected that sometimes this function will need to acquire the lock for this thread,
// and sometimes it'll already be acquired.
// The reason is because for legacy code that calls ErrorReport directly, this function is the first entry point into this class.
// But for code that needs the new secondaryAction functionality, it needs to enter through CustomNotifyUser*().
// That function wants to acquire a lock so that the instance variables it sets aren't modified by any other thread before
// entering this NotifyUserOfProblem() function.
bool wasAlreadyLocked = System.Threading.Monitor.IsEntered(_lock);
if (!wasAlreadyLocked)
{
System.Threading.Monitor.Enter(_lock);
}
try
{
ErrorResult result = ErrorResult.OK;
if (policy.ShouldShowMessage(message))
{
ErrorReport.OnShowDetails = null;
var reportButtonLabel = GetReportButtonLabel(alternateButton1Label);
result = ShowNotifyDialog(ProblemLevel.kNotify, message, null, reportButtonLabel, resultIfAlternateButtonPressed, this.SecondaryActionButtonLabel, this.SecondaryActionResult);
}
ResetToDefaults();
return result;
}
catch (Exception e)
{
var fallbackReporter = new WinFormsErrorReporter();
fallbackReporter.ReportNonFatalException(e, new ShowAlwaysPolicy());
return ErrorResult.Abort;
}
finally
{
// NOTE: Each thread needs to make sure it calls Exit() the same number of times as it calls Enter()
// in order for other threads to be able to acquire the lock later.
if (!wasAlreadyLocked)
{
System.Threading.Monitor.Exit(_lock);
}
}
}
// ENHANCE: I think it would be good if ProblemReportApi could be split out.
// Part of it is related to serving the API requests needed to make the Problem Report Dialog work. That should stay in ProblemReportApi.cs.
// Another part of it is related to bring up a browser dialog. I think that part should be moved here into this HtmlErrorReporter class.
// It'll be a big job though.
//
// Also, ProblemReportApi and this class share some parallel ideas because this class was derived from ProblemReportApi,
// but they're not 100% identical because this class revamped some of those ideas.
// So those will need to be merged.
public void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy)
{
// Note: I think it's better to call ProblemReportApi directly instead of through NonFatalProblem first.
// Otherwise you have to deal with NonFatalProblem's ModalIf, PassiveIf parameters.
// And you also have to worry about whether Sentry will happen twice.
ProblemReportApi.ShowProblemDialog(GetControlToUse(), exception, null, ProblemLevel.kNonFatal);
}
public void ReportNonFatalExceptionWithMessage(Exception error, string messageFormat, params object[] args)
{
var message = String.Format(messageFormat, args);
var shortMsg = error.Data["ProblemReportShortMessage"] as string;
var imageFilepath = error.Data["ProblemImagePath"] as string;
string[] extraFilepaths = null;
if (!String.IsNullOrEmpty(imageFilepath) && RobustFile.Exists(imageFilepath))
{
extraFilepaths = new string[] { imageFilepath };
}
ProblemReportApi.ShowProblemDialog(GetControlToUse(), error, message , ProblemLevel.kNonFatal,
shortMsg, additionalPathsToInclude: extraFilepaths);
}
public void ReportNonFatalMessageWithStackTrace(string messageFormat, params object[] args)
{
var stackTrace = new StackTrace(true);
var userLevelMessage = String.Format(messageFormat, args);
string detailedMessage = FormatMessageWithStackTrace(userLevelMessage, stackTrace);
ProblemReportApi.ShowProblemDialog(GetControlToUse(), null, detailedMessage, ProblemLevel.kNonFatal, userLevelMessage);
}
public void ReportFatalException(Exception e)
{
ProblemReportApi.ShowProblemDialog(GetControlToUse(), e, null, ProblemLevel.kFatal);
Quit();
}
public void ReportFatalMessageWithStackTrace(string messageFormat, object[] args)
{
var stackTrace = new StackTrace(true);
var userLevelMessage = String.Format(messageFormat, args);
string detailedMessage = FormatMessageWithStackTrace(userLevelMessage, stackTrace);
ProblemReportApi.ShowProblemDialog(GetControlToUse(), null, detailedMessage, ProblemLevel.kFatal, userLevelMessage);
Quit();
}
#endregion
protected Control GetControlToUse()
{
return this.Control ?? Form.ActiveForm ?? FatalExceptionHandler.ControlOnUIThread;
}
private string FormatMessageWithStackTrace(string message, StackTrace stackTrace)
{
return $"Message (not an exception): {message}" + Environment.NewLine
+ Environment.NewLine
+ "--Stack--" + Environment.NewLine
+ stackTrace.ToString();
}
private static void Quit() => Process.GetCurrentProcess().Kill(); // Same way WinFormsErrorReporter quits
protected string GetReportButtonLabel(string labelFromCaller)
{
// Note: We use null to indicate Not Set, so it will fall back to labelFromCaller
// "" is used to indicate that it was explicitly set and the desire is to disable the Report button.
if (this.ReportButtonLabel != null)
{
return this.ReportButtonLabel;
}
else if (labelFromCaller != "Details")
{
return labelFromCaller;
}
else
{
return DefaultReportLabel;
}
}
private ErrorResult ShowNotifyDialog(string severity, string messageText, Exception exception,
string reportButtonLabel, ErrorResult reportPressedResult,
string secondaryButtonLabel, ErrorResult? secondaryPressedResult)
{
// Before we do anything that might be "risky", put the problem in the log.
ProblemReportApi.LogProblem(exception, messageText, severity);
ErrorResult returnResult = ErrorResult.OK;
// ENHANCE: Allow the caller to pass in the control, which would be at the front of this.
//System.Windows.Forms.Control control = Form.ActiveForm ?? FatalExceptionHandler.ControlOnUIThread;
var control = GetControlToUse();
SafeInvoke.InvokeIfPossible("Show Error Reporter", control, false, () =>
{
// Uses a browser dialog to show the problem report
try
{
StartupScreenManager.CloseSplashScreen(); // if it's still up, it'll be on top of the dialog
var message = GetMessage(messageText, exception);
if (!Api.BloomServer.ServerIsListening)
{
// There's no hope of using the HtmlErrorReporter dialog if our server is not yet running.
// We'll likely get errors, maybe Javascript alerts, that won't lead to a clean fallback to
// the exception handler below. Besides, failure of HtmlErrorReporter in these circumstances
// is expected; we just want to cleanly report the original problem, not to report a
// failure of error handling.
// Note: HtmlErrorReporter supports up to 3 buttons (OK, Report, and [Secondary action]), but the fallback reporter only supports a max of two.
// Well, just going to have to drop the secondary action.
returnResult = (ErrorResult)ShowFallbackProblemDialog(severity, exception, messageText, null, false, reportButtonLabel, reportPressedResult);
return;
}
object props = new { level = ProblemLevel.kNotify, reportLabel = reportButtonLabel, secondaryLabel = secondaryButtonLabel, message = message };
// Precondition: we must be on the UI thread for Gecko to work.
using (var dlg = BrowserDialogFactory.CreateReactDialog("problemReportBundle", props))
{
dlg.FormBorderStyle = FormBorderStyle.FixedToolWindow; // Allows the window to be dragged around
dlg.ControlBox = true; // Add controls like the X button back to the top bar
dlg.Text = ""; // Remove the title from the WinForms top bar
dlg.Width = 620;
// 360px was experimentally determined as what was needed for the longest known text for NotifyUserOfProblem
// (which is "Before saving, Bloom did an integrity check of your book [...]" from BookStorage.cs)
// You can make this height taller if need be.
// A scrollbar will appear if the height is not tall enough for the text
dlg.Height = 360;
// ShowDialog will cause this thread to be blocked (because it spins up a modal) until the dialog is closed.
BloomServer.RegisterThreadBlocking();
try
{
dlg.ShowDialog();
// Take action if the user clicked a button other than Close
if (dlg.CloseSource == "closedByAlternateButton")
{
// OnShowDetails will be invoked if this method returns {resultIfAlternateButtonPressed}
// FYI, setting to null is OK. It should cause ErrorReport to reset to default handler.
ErrorReport.OnShowDetails = OnSecondaryActionPressed;
returnResult = secondaryPressedResult ?? reportPressedResult;
}
else if (dlg.CloseSource == "closedByReportButton")
{
ErrorReport.OnShowDetails = OnReportPressed;
returnResult = reportPressedResult;
}
// Note: With the way LibPalaso's ErrorReport is designed,
// its intention is that after OnShowDetails is invoked and closed, you will not come back to the Notify Dialog
// This code has been implemented to follow that model
//
// But now that we have more options, it might be nice to come back to this dialog.
// If so, you'd need to add/update some code in this section.
}
finally
{
BloomServer.RegisterThreadUnblocked();
}
}
}
catch (Exception errorReporterException)
{
Logger.WriteError("*** HtmlErrorReporter threw an exception trying to display", errorReporterException);
// At this point our problem reporter has failed for some reason, so we want the old WinForms handler
// to report both the original error for which we tried to open our dialog and this new one where
// the dialog itself failed.
// In order to do that, we create a new exception with the original exception (if there was one) as the
// inner exception. We include the message of the exception we just caught. Then we call the
// old WinForms fatal exception report directly.
// In any case, both of the errors will be logged by now.
var message = "Bloom's error reporting failed: " + errorReporterException.Message;
// Fallback to Winforms in case of trouble getting the browser to work
var fallbackReporter = new WinFormsErrorReporter();
fallbackReporter.ReportFatalException(new ApplicationException(message, exception ?? errorReporterException));
}
});
return returnResult;
}
internal static string GetMessage(string detailedMessage, Exception exception)
{
return !string.IsNullOrEmpty(detailedMessage) ? detailedMessage : exception.Message;
}
public static void OnReportPressed(Exception error, string message)
{
ErrorReport.ReportNonFatalExceptionWithMessage(error, message);
}
public static ErrorResult? ShowFallbackProblemDialog(string levelOfProblem, Exception exception, string detailedMessage, string shortUserLevelMessage, bool isShortMessagePreEncoded = false,
string notifySecondaryButtonLabel = null, ErrorResult? notifySecondaryPressedResult = null)
{
var fallbackReporter = new WinFormsErrorReporter();
if (shortUserLevelMessage == null)
shortUserLevelMessage = "";
string decodedShortUserLevelMessage = isShortMessagePreEncoded ? XmlString.FromXml(shortUserLevelMessage).Unencoded : shortUserLevelMessage;
string message = decodedShortUserLevelMessage;
if (!String.IsNullOrEmpty(detailedMessage))
message += $"\n{detailedMessage}";
if (levelOfProblem == ProblemLevel.kFatal)
{
if (exception != null)
fallbackReporter.ReportFatalException(exception);
else
fallbackReporter.ReportFatalMessageWithStackTrace(message, null);
return null;
}
else if (levelOfProblem == ProblemLevel.kNonFatal || levelOfProblem == ProblemLevel.kUser)
{
// FYI, if levelOfProblem==kUser, we're unfortunately going to be
// using the messaging from NonFatal even though we would ideally like to have the customized messaging for levelOfProblem==kUser,
// but we'll just live with it because there's no easy way to customize it. It's probably an extremely rare situation anyway
if (String.IsNullOrEmpty(message))
fallbackReporter.ReportNonFatalException(exception, new ShowAlwaysPolicy());
else
fallbackReporter.ReportNonFatalExceptionWithMessage(exception, message);
return null;
}
else // Presumably, levelOfProblem = "notify" now
{
if (String.IsNullOrEmpty(notifySecondaryButtonLabel) || notifySecondaryPressedResult == null)
{
return fallbackReporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), null, ErrorResult.OK,
message);
}
else
{
return fallbackReporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), notifySecondaryButtonLabel, notifySecondaryPressedResult ?? ErrorResult.OK, message);
}
}
}
}
}
| |
/*
* NPlot - A charting library for .NET
*
* LinearAxis.cs
* Copyright (C) 2003-2006 Matt Howlett and others.
* 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 System;
using System.Collections;
using System.Drawing;
using System.Text;
namespace NPlot
{
/// <summary>
/// Provides functionality for drawing axes with a linear numeric scale.
/// </summary>
public class LinearAxis : Axis, ICloneable
{
/// <summary>
/// If LargeTickStep isn't specified, then a suitable value is
/// calculated automatically. To determine the tick spacing, the
/// world axis length is divided by ApproximateNumberLargeTicks
/// and the next lowest distance m*10^e for some m in the Mantissas
/// set and some integer e is used as the large tick spacing.
/// </summary>
public float ApproxNumberLargeTicks = 3.0f;
/// <summary>
/// If LargeTickStep isn't specified, then a suitable value is
/// calculated automatically. The value will be of the form
/// m*10^e for some m in this set.
/// </summary>
public double[] Mantissas = {1.0, 2.0, 5.0};
/// <summary>
/// If NumberOfSmallTicks isn't specified then ....
/// If specified LargeTickStep manually, then no small ticks unless
/// NumberOfSmallTicks specified.
/// </summary>
public int[] SmallTickCounts = {4, 1, 4};
/// <summary>
/// If set !NaN, gives the distance between large ticks.
/// </summary>
private double largeTickStep_ = double.NaN;
private double largeTickValue_ = double.NaN;
private object numberSmallTicks_;
private double offset_;
private double scale_ = 1.0;
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="a">The Axis to clone</param>
public LinearAxis(Axis a)
: base(a)
{
Init();
}
/// <summary>
/// Default constructor.
/// </summary>
public LinearAxis()
{
Init();
}
/// <summary>
/// Construct a linear axis with the provided world min and max values.
/// </summary>
/// <param name="worldMin">the world minimum value of the axis.</param>
/// <param name="worldMax">the world maximum value of the axis.</param>
public LinearAxis(double worldMin, double worldMax)
: base(worldMin, worldMax)
{
Init();
}
/// <summary>
/// The distance between large ticks. If this is set to NaN [default],
/// this distance will be calculated automatically.
/// </summary>
public double LargeTickStep
{
set { largeTickStep_ = value; }
get { return largeTickStep_; }
}
/// <summary>
/// If set, a large tick will be placed at this position, and other large ticks will
/// be placed relative to this position.
/// </summary>
public double LargeTickValue
{
set { largeTickValue_ = value; }
get { return largeTickValue_; }
}
/// <summary>
/// The number of small ticks between large ticks.
/// </summary>
public int NumberOfSmallTicks
{
set { numberSmallTicks_ = value; }
get
{
// TODO: something better here.
return (int) numberSmallTicks_;
}
}
/// <summary>
/// Scale to apply to world values when labelling axis:
/// (labelWorld = world * scale + offset). This does not
/// affect the "real" world range of the axis.
/// </summary>
public double Scale
{
get { return scale_; }
set { scale_ = value; }
}
/// <summary>
/// Offset to apply to world values when labelling the axis:
/// (labelWorld = axisWorld * scale + offset). This does not
/// affect the "real" world range of the axis.
/// </summary>
public double Offset
{
get { return offset_; }
set { offset_ = value; }
}
/// <summary>
/// Deep copy of LinearAxis.
/// </summary>
/// <returns>A copy of the LinearAxis Class</returns>
public override object Clone()
{
LinearAxis a = new LinearAxis();
// ensure that this isn't being called on a derived type. If it is, then oh no!
if (GetType() != a.GetType())
{
throw new NPlotException("Clone not defined in derived type. Help!");
}
DoClone(this, a);
return a;
}
/// <summary>
/// Helper method for Clone.
/// </summary>
protected void DoClone(LinearAxis b, LinearAxis a)
{
Axis.DoClone(b, a);
a.numberSmallTicks_ = b.numberSmallTicks_;
a.largeTickValue_ = b.largeTickValue_;
a.largeTickStep_ = b.largeTickStep_;
a.offset_ = b.offset_;
a.scale_ = b.scale_;
}
private void Init()
{
NumberFormat = "{0:g5}";
}
/// <summary>
/// Draws the large and small ticks [and tick labels] for this axis.
/// </summary>
/// <param name="g">The graphics surface on which to draw.</param>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="boundingBox">out: smallest box that completely surrounds all ticks and associated labels for this axis.</param>
/// <param name="labelOffset">out: offset from the axis to draw the axis label.</param>
protected override void DrawTicks(
Graphics g,
Point physicalMin,
Point physicalMax,
out object labelOffset,
out object boundingBox)
{
Point tLabelOffset;
Rectangle tBoundingBox;
labelOffset = getDefaultLabelOffset(physicalMin, physicalMax);
boundingBox = null;
ArrayList largeTickPositions;
ArrayList smallTickPositions;
WorldTickPositions(physicalMin, physicalMax, out largeTickPositions, out smallTickPositions);
labelOffset = new Point(0, 0);
boundingBox = null;
if (largeTickPositions.Count > 0)
{
for (int i = 0; i < largeTickPositions.Count; ++i)
{
double labelNumber = (double) largeTickPositions[i];
// TODO: Find out why zero is sometimes significantly not zero [seen as high as 10^-16].
if (Math.Abs(labelNumber) < 0.000000000000001)
{
labelNumber = 0.0;
}
StringBuilder label = new StringBuilder();
label.AppendFormat(NumberFormat, labelNumber);
DrawTick(g, ((double) largeTickPositions[i]/scale_ - offset_),
LargeTickSize, label.ToString(),
new Point(0, 0), physicalMin, physicalMax,
out tLabelOffset, out tBoundingBox);
UpdateOffsetAndBounds(ref labelOffset, ref boundingBox,
tLabelOffset, tBoundingBox);
}
}
for (int i = 0; i < smallTickPositions.Count; ++i)
{
DrawTick(g, ((double) smallTickPositions[i]/scale_ - offset_),
SmallTickSize, "",
new Point(0, 0), physicalMin, physicalMax,
out tLabelOffset, out tBoundingBox);
// assume bounding box and label offset unchanged by small tick bounds.
}
}
/// <summary>
/// Determines the positions, in world coordinates, of the small ticks
/// if they have not already been generated.
/// </summary>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="largeTickPositions">The positions of the large ticks.</param>
/// <param name="smallTickPositions">If null, small tick positions are returned via this parameter. Otherwise this function does nothing.</param>
internal override void WorldTickPositions_SecondPass(
Point physicalMin,
Point physicalMax,
ArrayList largeTickPositions,
ref ArrayList smallTickPositions)
{
// return if already generated.
if (smallTickPositions != null)
return;
int physicalAxisLength = Utils.Distance(physicalMin, physicalMax);
double adjustedMax = AdjustedWorldValue(WorldMax);
double adjustedMin = AdjustedWorldValue(WorldMin);
smallTickPositions = new ArrayList();
// TODO: Can optimize this now.
bool shouldCullMiddle;
double bigTickSpacing = DetermineLargeTickStep(physicalAxisLength, out shouldCullMiddle);
int nSmall = DetermineNumberSmallTicks(bigTickSpacing);
double smallTickSpacing = bigTickSpacing/nSmall;
// if there is at least one big tick
if (largeTickPositions.Count > 0)
{
double pos1 = (double) largeTickPositions[0] - smallTickSpacing;
while (pos1 > adjustedMin)
{
smallTickPositions.Add(pos1);
pos1 -= smallTickSpacing;
}
}
for (int i = 0; i < largeTickPositions.Count; ++i)
{
for (int j = 1; j < nSmall; ++j)
{
double pos = (double) largeTickPositions[i] + (j)*smallTickSpacing;
if (pos <= adjustedMax)
{
smallTickPositions.Add(pos);
}
}
}
}
/// <summary>
/// Adjusts a real world value to one that has been modified to
/// reflect the Axis Scale and Offset properties.
/// </summary>
/// <param name="world">world value to adjust</param>
/// <returns>adjusted world value</returns>
public double AdjustedWorldValue(double world)
{
return world*scale_ + offset_;
}
/// <summary>
/// Determines the positions, in world coordinates, of the large ticks.
/// When the physical extent of the axis is small, some of the positions
/// that were generated in this pass may be converted to small tick
/// positions and returned as well.
/// If the LargeTickStep isn't set then this is calculated automatically and
/// depends on the physical extent of the axis.
/// </summary>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="largeTickPositions">ArrayList containing the positions of the large ticks.</param>
/// <param name="smallTickPositions">ArrayList containing the positions of the small ticks if calculated, null otherwise.</param>
internal override void WorldTickPositions_FirstPass(
Point physicalMin,
Point physicalMax,
out ArrayList largeTickPositions,
out ArrayList smallTickPositions
)
{
// (1) error check
if (double.IsNaN(WorldMin) || double.IsNaN(WorldMax))
{
throw new NPlotException("world extent of axis not set.");
}
double adjustedMax = AdjustedWorldValue(WorldMax);
double adjustedMin = AdjustedWorldValue(WorldMin);
// (2) determine distance between large ticks.
bool shouldCullMiddle;
double tickDist = DetermineLargeTickStep(
Utils.Distance(physicalMin, physicalMax),
out shouldCullMiddle);
// (3) determine starting position.
double first = 0.0f;
if (!double.IsNaN(largeTickValue_))
{
// this works for both case when largTickValue_ lt or gt adjustedMin.
first = largeTickValue_ + (Math.Ceiling((adjustedMin - largeTickValue_)/tickDist))*tickDist;
}
else
{
if (adjustedMin > 0.0)
{
double nToFirst = Math.Floor(adjustedMin/tickDist) + 1.0f;
first = nToFirst*tickDist;
}
else
{
double nToFirst = Math.Floor(-adjustedMin/tickDist) - 1.0f;
first = -nToFirst*tickDist;
}
// could miss one, if first is just below zero.
if ((first - tickDist) >= adjustedMin)
{
first -= tickDist;
}
}
// (4) now make list of large tick positions.
largeTickPositions = new ArrayList();
if (tickDist < 0.0) // some sanity checking. TODO: remove this.
throw new NPlotException("Tick dist is negative");
double position = first;
int safetyCount = 0;
while (
(position <= adjustedMax) &&
(++safetyCount < 5000))
{
largeTickPositions.Add(position);
position += tickDist;
}
// (5) if the physical extent is too small, and the middle
// ticks should be turned into small ticks, then do this now.
smallTickPositions = null;
if (shouldCullMiddle)
{
smallTickPositions = new ArrayList();
if (largeTickPositions.Count > 2)
{
for (int i = 1; i < largeTickPositions.Count - 1; ++i)
{
smallTickPositions.Add(largeTickPositions[i]);
}
}
ArrayList culledPositions = new ArrayList();
culledPositions.Add(largeTickPositions[0]);
culledPositions.Add(largeTickPositions[largeTickPositions.Count - 1]);
largeTickPositions = culledPositions;
}
}
/// <summary>
/// Calculates the world spacing between large ticks, based on the physical
/// axis length (parameter), world axis length, Mantissa values and
/// MinPhysicalLargeTickStep. A value such that at least two
/// </summary>
/// <param name="physicalLength">physical length of the axis</param>
/// <param name="shouldCullMiddle">
/// Returns true if we were forced to make spacing of
/// large ticks too small in order to ensure that there are at least two of
/// them. The draw ticks method should not draw more than two large ticks if this
/// returns true.
/// </param>
/// <returns>Large tick spacing</returns>
/// <remarks>TODO: This can be optimised a bit.</remarks>
private double DetermineLargeTickStep(float physicalLength, out bool shouldCullMiddle)
{
shouldCullMiddle = false;
if (double.IsNaN(WorldMin) || double.IsNaN(WorldMax))
{
throw new NPlotException("world extent of axis not set.");
}
// if the large tick has been explicitly set, then return this.
if (!double.IsNaN(largeTickStep_))
{
if (largeTickStep_ <= 0.0f)
{
throw new NPlotException(
"can't have negative or zero tick step - reverse WorldMin WorldMax instead."
);
}
return largeTickStep_;
}
// otherwise we need to calculate the large tick step ourselves.
// adjust world max and min for offset and scale properties of axis.
double adjustedMax = AdjustedWorldValue(WorldMax);
double adjustedMin = AdjustedWorldValue(WorldMin);
double range = adjustedMax - adjustedMin;
// if axis has zero world length, then return arbitrary number.
if (Utils.DoubleEqual(adjustedMax, adjustedMin))
{
return 1.0f;
}
double approxTickStep;
if (TicksIndependentOfPhysicalExtent)
{
approxTickStep = range/6.0f;
}
else
{
approxTickStep = (MinPhysicalLargeTickStep/physicalLength)*range;
}
double exponent = Math.Floor(Math.Log10(approxTickStep));
double mantissa = Math.Pow(10.0, Math.Log10(approxTickStep) - exponent);
// determine next whole mantissa below the approx one.
int mantissaIndex = Mantissas.Length - 1;
for (int i = 1; i < Mantissas.Length; ++i)
{
if (mantissa < Mantissas[i])
{
mantissaIndex = i - 1;
break;
}
}
// then choose next largest spacing.
mantissaIndex += 1;
if (mantissaIndex == Mantissas.Length)
{
mantissaIndex = 0;
exponent += 1.0;
}
if (!TicksIndependentOfPhysicalExtent)
{
// now make sure that the returned value is such that at least two
// large tick marks will be displayed.
double tickStep = Math.Pow(10.0, exponent)*Mantissas[mantissaIndex];
float physicalStep = (float) ((tickStep/range)*physicalLength);
while (physicalStep > physicalLength/2)
{
shouldCullMiddle = true;
mantissaIndex -= 1;
if (mantissaIndex == -1)
{
mantissaIndex = Mantissas.Length - 1;
exponent -= 1.0;
}
tickStep = Math.Pow(10.0, exponent)*Mantissas[mantissaIndex];
physicalStep = (float) ((tickStep/range)*physicalLength);
}
}
// and we're done.
return Math.Pow(10.0, exponent)*Mantissas[mantissaIndex];
}
/// <summary>
/// Given the large tick step, determine the number of small ticks that should
/// be placed in between.
/// </summary>
/// <param name="bigTickDist">the large tick step.</param>
/// <returns>the number of small ticks to place between large ticks.</returns>
private int DetermineNumberSmallTicks(double bigTickDist)
{
if (numberSmallTicks_ != null)
{
return (int) numberSmallTicks_ + 1;
}
if (SmallTickCounts.Length != Mantissas.Length)
{
throw new NPlotException("Mantissa.Length != SmallTickCounts.Length");
}
if (bigTickDist > 0.0f)
{
double exponent = Math.Floor(Math.Log10(bigTickDist));
double mantissa = Math.Pow(10.0, Math.Log10(bigTickDist) - exponent);
for (int i = 0; i < Mantissas.Length; ++i)
{
if (Math.Abs(mantissa - Mantissas[i]) < 0.001)
{
return SmallTickCounts[i] + 1;
}
}
}
return 0;
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using UnityEditorInternal;
using Cinemachine.Utility;
namespace Cinemachine.Editor
{
[CustomEditor(typeof(CinemachinePath))]
internal sealed class CinemachinePathEditor : BaseEditor<CinemachinePath>
{
private ReorderableList mWaypointList;
static bool mWaypointsExpanded;
static bool mPreferHandleSelection = true;
protected override List<string> GetExcludedPropertiesInInspector()
{
List<string> excluded = base.GetExcludedPropertiesInInspector();
excluded.Add(FieldPath(x => x.m_Waypoints));
return excluded;
}
void OnEnable()
{
mWaypointList = null;
}
public override void OnInspectorGUI()
{
BeginInspector();
if (mWaypointList == null)
SetupWaypointList();
if (mWaypointList.index >= mWaypointList.count)
mWaypointList.index = mWaypointList.count - 1;
// Ordinary properties
DrawRemainingPropertiesInInspector();
GUILayout.Label(new GUIContent("Selected Waypoint:"));
EditorGUILayout.BeginVertical(GUI.skin.box);
Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 3 + 10);
if (mWaypointList.index >= 0)
{
DrawWaypointEditor(rect, mWaypointList.index);
serializedObject.ApplyModifiedProperties();
}
else
{
if (Target.m_Waypoints.Length > 0)
{
EditorGUI.HelpBox(rect,
"Click on a waypoint in the scene view\nor in the Path Details list",
MessageType.Info);
}
else if (GUI.Button(rect, new GUIContent("Add a waypoint to the path")))
{
InsertWaypointAtIndex(mWaypointList.index);
mWaypointList.index = 0;
}
}
EditorGUILayout.EndVertical();
mPreferHandleSelection = EditorGUILayout.Toggle(
new GUIContent("Prefer Tangent Drag",
"When editing the path, if waypoint position and tangent coincide, dragging will apply preferentially to the tangent"),
mPreferHandleSelection);
mWaypointsExpanded = EditorGUILayout.Foldout(mWaypointsExpanded, "Path Details");
if (mWaypointsExpanded)
{
EditorGUI.BeginChangeCheck();
mWaypointList.DoLayoutList();
if (EditorGUI.EndChangeCheck())
serializedObject.ApplyModifiedProperties();
}
}
void SetupWaypointList()
{
mWaypointList = new ReorderableList(
serializedObject, FindProperty(x => x.m_Waypoints),
true, true, true, true);
mWaypointList.elementHeight *= 3;
mWaypointList.drawHeaderCallback = (Rect rect) =>
{
EditorGUI.LabelField(rect, "Waypoints");
};
mWaypointList.drawElementCallback
= (Rect rect, int index, bool isActive, bool isFocused) =>
{
DrawWaypointEditor(rect, index);
};
mWaypointList.onAddCallback = (ReorderableList l) =>
{
InsertWaypointAtIndex(l.index);
};
}
void DrawWaypointEditor(Rect rect, int index)
{
// Needed for accessing string names of fields
CinemachinePath.Waypoint def = new CinemachinePath.Waypoint();
Vector2 numberDimension = GUI.skin.button.CalcSize(new GUIContent("999"));
Vector2 labelDimension = GUI.skin.label.CalcSize(new GUIContent("Position"));
Vector2 addButtonDimension = new Vector2(labelDimension.y + 5, labelDimension.y + 1);
float vSpace = 2;
float hSpace = 3;
SerializedProperty element = mWaypointList.serializedProperty.GetArrayElementAtIndex(index);
rect.y += vSpace / 2;
Rect r = new Rect(rect.position, numberDimension);
Color color = GUI.color;
// GUI.color = Target.m_Appearance.pathColor;
if (GUI.Button(r, new GUIContent(index.ToString(), "Go to the waypoint in the scene view")))
{
mWaypointList.index = index;
SceneView.lastActiveSceneView.pivot = Target.EvaluatePosition(index);
SceneView.lastActiveSceneView.size = 3;
SceneView.lastActiveSceneView.Repaint();
}
GUI.color = color;
r = new Rect(rect.position, labelDimension);
r.x += hSpace + numberDimension.x;
EditorGUI.LabelField(r, "Position");
r.x += hSpace + r.width;
r.width = rect.width - (numberDimension.x + hSpace + r.width + hSpace + addButtonDimension.x + hSpace);
EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.position), GUIContent.none);
r.x += r.width + hSpace;
r.size = addButtonDimension;
GUIContent buttonContent = EditorGUIUtility.IconContent("d_RectTransform Icon");
buttonContent.tooltip = "Set to scene-view camera position";
GUIStyle style = new GUIStyle(GUI.skin.label);
style.alignment = TextAnchor.MiddleCenter;
if (GUI.Button(r, buttonContent, style))
{
Undo.RecordObject(Target, "Set waypoint");
CinemachinePath.Waypoint wp = Target.m_Waypoints[index];
Vector3 pos = SceneView.lastActiveSceneView.camera.transform.position;
wp.position = Target.transform.InverseTransformPoint(pos);
Target.m_Waypoints[index] = wp;
}
r = new Rect(rect.position, labelDimension);
r.y += numberDimension.y + vSpace;
r.x += hSpace + numberDimension.x; r.width = labelDimension.x;
EditorGUI.LabelField(r, "Tangent");
r.x += hSpace + r.width;
r.width = rect.width - (numberDimension.x + hSpace + r.width + hSpace + addButtonDimension.x + hSpace);
EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.tangent), GUIContent.none);
r.x += r.width + hSpace;
r.size = addButtonDimension;
buttonContent = EditorGUIUtility.IconContent("ol minus@2x");
buttonContent.tooltip = "Remove this waypoint";
if (GUI.Button(r, buttonContent, style))
{
Undo.RecordObject(Target, "Delete waypoint");
var list = new List<CinemachinePath.Waypoint>(Target.m_Waypoints);
list.RemoveAt(index);
Target.m_Waypoints = list.ToArray();
if (index == Target.m_Waypoints.Length)
mWaypointList.index = index - 1;
}
r = new Rect(rect.position, labelDimension);
r.y += 2 * (numberDimension.y + vSpace);
r.x += hSpace + numberDimension.x; r.width = labelDimension.x;
EditorGUI.LabelField(r, "Roll");
r.x += hSpace + labelDimension.x;
r.width = rect.width
- (numberDimension.x + hSpace)
- (labelDimension.x + hSpace)
- (addButtonDimension.x + hSpace);
r.width /= 3;
EditorGUI.MultiPropertyField(r, new GUIContent[] { new GUIContent(" ") },
element.FindPropertyRelative(() => def.roll));
r.x = rect.x + rect.width - addButtonDimension.x;
r.size = addButtonDimension;
buttonContent = EditorGUIUtility.IconContent("ol plus@2x");
buttonContent.tooltip = "Add a new waypoint after this one";
if (GUI.Button(r, buttonContent, style))
{
mWaypointList.index = index;
InsertWaypointAtIndex(index);
}
}
void InsertWaypointAtIndex(int indexA)
{
Vector3 pos = Vector3.forward;
Vector3 tangent = Vector3.right;
float roll = 0;
// Get new values from the current indexA (if any)
int numWaypoints = Target.m_Waypoints.Length;
if (indexA < 0)
indexA = numWaypoints - 1;
if (indexA >= 0)
{
int indexB = indexA + 1;
if (Target.m_Looped && indexB >= numWaypoints)
indexB = 0;
if (indexB >= numWaypoints)
{
// Extrapolate the end
if (!Target.m_Waypoints[indexA].tangent.AlmostZero())
tangent = Target.m_Waypoints[indexA].tangent;
pos = Target.m_Waypoints[indexA].position + tangent;
roll = Target.m_Waypoints[indexA].roll;
}
else
{
// Interpolate
pos = Target.transform.InverseTransformPoint(
Target.EvaluatePosition(0.5f + indexA));
tangent = Target.transform.InverseTransformDirection(
Target.EvaluateTangent(0.5f + indexA).normalized);
roll = Mathf.Lerp(
Target.m_Waypoints[indexA].roll, Target.m_Waypoints[indexB].roll, 0.5f);
}
}
Undo.RecordObject(Target, "Add waypoint");
var wp = new CinemachinePath.Waypoint();
wp.position = pos;
wp.tangent = tangent;
wp.roll = roll;
var list = new List<CinemachinePath.Waypoint>(Target.m_Waypoints);
list.Insert(indexA + 1, wp);
Target.m_Waypoints = list.ToArray();
mWaypointList.index = indexA + 1; // select it
}
void OnSceneGUI()
{
if (mWaypointList == null)
SetupWaypointList();
if (Tools.current == Tool.Move)
{
Matrix4x4 mOld = Handles.matrix;
Color colorOld = Handles.color;
Handles.matrix = Target.transform.localToWorldMatrix;
for (int i = 0; i < Target.m_Waypoints.Length; ++i)
{
DrawSelectionHandle(i);
if (mWaypointList.index == i)
{
// Waypoint is selected
if (mPreferHandleSelection)
{
DrawPositionControl(i);
DrawTangentControl(i);
}
else
{
DrawTangentControl(i);
DrawPositionControl(i);
}
}
}
Handles.color = colorOld;
Handles.matrix = mOld;
}
}
void DrawSelectionHandle(int i)
{
if (Event.current.button != 1)
{
Vector3 pos = Target.m_Waypoints[i].position;
float size = HandleUtility.GetHandleSize(pos) * 0.2f;
Handles.color = Color.white;
if (Handles.Button(pos, Quaternion.identity, size, size, Handles.SphereHandleCap)
&& mWaypointList.index != i)
{
mWaypointList.index = i;
InternalEditorUtility.RepaintAllViews();
}
// Label it
Handles.BeginGUI();
Vector2 labelSize = new Vector2(
EditorGUIUtility.singleLineHeight * 2, EditorGUIUtility.singleLineHeight);
Vector2 labelPos = HandleUtility.WorldToGUIPoint(pos);
labelPos.y -= labelSize.y / 2;
labelPos.x -= labelSize.x / 2;
GUILayout.BeginArea(new Rect(labelPos, labelSize));
GUIStyle style = new GUIStyle();
style.normal.textColor = Color.black;
style.alignment = TextAnchor.MiddleCenter;
GUILayout.Label(new GUIContent(i.ToString(), "Waypoint " + i), style);
GUILayout.EndArea();
Handles.EndGUI();
}
}
void DrawTangentControl(int i)
{
CinemachinePath.Waypoint wp = Target.m_Waypoints[i];
Vector3 hPos = wp.position + wp.tangent;
Handles.color = Color.yellow;
Handles.DrawLine(wp.position, hPos);
EditorGUI.BeginChangeCheck();
Quaternion rotation = (Tools.pivotRotation == PivotRotation.Local)
? Quaternion.identity : Quaternion.Inverse(Target.transform.rotation);
float size = HandleUtility.GetHandleSize(hPos) * 0.1f;
Handles.SphereHandleCap(0, hPos, rotation, size, EventType.Repaint);
Vector3 newPos = Handles.PositionHandle(hPos, rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Change Waypoint Tangent");
wp.tangent = newPos - wp.position;
Target.m_Waypoints[i] = wp;
Target.InvalidateDistanceCache();
}
}
void DrawPositionControl(int i)
{
CinemachinePath.Waypoint wp = Target.m_Waypoints[i];
EditorGUI.BeginChangeCheck();
Handles.color = Target.m_Appearance.pathColor;
Quaternion rotation = (Tools.pivotRotation == PivotRotation.Local)
? Quaternion.identity : Quaternion.Inverse(Target.transform.rotation);
float size = HandleUtility.GetHandleSize(wp.position) * 0.1f;
Handles.SphereHandleCap(0, wp.position, rotation, size, EventType.Repaint);
Vector3 pos = Handles.PositionHandle(wp.position, rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Move Waypoint");
wp.position = pos;
Target.m_Waypoints[i] = wp;
Target.InvalidateDistanceCache();
}
}
internal static void DrawPathGizmo(CinemachinePathBase path, Color pathColor)
{
// Draw the path
Color colorOld = Gizmos.color;
Gizmos.color = pathColor;
float step = 1f / path.m_Resolution;
Vector3 lastPos = path.EvaluatePosition(path.MinPos);
Vector3 lastW = (path.EvaluateOrientation(path.MinPos)
* Vector3.right) * path.m_Appearance.width / 2;
for (float t = path.MinPos + step; t <= path.MaxPos + step / 2; t += step)
{
Vector3 p = path.EvaluatePosition(t);
Quaternion q = path.EvaluateOrientation(t);
Vector3 w = (q * Vector3.right) * path.m_Appearance.width / 2;
Vector3 w2 = w * 1.2f;
Vector3 p0 = p - w2;
Vector3 p1 = p + w2;
Gizmos.DrawLine(p0, p1);
Gizmos.DrawLine(lastPos - lastW, p - w);
Gizmos.DrawLine(lastPos + lastW, p + w);
#if false
// Show the normals, for debugging
Gizmos.color = Color.red;
Vector3 y = (q * Vector3.up) * width / 2;
Gizmos.DrawLine(p, p + y);
Gizmos.color = pathColor;
#endif
lastPos = p;
lastW = w;
}
Gizmos.color = colorOld;
}
[DrawGizmo(GizmoType.Active | GizmoType.NotInSelectionHierarchy
| GizmoType.InSelectionHierarchy | GizmoType.Pickable, typeof(CinemachinePath))]
static void DrawGizmos(CinemachinePath path, GizmoType selectionType)
{
DrawPathGizmo(path,
(Selection.activeGameObject == path.gameObject)
? path.m_Appearance.pathColor : path.m_Appearance.inactivePathColor);
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
#region Enums
/// <summary>
/// Simulator (region) properties
/// </summary>
[Flags]
public enum RegionFlags
{
/// <summary>No flags set</summary>
None = 0,
/// <summary>Agents can take damage and be killed</summary>
AllowDamage = 1 << 0,
/// <summary>Landmarks can be created here</summary>
AllowLandmark = 1 << 1,
/// <summary>Home position can be set in this sim</summary>
AllowSetHome = 1 << 2,
/// <summary>Home position is reset when an agent teleports away</summary>
ResetHomeOnTeleport = 1 << 3,
/// <summary>Sun does not move</summary>
SunFixed = 1 << 4,
/// <summary>No object, land, etc. taxes</summary>
TaxFree = 1 << 5,
/// <summary>Disable heightmap alterations (agents can still plant
/// foliage)</summary>
BlockTerraform = 1 << 6,
/// <summary>Land cannot be released, sold, or purchased</summary>
BlockLandResell = 1 << 7,
/// <summary>All content is wiped nightly</summary>
Sandbox = 1 << 8,
/// <summary></summary>
NullLayer = 1 << 9,
/// <summary></summary>
SkipAgentAction = 1 << 10,
/// <summary></summary>
SkipUpdateInterestList = 1 << 11,
/// <summary>No collision detection for non-agent objects</summary>
SkipCollisions = 1 << 12,
/// <summary>No scripts are ran</summary>
SkipScripts = 1 << 13,
/// <summary>All physics processing is turned off</summary>
SkipPhysics = 1 << 14,
/// <summary></summary>
ExternallyVisible = 1 << 15,
/// <summary></summary>
MainlandVisible = 1 << 16,
/// <summary></summary>
PublicAllowed = 1 << 17,
/// <summary></summary>
BlockDwell = 1 << 18,
/// <summary>Flight is disabled (not currently enforced by the sim)</summary>
NoFly = 1 << 19,
/// <summary>Allow direct (p2p) teleporting</summary>
AllowDirectTeleport = 1 << 20,
/// <summary>Estate owner has temporarily disabled scripting</summary>
EstateSkipScripts = 1 << 21,
/// <summary></summary>
RestrictPushObject = 1 << 22,
/// <summary>Deny agents with no payment info on file</summary>
DenyAnonymous = 1 << 23,
/// <summary>Deny agents with payment info on file</summary>
DenyIdentified = 1 << 24,
/// <summary>Deny agents who have made a monetary transaction</summary>
DenyTransacted = 1 << 25,
/// <summary></summary>
AllowParcelChanges = 1 << 26,
/// <summary></summary>
AbuseEmailToEstateOwner = 1 << 27,
/// <summary>Region is Voice Enabled</summary>
AllowVoice = 1 << 28
}
/// <summary>
/// Access level for a simulator
/// </summary>
public enum SimAccess : byte
{
/// <summary>Minimum access level, no additional checks</summary>
Min = 0,
/// <summary>Trial accounts allowed</summary>
Trial = 7,
/// <summary>PG rating</summary>
PG = 13,
/// <summary>Mature rating</summary>
Mature = 21,
/// <summary>Simulator is offline</summary>
Down = 254,
/// <summary>Simulator does not exist</summary>
NonExistent = 255
}
#endregion Enums
/// <summary>
///
/// </summary>
public class Simulator : UDPBase, IDisposable
{
#region Structs
/// <summary>
/// Simulator Statistics
/// </summary>
public struct SimStats
{
/// <summary>Total number of packets sent by this simulator to this agent</summary>
public ulong SentPackets;
/// <summary>Total number of packets received by this simulator to this agent</summary>
public ulong RecvPackets;
/// <summary>Total number of bytes sent by this simulator to this agent</summary>
public ulong SentBytes;
/// <summary>Total number of bytes received by this simulator to this agent</summary>
public ulong RecvBytes;
/// <summary>Time in seconds agent has been connected to simulator</summary>
public int ConnectTime;
/// <summary>Total number of packets that have been resent</summary>
public int ResentPackets;
/// <summary>Total number of resent packets recieved</summary>
public int ReceivedResends;
/// <summary>Total number of pings sent to this simulator by this agent</summary>
public int SentPings;
/// <summary>Total number of ping replies sent to this agent by this simulator</summary>
public int ReceivedPongs;
/// <summary>
/// Incoming bytes per second
/// </summary>
/// <remarks>It would be nice to have this claculated on the fly, but
/// this is far, far easier</remarks>
public int IncomingBPS;
/// <summary>
/// Outgoing bytes per second
/// </summary>
/// <remarks>It would be nice to have this claculated on the fly, but
/// this is far, far easier</remarks>
public int OutgoingBPS;
/// <summary>Time last ping was sent</summary>
public int LastPingSent;
/// <summary>ID of last Ping sent</summary>
public byte LastPingID;
/// <summary></summary>
public int LastLag;
/// <summary></summary>
public int MissedPings;
/// <summary>Current time dilation of this simulator</summary>
public float Dilation;
/// <summary>Current Frames per second of simulator</summary>
public int FPS;
/// <summary>Current Physics frames per second of simulator</summary>
public float PhysicsFPS;
/// <summary></summary>
public float AgentUpdates;
/// <summary></summary>
public float FrameTime;
/// <summary></summary>
public float NetTime;
/// <summary></summary>
public float PhysicsTime;
/// <summary></summary>
public float ImageTime;
/// <summary></summary>
public float ScriptTime;
/// <summary></summary>
public float AgentTime;
/// <summary></summary>
public float OtherTime;
/// <summary>Total number of objects Simulator is simulating</summary>
public int Objects;
/// <summary>Total number of Active (Scripted) objects running</summary>
public int ScriptedObjects;
/// <summary>Number of agents currently in this simulator</summary>
public int Agents;
/// <summary>Number of agents in neighbor simulators</summary>
public int ChildAgents;
/// <summary>Number of Active scripts running in this simulator</summary>
public int ActiveScripts;
/// <summary></summary>
public int LSLIPS;
/// <summary></summary>
public int INPPS;
/// <summary></summary>
public int OUTPPS;
/// <summary>Number of downloads pending</summary>
public int PendingDownloads;
/// <summary>Number of uploads pending</summary>
public int PendingUploads;
/// <summary></summary>
public int VirtualSize;
/// <summary></summary>
public int ResidentSize;
/// <summary>Number of local uploads pending</summary>
public int PendingLocalUploads;
/// <summary>Unacknowledged bytes in queue</summary>
public int UnackedBytes;
}
#endregion Structs
#region Public Members
/// <summary>A public reference to the client that this Simulator object
/// is attached to</summary>
public GridClient Client;
/// <summary></summary>
public UUID ID = UUID.Zero;
/// <summary>The capabilities for this simulator</summary>
public Caps Caps = null;
/// <summary></summary>
public ulong Handle;
/// <summary>The current version of software this simulator is running</summary>
public string SimVersion = String.Empty;
/// <summary></summary>
public string Name = String.Empty;
/// <summary>A 64x64 grid of parcel coloring values. The values stored
/// in this array are of the <seealso cref="ParcelArrayType"/> type</summary>
public byte[] ParcelOverlay = new byte[4096];
/// <summary></summary>
public int ParcelOverlaysReceived;
/// <summary></summary>
public float TerrainHeightRange00;
/// <summary></summary>
public float TerrainHeightRange01;
/// <summary></summary>
public float TerrainHeightRange10;
/// <summary></summary>
public float TerrainHeightRange11;
/// <summary></summary>
public float TerrainStartHeight00;
/// <summary></summary>
public float TerrainStartHeight01;
/// <summary></summary>
public float TerrainStartHeight10;
/// <summary></summary>
public float TerrainStartHeight11;
/// <summary></summary>
public float WaterHeight;
/// <summary></summary>
public UUID SimOwner = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase0 = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase1 = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase2 = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase3 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail0 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail1 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail2 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail3 = UUID.Zero;
/// <summary></summary>
public bool IsEstateManager;
/// <summary></summary>
public EstateTools Estate;
/// <summary></summary>
public RegionFlags Flags;
/// <summary></summary>
public SimAccess Access;
/// <summary></summary>
public float BillableFactor;
/// <summary>Statistics information for this simulator and the
/// connection to the simulator, calculated by the simulator itself
/// and the library</summary>
public SimStats Stats;
/// <summary>Provides access to two thread-safe dictionaries containing
/// avatars and primitives found in this simulator</summary>
//public ObjectTracker Objects = new ObjectTracker();
public InternalDictionary<uint, Avatar> ObjectsAvatars = new InternalDictionary<uint, Avatar>();
public InternalDictionary<uint, Primitive> ObjectsPrimitives = new InternalDictionary<uint, Primitive>();
/// <summary>The current sequence number for packets sent to this
/// simulator. Must be Interlocked before modifying. Only
/// useful for applications manipulating sequence numbers</summary>
public int Sequence;
/// <summary>
/// Provides access to an internal thread-safe dictionary containing parcel
/// information found in this simulator
/// </summary>
public InternalDictionary<int, Parcel> Parcels = new InternalDictionary<int, Parcel>();
/// <summary>
/// Provides access to an internal thread-safe multidimensional array containing a x,y grid mapped
/// each 64x64 parcel's LocalID.
/// </summary>
public int[,] ParcelMap
{
get
{
lock (this)
return _ParcelMap;
}
set
{
lock (this)
_ParcelMap = value;
}
}
/// <summary>
/// Checks simulator parcel map to make sure it has downloaded all data successfully
/// </summary>
/// <returns>true if map is full (contains no 0's)</returns>
public bool IsParcelMapFull()
{
//int ny = this.ParcelMap.GetLength(0);
//int nx = this.ParcelMap.GetLength(1);
for (int y = 0; y < 64; y++)
{
for (int x = 0; x < 64; x++)
{
if (this.ParcelMap[y, x] == 0)
return false;
}
}
return true;
}
#endregion Public Members
#region Properties
/// <summary>The IP address and port of the server</summary>
public IPEndPoint IPEndPoint { get { return ipEndPoint; } }
/// <summary>Whether there is a working connection to the simulator or
/// not</summary>
public bool Connected { get { return connected; } }
/// <summary>Coarse locations of avatars in this simulator</summary>
public List<Vector3> AvatarPositions { get { return avatarPositions; } }
/// <summary>AvatarPositions index representing your avatar</summary>
public int PositionIndexYou { get { return positionIndexYou; } }
/// <summary>AvatarPositions index representing TrackAgent target</summary>
public int PositionIndexPrey { get { return positionIndexPrey; } }
#endregion Properties
#region Internal/Private Members
/// <summary>Used internally to track sim disconnections</summary>
internal bool DisconnectCandidate = false;
/// <summary>Event that is triggered when the simulator successfully
/// establishes a connection</summary>
internal AutoResetEvent ConnectedEvent = new AutoResetEvent(false);
/// <summary>Whether this sim is currently connected or not. Hooked up
/// to the property Connected</summary>
internal bool connected;
/// <summary>Coarse locations of avatars in this simulator</summary>
internal List<Vector3> avatarPositions = new List<Vector3>();
/// <summary>AvatarPositions index representing your avatar</summary>
internal int positionIndexYou = -1;
/// <summary>AvatarPositions index representing TrackAgent target</summary>
internal int positionIndexPrey = -1;
/// <summary>Sequence numbers of packets we've received
/// (for duplicate checking)</summary>
internal Queue<uint> PacketArchive;
/// <summary>Packets we sent out that need ACKs from the simulator</summary>
internal Dictionary<uint, NetworkManager.OutgoingPacket> NeedAck = new Dictionary<uint, NetworkManager.OutgoingPacket>();
/// <summary>Sequence number for pause/resume</summary>
internal int pauseSerial;
private NetworkManager Network;
private Queue<ulong> InBytes, OutBytes;
// ACKs that are queued up to be sent to the simulator
private SortedList<uint, uint> PendingAcks = new SortedList<uint, uint>();
private IPEndPoint ipEndPoint;
private Timer AckTimer;
private Timer PingTimer;
private Timer StatsTimer;
// simulator <> parcel LocalID Map
private int[,] _ParcelMap = new int[64, 64];
internal bool DownloadingParcelMap = false;
#endregion Internal/Private Members
/// <summary>
///
/// </summary>
/// <param name="client">Reference to the GridClient object</param>
/// <param name="address">IPEndPoint of the simulator</param>
/// <param name="handle">handle of the simulator</param>
public Simulator(GridClient client, IPEndPoint address, ulong handle)
: base(address)
{
Client = client;
ipEndPoint = address;
Handle = handle;
Estate = new EstateTools(Client);
Network = Client.Network;
PacketArchive = new Queue<uint>(Settings.PACKET_ARCHIVE_SIZE);
InBytes = new Queue<ulong>(Client.Settings.STATS_QUEUE_SIZE);
OutBytes = new Queue<ulong>(Client.Settings.STATS_QUEUE_SIZE);
}
/// <summary>
/// Called when this Simulator object is being destroyed
/// </summary>
public void Dispose()
{
// Force all the CAPS connections closed for this simulator
if (Caps != null)
{
Caps.Disconnect(true);
}
}
/// <summary>
/// Attempt to connect to this simulator
/// </summary>
/// <param name="moveToSim">Whether to move our agent in to this sim or not</param>
/// <returns>True if the connection succeeded or connection status is
/// unknown, false if there was a failure</returns>
public bool Connect(bool moveToSim)
{
if (connected)
{
Client.Self.CompleteAgentMovement(this);
return true;
}
#region Start Timers
// Destroy the timers
if (AckTimer != null) AckTimer.Dispose();
if (StatsTimer != null) StatsTimer.Dispose();
if (PingTimer != null) PingTimer.Dispose();
// Timer for sending out queued packet acknowledgements
AckTimer = new Timer(new TimerCallback(AckTimer_Elapsed), null, Settings.NETWORK_TICK_INTERVAL,
Settings.NETWORK_TICK_INTERVAL);
// Timer for recording simulator connection statistics
StatsTimer = new Timer(new TimerCallback(StatsTimer_Elapsed), null, 1000, 1000);
// Timer for periodically pinging the simulator
if (Client.Settings.SEND_PINGS)
PingTimer = new Timer(new TimerCallback(PingTimer_Elapsed), null, Settings.PING_INTERVAL,
Settings.PING_INTERVAL);
#endregion Start Timers
Logger.Log("Connecting to " + this.ToString(), Helpers.LogLevel.Info, Client);
try
{
// Create the UDP connection
Start();
// Mark ourselves as connected before firing everything else up
connected = true;
// Send the UseCircuitCode packet to initiate the connection
UseCircuitCodePacket use = new UseCircuitCodePacket();
use.CircuitCode.Code = Network.CircuitCode;
use.CircuitCode.ID = Client.Self.AgentID;
use.CircuitCode.SessionID = Client.Self.SessionID;
// Send the initial packet out
SendPacket(use, true);
Stats.ConnectTime = Environment.TickCount;
// Move our agent in to the sim to complete the connection
if (moveToSim) Client.Self.CompleteAgentMovement(this);
if (Client.Settings.SEND_AGENT_UPDATES)
Client.Self.Movement.SendUpdate(true, this);
if (!ConnectedEvent.WaitOne(Client.Settings.SIMULATOR_TIMEOUT, false))
{
Logger.Log("Giving up on waiting for RegionHandshake for " + this.ToString(),
Helpers.LogLevel.Warning, Client);
}
return true;
}
catch (Exception e)
{
Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e);
}
return false;
}
public void SetSeedCaps(string seedcaps)
{
if (Caps != null)
{
if (Caps._SeedCapsURI == seedcaps) return;
Logger.Log("Unexpected change of seed capability", Helpers.LogLevel.Warning, Client);
Caps.Disconnect(true);
Caps = null;
}
if (Client.Settings.ENABLE_CAPS)
{
// Connect to the new CAPS system
if (!String.IsNullOrEmpty(seedcaps))
Caps = new Caps(this, seedcaps);
else
Logger.Log("Setting up a sim without a valid capabilities server!", Helpers.LogLevel.Error, Client);
}
}
/// <summary>
/// Disconnect from this simulator
/// </summary>
public void Disconnect(bool sendCloseCircuit)
{
if (connected)
{
connected = false;
// Destroy the timers
if (AckTimer != null) AckTimer.Dispose();
if (StatsTimer != null) StatsTimer.Dispose();
if (PingTimer != null) PingTimer.Dispose();
// Kill the current CAPS system
if (Caps != null)
{
Caps.Disconnect(true);
Caps = null;
}
if (sendCloseCircuit)
{
// Try to send the CloseCircuit notice
CloseCircuitPacket close = new CloseCircuitPacket();
UDPPacketBuffer buf = new UDPPacketBuffer(ipEndPoint);
byte[] data = close.ToBytes();
Buffer.BlockCopy(data, 0, buf.Data, 0, data.Length);
buf.DataLength = data.Length;
AsyncBeginSend(buf);
}
// Shut the socket communication down
Stop();
}
}
/// <summary>
/// Instructs the simulator to stop sending update (and possibly other) packets
/// </summary>
public void Pause()
{
AgentPausePacket pause = new AgentPausePacket();
pause.AgentData.AgentID = Client.Self.AgentID;
pause.AgentData.SessionID = Client.Self.SessionID;
pause.AgentData.SerialNum = (uint)Interlocked.Exchange(ref pauseSerial, pauseSerial + 1);
Client.Network.SendPacket(pause, this);
}
/// <summary>
/// Instructs the simulator to resume sending update packets (unpause)
/// </summary>
public void Resume()
{
AgentResumePacket resume = new AgentResumePacket();
resume.AgentData.AgentID = Client.Self.AgentID;
resume.AgentData.SessionID = Client.Self.SessionID;
resume.AgentData.SerialNum = (uint)Interlocked.Exchange(ref pauseSerial, pauseSerial + 1);
Client.Network.SendPacket(resume, this);
}
/// <summary>
/// Sends a packet
/// </summary>
/// <param name="packet">Packet to be sent</param>
/// <param name="setSequence">True to set the sequence number, false to
/// leave it as is</param>
public void SendPacket(Packet packet, bool setSequence)
{
// Send ACK and logout packets directly, everything else goes through the queue
if (packet.Type == PacketType.PacketAck ||
packet.Header.AppendedAcks ||
packet.Type == PacketType.LogoutRequest)
{
SendPacketUnqueued(packet, setSequence);
}
else
{
Network.PacketOutbox.Enqueue(new NetworkManager.OutgoingPacket(this, packet, setSequence));
}
}
/// <summary>
/// Sends a packet directly to the simulator without queuing
/// </summary>
/// <param name="packet">Packet to be sent</param>
/// <param name="setSequence">True to set the sequence number, false to
/// leave it as is</param>
public void SendPacketUnqueued(Packet packet, bool setSequence)
{
byte[] buffer;
int bytes;
// Set sequence implies that this is not a resent packet
if (setSequence)
{
// Reset to zero if we've hit the upper sequence number limit
Interlocked.CompareExchange(ref Sequence, 0, Settings.MAX_SEQUENCE);
// Increment and fetch the current sequence number
packet.Header.Sequence = (uint)Interlocked.Increment(ref Sequence);
if (packet.Header.Reliable)
{
// Wrap this packet in a struct to track timeouts and resends
NetworkManager.OutgoingPacket outgoing = new NetworkManager.OutgoingPacket(this, packet, true);
// Keep track of when this packet was first sent out (right now)
outgoing.TickCount = Environment.TickCount;
// Add this packet to the list of ACK responses we are waiting on from the server
lock (NeedAck)
{
NeedAck[packet.Header.Sequence] = outgoing;
}
if (packet.Header.Resent)
{
// This packet has already been sent out once, strip any appended ACKs
// off it and reinsert them into the outgoing ACK queue under the
// assumption that this packet will continually be rejected from the
// server or that the appended ACKs are possibly making the delivery fail
if (packet.Header.AckList.Length > 0)
{
Logger.DebugLog(String.Format("Purging ACKs from packet #{0} ({1}) which will be resent.",
packet.Header.Sequence, packet.GetType()));
lock (PendingAcks)
{
foreach (uint sequence in packet.Header.AckList)
{
if (!PendingAcks.ContainsKey(sequence))
PendingAcks[sequence] = sequence;
}
}
packet.Header.AppendedAcks = false;
packet.Header.AckList = new uint[0];
}
// Update the sent time for this packet
SetResentTime(packet.Header.Sequence);
}
else
{
// This packet is not a resend, check if the conditions are favorable
// to ACK appending
if (packet.Type != PacketType.PacketAck &&
packet.Type != PacketType.LogoutRequest)
{
lock (PendingAcks)
{
if (PendingAcks.Count > 0 &&
PendingAcks.Count < Client.Settings.MAX_APPENDED_ACKS)
{
// Append all of the queued up outgoing ACKs to this packet
packet.Header.AckList = new uint[PendingAcks.Count];
for (int i = 0; i < PendingAcks.Count; i++)
packet.Header.AckList[i] = PendingAcks.Values[i];
PendingAcks.Clear();
packet.Header.AppendedAcks = true;
}
}
}
}
}
else if (packet.Header.AckList.Length > 0)
{
// Sanity check for ACKS appended on an unreliable packet, this is bad form
Logger.Log("Sending appended ACKs on an unreliable packet", Helpers.LogLevel.Warning);
}
}
// Serialize the packet
buffer = packet.ToBytes();
bytes = buffer.Length;
Stats.SentBytes += (ulong)bytes;
++Stats.SentPackets;
UDPPacketBuffer buf = new UDPPacketBuffer(ipEndPoint);
// Zerocode if needed
if (packet.Header.Zerocoded)
bytes = Helpers.ZeroEncode(buffer, bytes, buf.Data);
else
Buffer.BlockCopy(buffer, 0, buf.Data, 0, bytes);
buf.DataLength = bytes;
AsyncBeginSend(buf);
}
/// <summary>
/// Send a raw byte array payload as a packet
/// </summary>
/// <param name="payload">The packet payload</param>
/// <param name="setSequence">Whether the second, third, and fourth bytes
/// should be modified to the current stream sequence number</param>
public void SendPacketUnqueued(byte[] payload, bool setSequence)
{
try
{
if (setSequence && payload.Length > 3)
{
uint sequence = (uint)Interlocked.Increment(ref Sequence);
payload[1] = (byte)(sequence >> 16);
payload[2] = (byte)(sequence >> 8);
payload[3] = (byte)(sequence % 256);
}
Stats.SentBytes += (ulong)payload.Length;
++Stats.SentPackets;
UDPPacketBuffer buf = new UDPPacketBuffer(ipEndPoint);
Buffer.BlockCopy(payload, 0, buf.Data, 0, payload.Length);
buf.DataLength = payload.Length;
AsyncBeginSend(buf);
}
catch (SocketException)
{
Logger.Log("Tried to send a " + payload.Length +
" byte payload on a closed socket, shutting down " + this.ToString(),
Helpers.LogLevel.Info, Client);
Network.DisconnectSim(this, false);
return;
}
catch (Exception e)
{
Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e);
}
}
/// <summary>
///
/// </summary>
public void SendPing()
{
StartPingCheckPacket ping = new StartPingCheckPacket();
ping.PingID.PingID = Stats.LastPingID++;
ping.PingID.OldestUnacked = 0; // FIXME
ping.Header.Reliable = false;
SendPacket(ping, true);
Stats.LastPingSent = Environment.TickCount;
}
/// <summary>
/// Returns Simulator Name as a String
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (!String.IsNullOrEmpty(Name))
return String.Format("{0} ({1})", Name, ipEndPoint);
else
return String.Format("({0})", ipEndPoint);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return Handle.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
Simulator sim = obj as Simulator;
if (sim == null)
return false;
return (ipEndPoint.Equals(sim.ipEndPoint));
}
public static bool operator ==(Simulator lhs, Simulator rhs)
{
// If both are null, or both are same instance, return true
if (System.Object.ReferenceEquals(lhs, rhs))
{
return true;
}
// If one is null, but not both, return false.
if (((object)lhs == null) || ((object)rhs == null))
{
return false;
}
return lhs.ipEndPoint.Equals(rhs.ipEndPoint);
}
public static bool operator !=(Simulator lhs, Simulator rhs)
{
return !(lhs == rhs);
}
protected override void PacketReceived(UDPPacketBuffer buffer)
{
Packet packet = null;
// Check if this packet came from the server we expected it to come from
if (!ipEndPoint.Address.Equals(((IPEndPoint)buffer.RemoteEndPoint).Address))
{
Logger.Log("Received " + buffer.DataLength + " bytes of data from unrecognized source " +
((IPEndPoint)buffer.RemoteEndPoint).ToString(), Helpers.LogLevel.Warning, Client);
return;
}
// Update the disconnect flag so this sim doesn't time out
DisconnectCandidate = false;
#region Packet Decoding
int packetEnd = buffer.DataLength - 1;
try
{
packet = Packet.BuildPacket(buffer.Data, ref packetEnd, buffer.ZeroData);
}
catch (MalformedDataException)
{
Logger.Log(String.Format("Malformed data, cannot parse packet:\n{0}",
Utils.BytesToHexString(buffer.Data, buffer.DataLength, null)), Helpers.LogLevel.Error);
}
// Fail-safe check
if (packet == null)
{
Logger.Log("Couldn't build a message from the incoming data", Helpers.LogLevel.Warning, Client);
return;
}
Stats.RecvBytes += (ulong)buffer.DataLength;
++Stats.RecvPackets;
#endregion Packet Decoding
#region Reliable Handling
if (packet.Header.Reliable)
{
// Add this packet to the list of ACKs that need to be sent out
lock (PendingAcks)
{
uint sequence = (uint)packet.Header.Sequence;
if (!PendingAcks.ContainsKey(sequence)) PendingAcks[sequence] = sequence;
}
// Send out ACKs if we have a lot of them
if (PendingAcks.Count >= Client.Settings.MAX_PENDING_ACKS)
SendAcks();
if (packet.Header.Resent) ++Stats.ReceivedResends;
}
#endregion Reliable Handling
#region Inbox Insertion
NetworkManager.IncomingPacket incomingPacket;
incomingPacket.Simulator = this;
incomingPacket.Packet = packet;
// TODO: Prioritize the queue
Network.PacketInbox.Enqueue(incomingPacket);
#endregion Inbox Insertion
}
protected override void PacketSent(UDPPacketBuffer buffer, int bytesSent)
{
}
private void SetResentTime(uint sequence)
{
NetworkManager.OutgoingPacket outgoing;
if (NeedAck.TryGetValue(sequence, out outgoing))
outgoing.SetTickCount();
}
/// <summary>
/// Sends out pending acknowledgements
/// </summary>
private void SendAcks()
{
lock (PendingAcks)
{
if (PendingAcks.Count > 0)
{
if (PendingAcks.Count > 250)
{
Logger.Log("Too many ACKs queued up!", Helpers.LogLevel.Error, Client);
return;
}
PacketAckPacket acks = new PacketAckPacket();
acks.Header.Reliable = false;
acks.Packets = new PacketAckPacket.PacketsBlock[PendingAcks.Count];
for (int i = 0; i < PendingAcks.Count; i++)
{
acks.Packets[i] = new PacketAckPacket.PacketsBlock();
acks.Packets[i].ID = PendingAcks.Values[i];
}
SendPacket(acks, true);
PendingAcks.Clear();
}
}
}
/// <summary>
/// Resend unacknowledged packets
/// </summary>
private void ResendUnacked()
{
lock (NeedAck)
{
List<uint> dropAck = new List<uint>();
int now = Environment.TickCount;
// Resend packets
foreach (NetworkManager.OutgoingPacket outgoing in NeedAck.Values)
{
if (outgoing.TickCount != 0 && now - outgoing.TickCount > Client.Settings.RESEND_TIMEOUT)
{
if (outgoing.ResendCount < Client.Settings.MAX_RESEND_COUNT)
{
try
{
if (Client.Settings.LOG_RESENDS)
{
Logger.DebugLog(String.Format("Resending packet #{0} ({1}), {2}ms have passed",
outgoing.Packet.Header.Sequence, outgoing.Packet.GetType(), now - outgoing.TickCount), Client);
}
outgoing.ZeroTickCount();
outgoing.Packet.Header.Resent = true;
++Stats.ResentPackets;
outgoing.IncrementResendCount();
SendPacket(outgoing.Packet, false);
}
catch (Exception ex)
{
Logger.DebugLog("Exception trying to resend packet: " + ex.ToString(), Client);
}
}
else
{
if (Client.Settings.LOG_RESENDS)
{
Logger.DebugLog(String.Format("Dropping packet #{0} ({1}) after {2} failed attempts",
outgoing.Packet.Header.Sequence, outgoing.Packet.GetType(), outgoing.ResendCount));
}
dropAck.Add(outgoing.Packet.Header.Sequence);
}
}
}
if (dropAck.Count != 0)
{
foreach (uint seq in dropAck)
NeedAck.Remove(seq);
}
}
}
private void AckTimer_Elapsed(object obj)
{
SendAcks();
ResendUnacked();
}
private void StatsTimer_Elapsed(object obj)
{
ulong old_in = 0, old_out = 0;
if (InBytes.Count >= Client.Settings.STATS_QUEUE_SIZE)
old_in = InBytes.Dequeue();
if (OutBytes.Count >= Client.Settings.STATS_QUEUE_SIZE)
old_out = OutBytes.Dequeue();
InBytes.Enqueue(Stats.RecvBytes);
OutBytes.Enqueue(Stats.SentBytes);
if (old_in > 0 && old_out > 0)
{
Stats.IncomingBPS = (int)(Stats.RecvBytes - old_in) / Client.Settings.STATS_QUEUE_SIZE;
Stats.OutgoingBPS = (int)(Stats.SentBytes - old_out) / Client.Settings.STATS_QUEUE_SIZE;
//Client.Log("Incoming: " + IncomingBPS + " Out: " + OutgoingBPS +
// " Lag: " + LastLag + " Pings: " + ReceivedPongs +
// "/" + SentPings, Helpers.LogLevel.Debug);
}
}
private void PingTimer_Elapsed(object obj)
{
SendPing();
Stats.SentPings++;
}
}
}
| |
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: [email protected]
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.ComponentModel.Design;
namespace System.Windows.Forms
{
[DesignTimeVisible(false)]
[Designer(typeof(RibbonPanelDesigner))]
public class RibbonPanel :
Component, IRibbonElement, IContainsSelectableRibbonItems, IContainsRibbonComponents
{
#region Fields
private bool _enabled;
private System.Drawing.Image _image;
private RibbonItemCollection _items;
private string _text;
private Ribbon _owner;
private Rectangle _bounds;
private Rectangle _contentBounds;
private bool _selected;
private object _tag;
private RibbonTab _ownerTab;
private RibbonElementSizeMode _sizeMode;
private RibbonPanelFlowDirection _flowsTo;
private Control _popUp;
private bool _pressed;
private Rectangle _buttonMoreBounds;
private bool _buttonMorePressed;
private bool _butonMoreSelected;
private bool _buttonMoreVisible;
private bool _buttonMoreEnabled;
internal Rectangle overflowBoundsBuffer;
private bool _popupShowed;
private bool _visible = true;
private bool _IsFirstPanel = false;
private bool _IsLastPanel = false;
private int _Index = -1;
#endregion
#region Events
/// <summary>
/// Occurs when the mouse pointer enters the panel
/// </summary>
public event MouseEventHandler MouseEnter;
/// <summary>
/// Occurs when the mouse pointer leaves the panel
/// </summary>
public event MouseEventHandler MouseLeave;
/// <summary>
/// Occurs when the mouse pointer is moved inside the panel
/// </summary>
public event MouseEventHandler MouseMove;
/// <summary>
/// Occurs when the panel is redrawn
/// </summary>
public event PaintEventHandler Paint;
/// <summary>
/// Occurs when the panel is resized
/// </summary>
public event EventHandler Resize;
public event EventHandler ButtonMoreClick;
public virtual event EventHandler Click;
public virtual event EventHandler DoubleClick;
public virtual event System.Windows.Forms.MouseEventHandler MouseDown;
public virtual event System.Windows.Forms.MouseEventHandler MouseUp;
#endregion
#region Ctor
/// <summary>
/// Creates a new RibbonPanel
/// </summary>
public RibbonPanel()
{
_items = new RibbonItemCollection();
_sizeMode = RibbonElementSizeMode.None;
_flowsTo = RibbonPanelFlowDirection.Bottom;
_buttonMoreEnabled = true;
_buttonMoreVisible = true;
_items.SetOwnerPanel(this);
_enabled = true;
}
/// <summary>
/// Creates a new RibbonPanel with the specified text
/// </summary>
/// <param name="text">Text of the panel</param>
public RibbonPanel(string text)
: this(text, RibbonPanelFlowDirection.Bottom)
{
}
/// <summary>
/// Creates a new RibbonPanel with the specified text and panel flow direction
/// </summary>
/// <param name="text">Text of the panel</param>
/// <param name="flowsTo">Flow direction of the content items</param>
public RibbonPanel(string text, RibbonPanelFlowDirection flowsTo)
: this(text, flowsTo, new RibbonItem[] { })
{
}
/// <summary>
/// Creates a new RibbonPanel with the specified text and panel flow direction
/// </summary>
/// <param name="text">Text of the panel</param>
/// <param name="flowsTo">Flow direction of the content items</param>
public RibbonPanel(string text, RibbonPanelFlowDirection flowsTo, IEnumerable<RibbonItem> items)
: this()
{
_text = text;
_flowsTo = flowsTo;
_items.AddRange(items);
}
protected override void Dispose(bool disposing)
{
if (disposing && RibbonDesigner.Current == null)
{
foreach (RibbonItem ri in _items)
ri.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Props
[Description("Sets if the panel should be enabled")]
[DefaultValue(true)]
public bool Enabled
{
get { return _enabled; }
set
{
_enabled = value;
foreach (RibbonItem item in Items)
{
item.Enabled = value;
}
}
}
[Description("Sets if the panel should be Visible")]
[DefaultValue(true)]
public virtual bool Visible
{
get
{
return _visible;
}
set
{
_visible = value;
//this.OwnerTab.UpdatePanelsRegions();
this.OwnerTab.Owner.PerformLayout();
this.Owner.Invalidate();
}
}
/// <summary>
/// Gets if this panel is currenlty collapsed
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Collapsed
{
get { return SizeMode == RibbonElementSizeMode.Overflow; }
}
/// <summary>
/// Gets or sets the visibility of the "More" button
/// </summary>
[Description("Sets the visibility of the \"More...\" button")]
[DefaultValue(true)]
public bool ButtonMoreVisible
{
get { return _buttonMoreVisible; }
set { _buttonMoreVisible = value; if (Owner != null) Owner.OnRegionsChanged(); }
}
/// <summary>
/// Gets or sets a value indicating if the "More" button should be enabled
/// </summary>
[Description(@"Enables/Disables the ""More..."" button")]
[DefaultValue(true)]
public bool ButtonMoreEnabled
{
get { return _buttonMoreEnabled; }
set { _buttonMoreEnabled = value; if (Owner != null) Owner.OnRegionsChanged(); }
}
/// <summary>
/// Gets if the "More" button is currently selected
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ButtonMoreSelected
{
get { return _butonMoreSelected; }
}
/// <summary>
/// Gets if the "More" button is currently pressed
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ButtonMorePressed
{
get { return _buttonMorePressed; }
}
/// <summary>
/// Gets the bounds of the "More" button
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle ButtonMoreBounds
{
get { return _buttonMoreBounds; }
}
/// <summary>
/// Gets if the panel is currently on overflow and pressed
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Pressed
{
get { return _pressed; }
}
/// <summary>
/// Gets or sets the pop up where the panel is being drawn (if any)
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
internal Control PopUp
{
get { return _popUp; }
set { _popUp = value; }
}
/// <summary>
/// Gets the current size mode of the panel
/// </summary>
public RibbonElementSizeMode SizeMode
{
get { return _sizeMode; }
}
/// <summary>
/// Gets the collection of RibbonItem elements of this panel
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RibbonItemCollection Items
{
get
{
return _items;
}
}
/// <summary>
/// Gets or sets the text that is to be displayed on the bottom of the panel
/// </summary>
[Localizable(true)]
public string Text
{
get
{
return _text;
}
set
{
_text = value;
if (Owner != null) Owner.OnRegionsChanged();
}
}
/// <summary>
/// Gets or sets the image that is to be displayed on the panel when shown as an overflow button
/// </summary>
[DefaultValue(null)]
public System.Drawing.Image Image
{
get
{
return _image;
}
set
{
_image = value;
if (Owner != null) Owner.OnRegionsChanged();
}
}
/// <summary>
/// Gets if the panel is in overflow mode
/// </summary>
/// <remarks>Overflow mode is when the available space to draw the panel is not enough to draw components, so panel is drawn as a button that shows the full content of the panel in a pop-up window when clicked</remarks>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool OverflowMode
{
get
{
return SizeMode == RibbonElementSizeMode.Overflow;
}
}
/// <summary>
/// Gets the Ribbon that contains this panel
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Ribbon Owner
{
get
{
return _owner;
}
}
/// <summary>
/// Gets the bounds of the panel relative to the Ribbon control
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle Bounds
{
get
{
return _bounds;
}
}
/// <summary>
/// Gets a value indicating whether the panel is selected
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool Selected
{
get
{
return _selected;
}
set
{
_selected = value;
}
}
/// <summary>
/// Gets a value indicating whether the panel is the first panel on the tab
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool IsFirstPanel
{
get
{
return _IsFirstPanel;
}
set
{
_IsFirstPanel = value;
}
}
/// <summary>
/// Gets a value indicating whether the panel is the last panel on the tab
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool IsLastPanel
{
get
{
return _IsLastPanel;
}
set
{
_IsLastPanel = value;
}
}
/// <summary>
/// Gets a value indicating what the index of the panel is in the Tabs panel collection
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual int Index
{
get
{
return _Index;
}
set
{
_Index = value;
}
}
/// <summary>
/// Gets or sets the object that contains data about the control
/// </summary>
[DescriptionAttribute("An Object field for associating custom data for this control")]
[DefaultValue(null)]
[TypeConverter(typeof(StringConverter))]
public object Tag
{
get
{
return _tag;
}
set
{
_tag = value;
}
}
/// <summary>
/// Gets the bounds of the content of the panel
/// </summary>
public Rectangle ContentBounds
{
get
{
return _contentBounds;
}
}
/// <summary>
/// Gets the RibbonTab that contains this panel
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public RibbonTab OwnerTab
{
get
{
return _ownerTab;
}
}
/// <summary>
/// Gets or sets the flow direction to layout items
/// </summary>
[DefaultValue(RibbonPanelFlowDirection.Bottom)]
public RibbonPanelFlowDirection FlowsTo
{
get
{
return _flowsTo;
}
set
{
_flowsTo = value;
if (Owner != null) Owner.OnRegionsChanged();
}
}
/// <summary>
/// Gets or sets if the popup is currently showing
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
internal bool PopupShowed
{
get { return _popupShowed; }
set { _popupShowed = value; }
}
#endregion
#region IRibbonElement Members
public Size SwitchToSize(Control ctl, Graphics g, RibbonElementSizeMode size)
{
Size s = MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, size));
Rectangle r = new Rectangle(0, 0, s.Width, s.Height);
//if (!(ctl is Ribbon))
// r = boundsBuffer;
//else
// r = new Rectangle(0, 0, 0, 0);
SetBounds(r);
UpdateItemsRegions(g, size);
return s;
}
/// <summary>
/// Raises the paint event and draws the
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void OnPaint(object sender, RibbonElementPaintEventArgs e)
{
if (Paint != null)
{
Paint(this, new PaintEventArgs(e.Graphics, e.Clip));
}
if (PopupShowed && e.Control == Owner)
{
//Draw a fake collapsed and pressed panel
#region Create fake panel
RibbonPanel fakePanel = new RibbonPanel(this.Text);
fakePanel.Image = this.Image;
fakePanel.SetSizeMode(RibbonElementSizeMode.Overflow);
fakePanel.SetBounds(overflowBoundsBuffer);
fakePanel.SetPressed(true);
fakePanel.SetOwner(Owner);
#endregion
Owner.Renderer.OnRenderRibbonPanelBackground(new RibbonPanelRenderEventArgs(Owner, e.Graphics, e.Clip, fakePanel, e.Control));
Owner.Renderer.OnRenderRibbonPanelText(new RibbonPanelRenderEventArgs(Owner, e.Graphics, e.Clip, fakePanel, e.Control));
}
else
{
//Draw normal
Owner.Renderer.OnRenderRibbonPanelBackground(new RibbonPanelRenderEventArgs(Owner, e.Graphics, e.Clip, this, e.Control));
Owner.Renderer.OnRenderRibbonPanelText(new RibbonPanelRenderEventArgs(Owner, e.Graphics, e.Clip, this, e.Control));
}
if (e.Mode != RibbonElementSizeMode.Overflow ||
(e.Control != null && e.Control == PopUp))
{
foreach (RibbonItem item in Items)
{
if (item.Visible || Owner.IsDesignMode())
item.OnPaint(this, new RibbonElementPaintEventArgs(item.Bounds, e.Graphics, item.SizeMode));
}
}
}
/// <summary>
/// Sets the bounds of the panel
/// </summary>
/// <param name="bounds"></param>
public void SetBounds(System.Drawing.Rectangle bounds)
{
bool trigger = _bounds != bounds;
_bounds = bounds;
OnResize(EventArgs.Empty);
if (Owner != null)
{
//Update contentBounds
_contentBounds = Rectangle.FromLTRB(
bounds.X + Owner.PanelMargin.Left + 0,
bounds.Y + Owner.PanelMargin.Top + 0,
bounds.Right - Owner.PanelMargin.Right,
bounds.Bottom - Owner.PanelMargin.Bottom);
}
//"More" bounds
if (ButtonMoreVisible)
{
SetMoreBounds(
Rectangle.FromLTRB(
bounds.Right - 15,
_contentBounds.Bottom + 1,
bounds.Right,
bounds.Bottom)
);
}
else
{
SetMoreBounds(Rectangle.Empty);
}
}
/// <summary>
/// Measures the size of the panel on the mode specified by the event object
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <returns></returns>
public Size MeasureSize(object sender, RibbonElementMeasureSizeEventArgs e)
{
Size result = Size.Empty;
Size minSize = Size.Empty;
if (!Visible && !Owner.IsDesignMode()) return new Size(0, 0);
int panelHeight = OwnerTab.TabContentBounds.Height - Owner.PanelPadding.Vertical;
#region Measure width of minSize
minSize.Width = e.Graphics.MeasureString(Text, Owner.Font).ToSize().Width + Owner.PanelMargin.Horizontal + 1;
if (ButtonMoreVisible)
{
minSize.Width += ButtonMoreBounds.Width + 3;
}
#endregion
if (e.SizeMode == RibbonElementSizeMode.Overflow)
{
Size textSize = RibbonButton.MeasureStringLargeSize(e.Graphics, Text, Owner.Font);
return new Size(textSize.Width + Owner.PanelMargin.Horizontal, panelHeight);
}
switch (FlowsTo)
{
case RibbonPanelFlowDirection.Left:
result = MeasureSizeFlowsToBottom(sender, e);
break;
case RibbonPanelFlowDirection.Right:
result = MeasureSizeFlowsToRight(sender, e);
break;
case RibbonPanelFlowDirection.Bottom:
result = MeasureSizeFlowsToBottom(sender, e);
break;
default:
result = Size.Empty;
break;
}
return new Size(Math.Max(result.Width, minSize.Width), panelHeight);
}
/// <summary>
/// Sets the value of the Owner Property
/// </summary>
internal void SetOwner(Ribbon owner)
{
_owner = owner;
Items.SetOwner(owner);
}
/// <summary>
/// Sets the value of the Selected property
/// </summary>
/// <param name="selected">Value that indicates if the element is selected</param>
internal void SetSelected(bool selected)
{
_selected = selected;
}
#endregion
#region Methods
/// <summary>
/// Raises the <see cref="Resize"/> method
/// </summary>
/// <param name="e"></param>
protected virtual void OnResize(EventArgs e)
{
if (Resize != null)
{
Resize(this, e);
}
}
/// <summary>
/// Shows the panel in a popup
/// </summary>
private void ShowOverflowPopup()
{
Rectangle b = Bounds;
RibbonPanelPopup f = new RibbonPanelPopup(this);
Point p = Owner.PointToScreen(new Point(b.Left, b.Bottom));
PopupShowed = true;
f.Show(p);
}
/// <summary>
/// Measures the size when flow direction is to right
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <returns></returns>
private Size MeasureSizeFlowsToRight(object sender, RibbonElementMeasureSizeEventArgs e)
{
int widthSum = Owner.PanelMargin.Horizontal;
int maxWidth = 0;
int maxHeight = 0;
int dividedWidth = 0;
foreach (RibbonItem item in Items)
{
if (item.Visible || Owner.IsDesignMode())
{
Size itemSize = item.MeasureSize(this, e);
widthSum += itemSize.Width + Owner.ItemPadding.Horizontal + 1;
maxWidth = Math.Max(maxWidth, itemSize.Width);
maxHeight = Math.Max(maxHeight, itemSize.Height);
}
}
switch (e.SizeMode)
{
case RibbonElementSizeMode.Large:
dividedWidth = widthSum / 1; //Show items on one row
break;
case RibbonElementSizeMode.Medium:
dividedWidth = widthSum / 2; //Show items on two rows
break;
case RibbonElementSizeMode.Compact:
dividedWidth = widthSum / 3; //Show items on three rows
break;
default:
break;
}
//Add padding
dividedWidth += Owner.PanelMargin.Horizontal;
return new Size(Math.Max(maxWidth, dividedWidth) + Owner.PanelMargin.Horizontal, 0); //Height is provided by MeasureSize
}
/// <summary>
/// Measures the size when flow direction is to bottom
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <returns></returns>
private Size MeasureSizeFlowsToBottom(object sender, RibbonElementMeasureSizeEventArgs e)
{
int curRight = Owner.PanelMargin.Left + Owner.ItemPadding.Horizontal;
int curBottom = ContentBounds.Top + Owner.ItemPadding.Vertical;
int lastRight = 0;
int lastBottom = 0;
int availableHeight = OwnerTab.TabContentBounds.Height - Owner.TabContentMargin.Vertical - Owner.PanelPadding.Vertical - Owner.PanelMargin.Vertical;
int maxRight = 0;
int maxBottom = 0;
foreach (RibbonItem item in Items)
{
if (item.Visible || Owner.IsDesignMode() || item.GetType() == typeof(RibbonSeparator))
{
Size itemSize = item.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(e.Graphics, e.SizeMode));
if (curBottom + itemSize.Height > ContentBounds.Bottom)
{
curBottom = ContentBounds.Top + Owner.ItemPadding.Vertical + 0;
curRight = maxRight + Owner.ItemPadding.Horizontal + 0;
}
Rectangle bounds = new Rectangle(curRight, curBottom, itemSize.Width, itemSize.Height);
lastRight = bounds.Right;
lastBottom = bounds.Bottom;
curBottom = bounds.Bottom + Owner.ItemPadding.Vertical + 1;
maxRight = Math.Max(maxRight, lastRight);
maxBottom = Math.Max(maxBottom, lastBottom);
}
}
return new Size(maxRight + Owner.ItemPadding.Right + Owner.PanelMargin.Right + 1, 0); //Height is provided by MeasureSize
}
/// <summary>
/// Sets the value of the SizeMode property
/// </summary>
/// <param name="sizeMode"></param>
internal void SetSizeMode(RibbonElementSizeMode sizeMode)
{
_sizeMode = sizeMode;
foreach (RibbonItem item in Items)
{
item.SetSizeMode(sizeMode);
}
}
/// <summary>
/// Sets the value of the ContentBounds property
/// </summary>
/// <param name="contentBounds">Bounds of the content on the panel</param>
internal void SetContentBounds(Rectangle contentBounds)
{
_contentBounds = contentBounds;
}
/// <summary>
/// Sets the value of the OwnerTab property
/// </summary>
/// <param name="ownerTab">RibbonTab where this item is located</param>
internal void SetOwnerTab(RibbonTab ownerTab)
{
_ownerTab = ownerTab;
Items.SetOwnerTab(OwnerTab);
}
/// <summary>
/// Updates the bounds of child elements
/// </summary>
internal void UpdateItemsRegions(Graphics g, RibbonElementSizeMode mode)
{
switch (FlowsTo)
{
case RibbonPanelFlowDirection.Right:
UpdateRegionsFlowsToRight(g, mode);
break;
case RibbonPanelFlowDirection.Bottom:
UpdateRegionsFlowsToBottom(g, mode);
break;
case RibbonPanelFlowDirection.Left:
UpdateRegionsFlowsToLeft(g, mode);
break;
}
///Center items on the panel
CenterItems();
}
/// <summary>
/// Updates the bounds of child elements when flow is to bottom
/// </summary>
private void UpdateRegionsFlowsToBottom(Graphics g, RibbonElementSizeMode mode)
{
int curRight = ContentBounds.Left + Owner.ItemPadding.Horizontal + 0;
int curBottom = ContentBounds.Top + Owner.ItemPadding.Vertical + 0;
int lastRight = curRight;
int lastBottom = 0;
List<RibbonItem> lastColumn = new List<RibbonItem>();
///Iterate thru items on panel
foreach (RibbonItem item in Items)
{
///Gets the last measured size (to avoid re-measuring calculations)
Size itemSize;
if (item.Visible || Owner.IsDesignMode())
itemSize = item.LastMeasuredSize;
else
itemSize = new Size(0, 0);
///If not enough space available, reset curBottom and advance curRight
if (curBottom + itemSize.Height > ContentBounds.Bottom)
{
curBottom = ContentBounds.Top + Owner.ItemPadding.Vertical + 0;
curRight = lastRight + Owner.ItemPadding.Horizontal + 0;
Items.CenterItemsVerticallyInto(lastColumn, ContentBounds);
lastColumn.Clear();
}
///Set the item's bounds
item.SetBounds(new Rectangle(curRight, curBottom, itemSize.Width, itemSize.Height));
///save last right and bottom
lastRight = Math.Max(item.Bounds.Right, lastRight);
lastBottom = item.Bounds.Bottom;
///update current bottom
curBottom = item.Bounds.Bottom + Owner.ItemPadding.Vertical + 1;
///Add to the collection of items of the last column
lastColumn.Add(item);
}
///Center the items vertically on the last column
Items.CenterItemsVerticallyInto(lastColumn, ContentBounds);
}
/// <summary>
/// Updates the bounds of child elements when flow is to Left.
/// </summary>
private void UpdateRegionsFlowsToLeft(Graphics g, RibbonElementSizeMode mode)
{
int curRight = ContentBounds.Left + Owner.ItemPadding.Horizontal + 0;
int curBottom = ContentBounds.Top + Owner.ItemPadding.Vertical + 0;
int lastRight = curRight;
int lastBottom = 0;
List<RibbonItem> lastColumn = new List<RibbonItem>();
///Iterate thru items on panel
for (int i = Items.Count - 1; i >= 0; i--)
{
RibbonItem item = Items[i];
///Gets the last measured size (to avoid re-measuring calculations)
Size itemSize;
if (item.Visible)
itemSize = item.LastMeasuredSize;
else
itemSize = new Size(0, 0);
///If not enough space available, reset curBottom and advance curRight
if (curBottom + itemSize.Height > ContentBounds.Bottom)
{
curBottom = ContentBounds.Top + Owner.ItemPadding.Vertical + 0;
curRight = lastRight + Owner.ItemPadding.Horizontal + 0;
Items.CenterItemsVerticallyInto(lastColumn, ContentBounds);
lastColumn.Clear();
}
///Set the item's bounds
item.SetBounds(new Rectangle(curRight, curBottom, itemSize.Width, itemSize.Height));
///save last right and bottom
lastRight = Math.Max(item.Bounds.Right, lastRight);
lastBottom = item.Bounds.Bottom;
///update current bottom
curBottom = item.Bounds.Bottom + Owner.ItemPadding.Vertical + 1;
///Add to the collection of items of the last column
lastColumn.Add(item);
}
///Center the items vertically on the last column
Items.CenterItemsVerticallyInto(lastColumn, Items.GetItemsBounds());
}
/// <summary>
/// Updates the bounds of child elements when flow is to bottom
/// </summary>
private void UpdateRegionsFlowsToRight(Graphics g, RibbonElementSizeMode mode)
{
int curLeft = ContentBounds.Left;
int curTop = ContentBounds.Top;
int padding = mode == RibbonElementSizeMode.Medium ? 7 : 0;
int maxBottom = 0;
#region Sorts from larger to smaller
RibbonItem[] array = Items.ToArray();
for (int i = (array.Length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (array[j - 1].LastMeasuredSize.Width < array[j].LastMeasuredSize.Width)
{
RibbonItem temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
#endregion
List<RibbonItem> list = new List<RibbonItem>(array);
///Attend elements, deleting every attended element from the list
while (list.Count > 0)
{
///Extract item and delete it
RibbonItem item = list[0];
list.Remove(item);
///If not enough space left, reset left and advance top
if (curLeft + item.LastMeasuredSize.Width > ContentBounds.Right)
{
curLeft = ContentBounds.Left;
curTop = maxBottom + Owner.ItemPadding.Vertical + 1 + padding;
}
///Set item's bounds
item.SetBounds(new Rectangle(new Point(curLeft, curTop), item.LastMeasuredSize));
///Increment reminders
curLeft += item.Bounds.Width + Owner.ItemPadding.Horizontal;
maxBottom = Math.Max(maxBottom, item.Bounds.Bottom);
///Check available space after placing item
int spaceAvailable = ContentBounds.Right - curLeft;
///Check for elements that fit on available space
for (int i = 0; i < list.Count; i++)
{
///If item fits on the available space
if (list[i].LastMeasuredSize.Width < spaceAvailable)
{
///Place the item there and reset the counter to check for further items
list[i].SetBounds(new Rectangle(new Point(curLeft, curTop), list[i].LastMeasuredSize));
curLeft += list[i].Bounds.Width + Owner.ItemPadding.Horizontal;
maxBottom = Math.Max(maxBottom, list[i].Bounds.Bottom);
spaceAvailable = ContentBounds.Right - curLeft;
list.RemoveAt(i);
i = 0;
}
}
}
}
/// <summary>
/// Centers the items on the tab conent
/// </summary>
private void CenterItems()
{
Items.CenterItemsInto(ContentBounds);
}
/// <summary>
/// Overriden. Gives info about the panel as a string
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("Panel: {0} ({1})", Text, SizeMode);
}
/// <summary>
/// Sets the value of the Pressed property
/// </summary>
/// <param name="pressed"></param>
public void SetPressed(bool pressed)
{
_pressed = pressed;
}
/// <summary>
/// Sets the value of the ButtonMorePressed property
/// </summary>
/// <param name="bounds">property value</param>
internal void SetMorePressed(bool pressed)
{
_buttonMorePressed = pressed;
}
/// <summary>
/// Sets the value of the ButtonMoreSelected property
/// </summary>
/// <param name="bounds">property value</param>
internal void SetMoreSelected(bool selected)
{
_butonMoreSelected = selected;
}
/// <summary>
/// Sets the value of the ButtonMoreBounds property
/// </summary>
/// <param name="bounds">property value</param>
internal void SetMoreBounds(Rectangle bounds)
{
_buttonMoreBounds = bounds;
}
/// <summary>
/// Raised the <see cref="ButtonMoreClick"/> event
/// </summary>
/// <param name="e"></param>
protected void OnButtonMoreClick(EventArgs e)
{
if (ButtonMoreClick != null)
{
ButtonMoreClick(this, e);
}
}
#endregion
#region IContainsRibbonItems Members
public IEnumerable<RibbonItem> GetItems()
{
return Items;
}
public Rectangle GetContentBounds()
{
return ContentBounds;
}
/// <summary>
/// Raises the MouseEnter event
/// </summary>
/// <param name="e">Event data</param>
public virtual void OnMouseEnter(MouseEventArgs e)
{
if (!Enabled) return;
if (MouseEnter != null)
{
MouseEnter(this, e);
}
}
/// <summary>
/// Raises the MouseLeave event
/// </summary>
/// <param name="e">Event data</param>
public virtual void OnMouseLeave(MouseEventArgs e)
{
if (!Enabled) return;
if (MouseLeave != null)
{
MouseLeave(this, e);
}
}
/// <summary>
/// Raises the MouseMove event
/// </summary>
/// <param name="e">Event data</param>
public virtual void OnMouseMove(MouseEventArgs e)
{
if (!Enabled) return;
if (MouseMove != null)
{
MouseMove(this, e);
}
bool redraw = false;
if (ButtonMoreEnabled && ButtonMoreVisible && ButtonMoreBounds.Contains(e.X, e.Y) && !Collapsed)
{
SetMoreSelected(true);
redraw = true;
}
else
{
redraw = ButtonMoreSelected;
SetMoreSelected(false);
}
if (redraw)
{
Owner.Invalidate(Bounds);
}
}
/// <summary>
/// Raises the Click event
/// </summary>
/// <param name="e">Event data</param>
public virtual void OnClick(EventArgs e)
{
if (!Enabled) return;
if (Click != null)
{
Click(this, e);
}
if (Collapsed && PopUp == null)
{
ShowOverflowPopup();
}
}
/// <summary>
/// Raises the DoubleClick event
/// </summary>
/// <param name="e">Event data</param>
public virtual void OnDoubleClick(EventArgs e)
{
if (!Enabled) return;
if (DoubleClick != null)
{
DoubleClick(this, e);
}
}
/// <summary>
/// Raises the MouseDown event
/// </summary>
/// <param name="e">Event data</param>
public virtual void OnMouseDown(MouseEventArgs e)
{
if (!Enabled) return;
if (MouseDown != null)
{
MouseDown(this, e);
}
SetPressed(true);
bool redraw = false;
if (ButtonMoreEnabled && ButtonMoreVisible && ButtonMoreBounds.Contains(e.X, e.Y) && !Collapsed)
{
SetMorePressed(true);
redraw = true;
}
else
{
redraw = ButtonMoreSelected;
SetMorePressed(false);
}
if (redraw)
{
Owner.Invalidate(Bounds);
}
}
/// <summary>
/// Raises the MouseUp event
/// </summary>
/// <param name="e">Event data</param>
public virtual void OnMouseUp(MouseEventArgs e)
{
if (!Enabled) return;
if (MouseUp != null)
{
MouseUp(this, e);
}
if (ButtonMoreEnabled && ButtonMoreVisible && ButtonMorePressed && !Collapsed)
{
OnButtonMoreClick(EventArgs.Empty);
}
SetPressed(false);
SetMorePressed(false);
}
#endregion
#region IContainsRibbonComponents Members
public IEnumerable<Component> GetAllChildComponents()
{
return Items.ToArray();
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Market;
using QuantConnect.Logging;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Util
{
/// <summary>
/// Provides methods for generating lean data file content
/// </summary>
public static class LeanData
{
/// <summary>
/// The different <see cref="SecurityType"/> used for data paths
/// </summary>
/// <remarks>This includes 'alternative'</remarks>
public static HashSet<string> SecurityTypeAsDataPath => Enum.GetNames(typeof(SecurityType))
.Select(x => x.ToLowerInvariant()).Union(new[] { "alternative" }).ToHashSet();
/// <summary>
/// Converts the specified base data instance into a lean data file csv line.
/// This method takes into account the fake that base data instances typically
/// are time stamped in the exchange time zone, but need to be written to disk
/// in the data time zone.
/// </summary>
public static string GenerateLine(IBaseData data, Resolution resolution, DateTimeZone exchangeTimeZone, DateTimeZone dataTimeZone)
{
var clone = data.Clone();
clone.Time = data.Time.ConvertTo(exchangeTimeZone, dataTimeZone);
return GenerateLine(clone, clone.Symbol.ID.SecurityType, resolution);
}
/// <summary>
/// Converts the specified base data instance into a lean data file csv line
/// </summary>
public static string GenerateLine(IBaseData data, SecurityType securityType, Resolution resolution)
{
var milliseconds = data.Time.TimeOfDay.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
var longTime = data.Time.ToStringInvariant(DateFormat.TwelveCharacter);
switch (securityType)
{
case SecurityType.Equity:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick) data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds, Scale(tick.LastPrice), tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds, Scale(tick.BidPrice), tick.BidSize, Scale(tick.AskPrice), tick.AskSize, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
break;
case Resolution.Minute:
case Resolution.Second:
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds, Scale(tradeBar.Open), Scale(tradeBar.High), Scale(tradeBar.Low), Scale(tradeBar.Close), tradeBar.Volume);
}
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
break;
case Resolution.Hour:
case Resolution.Daily:
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, Scale(bigTradeBar.Open), Scale(bigTradeBar.High), Scale(bigTradeBar.Low), Scale(bigTradeBar.Close), bigTradeBar.Volume);
}
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
break;
}
break;
case SecurityType.Crypto:
switch (resolution)
{
case Resolution.Tick:
var tick = data as Tick;
if (tick == null)
{
throw new ArgumentException("Crypto tick could not be created", nameof(data));
}
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds, tick.LastPrice, tick.Quantity, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds, tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.Suspicious ? "1" : "0");
}
throw new ArgumentException("Cryto tick could not be created");
case Resolution.Second:
case Resolution.Minute:
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds, tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume);
}
throw new ArgumentException("Cryto minute/second bar could not be created", nameof(data));
case Resolution.Hour:
case Resolution.Daily:
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime,
bigTradeBar.Open,
bigTradeBar.High,
bigTradeBar.Low,
bigTradeBar.Close,
bigTradeBar.Volume);
}
throw new ArgumentException("Cryto hour/daily bar could not be created", nameof(data));
}
break;
case SecurityType.Forex:
case SecurityType.Cfd:
switch (resolution)
{
case Resolution.Tick:
var tick = data as Tick;
if (tick == null)
{
throw new ArgumentException("Expected data of type 'Tick'", nameof(data));
}
return ToCsv(milliseconds, tick.BidPrice, tick.AskPrice);
case Resolution.Second:
case Resolution.Minute:
var bar = data as QuoteBar;
if (bar == null)
{
throw new ArgumentException("Expected data of type 'QuoteBar'", nameof(data));
}
return ToCsv(milliseconds,
ToNonScaledCsv(bar.Bid), bar.LastBidSize,
ToNonScaledCsv(bar.Ask), bar.LastAskSize);
case Resolution.Hour:
case Resolution.Daily:
var bigBar = data as QuoteBar;
if (bigBar == null)
{
throw new ArgumentException("Expected data of type 'QuoteBar'", nameof(data));
}
return ToCsv(longTime,
ToNonScaledCsv(bigBar.Bid), bigBar.LastBidSize,
ToNonScaledCsv(bigBar.Ask), bigBar.LastAskSize);
}
break;
case SecurityType.Index:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick) data;
return ToCsv(milliseconds, tick.LastPrice, tick.Quantity, string.Empty, string.Empty, "0");
case Resolution.Second:
case Resolution.Minute:
var bar = data as TradeBar;
if (bar == null)
{
throw new ArgumentException("Expected data of type 'TradeBar'", nameof(data));
}
return ToCsv(milliseconds, bar.Open, bar.High, bar.Low, bar.Close, bar.Volume);
case Resolution.Hour:
case Resolution.Daily:
var bigTradeBar = data as TradeBar;
return ToCsv(longTime, bigTradeBar.Open, bigTradeBar.High, bigTradeBar.Low, bigTradeBar.Close, bigTradeBar.Volume);
}
break;
case SecurityType.Option:
case SecurityType.IndexOption:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick)data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds,
Scale(tick.LastPrice), tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds,
Scale(tick.BidPrice), tick.BidSize, Scale(tick.AskPrice), tick.AskSize, tick.ExchangeCode, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.OpenInterest)
{
return ToCsv(milliseconds, tick.Value);
}
break;
case Resolution.Second:
case Resolution.Minute:
// option and future data can be quote or trade bars
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds,
Scale(tradeBar.Open), Scale(tradeBar.High), Scale(tradeBar.Low), Scale(tradeBar.Close), tradeBar.Volume);
}
var openInterest = data as OpenInterest;
if (openInterest != null)
{
return ToCsv(milliseconds, openInterest.Value);
}
break;
case Resolution.Hour:
case Resolution.Daily:
// option and future data can be quote or trade bars
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, ToScaledCsv(bigTradeBar), bigTradeBar.Volume);
}
var bigOpenInterest = data as OpenInterest;
if (bigOpenInterest != null)
{
return ToCsv(longTime, bigOpenInterest.Value);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
}
break;
case SecurityType.FutureOption:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick)data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds,
tick.LastPrice, tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds,
tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.ExchangeCode, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.OpenInterest)
{
return ToCsv(milliseconds, tick.Value);
}
break;
case Resolution.Second:
case Resolution.Minute:
// option and future data can be quote or trade bars
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds,
tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume);
}
var openInterest = data as OpenInterest;
if (openInterest != null)
{
return ToCsv(milliseconds, openInterest.Value);
}
break;
case Resolution.Hour:
case Resolution.Daily:
// option and future data can be quote or trade bars
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, ToNonScaledCsv(bigTradeBar), bigTradeBar.Volume);
}
var bigOpenInterest = data as OpenInterest;
if (bigOpenInterest != null)
{
return ToCsv(longTime, bigOpenInterest.Value);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
}
break;
case SecurityType.Future:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick)data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds,
tick.LastPrice, tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1": "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds,
tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.ExchangeCode, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.OpenInterest)
{
return ToCsv(milliseconds, tick.Value);
}
break;
case Resolution.Second:
case Resolution.Minute:
// option and future data can be quote or trade bars
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds,
tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume);
}
var openInterest = data as OpenInterest;
if (openInterest != null)
{
return ToCsv(milliseconds, openInterest.Value);
}
break;
case Resolution.Hour:
case Resolution.Daily:
// option and future data can be quote or trade bars
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, ToNonScaledCsv(bigTradeBar), bigTradeBar.Volume);
}
var bigOpenInterest = data as OpenInterest;
if (bigOpenInterest != null)
{
return ToCsv(longTime, bigOpenInterest.Value);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(securityType), securityType, null);
}
throw new NotImplementedException(Invariant(
$"LeanData.GenerateLine has not yet been implemented for security type: {securityType} at resolution: {resolution}"
));
}
/// <summary>
/// Gets the data type required for the specified combination of resolution and tick type
/// </summary>
/// <param name="resolution">The resolution, if Tick, the Type returned is always Tick</param>
/// <param name="tickType">The <see cref="TickType"/> that primarily dictates the type returned</param>
/// <returns>The Type used to create a subscription</returns>
public static Type GetDataType(Resolution resolution, TickType tickType)
{
if (resolution == Resolution.Tick) return typeof(Tick);
if (tickType == TickType.OpenInterest) return typeof(OpenInterest);
if (tickType == TickType.Quote) return typeof(QuoteBar);
return typeof(TradeBar);
}
/// <summary>
/// Determines if the Type is a 'common' type used throughout lean
/// This method is helpful in creating <see cref="SubscriptionDataConfig"/>
/// </summary>
/// <param name="baseDataType">The Type to check</param>
/// <returns>A bool indicating whether the type is of type <see cref="TradeBar"/>
/// <see cref="QuoteBar"/> or <see cref="OpenInterest"/></returns>
public static bool IsCommonLeanDataType(Type baseDataType)
{
if (baseDataType == typeof(Tick) ||
baseDataType == typeof(TradeBar) ||
baseDataType == typeof(QuoteBar) ||
baseDataType == typeof(OpenInterest))
{
return true;
}
return false;
}
/// <summary>
/// Generates the full zip file path rooted in the <paramref name="dataDirectory"/>
/// </summary>
public static string GenerateZipFilePath(string dataDirectory, Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
return Path.Combine(dataDirectory, GenerateRelativeZipFilePath(symbol, date, resolution, tickType));
}
/// <summary>
/// Generates the full zip file path rooted in the <paramref name="dataDirectory"/>
/// </summary>
public static string GenerateZipFilePath(string dataDirectory, string symbol, SecurityType securityType, string market, DateTime date, Resolution resolution)
{
return Path.Combine(dataDirectory, GenerateRelativeZipFilePath(symbol, securityType, market, date, resolution));
}
/// <summary>
/// Generates the relative zip directory for the specified symbol/resolution
/// </summary>
public static string GenerateRelativeZipFileDirectory(Symbol symbol, Resolution resolution)
{
var isHourOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
var securityType = symbol.SecurityType.SecurityTypeToLower();
var market = symbol.ID.Market.ToLowerInvariant();
var res = resolution.ResolutionToLower();
var directory = Path.Combine(securityType, market, res);
switch (symbol.ID.SecurityType)
{
case SecurityType.Base:
case SecurityType.Equity:
case SecurityType.Index:
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return !isHourOrDaily ? Path.Combine(directory, symbol.Value.ToLowerInvariant()) : directory;
case SecurityType.Option:
case SecurityType.IndexOption:
// options uses the underlying symbol for pathing.
return !isHourOrDaily ? Path.Combine(directory, symbol.Underlying.Value.ToLowerInvariant()) : directory;
case SecurityType.FutureOption:
// For futures options, we use the canonical option ticker plus the underlying's expiry
// since it can differ from the underlying's ticker. We differ from normal futures
// because the option chain can be extraordinarily large compared to equity option chains.
var futureOptionPath = Path.Combine(symbol.ID.Symbol, symbol.Underlying.ID.Date.ToStringInvariant(DateFormat.EightCharacter))
.ToLowerInvariant();
return Path.Combine(directory, futureOptionPath);
case SecurityType.Future:
return !isHourOrDaily ? Path.Combine(directory, symbol.ID.Symbol.ToLowerInvariant()) : directory;
case SecurityType.Commodity:
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Generates relative factor file paths for equities
/// </summary>
public static string GenerateRelativeFactorFilePath(Symbol symbol)
{
return Path.Combine(Globals.DataFolder,
"equity",
symbol.ID.Market,
"factor_files",
symbol.Value.ToLowerInvariant() + ".csv");
}
/// <summary>
/// Generates the relative zip file path rooted in the /Data directory
/// </summary>
public static string GenerateRelativeZipFilePath(Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
return Path.Combine(GenerateRelativeZipFileDirectory(symbol, resolution), GenerateZipFileName(symbol, date, resolution, tickType));
}
/// <summary>
/// Generates the relative zip file path rooted in the /Data directory
/// </summary>
public static string GenerateRelativeZipFilePath(string symbol, SecurityType securityType, string market, DateTime date, Resolution resolution)
{
var directory = Path.Combine(securityType.SecurityTypeToLower(), market.ToLowerInvariant(), resolution.ResolutionToLower());
if (resolution != Resolution.Daily && resolution != Resolution.Hour)
{
directory = Path.Combine(directory, symbol.ToLowerInvariant());
}
return Path.Combine(directory, GenerateZipFileName(symbol, securityType, date, resolution));
}
/// <summary>
/// Generate's the zip entry name to hold the specified data.
/// </summary>
public static string GenerateZipEntryName(Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
var formattedDate = date.ToStringInvariant(DateFormat.EightCharacter);
var isHourOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
switch (symbol.ID.SecurityType)
{
case SecurityType.Base:
case SecurityType.Equity:
case SecurityType.Index:
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
if (resolution == Resolution.Tick && symbol.SecurityType == SecurityType.Equity)
{
return Invariant($"{formattedDate}_{symbol.Value.ToLowerInvariant()}_{tickType}_{resolution}.csv");
}
if (isHourOrDaily)
{
return $"{symbol.Value.ToLowerInvariant()}.csv";
}
return Invariant($"{formattedDate}_{symbol.Value.ToLowerInvariant()}_{resolution.ResolutionToLower()}_{tickType.TickTypeToLower()}.csv");
case SecurityType.Option:
case SecurityType.IndexOption:
var optionPath = symbol.Underlying.Value.ToLowerInvariant();
if (isHourOrDaily)
{
return string.Join("_",
optionPath,
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.OptionStyleToLower(),
symbol.ID.OptionRight.OptionRightToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
}
return string.Join("_",
formattedDate,
optionPath,
resolution.ResolutionToLower(),
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.OptionStyleToLower(),
symbol.ID.OptionRight.OptionRightToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
case SecurityType.FutureOption:
// We want the future option ticker as the lookup name inside the ZIP file
var futureOptionPath = symbol.ID.Symbol.ToLowerInvariant();
if (isHourOrDaily)
{
return string.Join("_",
futureOptionPath,
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.OptionStyleToLower(),
symbol.ID.OptionRight.OptionRightToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
}
return string.Join("_",
formattedDate,
futureOptionPath,
resolution.ResolutionToLower(),
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.OptionStyleToLower(),
symbol.ID.OptionRight.OptionRightToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
case SecurityType.Future:
if (symbol.HasUnderlying)
{
symbol = symbol.Underlying;
}
var expiryDate = symbol.ID.Date;
var monthsToAdd = FuturesExpiryUtilityFunctions.GetDeltaBetweenContractMonthAndContractExpiry(symbol.ID.Symbol, expiryDate.Date);
var contractYearMonth = expiryDate.AddMonths(monthsToAdd).ToStringInvariant(DateFormat.YearMonth);
if (isHourOrDaily)
{
return string.Join("_",
symbol.ID.Symbol.ToLowerInvariant(),
tickType.TickTypeToLower(),
contractYearMonth,
expiryDate.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
}
return string.Join("_",
formattedDate,
symbol.ID.Symbol.ToLowerInvariant(),
resolution.ResolutionToLower(),
tickType.TickTypeToLower(),
contractYearMonth,
expiryDate.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
case SecurityType.Commodity:
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Generates the zip file name for the specified date of data.
/// </summary>
public static string GenerateZipFileName(Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
var tickTypeString = tickType.TickTypeToLower();
var formattedDate = date.ToStringInvariant(DateFormat.EightCharacter);
var isHourOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
switch (symbol.ID.SecurityType)
{
case SecurityType.Base:
case SecurityType.Index:
case SecurityType.Equity:
case SecurityType.Forex:
case SecurityType.Cfd:
if (isHourOrDaily)
{
return $"{symbol.Value.ToLowerInvariant()}.zip";
}
return $"{formattedDate}_{tickTypeString}.zip";
case SecurityType.Crypto:
if (isHourOrDaily)
{
return $"{symbol.Value.ToLowerInvariant()}_{tickTypeString}.zip";
}
return $"{formattedDate}_{tickTypeString}.zip";
case SecurityType.Option:
case SecurityType.IndexOption:
if (isHourOrDaily)
{
// see TryParsePath: he knows tick type position is 3
var optionPath = symbol.Underlying.Value.ToLowerInvariant();
return $"{optionPath}_{date.Year}_{tickTypeString}_{symbol.ID.OptionStyle.OptionStyleToLower()}.zip";
}
return $"{formattedDate}_{tickTypeString}_{symbol.ID.OptionStyle.OptionStyleToLower()}.zip";
case SecurityType.FutureOption:
if (isHourOrDaily)
{
// see TryParsePath: he knows tick type position is 3
var futureOptionPath = symbol.ID.Symbol.ToLowerInvariant();
return $"{futureOptionPath}_{date.Year}_{tickTypeString}_{symbol.ID.OptionStyle.OptionStyleToLower()}.zip";
}
return $"{formattedDate}_{tickTypeString}_{symbol.ID.OptionStyle.OptionStyleToLower()}.zip";
case SecurityType.Future:
if (isHourOrDaily)
{
return $"{symbol.ID.Symbol.ToLowerInvariant()}_{tickTypeString}.zip";
}
return $"{formattedDate}_{tickTypeString}.zip";
case SecurityType.Commodity:
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Creates the zip file name for a QC zip data file
/// </summary>
public static string GenerateZipFileName(string symbol, SecurityType securityType, DateTime date, Resolution resolution, TickType? tickType = null)
{
if (resolution == Resolution.Hour || resolution == Resolution.Daily)
{
return $"{symbol.ToLowerInvariant()}.zip";
}
var zipFileName = date.ToStringInvariant(DateFormat.EightCharacter);
if (tickType == null)
{
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd) {
tickType = TickType.Quote;
}
else
{
tickType = TickType.Trade;
}
}
var suffix = Invariant($"_{tickType.Value.TickTypeToLower()}.zip");
return zipFileName + suffix;
}
/// <summary>
/// Gets the tick type most commonly associated with the specified security type
/// </summary>
/// <param name="securityType">The security type</param>
/// <returns>The most common tick type for the specified security type</returns>
public static TickType GetCommonTickType(SecurityType securityType)
{
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd || securityType == SecurityType.Crypto)
{
return TickType.Quote;
}
return TickType.Trade;
}
/// <summary>
/// Creates a symbol from the specified zip entry name
/// </summary>
/// <param name="symbol">The root symbol of the output symbol</param>
/// <param name="resolution">The resolution of the data source producing the zip entry name</param>
/// <param name="zipEntryName">The zip entry name to be parsed</param>
/// <returns>A new symbol representing the zip entry name</returns>
public static Symbol ReadSymbolFromZipEntry(Symbol symbol, Resolution resolution, string zipEntryName)
{
var isHourlyOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
var parts = zipEntryName.Replace(".csv", string.Empty).Split('_');
switch (symbol.ID.SecurityType)
{
case SecurityType.Option:
case SecurityType.FutureOption:
case SecurityType.IndexOption:
if (isHourlyOrDaily)
{
var style = parts[2].ParseOptionStyle();
var right = parts[3].ParseOptionRight();
var strike = Parse.Decimal(parts[4]) / 10000m;
var expiry = Parse.DateTimeExact(parts[5], DateFormat.EightCharacter);
return Symbol.CreateOption(symbol.Underlying, symbol.ID.Market, style, right, strike, expiry);
}
else
{
var style = parts[4].ParseOptionStyle();
var right = parts[5].ParseOptionRight();
var strike = Parse.Decimal(parts[6]) / 10000m;
var expiry = DateTime.ParseExact(parts[7], DateFormat.EightCharacter, CultureInfo.InvariantCulture);
return Symbol.CreateOption(symbol.Underlying, symbol.ID.Market, style, right, strike, expiry);
}
case SecurityType.Future:
if (isHourlyOrDaily)
{
var expiryYearMonth = Parse.DateTimeExact(parts[2], DateFormat.YearMonth);
var futureExpiryFunc = FuturesExpiryFunctions.FuturesExpiryFunction(symbol);
var futureExpiry = futureExpiryFunc(expiryYearMonth);
return Symbol.CreateFuture(parts[0], symbol.ID.Market, futureExpiry);
}
else
{
var expiryYearMonth = Parse.DateTimeExact(parts[4], DateFormat.YearMonth);
var futureExpiryFunc = FuturesExpiryFunctions.FuturesExpiryFunction(symbol);
var futureExpiry = futureExpiryFunc(expiryYearMonth);
return Symbol.CreateFuture(parts[1], symbol.ID.Market, futureExpiry);
}
default:
throw new NotImplementedException(Invariant(
$"ReadSymbolFromZipEntry is not implemented for {symbol.ID.SecurityType} {symbol.ID.Market} {resolution}"
));
}
}
/// <summary>
/// Scale and convert the resulting number to deci-cents int.
/// </summary>
private static long Scale(decimal value)
{
return (long)(value*10000);
}
/// <summary>
/// Create a csv line from the specified arguments
/// </summary>
private static string ToCsv(params object[] args)
{
// use culture neutral formatting for decimals
for (var i = 0; i < args.Length; i++)
{
var value = args[i];
if (value is decimal)
{
args[i] = ((decimal) value).Normalize();
}
}
return string.Join(",", args);
}
/// <summary>
/// Creates a scaled csv line for the bar, if null fills in empty strings
/// </summary>
private static string ToScaledCsv(IBar bar)
{
if (bar == null)
{
return ToCsv(string.Empty, string.Empty, string.Empty, string.Empty);
}
return ToCsv(Scale(bar.Open), Scale(bar.High), Scale(bar.Low), Scale(bar.Close));
}
/// <summary>
/// Creates a non scaled csv line for the bar, if null fills in empty strings
/// </summary>
private static string ToNonScaledCsv(IBar bar)
{
if (bar == null)
{
return ToCsv(string.Empty, string.Empty, string.Empty, string.Empty);
}
return ToCsv(bar.Open, bar.High, bar.Low, bar.Close);
}
/// <summary>
/// Get the <see cref="TickType"/> for common Lean data types.
/// If not a Lean common data type, return a TickType of Trade.
/// </summary>
/// <param name="type">A Type used to determine the TickType</param>
/// <param name="securityType">The SecurityType used to determine the TickType</param>
/// <returns>A TickType corresponding to the type</returns>
public static TickType GetCommonTickTypeForCommonDataTypes(Type type, SecurityType securityType)
{
if (type == typeof(TradeBar))
{
return TickType.Trade;
}
if (type == typeof(QuoteBar))
{
return TickType.Quote;
}
if (type == typeof(OpenInterest))
{
return TickType.OpenInterest;
}
if (type == typeof(ZipEntryName))
{
return TickType.Quote;
}
if (type == typeof(Tick))
{
if (securityType == SecurityType.Forex ||
securityType == SecurityType.Cfd ||
securityType == SecurityType.Crypto)
{
return TickType.Quote;
}
}
return TickType.Trade;
}
/// <summary>
/// Matches a data path security type with the <see cref="SecurityType"/>
/// </summary>
/// <remarks>This includes 'alternative'</remarks>
/// <param name="securityType">The data path security type</param>
/// <returns>The matching security type for the given data path</returns>
public static SecurityType ParseDataSecurityType(string securityType)
{
if (securityType.Equals("alternative", StringComparison.InvariantCultureIgnoreCase))
{
return SecurityType.Base;
}
return (SecurityType) Enum.Parse(typeof(SecurityType), securityType, true);
}
/// <summary>
/// Parses file name into a <see cref="Security"/> and DateTime
/// </summary>
/// <param name="fileName">File name to be parsed</param>
/// <param name="securityType">The securityType as parsed from the fileName</param>
/// <param name="market">The market as parsed from the fileName</param>
public static bool TryParseSecurityType(string fileName, out SecurityType securityType, out string market)
{
securityType = SecurityType.Base;
market = string.Empty;
try
{
var info = SplitDataPath(fileName);
// find the securityType and parse it
var typeString = info.Find(x => SecurityTypeAsDataPath.Contains(x.ToLowerInvariant()));
securityType = ParseDataSecurityType(typeString);
var existingMarkets = Market.SupportedMarkets();
var foundMarket = info.Find(x => existingMarkets.Contains(x.ToLowerInvariant()));
if (foundMarket != null)
{
market = foundMarket;
}
}
catch (Exception e)
{
Log.Error($"LeanData.TryParsePath(): Error encountered while parsing the path {fileName}. Error: {e.GetBaseException()}");
return false;
}
return true;
}
/// <summary>
/// Parses file name into a <see cref="Security"/> and DateTime
/// </summary>
/// <param name="filePath">File path to be parsed</param>
/// <param name="symbol">The symbol as parsed from the fileName</param>
/// <param name="date">Date of data in the file path. Only returned if the resolution is lower than Hourly</param>
/// <param name="resolution">The resolution of the symbol as parsed from the filePath</param>
/// <param name="tickType">The tick type</param>
/// <param name="dataType">The data type</param>
public static bool TryParsePath(string filePath, out Symbol symbol, out DateTime date,
out Resolution resolution, out TickType tickType, out Type dataType)
{
symbol = default;
tickType = default;
dataType = default;
date = default;
resolution = default;
try
{
if (!TryParsePath(filePath, out symbol, out date, out resolution))
{
return false;
}
tickType = GetCommonTickType(symbol.SecurityType);
var fileName = Path.GetFileNameWithoutExtension(filePath);
if (fileName.Contains("_"))
{
// example: 20140606_openinterest_american.zip
var tickTypePosition = 1;
if (resolution >= Resolution.Hour && symbol.SecurityType.IsOption())
{
// daily and hourly have the year too, example: aapl_2014_openinterest_american.zip
// see GenerateZipFileName he's creating these paths
tickTypePosition = 2;
}
tickType = (TickType)Enum.Parse(typeof(TickType), fileName.Split('_')[tickTypePosition], true);
}
dataType = GetDataType(resolution, tickType);
return true;
}
catch (Exception ex)
{
Log.Debug($"LeanData.TryParsePath(): Error encountered while parsing the path {filePath}. Error: {ex.GetBaseException()}");
}
return false;
}
/// <summary>
/// Parses file name into a <see cref="Security"/> and DateTime
/// </summary>
/// <param name="fileName">File name to be parsed</param>
/// <param name="symbol">The symbol as parsed from the fileName</param>
/// <param name="date">Date of data in the file path. Only returned if the resolution is lower than Hourly</param>
/// <param name="resolution">The resolution of the symbol as parsed from the filePath</param>
public static bool TryParsePath(string fileName, out Symbol symbol, out DateTime date, out Resolution resolution)
{
symbol = null;
resolution = Resolution.Daily;
date = default(DateTime);
try
{
var info = SplitDataPath(fileName);
// find where the useful part of the path starts - i.e. the securityType
var startIndex = info.FindIndex(x => SecurityTypeAsDataPath.Contains(x.ToLowerInvariant()));
var securityType = ParseDataSecurityType(info[startIndex]);
var market = Market.USA;
string ticker;
if (securityType == SecurityType.Base)
{
if (!Enum.TryParse(info[startIndex + 2], true, out resolution))
{
resolution = Resolution.Daily;
}
// the last part of the path is the file name
var fileNameNoPath = info[info.Count - 1].Split('_').First();
if (!DateTime.TryParseExact(fileNameNoPath,
DateFormat.EightCharacter,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out date))
{
// if parsing the date failed we assume filename is ticker
ticker = fileNameNoPath;
}
else
{
// ticker must be the previous part of the path
ticker = info[info.Count - 2];
}
}
else
{
resolution = (Resolution)Enum.Parse(typeof(Resolution), info[startIndex + 2], true);
// Gather components used to create the security
market = info[startIndex + 1];
ticker = info[startIndex + 3];
// Remove the ticktype from the ticker (Only exists in Crypto and Future data but causes no issues)
ticker = ticker.Split('_').First();
// If resolution is Daily or Hour, we do not need to set the date
if (resolution < Resolution.Hour)
{
// Future options are special and have the following format Market/Resolution/Ticker/FutureExpiry/Date
var dateIndex = securityType == SecurityType.FutureOption ? startIndex + 5 : startIndex + 4;
date = Parse.DateTimeExact(info[dateIndex].Substring(0, 8), DateFormat.EightCharacter);
}
}
// Future Options cannot use Symbol.Create
if (securityType == SecurityType.FutureOption)
{
// Future options have underlying FutureExpiry date as the parent dir for the zips, we need this for our underlying
var underlyingFutureExpiryDate = Parse.DateTimeExact(info[startIndex + 4].Substring(0, 8), DateFormat.EightCharacter);
// Create our underlying future and then the Canonical option for this future
var underlyingFuture = Symbol.CreateFuture(ticker, market, underlyingFutureExpiryDate);
symbol = Symbol.CreateCanonicalOption(underlyingFuture);
}
else
{
symbol = Symbol.Create(ticker, securityType, market);
}
}
catch (Exception ex)
{
Log.Debug($"LeanData.TryParsePath(): Error encountered while parsing the path {fileName}. Error: {ex.GetBaseException()}");
return false;
}
return true;
}
private static List<string> SplitDataPath(string fileName)
{
var pathSeparators = new[] { '/', '\\' };
// Removes file extension
fileName = fileName.Replace(fileName.GetExtension(), string.Empty);
// remove any relative file path
while (fileName.First() == '.' || pathSeparators.Any(x => x == fileName.First()))
{
fileName = fileName.Remove(0, 1);
}
// split path into components
return fileName.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries).ToList();
}
/// <summary>
/// Aggregates a list of second/minute bars at the requested resolution
/// </summary>
/// <param name="bars">List of <see cref="TradeBar"/>s</param>
/// <param name="symbol">Symbol of all tradeBars</param>
/// <param name="resolution">Desired resolution for new <see cref="TradeBar"/>s</param>
/// <returns>List of aggregated <see cref="TradeBar"/>s</returns>
public static IEnumerable<TradeBar> AggregateTradeBars(IEnumerable<TradeBar> bars, Symbol symbol, TimeSpan resolution)
{
return
from b in bars
group b by b.Time.RoundDown(resolution)
into g
select new TradeBar
{
Symbol = symbol,
Time = g.Key,
Open = g.First().Open,
High = g.Max(b => b.High),
Low = g.Min(b => b.Low),
Close = g.Last().Close,
Value = g.Last().Close,
DataType = MarketDataType.TradeBar,
Period = resolution
};
}
/// <summary>
/// Aggregates a list of second/minute bars at the requested resolution
/// </summary>
/// <param name="bars">List of <see cref="QuoteBar"/>s</param>
/// <param name="symbol">Symbol of all QuoteBars</param>
/// <param name="resolution">Desired resolution for new <see cref="QuoteBar"/>s</param>
/// <returns>List of aggregated <see cref="QuoteBar"/>s</returns>
public static IEnumerable<QuoteBar> AggregateQuoteBars(IEnumerable<QuoteBar> bars, Symbol symbol, TimeSpan resolution)
{
return
from b in bars
group b by b.Time.RoundDown(resolution)
into g
select new QuoteBar
{
Symbol = symbol,
Time = g.Key,
Bid = new Bar
{
Open = g.First().Bid.Open,
High = g.Max(b => b.Bid.High),
Low = g.Min(b => b.Bid.Low),
Close = g.Last().Bid.Close
},
Ask = new Bar
{
Open = g.First().Ask.Open,
High = g.Max(b => b.Ask.High),
Low = g.Min(b => b.Ask.Low),
Close = g.Last().Ask.Close
},
Period = resolution
};
}
/// <summary>
/// Aggregates a list of ticks at the requested resolution
/// </summary>
/// <param name="ticks">List of <see cref="QuoteBar"/>s</param>
/// <param name="symbol">Symbol of all QuoteBars</param>
/// <param name="resolution">Desired resolution for new <see cref="QuoteBar"/>s</param>
/// <returns>List of aggregated <see cref="QuoteBar"/>s</returns>
public static IEnumerable<QuoteBar> AggregateTicks(IEnumerable<Tick> ticks, Symbol symbol, TimeSpan resolution)
{
return
from t in ticks
group t by t.Time.RoundDown(resolution)
into g
select new QuoteBar
{
Symbol = symbol,
Time = g.Key,
Bid = new Bar
{
Open = g.First().BidPrice,
High = g.Max(b => b.BidPrice),
Low = g.Min(b => b.BidPrice),
Close = g.Last().BidPrice
},
Ask = new Bar
{
Open = g.First().AskPrice,
High = g.Max(b => b.AskPrice),
Low = g.Min(b => b.AskPrice),
Close = g.Last().AskPrice
},
Period = resolution
};
}
/// <summary>
/// Helper to separate filename and entry from a given key for DataProviders
/// </summary>
/// <param name="key">The key to parse</param>
/// <param name="fileName">File name extracted</param>
/// <param name="entryName">Entry name extracted</param>
public static void ParseKey(string key, out string fileName, out string entryName)
{
// Default scenario, no entryName included in key
entryName = null; // default to all entries
fileName = key;
if (key == null)
{
return;
}
// Try extracting an entry name; Anything after a # sign
var hashIndex = key.LastIndexOf("#", StringComparison.Ordinal);
if (hashIndex != -1)
{
entryName = key.Substring(hashIndex + 1);
fileName = key.Substring(0, hashIndex);
}
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2007 Jonathan Mark Porter. http://physics2d.googlepages.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.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
using AdvanceMath.Design;
namespace AdvanceMath
{
/// <summary>
///
/// </summary>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29"/></remarks>
[StructLayout(LayoutKind.Sequential, Size = Vector3D.Size, Pack = 0), Serializable]
[AdvBrowsableOrder("X,Y,Z")]
[System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<Vector3D>))]
public struct Vector3D : IVector<Vector3D>
{
#region const fields
/// <summary>
/// The number of Scalar values in the class.
/// </summary>
public const int Count = 3;
/// <summary>
/// The Size of the class in bytes;
/// </summary>
public const int Size = sizeof(Scalar) * Count;
#endregion
#region readonly fields
/// <summary>
/// Vector3D(0,0,0)
/// </summary>
public static readonly Vector3D Origin = new Vector3D();
/// <summary>
/// Vector3D(0,0,0)
/// </summary>
public static readonly Vector3D Zero = new Vector3D();
/// <summary>
/// Vector3D(1,0,0)
/// </summary>
public static readonly Vector3D XAxis = new Vector3D(1, 0, 0);
/// <summary>
/// Vector3D(0,1,0)
/// </summary>
public static readonly Vector3D YAxis = new Vector3D(0, 1, 0);
/// <summary>
/// Vector3D(0,0,1)
/// </summary>
public static readonly Vector3D ZAxis = new Vector3D(0, 0, 1);
private static readonly string FormatString = MatrixHelper.CreateVectorFormatString(Count);
private readonly static string FormatableString = MatrixHelper.CreateVectorFormatableString(Count);
#endregion
#region static methods
public static void Copy(ref Vector3D vector, Scalar[] destArray)
{
Copy(ref vector, destArray, 0);
}
public static void Copy(ref Vector3D vector, Scalar[] destArray, int index)
{
ThrowHelper.CheckCopy(destArray, index, Count);
destArray[index] = vector.X;
destArray[++index] = vector.Y;
destArray[++index] = vector.Z;
}
public static void Copy(Scalar[] sourceArray, out Vector3D result)
{
Copy(sourceArray, 0, out result);
}
public static void Copy(Scalar[] sourceArray, int index, out Vector3D result)
{
ThrowHelper.CheckCopy(sourceArray, index, Count);
result.X = sourceArray[index];
result.Y = sourceArray[++index];
result.Z = sourceArray[++index];
}
public static void Copy(ref Vector4D source, out Vector3D dest)
{
dest.X = source.X;
dest.Y = source.Y;
dest.Z = source.Z;
}
public static void Copy(ref Vector2D source, ref Vector3D dest)
{
dest.X = source.X;
dest.Y = source.Y;
}
public static Vector3D Clamp(Vector3D value, Vector3D lower, Vector3D upper)
{
Vector3D result;
MathHelper.Clamp(ref value.X, ref lower.X, ref upper.X, out result.X);
MathHelper.Clamp(ref value.Y, ref lower.Y, ref upper.Y, out result.Y);
MathHelper.Clamp(ref value.Z, ref lower.Z, ref upper.Z, out result.Z);
return result;
}
public static void Clamp(ref Vector3D value, ref Vector3D lower, ref Vector3D upper, out Vector3D result)
{
MathHelper.Clamp(ref value.X, ref lower.X, ref upper.X, out result.X);
MathHelper.Clamp(ref value.Y, ref lower.Y, ref upper.Y, out result.Y);
MathHelper.Clamp(ref value.Z, ref lower.Z, ref upper.Z, out result.Z);
}
public static Vector3D Lerp(Vector3D left, Vector3D right, Scalar amount)
{
Vector3D result;
Lerp(ref left, ref right, ref amount, out result);
return result;
}
public static void Lerp(ref Vector3D left, ref Vector3D right, ref Scalar amount, out Vector3D result)
{
result.X = (right.X - left.X) * amount + left.X;
result.Y = (right.Y - left.Y) * amount + left.Y;
result.Z = (right.Z - left.Z) * amount + left.Z;
}
public static Vector3D Lerp(Vector3D left, Vector3D right, Vector3D amount)
{
Vector3D result;
Lerp(ref left, ref right, ref amount, out result);
return result;
}
public static void Lerp(ref Vector3D left, ref Vector3D right, ref Vector3D amount, out Vector3D result)
{
result.X = (right.X - left.X) * amount.X + left.X;
result.Y = (right.Y - left.Y) * amount.Y + left.Y;
result.Z = (right.Z - left.Z) * amount.Z + left.Z;
}
public static Vector3D FromArray(Scalar[] array)
{
return FromArray(array, 0);
}
public static Vector3D FromArray(Scalar[] array, int index)
{
Vector3D result;
Copy(array, index, out result);
return result;
}
/// <summary>
/// Adds 2 Vectors2Ds.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Sum of the 2 Vector3Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector3D Add(Vector3D left, Vector3D right)
{
Vector3D result;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
return result;
}
public static void Add(ref Vector3D left, ref Vector3D right, out Vector3D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
}
public static Vector3D Add(Vector2D left, Vector3D right)
{
Vector3D result;
Add(ref left, ref right, out result);
return result;
}
public static void Add(ref Vector2D left, ref Vector3D right, out Vector3D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = right.Z;
}
public static Vector3D Add(Vector3D left, Vector2D right)
{
Vector3D result;
Add(ref left, ref right, out result);
return result;
}
public static void Add(ref Vector3D left, ref Vector2D right, out Vector3D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z;
}
/// <summary>
/// Subtracts 2 Vector3Ds.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Difference of the 2 Vector3Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector3D Subtract(Vector3D left, Vector3D right)
{
Vector3D result;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
return result;
}
public static void Subtract(ref Vector3D left, ref Vector3D right, out Vector3D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
}
public static Vector3D Subtract(Vector2D left, Vector3D right)
{
Vector3D result;
Subtract(ref left, ref right, out result);
return result;
}
public static void Subtract(ref Vector2D left, ref Vector3D right, out Vector3D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = -right.Z;
}
public static Vector3D Subtract(Vector3D left, Vector2D right)
{
Vector3D result;
Subtract(ref left, ref right, out result);
return result;
}
public static void Subtract(ref Vector3D left, ref Vector2D right, out Vector3D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z;
}
/// <summary>
/// Does Scaler Multiplication on a Vector3D.
/// </summary>
/// <param name="source">The Vector3D to be multiplied.</param>
/// <param name="scalar">The scalar value that will multiply the Vector3D.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Scalar_multiplication"/></remarks>
public static Vector3D Multiply(Vector3D source, Scalar scalar)
{
Vector3D result;
result.X = source.X * scalar;
result.Y = source.Y * scalar;
result.Z = source.Z * scalar;
return result;
}
public static void Multiply(ref Vector3D source, ref Scalar scalar, out Vector3D result)
{
result.X = source.X * scalar;
result.Y = source.Y * scalar;
result.Z = source.Z * scalar;
}
/// <summary>
/// matrix * vector [3x3 * 3x1 = 3x1]
/// </summary>
/// <param name="vector"></param>
/// <param name="matrix"></param>
/// <returns></returns>
public static Vector3D Transform(Matrix3x3 matrix, Vector3D vector)
{
Vector3D result;
result.X = matrix.m00 * vector.X + matrix.m01 * vector.Y + matrix.m02 * vector.Z;
result.Y = matrix.m10 * vector.X + matrix.m11 * vector.Y + matrix.m12 * vector.Z;
result.Z = matrix.m20 * vector.X + matrix.m21 * vector.Y + matrix.m22 * vector.Z;
return result;
}
public static void Transform(ref Matrix3x3 matrix, ref Vector3D vector, out Vector3D result)
{
Scalar X = vector.X;
Scalar Y = vector.Y;
result.X = matrix.m00 * X + matrix.m01 * Y + matrix.m02 * vector.Z;
result.Y = matrix.m10 * X + matrix.m11 * Y + matrix.m12 * vector.Z;
result.Z = matrix.m20 * X + matrix.m21 * Y + matrix.m22 * vector.Z;
}
/// <summary>
/// vector * matrix [1x3 * 3x3 = 1x3]
/// </summary>
/// <param name="vector"></param>
/// <param name="matrix"></param>
/// <returns></returns>
public static Vector3D Transform(Vector3D vector, Matrix3x3 matrix)
{
Vector3D result;
result.X = matrix.m00 * vector.X + matrix.m01 * vector.Y + matrix.m02 * vector.Z;
result.Y = matrix.m10 * vector.X + matrix.m11 * vector.Y + matrix.m12 * vector.Z;
result.Z = matrix.m20 * vector.X + matrix.m21 * vector.Y + matrix.m22 * vector.Z;
return result;
}
public static void Transform(ref Vector3D vector, ref Matrix3x3 matrix, out Vector3D result)
{
Scalar X = vector.X;
Scalar Y = vector.Y;
result.X = matrix.m00 * X + matrix.m01 * Y + matrix.m02 * vector.Z;
result.Y = matrix.m10 * X + matrix.m11 * Y + matrix.m12 * vector.Z;
result.Z = matrix.m20 * X + matrix.m21 * Y + matrix.m22 * vector.Z;
}
/// <summary>
/// Transforms the given 3-D vector by the matrix, projecting the
/// result back into <i>w</i> = 1.
/// <p/>
/// This means that the initial <i>w</i> is considered to be 1.0,
/// and then all the tree elements of the resulting 3-D vector are
/// divided by the resulting <i>w</i>.
/// </summary>
/// <param name="matrix">A Matrix4.</param>
/// <param name="vector">A Vector3D.</param>
/// <returns>A new vector.</returns>
public static Vector3D Transform(Matrix4x4 matrix, Vector3D vector)
{
Vector3D result;
Scalar inverseW = 1.0f / (matrix.m30 * vector.X + matrix.m31 * vector.Y + matrix.m32 * vector.Z + matrix.m33);
result.X = ((matrix.m00 * vector.X) + (matrix.m01 * vector.Y) + (matrix.m02 * vector.Z) + matrix.m03) * inverseW;
result.Y = ((matrix.m10 * vector.X) + (matrix.m11 * vector.Y) + (matrix.m12 * vector.Z) + matrix.m13) * inverseW;
result.Z = ((matrix.m20 * vector.X) + (matrix.m21 * vector.Y) + (matrix.m22 * vector.Z) + matrix.m23) * inverseW;
return result;
}
public static void Transform(ref Matrix4x4 matrix, ref Vector3D vector, out Vector3D result)
{
Scalar X = vector.X;
Scalar Y = vector.Y;
Scalar inverseW = 1.0f / (matrix.m30 * vector.X + matrix.m31 * vector.Y + matrix.m32 * vector.Z + matrix.m33);
result.X = ((matrix.m00 * X) + (matrix.m01 * Y) + (matrix.m02 * vector.Z) + matrix.m03) * inverseW;
result.Y = ((matrix.m10 * X) + (matrix.m11 * Y) + (matrix.m12 * vector.Z) + matrix.m13) * inverseW;
result.Z = ((matrix.m20 * X) + (matrix.m21 * Y) + (matrix.m22 * vector.Z) + matrix.m23) * inverseW;
}
public static Vector3D Multiply(Quaternion quat, Vector3D vector)
{
// nVidia SDK implementation
Vector3D uv, uuv;
Vector3D qvec;// = new Vector3D(quat.X, quat.Y, quat.Z);
qvec.X = quat.X;
qvec.Y = quat.Y;
qvec.Z = quat.Z;
Vector3D.Cross(ref qvec, ref vector, out uv);
Vector3D.Cross(ref qvec, ref uv, out uuv);
Vector3D.Cross(ref qvec, ref uv, out uuv);
Vector3D.Multiply(ref uv, ref quat.W, out uv);
Vector3D.Add(ref uv, ref uuv, out uv);
Vector3D.Multiply(ref uv, ref MathHelper.Two, out uv);
Vector3D.Add(ref vector, ref uv, out uv);
return uv;
//uv = qvec ^ vector;
//uuv = qvec ^ uv;
//uv *= (2.0f * quat.W);
//uuv *= 2.0f;
//return vector + uv + uuv;
// get the rotation matriX of the Quaternion and multiplY it times the vector
//return quat.ToRotationMatrix() * vector;
}
public static void Multiply(ref Quaternion quat, ref Vector3D vector,out Vector3D result)
{
// nVidia SDK implementation
Vector3D uv, uuv;
Vector3D qvec;// = new Vector3D(quat.X, quat.Y, quat.Z);
qvec.X = quat.X;
qvec.Y = quat.Y;
qvec.Z = quat.Z;
Vector3D.Cross(ref qvec, ref vector, out uv);
Vector3D.Cross(ref qvec, ref uv, out uuv);
Vector3D.Cross(ref qvec, ref uv, out uuv);
Vector3D.Multiply(ref uv, ref quat.W, out uv);
Vector3D.Add(ref uv, ref uuv, out uv);
Vector3D.Multiply(ref uv, ref MathHelper.Two, out uv);
Vector3D.Add(ref vector, ref uv, out result);
//uv = qvec ^ vector;
//uuv = qvec ^ uv;
//uv *= (2.0f * quat.W);
//uuv *= 2.0f;
//return vector + uv + uuv;
// get the rotation matriX of the Quaternion and multiplY it times the vector
//return quat.ToRotationMatrix() * vector;
}
/// <summary>
/// Does a Dot Operation Also know as an Inner Product.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Dot Product (Inner Product).</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Dot_product"/></remarks>
public static Scalar Dot(Vector3D left, Vector3D right)
{
return left.Y * right.Y + left.X * right.X + left.Z * right.Z;
}
public static void Dot(ref Vector3D left,ref Vector3D right,out Scalar result)
{
result = left.Y * right.Y + left.X * right.X + left.Z * right.Z;
}
/// <summary>
/// Does a Cross Operation Also know as an Outer Product.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Cross Product.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Cross_product"/></remarks>
public static Vector3D Cross(Vector3D left, Vector3D right)
{
Vector3D result;
result.X = left.Y * right.Z - left.Z * right.Y;
result.Y = left.Z * right.X - left.X * right.Z;
result.Z = left.X * right.Y - left.Y * right.X;
return result;
}
public static void Cross(ref Vector3D left, ref Vector3D right, out Vector3D result)
{
Scalar X = left.Y * right.Z - left.Z * right.Y;
Scalar Y = left.Z * right.X - left.X * right.Z;
result.Z = left.X * right.Y - left.Y * right.X;
result.X = X;
result.Y = Y;
}
/// <summary>
/// Gets the Squared <see cref="Magnitude"/> of the Vector3D that is passed.
/// </summary>
/// <param name="source">The Vector3D whos Squared Magnitude is te be returned.</param>
/// <returns>The Squared Magnitude.</returns>
public static Scalar GetMagnitudeSq(Vector3D source)
{
return source.X * source.X + source.Y * source.Y + source.Z * source.Z;
}
public static void GetMagnitudeSq(ref Vector3D source, out Scalar result)
{
result = source.X * source.X + source.Y * source.Y + source.Z * source.Z;
}
/// <summary>
/// Gets the <see cref="Magnitude"/> of the Vector3D that is passed.
/// </summary>
/// <param name="source">The Vector3D whos Magnitude is te be returned.</param>
/// <returns>The Magnitude.</returns>
public static Scalar GetMagnitude(Vector3D source)
{
return MathHelper.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z);
}
public static void GetMagnitude(ref Vector3D source, out Scalar result)
{
result= MathHelper.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z);
}
/// <summary>
/// Sets the <see cref="Magnitude"/> of a Vector3D.
/// </summary>
/// <param name="source">The Vector3D whose Magnitude is to be changed.</param>
/// <param name="magnitude">The Magnitude.</param>
/// <returns>A Vector3D with the new Magnitude</returns>
public static Vector3D SetMagnitude(Vector3D source, Scalar magnitude)
{
Vector3D result;
SetMagnitude(ref source, ref magnitude, out result);
return result;
}
public static void SetMagnitude(ref Vector3D source, ref Scalar magnitude, out Vector3D result)
{
Scalar oldmagnitude;
GetMagnitude(ref source, out oldmagnitude);
if (oldmagnitude > 0 && magnitude != 0)
{
oldmagnitude = (magnitude / oldmagnitude);
Multiply(ref source, ref oldmagnitude, out result);
}
else
{
result = Zero;
}
}
/// <summary>
/// This returns the Normalized Vector3D that is passed. This is also known as a Unit Vector.
/// </summary>
/// <param name="source">The Vector3D to be Normalized.</param>
/// <returns>The Normalized Vector3D. (Unit Vector)</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Unit_vector"/></remarks>
public static Vector3D Normalize(Vector3D source)
{
Vector3D result;
SetMagnitude(ref source, ref MathHelper.One, out result);
return result;
}
public static void Normalize(ref Vector3D source, out Vector3D result)
{
SetMagnitude(ref source, ref MathHelper.One, out result);
}
[CLSCompliant(false)]
public static void Normalize(ref Vector3D source)
{
SetMagnitude(ref source, ref MathHelper.One, out source);
}
/// <summary>
/// Negates a Vector3D.
/// </summary>
/// <param name="source">The Vector3D to be Negated.</param>
/// <returns>The Negated Vector3D.</returns>
public static Vector3D Negate(Vector3D source)
{
Vector3D result;
result.X = -source.X;
result.Y = -source.Y;
result.Z = -source.Z;
return result;
}
[CLSCompliant(false)]
public static void Negate(ref Vector3D source)
{
Negate(ref source, out source);
}
public static void Negate(ref Vector3D source, out Vector3D result)
{
result.X = -source.X;
result.Y = -source.Y;
result.Z = -source.Z;
}
/// <summary>
/// Thie Projects the left Vector3D onto the Right Vector3D.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Projected Vector3D.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Projection_%28linear_algebra%29"/></remarks>
public static Vector3D Project(Vector3D left, Vector3D right)
{
Vector3D result;
Project(ref left, ref right, out result);
return result;
}
public static void Project(ref Vector3D left, ref Vector3D right, out Vector3D result)
{
Scalar tmp, magsq;
Dot(ref left, ref right, out tmp);
GetMagnitudeSq(ref right, out magsq);
tmp /= magsq;
Multiply(ref right, ref tmp, out result);
}
#endregion
#region fields
/// <summary>
/// This is the X value.
/// </summary>
[XmlAttribute]
[AdvBrowsable]
[System.ComponentModel.Description("The Magnitude on the X-Axis")]
public Scalar X;
/// <summary>
/// This is the Y value.
/// </summary>
[XmlAttribute]
[AdvBrowsable]
[System.ComponentModel.Description("The Magnitude on the Y-Axis")]
public Scalar Y;
/// <summary>
/// This is the Z value.
/// </summary>
[XmlAttribute]
[AdvBrowsable]
[System.ComponentModel.Description("The Magnitude on the Z-Axis")]
public Scalar Z;
#endregion
#region constructors
/// <summary>
/// Creates a New Vector3D Instance on the Stack.
/// </summary>
/// <param name="X">The X value.</param>
/// <param name="Y">The Y value.</param>
/// <param name="Z">The Z value.</param>
[InstanceConstructor("X,Y,Z")]
public Vector3D(Scalar X, Scalar Y, Scalar Z)
{
//this.Vector2D = Vector2D.Zero;
this.X = X;
this.Y = Y;
this.Z = Z;
}
public Vector3D(Scalar[] vals): this(vals,0){}
public Vector3D(Scalar[] vals, int index)
{
Copy(vals, index, out this);
}
#endregion
#region indexers
/// <summary>
/// Allows the Vector to be accessed linearly (v[0] -> v[Count-1]).
/// </summary>
/// <remarks>
/// This indexer is only provided as a convenience, and is <b>not</b> recommended for use in
/// intensive applications.
/// </remarks>
public Scalar this[int index]
{
get
{
ThrowHelper.CheckIndex("index", index, Count);
unsafe
{
fixed (Scalar* ptr = &this.X)
{
return ptr[index];
}
}
}
set
{
ThrowHelper.CheckIndex("index", index, Count);
unsafe
{
fixed (Scalar* ptr = &this.X)
{
ptr[index] = value;
}
}
}
}
#endregion
#region public properties
/// <summary>
/// Gets or Sets the Magnitude (Length) of the Vector3D.
/// </summary>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Length_of_a_vector"/></remarks>
[XmlIgnore]
public Scalar Magnitude
{
get
{
return MathHelper.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z);
}
set
{
this = SetMagnitude(this, value);
}
}
/// <summary>
/// Gets the Squared Magnitude of the Vector3D.
/// </summary>
public Scalar MagnitudeSq
{
get
{
return this.X * this.X + this.Y * this.Y + this.Z * this.Z;
}
}
/// <summary>
/// Gets the Normalized Vector3D. (Unit Vector)
/// </summary>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Unit_vector"/></remarks>
public Vector3D Normalized
{
get
{
return Normalize(this);
}
}
/// <summary>
/// The Number of Variables accesable though the indexer.
/// </summary>
int IAdvanceValueType.Count { get { return Count; } }
#endregion
#region public methods
public Scalar[] ToArray()
{
Scalar[] array = new Scalar[Count];
Copy(ref this, array, 0);
return array;
}
public void CopyFrom(Scalar[] array, int index)
{
Copy(array, index, out this);
}
public void CopyTo(Scalar[] array, int index)
{
Copy(ref this, array, index);
}
#endregion
#region operators
/// <summary>
/// Adds 2 Vectors2Ds.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Sum of the 2 Vector3Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector3D operator +(Vector3D left, Vector3D right)
{
Vector3D result;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
return result;
}
public static Vector3D operator +(Vector2D left, Vector3D right)
{
Vector3D result;
Add(ref left, ref right, out result);
return result;
}
public static Vector3D operator +(Vector3D left, Vector2D right)
{
Vector3D result;
Add(ref left, ref right, out result);
return result;
}
/// <summary>
/// Subtracts 2 Vector3Ds.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Difference of the 2 Vector3Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector3D operator -(Vector3D left, Vector3D right)
{
Vector3D result;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
return result;
}
public static Vector3D operator -(Vector2D left, Vector3D right)
{
Vector3D result;
Subtract(ref left, ref right, out result);
return result;
}
public static Vector3D operator -(Vector3D left, Vector2D right)
{
Vector3D result;
Subtract(ref left, ref right, out result);
return result;
}
/// <summary>
/// Does Scaler Multiplication on a Vector3D.
/// </summary>
/// <param name="source">The Vector3D to be multiplied.</param>
/// <param name="scalar">The scalar value that will multiply the Vector3D.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Scalar_multiplication"/></remarks>
public static Vector3D operator *(Vector3D source, Scalar scalar)
{
Vector3D result;
result.X = source.X * scalar;
result.Y = source.Y * scalar;
result.Z = source.Z * scalar;
return result;
}
/// <summary>
/// Does Scaler Multiplication on a Vector3D.
/// </summary>
/// <param name="scalar">The scalar value that will multiply the Vector3D.</param>
/// <param name="source">The Vector3D to be multiplied.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Scalar_multiplication"/></remarks>
public static Vector3D operator *(Scalar scalar, Vector3D source)
{
Vector3D result;
result.X = scalar * source.X;
result.Y = scalar * source.Y;
result.Z = scalar * source.Z;
return result;
}
/// <summary>
/// Does a Dot Operation Also know as an Inner Product.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Dot Product (Inner Product).</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Dot_product"/></remarks>
public static Scalar operator *(Vector3D left, Vector3D right)
{
return left.X * right.X + left.Y * right.Y + left.Z * right.Z;
}
/// <summary>
/// Transforms the given 3-D vector by the matrix, projecting the
/// result back into <i>w</i> = 1.
/// <p/>
/// This means that the initial <i>w</i> is considered to be 1.0,
/// and then all the tree elements of the resulting 3-D vector are
/// divided by the resulting <i>w</i>.
/// </summary>
/// <param name="matrix">A Matrix4.</param>
/// <param name="vector">A Vector3D.</param>
/// <returns>A new vector.</returns>
public static Vector3D operator *(Matrix4x4 matrix, Vector3D vector)
{
Vector3D result;
Scalar inverseW = 1.0f / (matrix.m30 * vector.X + matrix.m31 * vector.Y + matrix.m32 * vector.Z + matrix.m33);
result.X = ((matrix.m00 * vector.X) + (matrix.m01 * vector.Y) + (matrix.m02 * vector.Z) + matrix.m03) * inverseW;
result.Y = ((matrix.m10 * vector.X) + (matrix.m11 * vector.Y) + (matrix.m12 * vector.Z) + matrix.m13) * inverseW;
result.Z = ((matrix.m20 * vector.X) + (matrix.m21 * vector.Y) + (matrix.m22 * vector.Z) + matrix.m23) * inverseW;
return result;
}
/// <summary>
/// matrix * vector [3x3 * 3x1 = 3x1]
/// </summary>
/// <param name="vector"></param>
/// <param name="matrix"></param>
/// <returns></returns>
public static Vector3D operator *(Matrix3x3 matrix, Vector3D vector)
{
Vector3D result;
result.X = matrix.m00 * vector.X + matrix.m01 * vector.Y + matrix.m02 * vector.Z;
result.Y = matrix.m10 * vector.X + matrix.m11 * vector.Y + matrix.m12 * vector.Z;
result.Z = matrix.m20 * vector.X + matrix.m21 * vector.Y + matrix.m22 * vector.Z;
return result;
}
public static Vector3D operator *(Quaternion quat, Vector3D vector)
{
// nVidia SDK implementation
Vector3D uv, uuv;
Vector3D qvec;// = new Vector3D(quat.X, quat.Y, quat.Z);
qvec.X = quat.X;
qvec.Y = quat.Y;
qvec.Z = quat.Z;
Cross(ref qvec, ref vector, out uv);
Cross(ref qvec, ref uv, out uuv);
Cross(ref qvec, ref uv, out uuv);
Multiply(ref uv, ref quat.W, out uv);
Add(ref uv, ref uuv, out uv);
Multiply(ref uv, ref MathHelper.Two, out uv);
Add(ref vector, ref uv, out uv);
return uv;
//uv = qvec ^ vector;
//uuv = qvec ^ uv;
//uv *= (2.0f * quat.W);
//uuv *= 2.0f;
//return vector + uv + uuv;
// get the rotation matriX of the Quaternion and multiplY it times the vector
//return quat.ToRotationMatrix() * vector;
}
/// <summary>
/// vector * matrix [1x3 * 3x3 = 1x3]
/// </summary>
/// <param name="vector"></param>
/// <param name="matrix"></param>
/// <returns></returns>
public static Vector3D operator *(Vector3D vector, Matrix3x3 matrix)
{
Vector3D result;
result.X = matrix.m00 * vector.X + matrix.m01 * vector.Y + matrix.m02 * vector.Z;
result.Y = matrix.m10 * vector.X + matrix.m11 * vector.Y + matrix.m12 * vector.Z;
result.Z = matrix.m20 * vector.X + matrix.m21 * vector.Y + matrix.m22 * vector.Z;
return result;
}
/// <summary>
/// Negates a Vector3D.
/// </summary>
/// <param name="source">The Vector3D to be Negated.</param>
/// <returns>The Negated Vector3D.</returns>
public static Vector3D operator -(Vector3D source)
{
Vector3D result;
result.X = -source.X;
result.Y = -source.Y;
result.Z = -source.Z;
return result;
}
/// <summary>
/// Does a "2D" Cross Product also know as an Outer Product.
/// </summary>
/// <param name="left">The left Vector3D operand.</param>
/// <param name="right">The right Vector3D operand.</param>
/// <returns>The Z value of the resulting vector.</returns>
/// <remarks>
/// <seealso href="http://en.wikipedia.org/wiki/Cross_product"/>
/// </remarks>
public static Vector3D operator ^(Vector3D left, Vector3D right)
{
Vector3D result;
result.X = left.Y * right.Z - left.Z * right.Y;
result.Y = left.Z * right.X - left.X * right.Z;
result.Z = left.X * right.Y - left.Y * right.X;
return result;
}
/// <summary>
/// Specifies whether the Vector3Ds contain the same coordinates.
/// </summary>
/// <param name="left">The left Vector3D to test.</param>
/// <param name="right">The right Vector3D to test.</param>
/// <returns>true if the Vector3Ds have the same coordinates; otherwise false</returns>
public static bool operator ==(Vector3D left, Vector3D right)
{
return left.X == right.X && left.Y == right.Y && left.Z == right.Z;
}
/// <summary>
/// Specifies whether the Vector3Ds do not contain the same coordinates.
/// </summary>
/// <param name="left">The left Vector3D to test.</param>
/// <param name="right">The right Vector3D to test.</param>
/// <returns>true if the Vector3Ds do not have the same coordinates; otherwise false</returns>
public static bool operator !=(Vector3D left, Vector3D right)
{
return !(left.X == right.X && left.Y == right.Y && left.Z == right.Z);
}
public static explicit operator Vector3D(Vector2D source)
{
Vector3D result;
result.X = source.X;
result.Y = source.Y;
result.Z = 0;
return result;
}
public static explicit operator Vector3D(Vector4D source)
{
Vector3D result;
result.X = source.X;
result.Y = source.Y;
result.Z = source.Z;
return result;
}
#endregion
#region overrides
private string ToStringInternal(string FormatString)
{
return string.Format(FormatString, X, Y, Z);
}
public string ToString(string format)
{
return ToStringInternal(string.Format(FormatableString, format));
}
public override string ToString()
{
return ToStringInternal(FormatString);
}
public static bool TryParse(string s, out Vector3D result)
{
if (s == null)
{
result = Zero;
return false;
}
string[] vals = ParseHelper.SplitStringVector(s);
if (vals.Length != Count)
{
result = Zero;
return false;
}
if (Scalar.TryParse(vals[0], out result.X) &&
Scalar.TryParse(vals[1], out result.Y) &&
Scalar.TryParse(vals[2], out result.Z))
{
return true;
}
else
{
result = Zero;
return false;
}
}
[ParseMethod]
public static Vector3D Parse(string s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
string[] vals = ParseHelper.SplitStringVector(s);
if (vals.Length != Count)
{
ThrowHelper.ThrowVectorFormatException(s, Count, FormatString);
}
Vector3D value;
value.X = Scalar.Parse(vals[0]);
value.Y = Scalar.Parse(vals[1]);
value.Z = Scalar.Parse(vals[2]);
return value;
}
/// <summary>
/// Provides a unique hash code based on the member variables of this
/// class. This should be done because the equality operators (==, !=)
/// have been overriden by this class.
/// <p/>
/// The standard implementation is a simple XOR operation between all local
/// member variables.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
/// <summary>
/// Compares this Vector to another object. This should be done because the
/// equality operators (==, !=) have been overriden by this class.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (obj is Vector3D) && Equals((Vector3D)obj);
}
public bool Equals(Vector3D other)
{
return Equals(ref this, ref other);
}
public static bool Equals(Vector3D left, Vector3D right)
{
return
left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z;
}
[CLSCompliant(false)]
public static bool Equals(ref Vector3D left, ref Vector3D right)
{
return
left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace System.Linq.Expressions
{
internal abstract class OldExpressionVisitor
{
internal OldExpressionVisitor()
{
}
internal virtual Expression Visit(Expression exp)
{
if (exp == null)
return exp;
switch (exp.NodeType)
{
case ExpressionType.UnaryPlus:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return this.VisitUnary((UnaryExpression)exp);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Power:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return this.VisitBinary((BinaryExpression)exp);
case ExpressionType.TypeIs:
return this.VisitTypeIs((TypeBinaryExpression)exp);
case ExpressionType.Conditional:
return this.VisitConditional((ConditionalExpression)exp);
case ExpressionType.Constant:
return this.VisitConstant((ConstantExpression)exp);
case ExpressionType.Parameter:
return this.VisitParameter((ParameterExpression)exp);
case ExpressionType.MemberAccess:
return this.VisitMemberAccess((MemberExpression)exp);
case ExpressionType.Call:
return this.VisitMethodCall((MethodCallExpression)exp);
case ExpressionType.Lambda:
return this.VisitLambda((LambdaExpression)exp);
case ExpressionType.New:
return this.VisitNew((NewExpression)exp);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return this.VisitNewArray((NewArrayExpression)exp);
case ExpressionType.Invoke:
return this.VisitInvocation((InvocationExpression)exp);
case ExpressionType.MemberInit:
return this.VisitMemberInit((MemberInitExpression)exp);
case ExpressionType.ListInit:
return this.VisitListInit((ListInitExpression)exp);
default:
throw Error.UnhandledExpressionType(exp.NodeType);
}
}
internal virtual MemberBinding VisitBinding(MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return this.VisitMemberAssignment((MemberAssignment)binding);
case MemberBindingType.MemberBinding:
return this.VisitMemberMemberBinding((MemberMemberBinding)binding);
case MemberBindingType.ListBinding:
return this.VisitMemberListBinding((MemberListBinding)binding);
default:
throw Error.UnhandledBindingType(binding.BindingType);
}
}
internal virtual ElementInit VisitElementInitializer(ElementInit initializer)
{
ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments);
if (arguments != initializer.Arguments)
{
return Expression.ElementInit(initializer.AddMethod, arguments);
}
return initializer;
}
internal virtual Expression VisitUnary(UnaryExpression u)
{
Expression operand = this.Visit(u.Operand);
if (operand != u.Operand)
{
return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method);
}
return u;
}
internal virtual Expression VisitBinary(BinaryExpression b)
{
Expression left = this.Visit(b.Left);
Expression right = this.Visit(b.Right);
Expression conversion = this.Visit(b.Conversion);
if (left != b.Left || right != b.Right || conversion != b.Conversion)
{
if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null)
return Expression.Coalesce(left, right, conversion as LambdaExpression);
else
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
return b;
}
internal virtual Expression VisitTypeIs(TypeBinaryExpression b)
{
Expression expr = this.Visit(b.Expression);
if (expr != b.Expression)
{
return Expression.TypeIs(expr, b.TypeOperand);
}
return b;
}
internal virtual Expression VisitConstant(ConstantExpression c)
{
return c;
}
internal virtual Expression VisitConditional(ConditionalExpression c)
{
Expression test = this.Visit(c.Test);
Expression ifTrue = this.Visit(c.IfTrue);
Expression ifFalse = this.Visit(c.IfFalse);
if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse)
{
return Expression.Condition(test, ifTrue, ifFalse);
}
return c;
}
internal virtual Expression VisitParameter(ParameterExpression p)
{
return p;
}
internal virtual Expression VisitMemberAccess(MemberExpression m)
{
Expression exp = this.Visit(m.Expression);
if (exp != m.Expression)
{
return Expression.MakeMemberAccess(exp, m.Member);
}
return m;
}
internal virtual Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = this.Visit(m.Object);
IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments);
if (obj != m.Object || args != m.Arguments)
{
return Expression.Call(obj, m.Method, args);
}
return m;
}
internal virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = this.Visit(original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
return list.ToReadOnlyCollection();
return original;
}
internal virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{
Expression e = this.Visit(assignment.Expression);
if (e != assignment.Expression)
{
return Expression.Bind(assignment.Member, e);
}
return assignment;
}
internal virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings);
if (bindings != binding.Bindings)
{
return Expression.MemberBind(binding.Member, bindings);
}
return binding;
}
internal virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers);
if (initializers != binding.Initializers)
{
return Expression.ListBind(binding.Member, initializers);
}
return binding;
}
internal virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original)
{
List<MemberBinding> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
MemberBinding b = this.VisitBinding(original[i]);
if (list != null)
{
list.Add(b);
}
else if (b != original[i])
{
list = new List<MemberBinding>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(b);
}
}
if (list != null)
return list;
return original;
}
internal virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original)
{
List<ElementInit> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
ElementInit init = this.VisitElementInitializer(original[i]);
if (list != null)
{
list.Add(init);
}
else if (init != original[i])
{
list = new List<ElementInit>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(init);
}
}
if (list != null)
return list;
return original;
}
internal virtual Expression VisitLambda(LambdaExpression lambda)
{
Expression body = this.Visit(lambda.Body);
if (body != lambda.Body)
{
return Expression.Lambda(lambda.Type, body, lambda.Parameters);
}
return lambda;
}
internal virtual NewExpression VisitNew(NewExpression nex)
{
IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments);
if (args != nex.Arguments)
{
if (nex.Members != null)
return Expression.New(nex.Constructor, args, nex.Members);
else
return Expression.New(nex.Constructor, args);
}
return nex;
}
internal virtual Expression VisitMemberInit(MemberInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings);
if (n != init.NewExpression || bindings != init.Bindings)
{
return Expression.MemberInit(n, bindings);
}
return init;
}
internal virtual Expression VisitListInit(ListInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers);
if (n != init.NewExpression || initializers != init.Initializers)
{
return Expression.ListInit(n, initializers);
}
return init;
}
internal virtual Expression VisitNewArray(NewArrayExpression na)
{
IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions);
if (exprs != na.Expressions)
{
if (na.NodeType == ExpressionType.NewArrayInit)
{
return Expression.NewArrayInit(na.Type.GetElementType(), exprs);
}
else
{
return Expression.NewArrayBounds(na.Type.GetElementType(), exprs);
}
}
return na;
}
internal virtual Expression VisitInvocation(InvocationExpression iv)
{
IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments);
Expression expr = this.Visit(iv.Expression);
if (args != iv.Arguments || expr != iv.Expression)
{
return Expression.Invoke(expr, args);
}
return iv;
}
}
}
| |
// 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,
// MERCHANTABLITY 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 AnalysisTests;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.PythonTools.Refactoring;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace PythonToolsTests {
using AP = AnalysisProtocol;
[TestClass]
public class ExtractMethodTests {
private const string ErrorReturn = "When the selection contains a return statement, all code paths must be terminated by a return statement too.";
private const string ErrorYield = "Cannot extract code containing \"yield\" expression";
private const string ErrorContinue = "The selection contains a \"continue\" statement, but not the enclosing loop";
private const string ErrorBreak = "The selection contains a \"break\" statement, but not the enclosing loop";
private const string ErrorReturnWithOutputs = "Cannot extract method that assigns to variables and returns";
private const string ErrorImportStar = "Cannot extract method containing from ... import * statement";
private const string ErrorExtractFromClass = "Cannot extract statements from a class definition";
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
[TestMethod, Priority(1)]
public void TestGlobalNonLocalVars() {
SuccessTest("ABC = 42",
@"def f():
ABC = 42
def f():
nonlocal ABC
ABC = 200
print(ABC)
return f",
@"def g():
ABC = 42
return ABC
def f():
ABC = g()
def f():
nonlocal ABC
ABC = 200
print(ABC)
return f");
SuccessTest("ABC = 42",
@"def f():
ABC = 42
def f():
print(ABC)
return f",
@"def g():
ABC = 42
return ABC
def f():
ABC = g()
def f():
print(ABC)
return f");
SuccessTest("ABC = 42",
@"def f():
global ABC
ABC = 42",
@"def g():
ABC = 42
return ABC
def f():
global ABC
ABC = g()");
}
[TestMethod, Priority(1)]
public void TestDefinitions() {
SuccessTest("x = .. = h()",
@"def f():
def g():
return 42
def h():
return 23
x = g()
z = h()
",
@"def g(g, h):
x = g()
z = h()
def f():
def g():
return 42
def h():
return 23
g(g, h)
");
SuccessTest("x = .. = h()",
@"def f():
class g():
pass
class h():
pass
x = g()
z = h()
",
@"def g(g, h):
x = g()
z = h()
def f():
class g():
pass
class h():
pass
g(g, h)
");
SuccessTest("@ .. pass",
@"@property
def f(): pass",
@"def g():
@property
def f(): pass
return f
f = g()");
}
[TestMethod, Priority(1)]
public void TestLeadingComment() {
SuccessTest("x = 41",
@"# fob
x = 41",
@"# fob
def g():
x = 41
return x
x = g()");
}
[TestMethod, Priority(1)]
public void AssignInIfStatementReadAfter() {
ExtractMethodTest(@"class C:
def fob(self):
if False: # fob
oar = player = Player()
else:
player.update()
", "oar = player = Player()", TestResult.Success(
@"class C:
def g(self):
oar = player = Player()
def fob(self):
if False: # fob
self.g()
else:
player.update()
"
), scopeName: "C");
ExtractMethodTest(@"class C:
def fob(self):
if False:
oar = player = Player()
else:
player.update()
", "oar = player = Player()", TestResult.Success(
@"class C:
def g(self):
oar = player = Player()
def fob(self):
if False:
self.g()
else:
player.update()
"
), scopeName: "C");
ExtractMethodTest(@"class C:
def fob(self):
if False:
oar = player = Player()
player.update()
", "oar = player = Player()", TestResult.Success(
@"class C:
def g(self):
oar = player = Player()
return player
def fob(self):
if False:
player = self.g()
player.update()
"
), scopeName: "C");
}
[TestMethod, Priority(1)]
public void ExtractMethodIndexExpr() {
ExtractMethodTest(@"class C:
def process_kinect_event(self, e):
for skeleton in e.skeletons:
fob[skeleton.dwTrackingID] = Player()
", "fob[skeleton.dwTrackingID] = Player()", TestResult.Success(
@"class C:
def g(self, skeleton):
fob[skeleton.dwTrackingID] = Player()
def process_kinect_event(self, e):
for skeleton in e.skeletons:
self.g(skeleton)
"
), scopeName: "C");
}
[TestMethod, Priority(1)]
public void TestExtractLambda() {
// lambda is present in the code
ExtractMethodTest(
@"def f():
pass
def x():
abc = lambda x: 42", "pass", TestResult.Success(
@"def g():
pass
def f():
g()
def x():
abc = lambda x: 42"));
// lambda is being extracted
ExtractMethodTest(
@"def f():
abc = lambda x: 42", "lambda x: 42", TestResult.Success(
@"def g():
return lambda x: 42
def f():
abc = g()"));
}
[TestMethod, Priority(1)]
public void TestExtractGenerator() {
var code = @"def f(imp = imp):
yield 42";
ExtractMethodTest(
code, () => new Span(code.IndexOf("= imp") + 2, 3), TestResult.Success(
@"def g():
return imp
def f(imp = g()):
yield 42"));
}
[TestMethod, Priority(1)]
public void TestExtractDefaultValue() {
var code = @"def f(imp = imp):
pass";
ExtractMethodTest(
code, () => new Span(code.IndexOf("= imp") + 2, 3), TestResult.Success(
@"def g():
return imp
def f(imp = g()):
pass"));
}
[TestMethod, Priority(1)]
public void TestFromImportStar() {
ExtractMethodTest(
@"def f():
from sys import *", "from sys import *", TestResult.Error(ErrorImportStar));
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfter() {
SuccessTest("x = 42",
@"def f():
x = 42
for x, y in []:
print x, y",
@"def g():
x = 42
def f():
g()
for x, y in []:
print x, y");
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfterStmtList() {
SuccessTest("x = 42",
@"def f():
x = 42; x = 100
for x, y in []:
print x, y",
@"def g():
x = 42
def f():
g(); x = 100
for x, y in []:
print x, y");
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfterStmtListRead() {
SuccessTest("x = 100",
@"def f():
x = 100; x
for x, y in []:
print (x, y)",
@"def g():
x = 100
return x
def f():
x = g(); x
for x, y in []:
print (x, y)");
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void TestAllNodes() {
var prefixes = new string[] { " # fob\r\n", "" };
var suffixes = new string[] { " # oar", "" };
foreach (var suffix in suffixes) {
foreach (var prefix in prefixes) {
foreach (var testCase in TestExpressions.Expressions) {
if (testCase.StartsWith("yield")) {
// not currently supported
continue;
}
var text = prefix + testCase + suffix;
string expected = String.Format("{1}def g():\r\n return {0}\r\n\r\ng(){2}", testCase, prefix, suffix);
SuccessTest(new Span(prefix.Length, testCase.Length), text, expected);
}
}
}
var bannedStmts = new[] { "break", "continue", "return abc" };
var allStmts = TestExpressions.Statements2x
.Except(bannedStmts)
.Select(text => new { Text = text, Version = PythonLanguageVersion.V27 })
.Concat(
TestExpressions.Statements3x
.Select(text => new { Text = text, Version = PythonLanguageVersion.V33 }));
foreach (var suffix in suffixes) {
foreach (var prefix in prefixes) {
foreach (var stmtTest in allStmts) {
var text = prefix + stmtTest.Text + suffix;
var assignments = GetAssignments(text, stmtTest.Version);
string expected;
if (assignments.Length > 0 && stmtTest.Text != "del x") {
expected = String.Format(
"{1}def g():\r\n{0}\r\n return {3}\r\n\r\n{3} = g(){2}",
TestExpressions.IndentCode(stmtTest.Text, " "),
prefix,
suffix,
String.Join(", ", assignments)
);
} else {
expected = String.Format(
"{1}def g():\r\n{0}\r\n\r\ng(){2}",
TestExpressions.IndentCode(stmtTest.Text, " "),
prefix,
suffix
);
}
SuccessTest(new Span(prefix.Length, stmtTest.Text.Length), text, expected, null, stmtTest.Version.ToVersion());
}
}
}
}
private string[] GetAssignments(string testCase, PythonLanguageVersion version) {
var ast = Parser.CreateParser(new StringReader(testCase), version).ParseFile();
var walker = new TestAssignmentWalker();
ast.Walk(walker);
return walker._names.ToArray();
}
class TestAssignmentWalker : AssignmentWalker {
private readonly NameWalker _walker;
internal readonly List<string> _names = new List<string>();
public TestAssignmentWalker() {
_walker = new NameWalker(this);
}
public override AssignedNameWalker Define {
get { return _walker; }
}
class NameWalker : AssignedNameWalker {
private readonly TestAssignmentWalker _outer;
public NameWalker(TestAssignmentWalker outer) {
_outer = outer;
}
public override bool Walk(NameExpression node) {
_outer._names.Add(node.Name);
return true;
}
}
public override bool Walk(FunctionDefinition node) {
_names.Add(node.Name);
return base.Walk(node);
}
public override bool Walk(ClassDefinition node) {
_names.Add(node.Name);
return base.Walk(node);
}
public override bool Walk(ImportStatement node) {
var vars = node.Variables;
for (int i = 0; i < vars.Length; i++) {
if (vars[i] != null) {
_names.Add(vars[i].Name);
}
}
return base.Walk(node);
}
public override bool Walk(FromImportStatement node) {
var vars = node.Variables;
for (int i = 0; i < vars.Length; i++) {
if (vars[i] != null) {
_names.Add(vars[i].Name);
}
}
return base.Walk(node);
}
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfterStmtListMultipleAssign() {
SuccessTest("x = 100; x = 200",
@"def f():
x = 100; x = 200; x
for x, y in []:
print (x, y)",
@"def g():
x = 100; x = 200
return x
def f():
x = g(); x
for x, y in []:
print (x, y)");
}
[TestMethod, Priority(1)]
public void TestExtractFromClass() {
ExtractMethodTest(
@"class C:
abc = 42
oar = 100", "abc .. 100", TestResult.Error(ErrorExtractFromClass));
}
[TestMethod, Priority(1)]
public void TestExtractSuiteWhiteSpace() {
SuccessTest("x .. 200",
@"def f():
x = 100
y = 200",
@"def g():
x = 100
y = 200
def f():
g()");
SuccessTest("x .. 200",
@"def f():
a = 300
x = 100
y = 200",
@"def g():
x = 100
y = 200
def f():
a = 300
g()");
}
/// <summary>
/// Test cases that verify we correctly identify when not all paths contain return statements.
/// </summary>
[TestMethod, Priority(1)]
public void TestNotAllCodePathsReturn() {
TestMissingReturn("for i .. 23", @"def f(x):
for i in xrange(100):
break
return 42
else:
return 23
");
TestMissingReturn("if x .. Exception()", @"def f(x):
if x:
return 42
elif x:
raise Exception()
");
TestMissingReturn("if x .. 200", @"def f(x):
if x:
def abc():
return 42
elif x:
return 100
else:
return 200
");
TestMissingReturn("if x .. 100", @"def f(x):
if x:
return 42
elif x:
return 100
");
TestMissingReturn("if x .. pass", @"def f(x):
if x:
return 42
elif x:
return 100
else:
pass
");
TestMissingReturn("if True .. pass", @"def f():
abc = 100
if True:
return 100
else:
pass
print('hello')");
TestMissingReturn("if x .. aaa",
@"class C:
def f(self):
if x == 0:
return aaa");
}
[TestMethod, Priority(1)]
public void TestReturnWithOutputVars() {
TestReturnWithOutputs("if x .. 100", @"def f(x):
if x:
x = 200
return 42
else:
return 100
print(x)
");
}
[TestMethod, Priority(1)]
public void TestCannotRefactorYield() {
TestBadYield("yield 42", @"def f(x):
yield 42
");
TestBadYield("yield 42", @"def f(x):
for i in xrange(100):
yield 42
");
}
[TestMethod, Priority(1)]
public void TestContinueWithoutLoop() {
TestBadContinue("continue", @"def f(x):
for i in xrange(100):
continue
");
}
[TestMethod, Priority(1)]
public void TestBreakWithoutLoop() {
TestBadBreak("break", @"def f(x):
for i in xrange(100):
break
");
}
/// <summary>
/// Test cases which make sure we have the right ranges for each statement when doing extract method
/// and that we don't mess up the code before/after the statement.
/// </summary>
[TestMethod, Priority(1)]
public void StatementTests() {
SuccessTest("b",
@"def f():
return (a or
b or
c)",
@"def g():
return b
def f():
return (a or
g() or
c)");
SuccessTest("assert False",
@"x = 1
assert False
x = 2",
@"x = 1
def g():
assert False
g()
x = 2");
SuccessTest("x += 2",
@"x = 1
x += 2
x = 2",
@"x = 1
def g():
x += 2
g()
x = 2");
SuccessTest("x = 100",
@"x = 1
x = 100
x = 2",
@"x = 1
def g():
x = 100
g()
x = 2");
SuccessTest("class C: pass",
@"x = 1
class C: pass
x = 2",
@"x = 1
def g():
class C: pass
return C
C = g()
x = 2");
SuccessTest("del fob",
@"x = 1
del fob
x = 2",
@"x = 1
def g():
del fob
g()
x = 2");
SuccessTest("pass",
@"x = 1
pass
x = 2",
@"x = 1
def g():
pass
g()
x = 2");
SuccessTest("def f(): pass",
@"x = 1
def f(): pass
x = 2",
@"x = 1
def g():
def f(): pass
return f
f = g()
x = 2");
SuccessTest("for .. pass",
@"x = 1
for i in xrange(100):
pass
x = 2",
@"x = 1
def g():
for i in xrange(100):
pass
return i
i = g()
x = 2");
SuccessTest("if True: .. pass",
@"x = 1
if True:
pass
x = 2",
@"x = 1
def g():
if True:
pass
g()
x = 2");
SuccessTest("if True: .. pass",
@"x = 1
if True:
42
else:
pass
x = 2",
@"x = 1
def g():
if True:
42
else:
pass
g()
x = 2");
SuccessTest("if True: .. pass",
@"x = 1
if True:
42
elif False:
pass
x = 2",
@"x = 1
def g():
if True:
42
elif False:
pass
g()
x = 2");
SuccessTest("import sys",
@"x = 1
import sys
x = 2",
@"x = 1
def g():
import sys
return sys
sys = g()
x = 2");
SuccessTest("print 42",
@"x = 1
print 42
x = 2",
@"x = 1
def g():
print 42
g()
x = 2");
SuccessTest("raise Exception()",
@"x = 1
raise Exception()
x = 2",
@"x = 1
def g():
raise Exception()
g()
x = 2");
SuccessTest("return 100",
@"x = 1
return 100
x = 2",
@"x = 1
def g():
return 100
return g()
x = 2");
SuccessTest("try: .. pass",
@"x = 1
try:
42
except:
pass
x = 2",
@"x = 1
def g():
try:
42
except:
pass
g()
x = 2");
SuccessTest("try: .. pass",
@"x = 1
try:
42
finally:
pass
x = 2",
@"x = 1
def g():
try:
42
finally:
pass
g()
x = 2");
SuccessTest("try: .. pass",
@"x = 1
try:
42
except:
100
else:
pass
x = 2",
@"x = 1
def g():
try:
42
except:
100
else:
pass
g()
x = 2");
SuccessTest("while .. pass",
@"x = 1
while True:
pass
x = 2",
@"x = 1
def g():
while True:
pass
g()
x = 2");
SuccessTest("while .. pass",
@"x = 1
while True:
42
else:
pass
x = 2",
@"x = 1
def g():
while True:
42
else:
pass
g()
x = 2");
SuccessTest("with .. pass",
@"x = 1
with abc:
pass
x = 2",
@"x = 1
def g():
with abc:
pass
g()
x = 2");
SuccessTest("with .. pass",
@"x = 1
with abc as fob:
pass
x = 2",
@"x = 1
def g():
with abc as fob:
pass
g()
x = 2");
SuccessTest("with .. (name)",
@"def f():
name = 'hello'
with open('Fob', 'rb') as f:
print(name)
",
@"def g(name):
with open('Fob', 'rb') as f:
print(name)
def f():
name = 'hello'
g(name)
");
SuccessTest("x .. Oar()",
@"class C:
def f():
if True:
pass
else:
pass
x = Fob()
y = Oar()",
@"def g():
x = Fob()
y = Oar()
class C:
def f():
if True:
pass
else:
pass
g()");
}
[TestMethod, Priority(1)]
public void ClassTests() {
SuccessTest("x = fob",
@"class C(object):
'''Doc string'''
def abc(self, fob):
x = fob
print(x)",
@"class C(object):
'''Doc string'''
def g(self, fob):
x = fob
return x
def abc(self, fob):
x = self.g(fob)
print(x)", scopeName: "C");
SuccessTest("print(self.abc)",
@"class C:
def f(self):
print(self.abc)",
@"class C:
def g(self):
print(self.abc)
def f(self):
self.g()", scopeName:"C");
SuccessTest("print(self.abc, aaa)",
@"class C:
def f(self):
aaa = 42
print(self.abc, aaa)",
@"class C:
def g(self, aaa):
print(self.abc, aaa)
def f(self):
aaa = 42
self.g(aaa)", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
def f(self):
aaa = 42",
@"class C:
def g(self):
aaa = 42
def f(self):
self.g()", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
@staticmethod
def f():
aaa = 42",
@"class C:
@staticmethod
def g():
aaa = 42
@staticmethod
def f():
C.g()", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
@classmethod
def f(cls):
aaa = 42",
@"class C:
@classmethod
def g(cls):
aaa = 42
@classmethod
def f(cls):
cls.g()", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
def f(weird):
aaa = 42",
@"class C:
def g(weird):
aaa = 42
def f(weird):
weird.g()", scopeName: "C");
SuccessTest("print('hello')",
@"class C:
class D:
def f(self):
print('hello')",
@"class C:
class D:
def g(self):
print('hello')
def f(self):
self.g()", scopeName: "D");
}
[TestMethod, Priority(1)]
public void TestComprehensions() {
SuccessTest("i % 2 == 0", @"def f():
x = [i for i in range(100) if i % 2 == 0]", @"def g(i):
return i % 2 == 0
def f():
x = [i for i in range(100) if g(i)]");
SuccessTest("i % 2 == 0", @"def f():
x = (i for i in range(100) if i % 2 == 0)", @"def g(i):
return i % 2 == 0
def f():
x = (i for i in range(100) if g(i))");
SuccessTest("i % 2 == 0", @"def f():
x = {i for i in range(100) if i % 2 == 0}", @"def g(i):
return i % 2 == 0
def f():
x = {i for i in range(100) if g(i)}", version: new Version(3, 2));
SuccessTest("(k+v) % 2 == 0", @"def f():
x = {k:v for k,v in range(100) if (k+v) % 2 == 0}", @"def g(k, v):
return (k+v) % 2 == 0
def f():
x = {k:v for k,v in range(100) if g(k, v)}", version: new Version(3, 2));
}
[TestMethod, Priority(1)]
public void SuccessfulTests() {
SuccessTest("x .. 100",
@"def f():
z = 200
x = z
z = 42
y = 100
print(x, y)",
@"def g(z):
x = z
z = 42
y = 100
return x, y
def f():
z = 200
x, y = g(z)
print(x, y)");
SuccessTest("x .. 100",
@"def f():
x = 42
y = 100
print(x, y)",
@"def g():
x = 42
y = 100
return x, y
def f():
x, y = g()
print(x, y)");
SuccessTest("42",
@"def f():
x = 42",
@"def g():
return 42
def f():
x = g()");
SuccessTest("oar;baz",
@"def f():
fob;oar;baz;quox",
@"def g():
oar;baz
def f():
fob;g();quox");
SuccessTest("x() .. = 100",
@"x = 42
while True:
x()
x = 100",
@"x = 42
def g(x):
x()
x = 100
return x
while True:
x = g(x)", parameters: new[] { "x" });
SuccessTest("x = 2 .. x)",
@"def f():
x = 1
x = 2
print(x)",
@"def g():
x = 2
print(x)
def f():
x = 1
g()");
SuccessTest("for i in .. return 42",
@"def f():
for i in xrange(100):
break
return 42",
@"def g():
for i in xrange(100):
break
return 42
def f():
g()");
SuccessTest("if x .. 100",
@"def f(x):
if x:
return 42
return 100",
@"def g(x):
if x:
return 42
return 100
def f(x):
return g(x)");
SuccessTest("if x .. 200",
@"def f(x):
if x:
return 42
elif x:
return 100
else:
return 200",
@"def g(x):
if x:
return 42
elif x:
return 100
else:
return 200
def f(x):
return g(x)");
SuccessTest("if x .. 200",
@"def f(x):
if x:
return 42
elif x:
raise Exception()
else:
return 200",
@"def g(x):
if x:
return 42
elif x:
raise Exception()
else:
return 200
def f(x):
return g(x)");
SuccessTest("if x .. Exception()",
@"def f(x):
if x:
return 42
else:
raise Exception()",
@"def g(x):
if x:
return 42
else:
raise Exception()
def f(x):
return g(x)");
SuccessTest("print(x)",
@"def f():
x = 1
print(x)",
@"def g(x):
print(x)
def f():
x = 1
g(x)");
SuccessTest("x = 2 .. x)",
@"def f():
x = 1
x = 2
print(x)",
@"def g():
x = 2
print(x)
def f():
x = 1
g()");
SuccessTest("class C: pass",
@"def f():
class C: pass
print C",
@"def g():
class C: pass
return C
def f():
C = g()
print C");
SuccessTest("def x(): pass",
@"def f():
def x(): pass
print x",
@"def g():
def x(): pass
return x
def f():
x = g()
print x");
SuccessTest("import sys",
@"def f():
import sys
print sys",
@"def g():
import sys
return sys
def f():
sys = g()
print sys");
SuccessTest("import sys as oar",
@"def f():
import sys as oar
print oar",
@"def g():
import sys as oar
return oar
def f():
oar = g()
print oar");
SuccessTest("from sys import oar",
@"def f():
from sys import oar
print oar",
@"def g():
from sys import oar
return oar
def f():
oar = g()
print oar");
SuccessTest("from sys import oar as baz",
@"def f():
from sys import oar as baz
print baz",
@"def g():
from sys import oar as baz
return baz
def f():
baz = g()
print baz");
SuccessTest("return 42",
@"def f():
return 42",
@"def g():
return 42
def f():
return g()");
SuccessTest("return x",
@"def f():
x = 42
return x",
@"def g(x):
return x
def f():
x = 42
return g(x)");
SuccessTest("x = .. = 100",
@"def f():
x = 42
y = 100
return x, y",
@"def g():
x = 42
y = 100
return x, y
def f():
x, y = g()
return x, y");
SuccessTest("x()",
@"x = 42
while True:
x()
x = 100",
@"x = 42
def g(x):
return x()
while True:
g(x)
x = 100",
parameters: new[] { "x"});
SuccessTest("x()",
@"x = 42
while True:
x()
x = 100",
@"x = 42
def g():
return x()
while True:
g()
x = 100");
SuccessTest("x = 42",
@"x = 42
print(x)",
@"def g():
x = 42
return x
x = g()
print(x)");
SuccessTest("l = .. return r",
@"def f():
r = None
l = fob()
if l:
r = l[0]
return r",
@"def g(r):
l = fob()
if l:
r = l[0]
return r
def f():
r = None
return g(r)");
SuccessTest("42",
@"def f(x):
return (42)",
@"def g():
return 42
def f(x):
return (g())");
}
[TestMethod, Priority(1)]
public void ExtractAsyncFunction() {
// Ensure extracted bodies that use await generate async functions
var V35 = new Version(3, 5);
SuccessTest("x",
@"async def f():
return await x",
@"def g():
return x
async def f():
return await g()", version: V35);
SuccessTest("await x",
@"async def f():
return await x",
@"async def g():
return await x
async def f():
return await g()", version: V35);
}
private void SuccessTest(Span extract, string input, string result, string scopeName = null, Version version = null, string[] parameters = null) {
ExtractMethodTest(input, extract, TestResult.Success(result), scopeName: scopeName, version: version, parameters: parameters);
}
private void SuccessTest(string extract, string input, string result, string scopeName = null, Version version = null, string[] parameters = null) {
ExtractMethodTest(input, extract, TestResult.Success(result), scopeName: scopeName, version: version, parameters: parameters);
}
class TestResult {
public readonly bool IsError;
public readonly string Text;
public static TestResult Error(string message) {
return new TestResult(message, true);
}
public static TestResult Success(string code) {
return new TestResult(code, false);
}
public TestResult(string text, bool isError) {
Text = text;
IsError = isError;
}
}
private void TestMissingReturn(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorReturn));
}
private void TestReturnWithOutputs(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorReturnWithOutputs));
}
private void TestBadYield(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorYield));
}
private void TestBadContinue(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorContinue));
}
private void TestBadBreak(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorBreak));
}
private void ExtractMethodTest(string input, object extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters) {
Func<Span> textRange = () => {
return GetSelectionSpan(input, extract);
};
ExtractMethodTest(input, textRange, expected, scopeName, targetName, version, parameters);
}
internal static Span GetSelectionSpan(string input, object extract) {
string exStr = extract as string;
if (exStr != null) {
if (exStr.IndexOf(" .. ") != -1) {
var pieces = exStr.Split(new[] { " .. " }, 2, StringSplitOptions.None);
int start = input.IndexOf(pieces[0]);
int end = input.IndexOf(pieces[1]) + pieces[1].Length;
return Span.FromBounds(start, end);
} else {
int start = input.IndexOf(exStr);
int length = exStr.Length;
return new Span(start, length);
}
}
return (Span)extract;
}
private void ExtractMethodTest(string input, Func<Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters) {
var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));
var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
using (var analyzer = new VsProjectAnalyzer(serviceProvider, fact)) {
var buffer = new MockTextBuffer(input, "Python", "C:\\fob.py");
var view = new MockTextView(buffer);
buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
analyzer.MonitorTextBufferAsync(buffer).Wait();
var extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);
view.Selection.Select(
new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()),
false
);
new MethodExtractor(serviceProvider, view).ExtractMethod(extractInput).Wait();
if (expected.IsError) {
Assert.AreEqual(expected.Text, extractInput.FailureReason);
Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
} else {
Assert.AreEqual(null, extractInput.FailureReason);
Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
}
}
}
class ExtractMethodTestInput : IExtractMethodInput {
private readonly bool _shouldExpand;
private readonly string _scopeName, _targetName;
private readonly string[] _parameters;
private string _failureReason;
public ExtractMethodTestInput(bool shouldExpand, string scopeName, string targetName, string[] parameters) {
_shouldExpand = shouldExpand;
_scopeName = scopeName;
_parameters = parameters;
_targetName = targetName;
}
public bool ShouldExpandSelection() {
return _shouldExpand;
}
public ExtractMethodRequest GetExtractionInfo(ExtractedMethodCreator previewer) {
AP.ScopeInfo scope = null;
if (_scopeName == null) {
scope = previewer.LastExtraction.scopes[0];
} else {
foreach (var foundScope in previewer.LastExtraction.scopes) {
if (foundScope.name == _scopeName) {
scope = foundScope;
break;
}
}
}
Assert.AreNotEqual(null, scope);
var requestView = new ExtractMethodRequestView(PythonToolsTestUtilities.CreateMockServiceProvider(), previewer);
requestView.TargetScope = requestView.TargetScopes.Single(s => s.Scope == scope);
requestView.Name = _targetName;
foreach (var cv in requestView.ClosureVariables) {
cv.IsClosure = !_parameters.Contains(cv.Name);
}
Assert.IsTrue(requestView.IsValid);
var request = requestView.GetRequest();
Assert.IsNotNull(request);
return request;
}
public void CannotExtract(string reason) {
_failureReason = reason;
}
public string FailureReason {
get {
return _failureReason;
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
internal partial class DedicatedCircuitLinkAuthorizationOperations : IServiceOperations<ExpressRouteManagementClient>, IDedicatedCircuitLinkAuthorizationOperations
{
/// <summary>
/// Initializes a new instance of the
/// DedicatedCircuitLinkAuthorizationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DedicatedCircuitLinkAuthorizationOperations(ExpressRouteManagementClient client)
{
this._client = client;
}
private ExpressRouteManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient.
/// </summary>
public ExpressRouteManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Remove Dedicated Circuit Link Authorization operation deletes
/// an existing dedicated circuit link.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service key representing the dedicated circuit.
/// </param>
/// <param name='authId'>
/// Required. The GUID representing the authorization
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ExpressRouteOperationResponse> BeginRemoveAsync(string serviceKey, string authId, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (authId == null)
{
throw new ArgumentNullException("authId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("authId", authId);
TracingAdapter.Enter(invocationId, this, "BeginRemoveAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/authorizations/";
url = url + Uri.EscapeDataString(authId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
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.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-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.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
ExpressRouteOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the link authorization for the specified dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='authId'>
/// Required. The GUID representing the authorization
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get link authorization operation response.
/// </returns>
public async Task<DedicatedCircuitLinkAuthorizationGetResponse> GetAsync(string serviceKey, string authId, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (authId == null)
{
throw new ArgumentNullException("authId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("authId", authId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/authorizations/";
url = url + Uri.EscapeDataString(authId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
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("x-ms-version", "2011-10-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
DedicatedCircuitLinkAuthorizationGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitLinkAuthorizationGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitLinkAuthorizationElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitLinkAuthorizationElement != null)
{
AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization();
result.DedicatedCircuitLinkAuthorization = dedicatedCircuitLinkAuthorizationInstance;
XElement descriptionElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
if (descriptionElement != null)
{
string descriptionInstance = descriptionElement.Value;
dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance;
}
XElement limitElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure"));
if (limitElement != null)
{
int limitInstance = int.Parse(limitElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance;
}
XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure"));
if (linkAuthorizationIdElement != null)
{
string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value;
dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance;
}
XElement microsoftIdsElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure"));
if (microsoftIdsElement != null)
{
string microsoftIdsInstance = microsoftIdsElement.Value;
dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance;
}
XElement usedElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure"));
if (usedElement != null)
{
int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance;
}
}
}
result.StatusCode = statusCode;
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 Express Route operation status gets information on the
/// status of Express Route operations in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx
/// for more information)
/// </summary>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken)
{
// Validate
if (operationId == null)
{
throw new ArgumentNullException("operationId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationId", operationId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/operation/";
url = url + Uri.EscapeDataString(operationId);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-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
ExpressRouteOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationElement != null)
{
XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure"));
if (dataElement != null)
{
string dataInstance = dataElement.Value;
result.Data = dataInstance;
}
XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
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>
/// Lists the specified link authorization for the specified dedicated
/// circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List link authorization operation response.
/// </returns>
public async Task<DedicatedCircuitLinkAuthorizationListResponse> ListAsync(string serviceKey, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/authorizations";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
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("x-ms-version", "2011-10-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
DedicatedCircuitLinkAuthorizationListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitLinkAuthorizationListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitLinkAuthorizationsSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorizations", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitLinkAuthorizationsSequenceElement != null)
{
foreach (XElement dedicatedCircuitLinkAuthorizationsElement in dedicatedCircuitLinkAuthorizationsSequenceElement.Elements(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure")))
{
AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization();
result.DedicatedCircuitLinkAuthorizations.Add(dedicatedCircuitLinkAuthorizationInstance);
XElement descriptionElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
if (descriptionElement != null)
{
string descriptionInstance = descriptionElement.Value;
dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance;
}
XElement limitElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure"));
if (limitElement != null)
{
int limitInstance = int.Parse(limitElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance;
}
XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure"));
if (linkAuthorizationIdElement != null)
{
string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value;
dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance;
}
XElement microsoftIdsElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure"));
if (microsoftIdsElement != null)
{
string microsoftIdsInstance = microsoftIdsElement.Value;
dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance;
}
XElement usedElement = dedicatedCircuitLinkAuthorizationsElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure"));
if (usedElement != null)
{
int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance;
}
}
}
}
result.StatusCode = statusCode;
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>
/// Gets the specified link authorization for the specified dedicated
/// circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the new Dedicated Circuit link
/// authorization operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get link authorization operation response.
/// </returns>
public async Task<DedicatedCircuitLinkAuthorizationNewResponse> NewAsync(string serviceKey, DedicatedCircuitLinkAuthorizationNewParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "NewAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/authorizations";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
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("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement createDedicatedCircuitLinkAuthorizationElement = new XElement(XName.Get("CreateDedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(createDedicatedCircuitLinkAuthorizationElement);
if (parameters.Description != null)
{
XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
descriptionElement.Value = parameters.Description;
createDedicatedCircuitLinkAuthorizationElement.Add(descriptionElement);
}
XElement limitElement = new XElement(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure"));
limitElement.Value = parameters.Limit.ToString();
createDedicatedCircuitLinkAuthorizationElement.Add(limitElement);
if (parameters.MicrosoftIds != null)
{
XElement microsoftIdsElement = new XElement(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure"));
microsoftIdsElement.Value = parameters.MicrosoftIds;
createDedicatedCircuitLinkAuthorizationElement.Add(microsoftIdsElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
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, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitLinkAuthorizationNewResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitLinkAuthorizationNewResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitLinkAuthorizationElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitLinkAuthorizationElement != null)
{
AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization();
result.DedicatedCircuitLinkAuthorization = dedicatedCircuitLinkAuthorizationInstance;
XElement descriptionElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
if (descriptionElement2 != null)
{
string descriptionInstance = descriptionElement2.Value;
dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance;
}
XElement limitElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure"));
if (limitElement2 != null)
{
int limitInstance = int.Parse(limitElement2.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance;
}
XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure"));
if (linkAuthorizationIdElement != null)
{
string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value;
dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance;
}
XElement microsoftIdsElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure"));
if (microsoftIdsElement2 != null)
{
string microsoftIdsInstance = microsoftIdsElement2.Value;
dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance;
}
XElement usedElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure"));
if (usedElement != null)
{
int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance;
}
}
}
result.StatusCode = statusCode;
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 Remove Dedicated Circuit Link Authorization operation deletes
/// an existing dedicated circuit link.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service Key associated with the dedicated circuit.
/// </param>
/// <param name='authId'>
/// Required. The GUID representing the authorization
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, string authId, CancellationToken cancellationToken)
{
ExpressRouteManagementClient 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("serviceKey", serviceKey);
tracingParameters.Add("authId", authId);
TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse response = await client.DedicatedCircuitLinkAuthorizations.BeginRemoveAsync(serviceKey, authId, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.DedicatedCircuitLinkAuthorizations.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != ExpressRouteOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.DedicatedCircuitLinkAuthorizations.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != ExpressRouteOperationStatus.Successful)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Updates the specified link authorization for the specified
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='authId'>
/// Required. The GUID representing the authorization
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Dedicated Circuit link
/// authorization operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Update link authorization operation response.
/// </returns>
public async Task<DedicatedCircuitLinkAuthorizationUpdateResponse> UpdateAsync(string serviceKey, string authId, DedicatedCircuitLinkAuthorizationUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (authId == null)
{
throw new ArgumentNullException("authId");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("authId", authId);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/authorizations/";
url = url + Uri.EscapeDataString(authId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
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 = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement updateDedicatedCircuitLinkAuthorizationElement = new XElement(XName.Get("UpdateDedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(updateDedicatedCircuitLinkAuthorizationElement);
if (parameters.Description != null)
{
XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
descriptionElement.Value = parameters.Description;
updateDedicatedCircuitLinkAuthorizationElement.Add(descriptionElement);
}
XElement limitElement = new XElement(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure"));
limitElement.Value = parameters.Limit.ToString();
updateDedicatedCircuitLinkAuthorizationElement.Add(limitElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
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, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitLinkAuthorizationUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitLinkAuthorizationUpdateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitLinkAuthorizationElement = responseDoc.Element(XName.Get("DedicatedCircuitLinkAuthorization", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitLinkAuthorizationElement != null)
{
AzureDedicatedCircuitLinkAuthorization dedicatedCircuitLinkAuthorizationInstance = new AzureDedicatedCircuitLinkAuthorization();
result.DedicatedCircuitLinkAuthorization = dedicatedCircuitLinkAuthorizationInstance;
XElement descriptionElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
if (descriptionElement2 != null)
{
string descriptionInstance = descriptionElement2.Value;
dedicatedCircuitLinkAuthorizationInstance.Description = descriptionInstance;
}
XElement limitElement2 = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Limit", "http://schemas.microsoft.com/windowsazure"));
if (limitElement2 != null)
{
int limitInstance = int.Parse(limitElement2.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Limit = limitInstance;
}
XElement linkAuthorizationIdElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("LinkAuthorizationId", "http://schemas.microsoft.com/windowsazure"));
if (linkAuthorizationIdElement != null)
{
string linkAuthorizationIdInstance = linkAuthorizationIdElement.Value;
dedicatedCircuitLinkAuthorizationInstance.LinkAuthorizationId = linkAuthorizationIdInstance;
}
XElement microsoftIdsElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("MicrosoftIds", "http://schemas.microsoft.com/windowsazure"));
if (microsoftIdsElement != null)
{
string microsoftIdsInstance = microsoftIdsElement.Value;
dedicatedCircuitLinkAuthorizationInstance.MicrosoftIds = microsoftIdsInstance;
}
XElement usedElement = dedicatedCircuitLinkAuthorizationElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure"));
if (usedElement != null)
{
int usedInstance = int.Parse(usedElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitLinkAuthorizationInstance.Used = usedInstance;
}
}
}
result.StatusCode = statusCode;
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();
}
}
}
}
}
| |
using System;
using InAudioSystem;
using InAudioSystem.InAudioEditor;
using InAudioSystem.Internal;
using InAudioSystem.TreeDrawer;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace InAudioSystem.InAudioEditor
{
public class AudioEventCreatorGUI : BaseCreatorGUI<InAudioEventNode>
{
public AudioEventCreatorGUI(EventWindow window)
: base(window)
{
}
private int leftWidth;
private int height;
public bool OnGUI(int leftWidth, int height)
{
BaseOnGUI();
this.leftWidth = leftWidth;
this.height = height;
EditorGUIHelper.DrawColums(DrawLeftSide, DrawRightSide);
return isDirty;
}
private void DrawLeftSide(Rect area)
{
Rect treeArea = EditorGUILayout.BeginVertical(GUILayout.Width(leftWidth), GUILayout.Height(height));
DrawSearchBar();
EditorGUILayout.BeginVertical();
isDirty |= treeDrawer.DrawTree(InAudioInstanceFinder.DataManager.EventTree, treeArea);
SelectedNode = treeDrawer.SelectedNode;
EditorGUILayout.EndVertical();
EditorGUILayout.EndVertical();
}
private void DrawRightSide(Rect area)
{
EditorGUILayout.BeginVertical();
if (SelectedNode != null)
{
try
{
isDirty |= AudioEventDrawer.Draw(SelectedNode);
}
catch (ExitGUIException e)
{
throw e;
}
catch (Exception e)
{
EditorGUILayout.HelpBox(
"An exception is getting caught while trying to draw node. If persistent, please contact [email protected]",
MessageType.Error,
true);
Debug.LogException(e);
}
}
EditorGUILayout.EndVertical();
}
public override void OnEnable()
{
treeDrawer.Filter(n => false);
treeDrawer.OnNodeDraw = EventDrawer.EventFoldout;
treeDrawer.OnContext = OnContext;
treeDrawer.CanDropObjects = CanDropObjects;
treeDrawer.OnDrop = OnDrop;
treeDrawer.CanPlaceHere = (parent, place) =>
{
if (parent._type == EventNodeType.Event)
{
return false;
}
return true;
};
}
public void ReceiveNode(InMusicGroup group)
{
if (SelectedNode != null)
{
InUndoHelper.DoInGroup(() =>
{
TreeWalker.ForEachParent(SelectedNode, n => n.EditorSettings.IsFoldedOut = true);
InUndoHelper.RecordObject(SelectedNode, "Send to Event");
if (SelectedNode.IsRootOrFolder)
{
var myEvent = AudioEventWorker.CreateNode(SelectedNode, EventNodeType.Event);
var myAction = AudioEventWorker.AddEventAction<InEventMusicControl>(myEvent, EventActionTypes.PlayMusic);
myAction.Target = group;
SelectedNode = myEvent;
treeDrawer.SelectedNode = myEvent;
}
else
{
var myAction = AudioEventWorker.AddEventAction<InEventMusicControl>(SelectedNode, EventActionTypes.PlayMusic);
myAction.Target = group;
}
});
}
}
public void ReceiveNode(InAudioNode node)
{
if (SelectedNode != null)
{
InUndoHelper.DoInGroup(() =>
{
TreeWalker.ForEachParent(SelectedNode, n => n.EditorSettings.IsFoldedOut = true);
InUndoHelper.RecordObject(SelectedNode, "Send to Event");
if (SelectedNode.IsRootOrFolder)
{
var myEvent = AudioEventWorker.CreateNode(SelectedNode, EventNodeType.Event);
var myAction = AudioEventWorker.AddEventAction<InEventAudioAction>(myEvent, EventActionTypes.Play);
myAction.Target = node;
SelectedNode = myEvent;
treeDrawer.SelectedNode = myEvent;
}
else
{
var myAction = AudioEventWorker.AddEventAction<InEventAudioAction>(SelectedNode, EventActionTypes.Play);
myAction.Target = node;
}
});
}
}
protected override void OnDrop(InAudioEventNode audioevent, Object[] objects)
{
AudioEventWorker.OnDrop(audioevent, objects);
treeDrawer.SelectedNode = audioevent;
}
protected override bool CanDropObjects(InAudioEventNode audioEvent, Object[] objects)
{
return AudioEventWorker.CanDropObjects(audioEvent, objects);
}
protected override void OnContext(InAudioEventNode node)
{
var menu = new GenericMenu();
#region Duplicate
if (!node.IsRoot)
menu.AddItem(new GUIContent("Duplicate"), false,
data => AudioEventWorker.Duplicate(data as InAudioEventNode),
node);
else
menu.AddDisabledItem(new GUIContent("Duplicate"));
menu.AddSeparator("");
#endregion
#region Duplicate
if (node.IsRootOrFolder)
{
menu.AddItem(new GUIContent("Create child folder in new prefab"), false, obj =>
{
CreateFolderInNewPrefab(node);
}, node);
menu.AddSeparator("");
}
#endregion
#region Create child
if (node._type == EventNodeType.Root || node._type == EventNodeType.Folder)
{
menu.AddItem(new GUIContent(@"Create Event"), false,
data => { CreateChild(node, EventNodeType.Event); }, node);
menu.AddItem(new GUIContent(@"Create Folder"), false,
data => { CreateChild(node, EventNodeType.Folder); }, node);
}
if (node._type == EventNodeType.Event)
{
menu.AddDisabledItem(new GUIContent(@"Create Event"));
menu.AddDisabledItem(new GUIContent(@"Create Folder"));
}
#endregion
menu.AddSeparator("");
#region Delete
menu.AddItem(new GUIContent(@"Delete"), false, data =>
{
treeDrawer.SelectedNode = TreeWalker.GetPreviousVisibleNode(treeDrawer.SelectedNode);
AudioEventWorker.DeleteNode(node);
}, node);
#endregion
menu.ShowAsContext();
}
private void CreateFolderInNewPrefab(InAudioEventNode parent)
{
InAudioWindowOpener.ShowNewDataWindow((gameObject =>
{
InUndoHelper.DoInGroup(() =>
{
var node = AudioEventWorker.CreateNode(parent, gameObject, EventNodeType.Folder);
node.Name += " (External)";
node.PlacedExternaly = true;
});
}));
isDirty = true;
}
private void CreateChild(InAudioEventNode node, EventNodeType type)
{
InUndoHelper.DoInGroup(() =>
{
InUndoHelper.RegisterUndo(node, "Event Creation");
AudioEventWorker.CreateNode(node, type);
});
node.EditorSettings.IsFoldedOut = true;
}
protected override InAudioEventNode Root()
{
if (InAudioInstanceFinder.DataManager == null)
{
return null;
}
return InAudioInstanceFinder.DataManager.EventTree;
}
protected override GUIPrefs GUIData
{
get
{
if (InAudioInstanceFinder.InAudioGuiUserPrefs != null)
return InAudioInstanceFinder.InAudioGuiUserPrefs.EventGUIData;
else
return null;
}
}
}
}
| |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Hotcakes.Commerce.Catalog;
using Hotcakes.Commerce.Membership;
using Hotcakes.Modules.Core.Admin.AppCode;
namespace Hotcakes.Modules.Core.Admin.Catalog
{
partial class Products_Edit_Inventory : BaseProductPage
{
private Product localProduct;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
PageTitle = "Edit Product Inventory";
CurrentTab = AdminTabType.Catalog;
ValidateCurrentUserHasPermission(SystemPermissions.CatalogView);
localProduct = HccApp.CatalogServices.Products.Find(ProductId);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack)
{
CurrentTab = AdminTabType.Catalog;
LoadInventory();
SetOutOfStockMode();
}
}
private void SetOutOfStockMode()
{
if (localProduct != null)
{
if (OutOfStockModeField.Items.FindByValue(((int) localProduct.InventoryMode).ToString()) != null)
{
OutOfStockModeField.ClearSelection();
OutOfStockModeField.Items.FindByValue(((int) localProduct.InventoryMode).ToString()).Selected = true;
}
}
}
private void LoadInventory()
{
var inventory = new List<ProductInventory>();
HccApp.CatalogServices.InventoryGenerateForProduct(localProduct);
HccApp.CatalogServices.CleanUpInventory(localProduct);
HccApp.CatalogServices.UpdateProductVisibleStatusAndSave(localProduct);
inventory = HccApp.CatalogServices.ProductInventories.FindByProductId(ProductId);
if (localProduct.IsAvailableForSale)
{
ucMessageBox.ShowOk("This product is displayed on the store based on inventory");
}
else
{
ucMessageBox.ShowWarning("This product is NOT displayed on the store based on inventory");
}
EditsGridView.DataSource = inventory;
EditsGridView.DataBind();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/DesktopModules/Hotcakes/Core/Admin/Catalog/Products_Edit.aspx?id=" +
Request.QueryString["id"]);
}
protected void btnSaveChanges_Click(object sender, EventArgs e)
{
if (Save())
{
ucMessageBox.ShowOk("Changes Saved!");
}
LoadInventory();
}
protected bool Save()
{
var result = false;
localProduct.InventoryMode = (ProductInventoryMode) int.Parse(OutOfStockModeField.SelectedValue);
HccApp.CatalogServices.ProductsUpdateWithSearchRebuild(localProduct);
// Process each variant/product row
foreach (GridViewRow row in EditsGridView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
ProcessRow(row);
}
}
HccApp.CatalogServices.UpdateProductVisibleStatusAndSave(localProduct);
result = true;
return result;
}
private void ProcessRow(GridViewRow row)
{
var inventoryBvin = (string) EditsGridView.DataKeys[row.RowIndex].Value;
var localInventory = HccApp.CatalogServices.ProductInventories.Find(inventoryBvin);
var AdjustmentField = (TextBox) row.FindControl("AdjustmentField");
var AdjustmentModeField = (DropDownList) row.FindControl("AdjustmentModeField");
var LowStockPointField = (TextBox) row.FindControl("LowPointField");
var OutOfStockPointField = (TextBox) row.FindControl("OutOfStockPointField");
if (LowStockPointField != null)
{
int temp;
if (int.TryParse(LowStockPointField.Text, out temp))
{
localInventory.LowStockPoint = temp;
}
}
if (OutOfStockModeField != null)
{
int tempOut;
if (int.TryParse(OutOfStockPointField.Text, out tempOut))
{
localInventory.OutOfStockPoint = tempOut;
}
}
if (AdjustmentModeField != null)
{
if (AdjustmentField != null)
{
var qty = 0;
int.TryParse(AdjustmentField.Text, out qty);
switch (AdjustmentModeField.SelectedValue)
{
case "1":
// Add
localInventory.QuantityOnHand += qty;
break;
case "2":
// Subtract
localInventory.QuantityOnHand -= qty;
break;
case "3":
// Set To
localInventory.QuantityOnHand = qty;
break;
default:
// Add
localInventory.QuantityOnHand += qty;
break;
}
}
}
HccApp.CatalogServices.ProductInventories.Update(localInventory);
}
protected void EditsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var rowP = (ProductInventory) e.Row.DataItem;
if (rowP != null)
{
var lblSKU = e.Row.FindControl("lblSKU") as Label;
if (lblSKU != null)
{
if (!string.IsNullOrEmpty(rowP.VariantId))
{
var v = localProduct.Variants.FindByBvin(rowP.VariantId);
if (v != null)
{
var sku = v.Sku;
if (string.IsNullOrWhiteSpace(v.Sku))
sku = localProduct.Sku;
var variantName = sku + "<br />";
var selectionNames = v.SelectionNames(localProduct.Options.VariantsOnly());
for (var i = 0; i < selectionNames.Count; i++)
{
variantName += selectionNames[i];
if (i != selectionNames.Count - 1)
variantName += ", ";
}
lblSKU.Text = variantName;
}
}
else
{
lblSKU.Text = localProduct.Sku;
}
}
var lblQuantityOnHand = e.Row.FindControl("lblQuantityOnHand") as Label;
var lblQuantityReserved = e.Row.FindControl("lblQuantityReserved") as Label;
var lblQuantityAvailableForSale = e.Row.FindControl("lblQuantityAvailableForSale") as Label;
var LowStockPointField = e.Row.FindControl("LowPointField") as TextBox;
var OutOfStockPointField = e.Row.FindControl("OutOfStockPointField") as TextBox;
if (lblQuantityOnHand != null)
{
lblQuantityOnHand.Text = rowP.QuantityOnHand.ToString();
}
if (lblQuantityAvailableForSale != null)
{
lblQuantityAvailableForSale.Text = rowP.QuantityAvailableForSale.ToString();
}
if (lblQuantityReserved != null)
{
lblQuantityReserved.Text = rowP.QuantityReserved.ToString();
}
if (LowStockPointField != null)
{
LowStockPointField.Text = rowP.LowStockPoint.ToString();
}
if (OutOfStockPointField != null)
{
OutOfStockPointField.Text = rowP.OutOfStockPoint.ToString();
}
}
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using FluentMigrator.Builders.Alter.Table;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using Moq;
using NUnit.Framework;
namespace FluentMigrator.Tests.Unit.Builders.Alter
{
[TestFixture]
public class AlterTableExpressionBuilderTests
{
[Test]
public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString());
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(255));
}
[Test]
public void CallingAsAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsAnsiString(255));
}
[Test]
public void CallingAsBinarySetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary(255));
}
[Test]
public void CallingAsBinarySetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsBinary(255));
}
[Test]
public void CallingAsBooleanSetsColumnDbTypeToBoolean()
{
VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean());
}
[Test]
public void CallingAsByteSetsColumnDbTypeToByte()
{
VerifyColumnDbType(DbType.Byte, b => b.AsByte());
}
[Test]
public void CallingAsCurrencySetsColumnDbTypeToCurrency()
{
VerifyColumnDbType(DbType.Currency, b => b.AsCurrency());
}
[Test]
public void CallingAsDateSetsColumnDbTypeToDate()
{
VerifyColumnDbType(DbType.Date, b => b.AsDate());
}
[Test]
public void CallingAsDateTimeSetsColumnDbTypeToDateTime()
{
VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime());
}
[Test]
public void CallingAsDecimalSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal());
}
[Test]
public void CallingAsDecimalWithSizeSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(1, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue()
{
VerifyColumnPrecision(2, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDoubleSetsColumnDbTypeToDouble()
{
VerifyColumnDbType(DbType.Double, b => b.AsDouble());
}
[Test]
public void CallingAsGuidSetsColumnDbTypeToGuid()
{
VerifyColumnDbType(DbType.Guid, b => b.AsGuid());
}
[Test]
public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength()
{
VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength()
{
VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFloatSetsColumnDbTypeToSingle()
{
VerifyColumnDbType(DbType.Single, b => b.AsFloat());
}
[Test]
public void CallingAsInt16SetsColumnDbTypeToInt16()
{
VerifyColumnDbType(DbType.Int16, b => b.AsInt16());
}
[Test]
public void CallingAsInt32SetsColumnDbTypeToInt32()
{
VerifyColumnDbType(DbType.Int32, b => b.AsInt32());
}
[Test]
public void CallingAsInt64SetsColumnDbTypeToInt64()
{
VerifyColumnDbType(DbType.Int64, b => b.AsInt64());
}
[Test]
public void CallingAsStringSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString());
}
[Test]
public void CallingAsStringWithSizeSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString(255));
}
[Test]
public void CallingAsStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsTimeSetsColumnDbTypeToTime()
{
VerifyColumnDbType(DbType.Time, b => b.AsTime());
}
[Test]
public void CallingAsXmlSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml());
}
[Test]
public void CallingAsXmlWithSizeSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml(255));
}
[Test]
public void CallingAsXmlSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsXml(255));
}
[Test]
public void CallingAsCustomSetsTypeToNullAndSetsCustomType()
{
VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test"));
VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test"));
}
[Test]
public void CallingWithDefaultValueSetsDefaultValue()
{
const int value = 42;
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefaultValue(42);
columnMock.VerifySet(c => c.DefaultValue = value);
}
[Test]
public void CallingForeignKeySetsIsForeignKeyToTrue()
{
VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey());
}
[Test]
public void CallingReferencedByAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<AlterTableExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object)
{
CurrentColumn = columnMock.Object
};
builder.ReferencedBy("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingForeignKeyAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<AlterTableExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object)
{
CurrentColumn = columnMock.Object
};
builder.ForeignKey("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.PrimaryTable == "FooTable" &&
fk.ForeignKey.PrimaryColumns.Contains("BarColumn") &&
fk.ForeignKey.PrimaryColumns.Count == 1 &&
fk.ForeignKey.ForeignTable == "Bacon" &&
fk.ForeignKey.ForeignColumns.Contains("BaconId") &&
fk.ForeignKey.ForeignColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingIdentitySetsIsIdentityToTrue()
{
VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity());
}
[Test]
public void CallingIndexedSetsIsIndexedToTrue()
{
VerifyColumnProperty(c => c.IsIndexed = true, b => b.Indexed());
}
[Test]
public void CallingPrimaryKeySetsIsPrimaryKeyToTrue()
{
VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey());
}
[Test]
public void CallingNullableSetsIsNullableToTrue()
{
VerifyColumnProperty(c => c.IsNullable = true, b => b.Nullable());
}
[Test]
public void CallingNotNullableSetsIsNullableToFalse()
{
VerifyColumnProperty(c => c.IsNullable = false, b => b.NotNullable());
}
[Test]
public void CallingUniqueSetsIsUniqueToTrue()
{
VerifyColumnProperty(c => c.IsUnique = true, b => b.Unique());
}
private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(columnExpression);
}
private void VerifyColumnDbType(DbType expected, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Type = expected);
}
private void VerifyColumnSize(int expected, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Size = expected);
}
private void VerifyColumnPrecision(int expected, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Precision = expected);
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public readonly struct TypeDefinition
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint _treatmentAndRowId;
internal TypeDefinition(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private TypeDefTreatment Treatment
{
get { return (TypeDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private TypeDefinitionHandle Handle
{
get { return TypeDefinitionHandle.FromRowId(RowId); }
}
public TypeAttributes Attributes
{
get
{
if (Treatment == 0)
{
return _reader.TypeDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
/// <summary>
/// Indicates whether this is a nested type.
/// </summary>
public bool IsNested => Attributes.IsNested();
/// <summary>
/// Name of the type.
/// </summary>
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return _reader.TypeDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
/// <summary>
/// Full name of the namespace where the type is defined, or nil if the type is nested or defined in a root namespace.
/// </summary>
public StringHandle Namespace
{
get
{
if (Treatment == 0)
{
return _reader.TypeDefTable.GetNamespace(Handle);
}
return GetProjectedNamespaceString();
}
}
/// <summary>
/// The definition handle of the namespace where the type is defined, or nil if the type is nested or defined in a root namespace.
/// </summary>
public NamespaceDefinitionHandle NamespaceDefinition
{
get
{
if (Treatment == 0)
{
return _reader.TypeDefTable.GetNamespaceDefinition(Handle);
}
return GetProjectedNamespace();
}
}
/// <summary>
/// The base type of the type definition: either
/// <see cref="TypeSpecificationHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeDefinitionHandle"/>.
/// </summary>
public EntityHandle BaseType
{
get
{
if (Treatment == 0)
{
return _reader.TypeDefTable.GetExtends(Handle);
}
return GetProjectedBaseType();
}
}
public TypeLayout GetLayout()
{
int classLayoutRowId = _reader.ClassLayoutTable.FindRow(Handle);
if (classLayoutRowId == 0)
{
// NOTE: We don't need a bool/TryGetLayout because zero also means use default:
//
// Spec:
// ClassSize of zero does not mean the class has zero size. It means that no .size directive was specified
// at definition time, in which case, the actual size is calculated from the field types, taking account of
// packing size (default or specified) and natural alignment on the target, runtime platform.
//
// PackingSize shall be one of {0, 1, 2, 4, 8, 16, 32, 64, 128}. (0 means use
// the default pack size for the platform on which the application is
// running.)
return default(TypeLayout);
}
uint size = _reader.ClassLayoutTable.GetClassSize(classLayoutRowId);
// The spec doesn't limit the size to 31bit. It only limits the size to 1MB if Parent is a value type.
// It however doesn't make much sense to define classes with >2GB size. So in order to keep the API
// clean of unsigned ints we impose the limit.
if (unchecked((int)size) != size)
{
throw new BadImageFormatException(SR.InvalidTypeSize);
}
int packingSize = _reader.ClassLayoutTable.GetPackingSize(classLayoutRowId);
return new TypeLayout((int)size, packingSize);
}
/// <summary>
/// Returns the enclosing type of a specified nested type or nil handle if the type is not nested.
/// </summary>
public TypeDefinitionHandle GetDeclaringType()
{
return _reader.NestedClassTable.FindEnclosingType(Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return _reader.GenericParamTable.FindGenericParametersForType(Handle);
}
public MethodDefinitionHandleCollection GetMethods()
{
return new MethodDefinitionHandleCollection(_reader, Handle);
}
public FieldDefinitionHandleCollection GetFields()
{
return new FieldDefinitionHandleCollection(_reader, Handle);
}
public PropertyDefinitionHandleCollection GetProperties()
{
return new PropertyDefinitionHandleCollection(_reader, Handle);
}
public EventDefinitionHandleCollection GetEvents()
{
return new EventDefinitionHandleCollection(_reader, Handle);
}
/// <summary>
/// Returns an array of types nested in the specified type.
/// </summary>
public ImmutableArray<TypeDefinitionHandle> GetNestedTypes()
{
return _reader.GetNestedTypes(Handle);
}
public MethodImplementationHandleCollection GetMethodImplementations()
{
return new MethodImplementationHandleCollection(_reader, Handle);
}
public InterfaceImplementationHandleCollection GetInterfaceImplementations()
{
return new InterfaceImplementationHandleCollection(_reader, Handle);
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(_reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle);
}
#region Projections
private TypeAttributes GetProjectedFlags()
{
var flags = _reader.TypeDefTable.GetFlags(Handle);
var treatment = Treatment;
switch (treatment & TypeDefTreatment.KindMask)
{
case TypeDefTreatment.NormalNonAttribute:
flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Import;
break;
case TypeDefTreatment.NormalAttribute:
flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Sealed;
break;
case TypeDefTreatment.UnmangleWinRTName:
flags = flags & ~TypeAttributes.SpecialName | TypeAttributes.Public;
break;
case TypeDefTreatment.PrefixWinRTName:
flags = flags & ~TypeAttributes.Public | TypeAttributes.Import;
break;
case TypeDefTreatment.RedirectedToClrType:
flags = flags & ~TypeAttributes.Public | TypeAttributes.Import;
break;
case TypeDefTreatment.RedirectedToClrAttribute:
flags &= ~TypeAttributes.Public;
break;
}
if ((treatment & TypeDefTreatment.MarkAbstractFlag) != 0)
{
flags |= TypeAttributes.Abstract;
}
if ((treatment & TypeDefTreatment.MarkInternalFlag) != 0)
{
flags &= ~TypeAttributes.Public;
}
return flags;
}
private StringHandle GetProjectedName()
{
var name = _reader.TypeDefTable.GetName(Handle);
return (Treatment & TypeDefTreatment.KindMask) switch
{
TypeDefTreatment.UnmangleWinRTName => name.SuffixRaw(MetadataReader.ClrPrefix.Length),
TypeDefTreatment.PrefixWinRTName => name.WithWinRTPrefix(),
_ => name,
};
}
private NamespaceDefinitionHandle GetProjectedNamespace()
{
// NOTE: NamespaceDefinitionHandle currently relies on never having virtual values. If this ever gets projected
// to a virtual namespace name, then that assumption will need to be removed.
// no change:
return _reader.TypeDefTable.GetNamespaceDefinition(Handle);
}
private StringHandle GetProjectedNamespaceString()
{
// no change:
return _reader.TypeDefTable.GetNamespace(Handle);
}
private EntityHandle GetProjectedBaseType()
{
// no change:
return _reader.TypeDefTable.GetExtends(Handle);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShuffleHighUInt16228()
{
var test = new ImmUnaryOpTest__ShuffleHighUInt16228();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShuffleHighUInt16228
{
private struct TestStruct
{
public Vector256<UInt16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShuffleHighUInt16228 testClass)
{
var result = Avx2.ShuffleHigh(_fld, 228);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector256<UInt16> _clsVar;
private Vector256<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable;
static ImmUnaryOpTest__ShuffleHighUInt16228()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public ImmUnaryOpTest__ShuffleHighUInt16228()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShuffleHigh(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
228
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShuffleHigh(
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
228
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShuffleHigh(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
228
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShuffleHigh), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
(byte)228
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShuffleHigh), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)228
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShuffleHigh), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)228
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShuffleHigh(
_clsVar,
228
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr);
var result = Avx2.ShuffleHigh(firstOp, 228);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ShuffleHigh(firstOp, 228);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ShuffleHigh(firstOp, 228);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShuffleHighUInt16228();
var result = Avx2.ShuffleHigh(test._fld, 228);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShuffleHigh(_fld, 228);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShuffleHigh(test._fld, 228);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != firstOp[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShuffleHigh)}<UInt16>(Vector256<UInt16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// Template.cs
//
// Author:
// Michael Hutchinson <[email protected]>
//
// Copyright (c) 2009 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;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TextTemplating;
namespace Mono.TextTemplating
{
public class ParsedTemplate
{
List<ISegment> segments = new List<ISegment> ();
List<ISegment> importedHelperSegments = new List<ISegment> ();
CompilerErrorCollection errors = new CompilerErrorCollection ();
string rootFileName;
public ParsedTemplate (string rootFileName)
{
this.rootFileName = rootFileName;
}
public List<ISegment> RawSegments {
get { return segments; }
}
public IEnumerable<Directive> Directives {
get {
foreach (ISegment seg in segments) {
Directive dir = seg as Directive;
if (dir != null)
yield return dir;
}
}
}
public IEnumerable<TemplateSegment> Content {
get {
foreach (ISegment seg in segments) {
TemplateSegment ts = seg as TemplateSegment;
if (ts != null)
yield return ts;
}
}
}
public CompilerErrorCollection Errors {
get { return errors; }
}
public static ParsedTemplate FromText (string content, ITextTemplatingEngineHost host)
{
ParsedTemplate template = new ParsedTemplate (host.TemplateFile);
try {
template.Parse (host, new Tokeniser (host.TemplateFile, content));
} catch (ParserException ex) {
template.LogError (ex.Message, ex.Location);
}
return template;
}
public void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser)
{
Parse (host, tokeniser, true);
}
public void ParseWithoutIncludes (Tokeniser tokeniser)
{
Parse (null, tokeniser, false);
}
void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser, bool parseIncludes)
{
Parse (host, tokeniser, parseIncludes, false);
}
void Parse (ITextTemplatingEngineHost host, Tokeniser tokeniser, bool parseIncludes, bool isImport)
{
bool skip = false;
bool addToImportedHelpers = false;
while ((skip || tokeniser.Advance ()) && tokeniser.State != State.EOF) {
skip = false;
ISegment seg = null;
switch (tokeniser.State) {
case State.Block:
if (!String.IsNullOrEmpty (tokeniser.Value))
seg = new TemplateSegment (SegmentType.Block, tokeniser.Value, tokeniser.Location);
break;
case State.Content:
if (!String.IsNullOrEmpty (tokeniser.Value))
seg = new TemplateSegment (SegmentType.Content, tokeniser.Value, tokeniser.Location);
break;
case State.Expression:
if (!String.IsNullOrEmpty (tokeniser.Value))
seg = new TemplateSegment (SegmentType.Expression, tokeniser.Value, tokeniser.Location);
break;
case State.Helper:
addToImportedHelpers = isImport;
if (!String.IsNullOrEmpty (tokeniser.Value))
seg = new TemplateSegment (SegmentType.Helper, tokeniser.Value, tokeniser.Location);
break;
case State.Directive:
Directive directive = null;
string attName = null;
while (!skip && tokeniser.Advance ()) {
switch (tokeniser.State) {
case State.DirectiveName:
if (directive == null) {
directive = new Directive (tokeniser.Value.ToLower (), tokeniser.Location);
directive.TagStartLocation = tokeniser.TagStartLocation;
if (!parseIncludes || directive.Name != "include")
segments.Add (directive);
} else
attName = tokeniser.Value;
break;
case State.DirectiveValue:
if (attName != null && directive != null)
directive.Attributes[attName.ToLower ()] = tokeniser.Value;
else
LogError ("Directive value without name", tokeniser.Location);
attName = null;
break;
case State.Directive:
if (directive != null)
directive.EndLocation = tokeniser.TagEndLocation;
break;
default:
skip = true;
break;
}
}
if (parseIncludes && directive.Name == "include")
Import (host, directive, Path.GetDirectoryName (tokeniser.Location.FileName));
break;
default:
throw new InvalidOperationException ();
}
if (seg != null) {
seg.TagStartLocation = tokeniser.TagStartLocation;
seg.EndLocation = tokeniser.TagEndLocation;
if (addToImportedHelpers)
importedHelperSegments.Add (seg);
else
segments.Add (seg);
}
}
if (!isImport)
AppendAnyImportedHelperSegments ();
}
void Import (ITextTemplatingEngineHost host, Directive includeDirective, string relativeToDirectory)
{
string fileName;
if (includeDirective.Attributes.Count > 1 || !includeDirective.Attributes.TryGetValue ("file", out fileName)) {
LogError ("Unexpected attributes in include directive", includeDirective.StartLocation);
return;
}
//try to resolve path relative to the file that included it
if (relativeToDirectory != null && !Path.IsPathRooted (fileName)) {
string possible = Path.Combine (relativeToDirectory, fileName);
if (File.Exists (possible))
fileName = possible;
}
string content, resolvedName;
if (host.LoadIncludeText (fileName, out content, out resolvedName))
Parse (host, new Tokeniser (resolvedName, content), true, true);
else
LogError ("Could not resolve include file '" + fileName + "'.", includeDirective.StartLocation);
}
void AppendAnyImportedHelperSegments ()
{
segments.AddRange (importedHelperSegments);
importedHelperSegments.Clear ();
}
void LogError (string message, Location location, bool isWarning)
{
CompilerError err = new CompilerError ();
err.ErrorText = message;
if (location.FileName != null) {
err.Line = location.Line;
err.Column = location.Column;
err.FileName = location.FileName ?? string.Empty;
} else {
err.FileName = rootFileName ?? string.Empty;
}
err.IsWarning = isWarning;
errors.Add (err);
}
public void LogError (string message)
{
LogError (message, Location.Empty, false);
}
public void LogWarning (string message)
{
LogError (message, Location.Empty, true);
}
public void LogError (string message, Location location)
{
LogError (message, location, false);
}
public void LogWarning (string message, Location location)
{
LogError (message, location, true);
}
}
public interface ISegment
{
Location StartLocation { get; }
Location EndLocation { get; set; }
Location TagStartLocation {get; set; }
}
public class TemplateSegment : ISegment
{
public TemplateSegment (SegmentType type, string text, Location start)
{
this.Type = type;
this.StartLocation = start;
this.Text = text;
}
public SegmentType Type { get; private set; }
public string Text { get; private set; }
public Location TagStartLocation { get; set; }
public Location StartLocation { get; private set; }
public Location EndLocation { get; set; }
}
public class Directive : ISegment
{
public Directive (string name, Location start)
{
this.Name = name;
this.Attributes = new Dictionary<string, string> ();
this.StartLocation = start;
}
public string Name { get; private set; }
public Dictionary<string,string> Attributes { get; private set; }
public Location TagStartLocation { get; set; }
public Location StartLocation { get; private set; }
public Location EndLocation { get; set; }
public string Extract (string key)
{
string value;
if (!Attributes.TryGetValue (key, out value))
return null;
Attributes.Remove (key);
return value;
}
}
public enum SegmentType
{
Block,
Expression,
Content,
Helper
}
public struct Location : IEquatable<Location>
{
public Location (string fileName, int line, int column) : this()
{
FileName = fileName;
Column = column;
Line = line;
}
public int Line { get; private set; }
public int Column { get; private set; }
public string FileName { get; private set; }
public static Location Empty {
get { return new Location (null, -1, -1); }
}
public Location AddLine ()
{
return new Location (this.FileName, this.Line + 1, 1);
}
public Location AddCol ()
{
return AddCols (1);
}
public Location AddCols (int number)
{
return new Location (this.FileName, this.Line, this.Column + number);
}
public override string ToString ()
{
return string.Format("[{0} ({1},{2})]", FileName, Line, Column);
}
public bool Equals (Location other)
{
return other.Line == Line && other.Column == Column && other.FileName == FileName;
}
}
}
| |
//
// SchemaTypes.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
namespace Altova.Types
{
public interface ISchemaType : IComparable, ICloneable
{
}
public class SchemaBoolean : ISchemaType
{
public bool Value;
public SchemaBoolean(SchemaBoolean obj)
{
Value = obj.Value;
}
public SchemaBoolean(bool Value)
{
this.Value = Value;
}
public SchemaBoolean(string Value)
{
this.Value = Value == "true" || Value == "1";
}
public override string ToString()
{
return Value ? "true" : "false";
}
public override int GetHashCode()
{
return Value ? 1231 : 1237;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is SchemaBoolean))
return false;
return Value == ((SchemaBoolean)obj).Value;
}
public static bool operator==(SchemaBoolean obj1, SchemaBoolean obj2)
{
return obj1.Value == obj2.Value;
}
public static bool operator!=(SchemaBoolean obj1, SchemaBoolean obj2)
{
return obj1.Value != obj2.Value;
}
public int CompareTo(object obj)
{
return Value.CompareTo(((SchemaBoolean)obj).Value);
}
public object Clone()
{
return new SchemaBoolean(Value);
}
}
public class SchemaInt : ISchemaType
{
public int Value;
public SchemaInt(SchemaInt obj)
{
Value = obj.Value;
}
public SchemaInt(int Value)
{
this.Value = Value;
}
public SchemaInt(string Value)
{
this.Value = Convert.ToInt32(Value);
}
public override string ToString()
{
return Convert.ToString(Value);
}
public override int GetHashCode()
{
return Value;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is SchemaInt))
return false;
return Value == ((SchemaInt)obj).Value;
}
public static bool operator==(SchemaInt obj1, SchemaInt obj2)
{
return obj1.Value == obj2.Value;
}
public static bool operator!=(SchemaInt obj1, SchemaInt obj2)
{
return obj1.Value != obj2.Value;
}
public int CompareTo(object obj)
{
return Value.CompareTo(((SchemaInt)obj).Value);
}
public object Clone()
{
return new SchemaInt(Value);
}
}
public class SchemaLong : ISchemaType
{
public long Value;
public SchemaLong(SchemaLong obj)
{
Value = obj.Value;
}
public SchemaLong(long Value)
{
this.Value = Value;
}
public SchemaLong(string Value)
{
this.Value = Convert.ToInt64(Value);
}
public override string ToString()
{
return Convert.ToString(Value);
}
public override int GetHashCode()
{
return (int)Value;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is SchemaLong))
return false;
return Value == ((SchemaLong)obj).Value;
}
public static bool operator==(SchemaLong obj1, SchemaLong obj2)
{
return obj1.Value == obj2.Value;
}
public static bool operator!=(SchemaLong obj1, SchemaLong obj2)
{
return obj1.Value != obj2.Value;
}
public int CompareTo(object obj)
{
return Value.CompareTo(((SchemaLong)obj).Value);
}
public object Clone()
{
return new SchemaLong(Value);
}
}
public class SchemaDecimal : ISchemaType
{
public decimal Value;
public SchemaDecimal(SchemaDecimal obj)
{
Value = obj.Value;
}
public SchemaDecimal(decimal Value)
{
this.Value = Value;
}
public SchemaDecimal(string Value)
{
this.Value = Convert.ToDecimal(Value);
}
public override string ToString()
{
return Convert.ToString(Value);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is SchemaDecimal))
return false;
return Value == ((SchemaDecimal)obj).Value;
}
public static bool operator==(SchemaDecimal obj1, SchemaDecimal obj2)
{
return obj1.Value == obj2.Value;
}
public static bool operator!=(SchemaDecimal obj1, SchemaDecimal obj2)
{
return obj1.Value != obj2.Value;
}
public int CompareTo(object obj)
{
return Value.CompareTo(((SchemaDecimal)obj).Value);
}
public object Clone()
{
return new SchemaDecimal(Value);
}
}
public class SchemaDateTime : ISchemaType
{
public DateTime Value;
public SchemaDateTime(SchemaDateTime obj)
{
Value = obj.Value;
}
public SchemaDateTime(DateTime Value)
{
this.Value = Value;
}
public SchemaDateTime(string Value)
{
this.Value = Convert.ToDateTime(Value);
}
public override string ToString()
{
return Value.GetDateTimeFormats('s')[0];
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is SchemaDateTime))
return false;
return Value == ((SchemaDateTime)obj).Value;
}
public static bool operator==(SchemaDateTime obj1, SchemaDateTime obj2)
{
return obj1.Value == obj2.Value;
}
public static bool operator!=(SchemaDateTime obj1, SchemaDateTime obj2)
{
return obj1.Value != obj2.Value;
}
public int CompareTo(object obj)
{
return Value.CompareTo(((SchemaDateTime)obj).Value);
}
public object Clone()
{
return new SchemaDateTime(Value);
}
}
public class SchemaString : ISchemaType
{
public string Value;
public SchemaString(SchemaString obj)
{
Value = obj.Value;
}
public SchemaString(string Value)
{
this.Value = Value;
}
public override string ToString()
{
return Value;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is SchemaString))
return false;
return Value == ((SchemaString)obj).Value;
}
public static bool operator==(SchemaString obj1, SchemaString obj2)
{
return obj1.Value == obj2.Value;
}
public static bool operator!=(SchemaString obj1, SchemaString obj2)
{
return obj1.Value != obj2.Value;
}
public int CompareTo(object obj)
{
return Value.CompareTo(((SchemaString)obj).Value);
}
public object Clone()
{
return new SchemaString(Value);
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] glUseShaderProgramEXT: Binding for glUseShaderProgramEXT.
/// </summary>
/// <param name="type">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="program">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects")]
public static void UseShaderProgramEXT(int type, uint program)
{
Debug.Assert(Delegates.pglUseShaderProgramEXT != null, "pglUseShaderProgramEXT not implemented");
Delegates.pglUseShaderProgramEXT(type, program);
LogCommand("glUseShaderProgramEXT", null, type, program );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glActiveProgramEXT: Binding for glActiveProgramEXT.
/// </summary>
/// <param name="program">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects")]
public static void ActiveProgramEXT(uint program)
{
Debug.Assert(Delegates.pglActiveProgramEXT != null, "pglActiveProgramEXT not implemented");
Delegates.pglActiveProgramEXT(program);
LogCommand("glActiveProgramEXT", null, program );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glCreateShaderProgramEXT: Binding for glCreateShaderProgramEXT.
/// </summary>
/// <param name="type">
/// A <see cref="T:ShaderType"/>.
/// </param>
/// <param name="string">
/// A <see cref="T:string"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects")]
public static uint CreateShaderProgramEXT(ShaderType type, string @string)
{
uint retValue;
Debug.Assert(Delegates.pglCreateShaderProgramEXT != null, "pglCreateShaderProgramEXT not implemented");
retValue = Delegates.pglCreateShaderProgramEXT((int)type, @string);
LogCommand("glCreateShaderProgramEXT", retValue, type, @string );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GL] glActiveShaderProgramEXT: Binding for glActiveShaderProgramEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="program">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void ActiveShaderProgramEXT(uint pipeline, uint program)
{
Debug.Assert(Delegates.pglActiveShaderProgramEXT != null, "pglActiveShaderProgramEXT not implemented");
Delegates.pglActiveShaderProgramEXT(pipeline, program);
LogCommand("glActiveShaderProgramEXT", null, pipeline, program );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glBindProgramPipelineEXT: Binding for glBindProgramPipelineEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void BindProgramPipelineEXT(uint pipeline)
{
Debug.Assert(Delegates.pglBindProgramPipelineEXT != null, "pglBindProgramPipelineEXT not implemented");
Delegates.pglBindProgramPipelineEXT(pipeline);
LogCommand("glBindProgramPipelineEXT", null, pipeline );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glCreateShaderProgramvEXT: Binding for glCreateShaderProgramvEXT.
/// </summary>
/// <param name="type">
/// A <see cref="T:ShaderType"/>.
/// </param>
/// <param name="count">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="strings">
/// A <see cref="T:string[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static uint CreateShaderProgramEXT(ShaderType type, int count, string[] strings)
{
uint retValue;
Debug.Assert(Delegates.pglCreateShaderProgramvEXT != null, "pglCreateShaderProgramvEXT not implemented");
retValue = Delegates.pglCreateShaderProgramvEXT((int)type, count, strings);
LogCommand("glCreateShaderProgramvEXT", retValue, type, count, strings );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GL] glCreateShaderProgramvEXT: Binding for glCreateShaderProgramvEXT.
/// </summary>
/// <param name="type">
/// A <see cref="T:ShaderType"/>.
/// </param>
/// <param name="strings">
/// A <see cref="T:string[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static uint CreateShaderProgramEXT(ShaderType type, string[] strings)
{
uint retValue;
Debug.Assert(Delegates.pglCreateShaderProgramvEXT != null, "pglCreateShaderProgramvEXT not implemented");
retValue = Delegates.pglCreateShaderProgramvEXT((int)type, strings.Length, strings);
LogCommand("glCreateShaderProgramvEXT", retValue, type, strings.Length, strings );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GL] glDeleteProgramPipelinesEXT: Binding for glDeleteProgramPipelinesEXT.
/// </summary>
/// <param name="pipelines">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void DeleteProgramPipelinesEXT(params uint[] pipelines)
{
unsafe {
fixed (uint* p_pipelines = pipelines)
{
Debug.Assert(Delegates.pglDeleteProgramPipelinesEXT != null, "pglDeleteProgramPipelinesEXT not implemented");
Delegates.pglDeleteProgramPipelinesEXT(pipelines.Length, p_pipelines);
LogCommand("glDeleteProgramPipelinesEXT", null, pipelines.Length, pipelines );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGenProgramPipelinesEXT: Binding for glGenProgramPipelinesEXT.
/// </summary>
/// <param name="pipelines">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void GenProgramPipelinesEXT(uint[] pipelines)
{
unsafe {
fixed (uint* p_pipelines = pipelines)
{
Debug.Assert(Delegates.pglGenProgramPipelinesEXT != null, "pglGenProgramPipelinesEXT not implemented");
Delegates.pglGenProgramPipelinesEXT(pipelines.Length, p_pipelines);
LogCommand("glGenProgramPipelinesEXT", null, pipelines.Length, pipelines );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGenProgramPipelinesEXT: Binding for glGenProgramPipelinesEXT.
/// </summary>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static uint GenProgramPipelineEXT()
{
uint retValue;
unsafe {
Delegates.pglGenProgramPipelinesEXT(1, &retValue);
LogCommand("glGenProgramPipelinesEXT", null, 1, "{ " + retValue + " }" );
}
DebugCheckErrors(null);
return (retValue);
}
/// <summary>
/// [GL] glGetProgramPipelineInfoLogEXT: Binding for glGetProgramPipelineInfoLogEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="bufSize">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="length">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="infoLog">
/// A <see cref="T:StringBuilder"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void GetProgramPipelineInfoLogEXT(uint pipeline, int bufSize, out int length, StringBuilder infoLog)
{
unsafe {
fixed (int* p_length = &length)
{
Debug.Assert(Delegates.pglGetProgramPipelineInfoLogEXT != null, "pglGetProgramPipelineInfoLogEXT not implemented");
Delegates.pglGetProgramPipelineInfoLogEXT(pipeline, bufSize, p_length, infoLog);
LogCommand("glGetProgramPipelineInfoLogEXT", null, pipeline, bufSize, length, infoLog );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramPipelineivEXT: Binding for glGetProgramPipelineivEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:PipelineParameterName"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void GetProgramPipelineEXT(uint pipeline, PipelineParameterName pname, [Out] int[] @params)
{
unsafe {
fixed (int* p_params = @params)
{
Debug.Assert(Delegates.pglGetProgramPipelineivEXT != null, "pglGetProgramPipelineivEXT not implemented");
Delegates.pglGetProgramPipelineivEXT(pipeline, (int)pname, p_params);
LogCommand("glGetProgramPipelineivEXT", null, pipeline, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramPipelineivEXT: Binding for glGetProgramPipelineivEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:PipelineParameterName"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void GetProgramPipelineEXT(uint pipeline, PipelineParameterName pname, out int @params)
{
unsafe {
fixed (int* p_params = &@params)
{
Debug.Assert(Delegates.pglGetProgramPipelineivEXT != null, "pglGetProgramPipelineivEXT not implemented");
Delegates.pglGetProgramPipelineivEXT(pipeline, (int)pname, p_params);
LogCommand("glGetProgramPipelineivEXT", null, pipeline, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glIsProgramPipelineEXT: Binding for glIsProgramPipelineEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static bool IsProgramPipelineEXT(uint pipeline)
{
bool retValue;
Debug.Assert(Delegates.pglIsProgramPipelineEXT != null, "pglIsProgramPipelineEXT not implemented");
retValue = Delegates.pglIsProgramPipelineEXT(pipeline);
LogCommand("glIsProgramPipelineEXT", retValue, pipeline );
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GL] glUseProgramStagesEXT: Binding for glUseProgramStagesEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="stages">
/// A <see cref="T:UseProgramStageMask"/>.
/// </param>
/// <param name="program">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void UseProgramStageEXT(uint pipeline, UseProgramStageMask stages, uint program)
{
Debug.Assert(Delegates.pglUseProgramStagesEXT != null, "pglUseProgramStagesEXT not implemented");
Delegates.pglUseProgramStagesEXT(pipeline, (uint)stages, program);
LogCommand("glUseProgramStagesEXT", null, pipeline, stages, program );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glValidateProgramPipelineEXT: Binding for glValidateProgramPipelineEXT.
/// </summary>
/// <param name="pipeline">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
public static void ValidateProgramPipelineEXT(uint pipeline)
{
Debug.Assert(Delegates.pglValidateProgramPipelineEXT != null, "pglValidateProgramPipelineEXT not implemented");
Delegates.pglValidateProgramPipelineEXT(pipeline);
LogCommand("glValidateProgramPipelineEXT", null, pipeline );
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_EXT_separate_shader_objects")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glUseShaderProgramEXT(int type, uint program);
[RequiredByFeature("GL_EXT_separate_shader_objects")]
[ThreadStatic]
internal static glUseShaderProgramEXT pglUseShaderProgramEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glActiveProgramEXT(uint program);
[RequiredByFeature("GL_EXT_separate_shader_objects")]
[ThreadStatic]
internal static glActiveProgramEXT pglActiveProgramEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects")]
[SuppressUnmanagedCodeSecurity]
internal delegate uint glCreateShaderProgramEXT(int type, string @string);
[RequiredByFeature("GL_EXT_separate_shader_objects")]
[ThreadStatic]
internal static glCreateShaderProgramEXT pglCreateShaderProgramEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glActiveShaderProgramEXT(uint pipeline, uint program);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glActiveShaderProgramEXT pglActiveShaderProgramEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glBindProgramPipelineEXT(uint pipeline);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glBindProgramPipelineEXT pglBindProgramPipelineEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate uint glCreateShaderProgramvEXT(int type, int count, string[] strings);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glCreateShaderProgramvEXT pglCreateShaderProgramvEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glDeleteProgramPipelinesEXT(int n, uint* pipelines);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glDeleteProgramPipelinesEXT pglDeleteProgramPipelinesEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGenProgramPipelinesEXT(int n, uint* pipelines);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glGenProgramPipelinesEXT pglGenProgramPipelinesEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramPipelineInfoLogEXT(uint pipeline, int bufSize, int* length, StringBuilder infoLog);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glGetProgramPipelineInfoLogEXT pglGetProgramPipelineInfoLogEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramPipelineivEXT(uint pipeline, int pname, int* @params);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glGetProgramPipelineivEXT pglGetProgramPipelineivEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
internal delegate bool glIsProgramPipelineEXT(uint pipeline);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glIsProgramPipelineEXT pglIsProgramPipelineEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glUseProgramStagesEXT(uint pipeline, uint stages, uint program);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glUseProgramStagesEXT pglUseProgramStagesEXT;
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glValidateProgramPipelineEXT(uint pipeline);
[RequiredByFeature("GL_EXT_separate_shader_objects", Api = "gles2")]
[ThreadStatic]
internal static glValidateProgramPipelineEXT pglValidateProgramPipelineEXT;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.OperationalInsights;
using Microsoft.Azure.Management.OperationalInsights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.OperationalInsights
{
/// <summary>
/// Operations for managing data sources under Workspaces.
/// </summary>
internal partial class DataSourceOperations : IServiceOperations<OperationalInsightsManagementClient>, IDataSourceOperations
{
/// <summary>
/// Initializes a new instance of the DataSourceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DataSourceOperations(OperationalInsightsManagementClient client)
{
this._client = client;
}
private OperationalInsightsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.OperationalInsights.OperationalInsightsManagementClient.
/// </summary>
public OperationalInsightsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create or update a data source.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data source.
/// </param>
/// <param name='workspaceName'>
/// Required. The name of the parent workspace that will contain the
/// data source
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data source.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update data source operation response.
/// </returns>
public async Task<DataSourceCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string workspaceName, DataSourceCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (workspaceName == null)
{
throw new ArgumentNullException("workspaceName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.DataSource != null)
{
if (parameters.DataSource.Name == null)
{
throw new ArgumentNullException("parameters.DataSource.Name");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", 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(resourceGroupName);
url = url + "/providers/Microsoft.OperationalInsights/workspaces/";
url = url + Uri.EscapeDataString(workspaceName);
url = url + "/dataSources/";
if (parameters.DataSource != null && parameters.DataSource.Name != null)
{
url = url + Uri.EscapeDataString(parameters.DataSource.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01-preview");
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.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject dataSourceCreateOrUpdateParametersValue = new JObject();
requestDoc = dataSourceCreateOrUpdateParametersValue;
if (parameters.DataSource != null)
{
if (parameters.DataSource.Properties != null)
{
dataSourceCreateOrUpdateParametersValue["properties"] = JObject.Parse(parameters.DataSource.Properties);
}
if (parameters.DataSource.ETag != null)
{
dataSourceCreateOrUpdateParametersValue["eTag"] = parameters.DataSource.ETag;
}
if (parameters.DataSource.Id != null)
{
dataSourceCreateOrUpdateParametersValue["id"] = parameters.DataSource.Id;
}
dataSourceCreateOrUpdateParametersValue["name"] = parameters.DataSource.Name;
if (parameters.DataSource.Type != null)
{
dataSourceCreateOrUpdateParametersValue["type"] = parameters.DataSource.Type;
}
if (parameters.DataSource.Kind != null)
{
dataSourceCreateOrUpdateParametersValue["kind"] = parameters.DataSource.Kind;
}
}
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.Created)
{
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
DataSourceCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataSourceCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DataSource dataSourceInstance = new DataSource();
result.DataSource = dataSourceInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented);
dataSourceInstance.Properties = propertiesInstance;
}
JToken eTagValue = responseDoc["eTag"];
if (eTagValue != null && eTagValue.Type != JTokenType.Null)
{
string eTagInstance = ((string)eTagValue);
dataSourceInstance.ETag = eTagInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataSourceInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataSourceInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dataSourceInstance.Type = typeInstance;
}
JToken kindValue = responseDoc["kind"];
if (kindValue != null && kindValue.Type != JTokenType.Null)
{
string kindInstance = ((string)kindValue);
dataSourceInstance.Kind = kindInstance;
}
}
}
result.StatusCode = statusCode;
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>
/// Deletes a data source instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data source.
/// </param>
/// <param name='workspaceName'>
/// Required. The name of the workspace that contains the data source.
/// </param>
/// <param name='datasourceName'>
/// Required. Name of the data source.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string workspaceName, string datasourceName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (workspaceName == null)
{
throw new ArgumentNullException("workspaceName");
}
if (datasourceName == null)
{
throw new ArgumentNullException("datasourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("datasourceName", datasourceName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", 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(resourceGroupName);
url = url + "/providers/Microsoft.OperationalInsights/workspaces/";
url = url + Uri.EscapeDataString(workspaceName);
url = url + "/dataSources/";
url = url + Uri.EscapeDataString(datasourceName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01-preview");
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.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
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>
/// Gets a data source instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data source.
/// </param>
/// <param name='workspaceName'>
/// Required. The name of the workspace that contains the data source.
/// </param>
/// <param name='dataSourceName'>
/// Required. Name of the data source
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The get data source operation response.
/// </returns>
public async Task<DataSourceGetResponse> GetAsync(string resourceGroupName, string workspaceName, string dataSourceName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (workspaceName == null)
{
throw new ArgumentNullException("workspaceName");
}
if (dataSourceName == null)
{
throw new ArgumentNullException("dataSourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("dataSourceName", dataSourceName);
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(resourceGroupName);
url = url + "/providers/Microsoft.OperationalInsights/workspaces/";
url = url + Uri.EscapeDataString(workspaceName);
url = url + "/dataSources/";
url = url + Uri.EscapeDataString(dataSourceName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-01-preview");
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("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
DataSourceGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataSourceGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DataSource dataSourceInstance = new DataSource();
result.DataSource = dataSourceInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented);
dataSourceInstance.Properties = propertiesInstance;
}
JToken eTagValue = responseDoc["eTag"];
if (eTagValue != null && eTagValue.Type != JTokenType.Null)
{
string eTagInstance = ((string)eTagValue);
dataSourceInstance.ETag = eTagInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataSourceInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataSourceInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dataSourceInstance.Type = typeInstance;
}
JToken kindValue = responseDoc["kind"];
if (kindValue != null && kindValue.Type != JTokenType.Null)
{
string kindInstance = ((string)kindValue);
dataSourceInstance.Kind = kindInstance;
}
}
}
result.StatusCode = statusCode;
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>
/// Gets the first page of data source instances in a workspace with
/// the link to the next page.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data sources.
/// </param>
/// <param name='workspaceName'>
/// Required. The workspace that contains the data sources.
/// </param>
/// <param name='kind'>
/// Required. Filter data sources by Kind.
/// </param>
/// <param name='skiptoken'>
/// Optional. Token for paging support.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The list data source operation response.
/// </returns>
public async Task<DataSourceListResponse> ListInWorkspaceAsync(string resourceGroupName, string workspaceName, string kind, string skiptoken, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (workspaceName == null)
{
throw new ArgumentNullException("workspaceName");
}
if (kind == null)
{
throw new ArgumentNullException("kind");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("kind", kind);
tracingParameters.Add("skiptoken", skiptoken);
TracingAdapter.Enter(invocationId, this, "ListInWorkspaceAsync", 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(resourceGroupName);
url = url + "/providers/Microsoft.OperationalInsights/workspaces/";
url = url + Uri.EscapeDataString(workspaceName);
url = url + "/dataSources";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
odataFilter.Add("kind+eq+'" + Uri.EscapeDataString(kind) + "'");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (skiptoken != null)
{
queryParameters.Add("$skiptoken=" + Uri.EscapeDataString(skiptoken));
}
queryParameters.Add("api-version=2015-11-01-preview");
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("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
DataSourceListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataSourceListResponse();
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))
{
DataSource dataSourceInstance = new DataSource();
result.DataSources.Add(dataSourceInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented);
dataSourceInstance.Properties = propertiesInstance;
}
JToken eTagValue = valueValue["eTag"];
if (eTagValue != null && eTagValue.Type != JTokenType.Null)
{
string eTagInstance = ((string)eTagValue);
dataSourceInstance.ETag = eTagInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataSourceInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataSourceInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dataSourceInstance.Type = typeInstance;
}
JToken kindValue = valueValue["kind"];
if (kindValue != null && kindValue.Type != JTokenType.Null)
{
string kindInstance = ((string)kindValue);
dataSourceInstance.Kind = kindInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
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>
/// Gets the next page of data source instances with the link to the
/// next page.
/// </summary>
/// <param name='nextLink'>
/// Required. The url to the next data source page.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The list data source operation response.
/// </returns>
public async Task<DataSourceListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
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());
// 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
DataSourceListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataSourceListResponse();
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))
{
DataSource dataSourceInstance = new DataSource();
result.DataSources.Add(dataSourceInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
string propertiesInstance = propertiesValue.ToString(Newtonsoft.Json.Formatting.Indented);
dataSourceInstance.Properties = propertiesInstance;
}
JToken eTagValue = valueValue["eTag"];
if (eTagValue != null && eTagValue.Type != JTokenType.Null)
{
string eTagInstance = ((string)eTagValue);
dataSourceInstance.ETag = eTagInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataSourceInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataSourceInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dataSourceInstance.Type = typeInstance;
}
JToken kindValue = valueValue["kind"];
if (kindValue != null && kindValue.Type != JTokenType.Null)
{
string kindInstance = ((string)kindValue);
dataSourceInstance.Kind = kindInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
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();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UrlImageViewHelper
{
public class LRUCache<TKey, TValue> : IDictionary<TKey, TValue>
{
object sync = new object();
Dictionary<TKey, TValue> data;
IndexedLinkedList<TKey> lruList = new IndexedLinkedList<TKey>();
ICollection<KeyValuePair<TKey, TValue>> dataAsCollection;
int capacity;
public LRUCache(int capacity)
{
if (capacity <= 0)
{
throw new ArgumentException("capacity should always be bigger than 0");
}
data = new Dictionary<TKey, TValue>(capacity);
dataAsCollection = data;
this.capacity = capacity;
}
public void Add(TKey key, TValue value)
{
if (!ContainsKey(key))
{
this[key] = value;
}
else
{
throw new ArgumentException("An attempt was made to insert a duplicate key in the cache.");
}
}
public bool ContainsKey(TKey key)
{
return data.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get
{
return data.Keys;
}
}
public bool Remove(TKey key)
{
bool existed = data.Remove(key);
lruList.Remove(key);
return existed;
}
public bool TryGetValue(TKey key, out TValue value)
{
return data.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
get { return data.Values; }
}
public TValue this[TKey key]
{
get
{
var value = data[key];
lruList.Remove(key);
lruList.Add(key);
return value;
}
set
{
data[key] = value;
lruList.Remove(key);
lruList.Add(key);
if (data.Count > capacity)
{
Remove(lruList.First);
lruList.RemoveFirst();
}
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
public void Clear()
{
data.Clear();
lruList.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return dataAsCollection.Contains(item);
}
public void ReclaimLRU(int itemsToReclaim)
{
while (--itemsToReclaim >= 0 && lruList.First != null)
Remove(lruList.First);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
dataAsCollection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return data.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
bool removed = dataAsCollection.Remove(item);
if (removed)
{
lruList.Remove(item.Key);
}
return removed;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return dataAsCollection.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)data).GetEnumerator();
}
}
public class IndexedLinkedList<T>
{
LinkedList<T> data = new LinkedList<T>();
Dictionary<T, LinkedListNode<T>> index = new Dictionary<T, LinkedListNode<T>>();
public void Add(T value)
{
index[value] = data.AddLast(value);
}
public void RemoveFirst()
{
index.Remove(data.First.Value);
data.RemoveFirst();
}
public void Remove(T value)
{
LinkedListNode<T> node;
if (index.TryGetValue(value, out node))
{
data.Remove(node);
index.Remove(value);
}
}
public int Count
{
get
{
return data.Count;
}
}
public void Clear()
{
data.Clear();
index.Clear();
}
public T First
{
get
{
return data.First.Value;
}
}
}
}
| |
using System;
using System.IO;
namespace Core.IO
{
// sqliteInt.h
public abstract class VFile
{
public static int PENDING_BYTE = 0x40000000;
public static int RESERVED_BYTE = (PENDING_BYTE + 1);
public static int SHARED_FIRST = (PENDING_BYTE + 2);
public static int SHARED_SIZE = 510;
public enum LOCK : byte
{
NO = 0,
SHARED = 1,
RESERVED = 2,
PENDING = 3,
EXCLUSIVE = 4,
UNKNOWN = 5,
}
// sqlite3.h
[Flags]
public enum SYNC : byte
{
NORMAL = 0x00002,
FULL = 0x00003,
DATAONLY = 0x00010,
// wal.h
WAL_TRANSACTIONS = 0x20, // Sync at the end of each transaction
WAL_MASK = 0x13, // Mask off the SQLITE_SYNC_* values
}
// sqlite3.h
public enum FCNTL : uint
{
LOCKSTATE = 1,
GET_LOCKPROXYFILE = 2,
SET_LOCKPROXYFILE = 3,
LAST_ERRNO = 4,
SIZE_HINT = 5,
CHUNK_SIZE = 6,
FILE_POINTER = 7,
SYNC_OMITTED = 8,
WIN32_AV_RETRY = 9,
PERSIST_WAL = 10,
OVERWRITE = 11,
VFSNAME = 12,
POWERSAFE_OVERWRITE = 13,
PRAGMA = 14,
BUSYHANDLER = 15,
TEMPFILENAME = 16,
MMAP_SIZE = 18,
// os.h
DB_UNCHANGED = 0xca093fa0,
}
// sqlite3.h
[Flags]
public enum IOCAP : uint
{
ATOMIC = 0x00000001,
ATOMIC512 = 0x00000002,
ATOMIC1K = 0x00000004,
ATOMIC2K = 0x00000008,
ATOMIC4K = 0x00000010,
ATOMIC8K = 0x00000020,
ATOMIC16K = 0x00000040,
ATOMIC32K = 0x00000080,
ATOMIC64K = 0x00000100,
SAFE_APPEND = 0x00000200,
SEQUENTIAL = 0x00000400,
UNDELETABLE_WHEN_OPEN = 0x00000800,
IOCAP_POWERSAFE_OVERWRITE = 0x00001000,
}
// sqlite3.h
[Flags]
public enum SHM : byte
{
UNLOCK = 1,
LOCK = 2,
SHARED = 4,
EXCLUSIVE = 8,
MAX = 8,
};
public byte Type;
public bool Opened;
public abstract RC Read(byte[] buffer, int amount, long offset);
public abstract RC Write(byte[] buffer, int amount, long offset);
public abstract RC Truncate(long size);
public abstract RC Close();
public abstract RC Sync(SYNC flags);
public abstract RC get_FileSize(out long size);
public virtual RC Lock(LOCK lock_) { return RC.OK; }
public virtual RC CheckReservedLock(ref int resOut) { return RC.OK; }
public virtual RC Unlock(LOCK lock_) { return RC.OK; }
public virtual RC FileControl(FCNTL op, ref long arg) { return RC.NOTFOUND; }
public virtual uint get_SectorSize() { return 0; }
public virtual IOCAP get_DeviceCharacteristics() { return 0; }
public virtual RC ShmMap(int region, int sizeRegion, bool isWrite, out object pp) { pp = null; return RC.OK; }
public virtual RC ShmLock(int offset, int count, SHM flags) { return RC.OK; }
public virtual void ShmBarrier() { }
public virtual RC ShmUnmap(bool deleteFlag) { return RC.OK; }
public RC Read4(int offset, out int valueOut)
{
uint u32_pRes = 0;
var rc = Read4(offset, out u32_pRes);
valueOut = (int)u32_pRes;
return rc;
}
public RC Read4(long offset, out uint valueOut) { return Read4((int)offset, out valueOut); }
public RC Read4(int offset, out uint valueOut)
{
var b = new byte[4];
var rc = Read(b, b.Length, offset);
valueOut = (rc == RC.OK ? ConvertEx.Get4(b) : 0);
return rc;
}
public RC Write4(long offset, uint val)
{
var ac = new byte[4];
ConvertEx.Put4(ac, val);
return Write(ac, 4, offset);
}
public RC CloseAndFree()
{
RC rc = Close();
//C._free(ref this);
return rc;
}
// extensions
#if ENABLE_ATOMIC_WRITE
internal static RC JournalVFileOpen(VSystem vfs, string name, ref VFile file, VSystem.OPEN flags, int bufferLength)
{
var p = new JournalVFile();
if (bufferLength > 0)
p.Buffer = C._alloc2(bufferLength, true);
else
{
VSystem.OPEN dummy;
return vfs.Open(name, p, flags, out dummy);
}
p.Type = 2;
p.BufferLength = bufferLength;
p.Flags = flags;
p.Journal = name;
p.Vfs = vfs;
file = p;
return RC.OK;
}
internal static int JournalVFileSize(VSystem vfs)
{
return 0;
}
internal static RC JournalVFileCreate(VFile file)
{
if (file.Type != 2)
return RC.OK;
return ((JournalVFile)file).CreateFile();
}
internal static bool HasJournalVFile(VFile file)
{
return (file.Type != 2 || ((JournalVFile)file).Real != null);
}
#else
internal static int JournalVFileSize(VSystem vfs) { return vfs.SizeOsFile; }
internal bool HasJournalVFile(VFile file) { return true; }
#endif
internal static void MemoryVFileOpen(ref VFile file)
{
file = new MemoryVFile();
file.Type = 1;
}
internal static bool HasMemoryVFile(VFile file)
{
return (file.Type == 1);
}
internal static int MemoryVFileSize()
{
return 0;
}
//#if ENABLE_ATOMIC_WRITE
// static int JournalOpen(VSystem vfs, string a, VFile b, int c, int d) { return 0; }
// static int JournalSize(VSystem vfs) { return 0; }
// static int JournalCreate(VFile v) { return 0; }
// static bool JournalExists(VFile v) { return true; }
//#else
// static int JournalSize(VSystem vfs) { return vfs.SizeOsFile; }
// static bool JournalExists(VFile v) { return true; }
//#endif
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type OnenoteSectionRequest.
/// </summary>
public partial class OnenoteSectionRequest : BaseRequest, IOnenoteSectionRequest
{
/// <summary>
/// Constructs a new OnenoteSectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public OnenoteSectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified OnenoteSection using POST.
/// </summary>
/// <param name="onenoteSectionToCreate">The OnenoteSection to create.</param>
/// <returns>The created OnenoteSection.</returns>
public System.Threading.Tasks.Task<OnenoteSection> CreateAsync(OnenoteSection onenoteSectionToCreate)
{
return this.CreateAsync(onenoteSectionToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified OnenoteSection using POST.
/// </summary>
/// <param name="onenoteSectionToCreate">The OnenoteSection to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created OnenoteSection.</returns>
public async System.Threading.Tasks.Task<OnenoteSection> CreateAsync(OnenoteSection onenoteSectionToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<OnenoteSection>(onenoteSectionToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified OnenoteSection.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified OnenoteSection.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<OnenoteSection>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified OnenoteSection.
/// </summary>
/// <returns>The OnenoteSection.</returns>
public System.Threading.Tasks.Task<OnenoteSection> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified OnenoteSection.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The OnenoteSection.</returns>
public async System.Threading.Tasks.Task<OnenoteSection> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<OnenoteSection>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified OnenoteSection using PATCH.
/// </summary>
/// <param name="onenoteSectionToUpdate">The OnenoteSection to update.</param>
/// <returns>The updated OnenoteSection.</returns>
public System.Threading.Tasks.Task<OnenoteSection> UpdateAsync(OnenoteSection onenoteSectionToUpdate)
{
return this.UpdateAsync(onenoteSectionToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified OnenoteSection using PATCH.
/// </summary>
/// <param name="onenoteSectionToUpdate">The OnenoteSection to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated OnenoteSection.</returns>
public async System.Threading.Tasks.Task<OnenoteSection> UpdateAsync(OnenoteSection onenoteSectionToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<OnenoteSection>(onenoteSectionToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionRequest Expand(Expression<Func<OnenoteSection, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IOnenoteSectionRequest Select(Expression<Func<OnenoteSection, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="onenoteSectionToInitialize">The <see cref="OnenoteSection"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(OnenoteSection onenoteSectionToInitialize)
{
if (onenoteSectionToInitialize != null && onenoteSectionToInitialize.AdditionalData != null)
{
if (onenoteSectionToInitialize.Pages != null && onenoteSectionToInitialize.Pages.CurrentPage != null)
{
onenoteSectionToInitialize.Pages.AdditionalData = onenoteSectionToInitialize.AdditionalData;
object nextPageLink;
onenoteSectionToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
onenoteSectionToInitialize.Pages.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.Versioning;
namespace System.Runtime.Caching
{
internal static class Dbg
{
#if DEBUG
static readonly DateTime MinValuePlusOneDay = DateTime.MinValue.AddDays(1);
static readonly DateTime MaxValueMinusOneDay = DateTime.MaxValue.AddDays(-1);
#endif
internal const string TAG_INTERNAL = "Internal";
internal const string TAG_EXTERNAL = "External";
internal const string TAG_ALL = "*";
internal const string DATE_FORMAT = @"yyyy/MM/dd HH:mm:ss.ffff";
internal const string TIME_FORMAT = @"HH:mm:ss:ffff";
#if DEBUG
private static class NativeMethods {
[DllImport("kernel32.dll")]
internal extern static void DebugBreak();
[DllImport("kernel32.dll")]
internal extern static int GetCurrentProcessId();
[DllImport("kernel32.dll")]
internal extern static int GetCurrentThreadId();
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
internal extern static IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
internal extern static bool IsDebuggerPresent();
[DllImport("kernel32.dll", SetLastError=true)]
internal extern static bool TerminateProcess(HandleRef processHandle, int exitCode);
internal const int PM_NOREMOVE = 0x0000;
internal const int PM_REMOVE = 0x0001;
[StructLayout(LayoutKind.Sequential)]
internal struct MSG {
internal IntPtr hwnd;
internal int message;
internal IntPtr wParam;
internal IntPtr lParam;
internal int time;
internal int pt_x;
internal int pt_y;
}
//[DllImport("user32.dll", CharSet=CharSet.Auto)]
//internal extern static bool PeekMessage([In, Out] ref MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove);
internal const int
MB_OK = 0x00000000,
MB_OKCANCEL = 0x00000001,
MB_ABORTRETRYIGNORE = 0x00000002,
MB_YESNOCANCEL = 0x00000003,
MB_YESNO = 0x00000004,
MB_RETRYCANCEL = 0x00000005,
MB_ICONHAND = 0x00000010,
MB_ICONQUESTION = 0x00000020,
MB_ICONEXCLAMATION = 0x00000030,
MB_ICONASTERISK = 0x00000040,
MB_USERICON = 0x00000080,
MB_ICONWARNING = 0x00000030,
MB_ICONERROR = 0x00000010,
MB_ICONINFORMATION = 0x00000040,
MB_DEFBUTTON1 = 0x00000000,
MB_DEFBUTTON2 = 0x00000100,
MB_DEFBUTTON3 = 0x00000200,
MB_DEFBUTTON4 = 0x00000300,
MB_APPLMODAL = 0x00000000,
MB_SYSTEMMODAL = 0x00001000,
MB_TASKMODAL = 0x00002000,
MB_HELP = 0x00004000,
MB_NOFOCUS = 0x00008000,
MB_SETFOREGROUND = 0x00010000,
MB_DEFAULT_DESKTOP_ONLY = 0x00020000,
MB_TOPMOST = 0x00040000,
MB_RIGHT = 0x00080000,
MB_RTLREADING = 0x00100000,
MB_SERVICE_NOTIFICATION = 0x00200000,
MB_SERVICE_NOTIFICATION_NT3X = 0x00040000,
MB_TYPEMASK = 0x0000000F,
MB_ICONMASK = 0x000000F0,
MB_DEFMASK = 0x00000F00,
MB_MODEMASK = 0x00003000,
MB_MISCMASK = 0x0000C000;
internal const int
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8,
IDHELP = 9;
//[DllImport("user32.dll", CharSet=CharSet.Auto, BestFitMapping=false)]
//internal extern static int MessageBox(HandleRef hWnd, string text, string caption, int type);
internal static readonly IntPtr HKEY_LOCAL_MACHINE = unchecked((IntPtr)(int)0x80000002);
internal const int READ_CONTROL = 0x00020000;
internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
internal const int SYNCHRONIZE = 0x00100000;
internal const int KEY_QUERY_VALUE = 0x0001;
internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
internal const int KEY_NOTIFY = 0x0010;
internal const int KEY_READ = ((STANDARD_RIGHTS_READ |
KEY_QUERY_VALUE |
KEY_ENUMERATE_SUB_KEYS |
KEY_NOTIFY)
&
(~SYNCHRONIZE));
internal const int REG_NOTIFY_CHANGE_NAME = 1;
internal const int REG_NOTIFY_CHANGE_LAST_SET = 4;
[DllImport("advapi32.dll", CharSet=CharSet.Auto, BestFitMapping=false, SetLastError=true)]
internal extern static int RegOpenKeyEx(IntPtr hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true)]
internal extern static int RegNotifyChangeKeyValue(SafeRegistryHandle hKey, bool watchSubTree, uint notifyFilter, SafeWaitHandle regEvent, bool async);
}
private enum TagValue {
Disabled = 0,
Enabled = 1,
Break = 2,
Min = Disabled,
Max = Break,
}
private const string TAG_ASSERT = "Assert";
private const string TAG_ASSERT_BREAK = "AssertBreak";
private const string TAG_DEBUG_VERBOSE = "DebugVerbose";
private const string TAG_DEBUG_MONITOR = "DebugMonitor";
private const string TAG_DEBUG_PREFIX = "DebugPrefix";
private const string TAG_DEBUG_THREAD_PREFIX = "DebugThreadPrefix";
private const string PRODUCT = "Microsoft .NET Framework";
private const string COMPONENT = "System.Web";
private static string s_regKeyName = @"Software\Microsoft\ASP.NET\Debug";
private static string s_listenKeyName = @"Software\Microsoft";
private static bool s_assert;
private static bool s_assertBreak;
private static bool s_includePrefix;
private static bool s_includeThreadPrefix;
private static bool s_monitor;
private static object s_lock;
private static volatile bool s_inited;
private static ReadOnlyCollection<Tag> s_tagDefaults;
private static List<Tag> s_tags;
private static AutoResetEvent s_notifyEvent;
private static RegisteredWaitHandle s_waitHandle;
private static SafeRegistryHandle s_regHandle;
private static bool s_stopMonitoring;
private static Hashtable s_tableAlwaysValidate;
private static Type[] s_DumpArgs;
private static Type[] s_ValidateArgs;
private class Tag {
string _name;
TagValue _value;
int _prefixLength;
internal Tag(string name, TagValue value) {
_name = name;
_value = value;
if (_name[_name.Length - 1] == '*') {
_prefixLength = _name.Length - 1;
}
else {
_prefixLength = -1;
}
}
internal string Name {
get {return _name;}
}
internal TagValue Value {
get {return _value;}
}
internal int PrefixLength {
get {return _prefixLength;}
}
}
static Dbg() {
s_lock = new object();
}
private static void EnsureInit() {
bool continueInit = false;
if (!s_inited) {
lock (s_lock) {
if (!s_inited) {
s_tableAlwaysValidate = new Hashtable();
s_DumpArgs = new Type[1] {typeof(string)};
s_ValidateArgs = new Type[0];
List<Tag> tagDefaults = new List<Tag>();
tagDefaults.Add(new Tag(TAG_ALL, TagValue.Disabled));
tagDefaults.Add(new Tag(TAG_INTERNAL, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_EXTERNAL, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_ASSERT, TagValue.Break));
tagDefaults.Add(new Tag(TAG_ASSERT_BREAK, TagValue.Disabled));
tagDefaults.Add(new Tag(TAG_DEBUG_VERBOSE, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_DEBUG_MONITOR, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_DEBUG_PREFIX, TagValue.Enabled));
tagDefaults.Add(new Tag(TAG_DEBUG_THREAD_PREFIX, TagValue.Enabled));
s_tagDefaults = tagDefaults.AsReadOnly();
s_tags = new List<Tag>(s_tagDefaults);
GetBuiltinTagValues();
continueInit = true;
s_inited = true;
}
}
}
// Work to do outside the init lock.
if (continueInit) {
ReadTagsFromRegistry();
Trace(TAG_DEBUG_VERBOSE, "Debugging package initialized");
// Need to read tags before starting to monitor in order to get TAG_DEBUG_MONITOR
StartRegistryMonitor();
}
}
private static bool StringEqualsIgnoreCase(string s1, string s2) {
return StringComparer.OrdinalIgnoreCase.Equals(s1, s2);
}
private static void WriteTagsToRegistry() {
try {
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(s_regKeyName)) {
List<Tag> tags = s_tags;
foreach (Tag tag in tags) {
key.SetValue(tag.Name, tag.Value, RegistryValueKind.DWord);
}
}
}
catch {
}
}
private static void GetBuiltinTagValues() {
// Use GetTagValue instead of IsTagEnabled because it does not call EnsureInit
// and potentially recurse.
s_assert = (GetTagValue(TAG_ASSERT) != TagValue.Disabled);
s_assertBreak = (GetTagValue(TAG_ASSERT_BREAK) != TagValue.Disabled);
s_includePrefix = (GetTagValue(TAG_DEBUG_PREFIX) != TagValue.Disabled);
s_includeThreadPrefix = (GetTagValue(TAG_DEBUG_THREAD_PREFIX) != TagValue.Disabled);
s_monitor = (GetTagValue(TAG_DEBUG_MONITOR) != TagValue.Disabled);
}
private static void ReadTagsFromRegistry() {
lock (s_lock) {
try {
List<Tag> tags = new List<Tag>(s_tagDefaults);
string[] names = null;
bool writeTags = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(s_regKeyName, false)) {
if (key != null) {
names = key.GetValueNames();
foreach (string name in names) {
TagValue value = TagValue.Disabled;
try {
TagValue keyvalue = (TagValue) key.GetValue(name);
if (TagValue.Min <= keyvalue && keyvalue <= TagValue.Max) {
value = keyvalue;
}
else {
writeTags = true;
}
}
catch {
writeTags = true;
}
// Add tag to list, making sure it is unique.
Tag tag = new Tag(name, (TagValue) value);
bool found = false;
for (int i = 0; i < s_tagDefaults.Count; i++) {
if (StringEqualsIgnoreCase(name, tags[i].Name)) {
found = true;
tags[i] = tag;
break;
}
}
if (!found) {
tags.Add(tag);
}
}
}
}
s_tags = tags;
GetBuiltinTagValues();
// Write tags out if there was an invalid value or
// not all default tags are present.
if (writeTags || (names != null && names.Length < tags.Count)) {
WriteTagsToRegistry();
}
}
catch {
s_tags = new List<Tag>(s_tagDefaults);
}
}
}
private static void StartRegistryMonitor() {
if (!s_monitor) {
Trace(TAG_DEBUG_VERBOSE, "WARNING: Registry monitoring disabled, changes during process execution will not be recognized.");
return;
}
Trace(TAG_DEBUG_VERBOSE, "Monitoring registry key " + s_listenKeyName + " for changes.");
// Event used to notify of changes.
s_notifyEvent = new AutoResetEvent(false);
// Register a wait on the event.
s_waitHandle = ThreadPool.RegisterWaitForSingleObject(s_notifyEvent, OnRegChangeKeyValue, null, -1, false);
// Monitor the registry.
MonitorRegistryForOneChange();
}
private static void StopRegistryMonitor() {
// Cleanup allocated handles
s_stopMonitoring = true;
if (s_regHandle != null) {
s_regHandle.Close();
s_regHandle = null;
}
if (s_waitHandle != null) {
s_waitHandle.Unregister(s_notifyEvent);
s_waitHandle = null;
}
if (s_notifyEvent != null) {
s_notifyEvent.Close();
s_notifyEvent = null;
}
Trace(TAG_DEBUG_VERBOSE, "Registry monitoring stopped.");
}
public static void OnRegChangeKeyValue(object state, bool timedOut) {
if (!s_stopMonitoring) {
if (timedOut) {
StopRegistryMonitor();
}
else {
// Monitor again
MonitorRegistryForOneChange();
// Once we're monitoring, read the changes to the registry.
// We have to do this after we start monitoring in order
// to catch all changes to the registry.
ReadTagsFromRegistry();
}
}
}
private static void MonitorRegistryForOneChange() {
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Close the open reg handle
if (s_regHandle != null)
{
s_regHandle.Close();
s_regHandle = null;
}
// Open the reg key
int result = NativeMethods.RegOpenKeyEx(NativeMethods.HKEY_LOCAL_MACHINE, s_listenKeyName, 0, NativeMethods.KEY_READ, out s_regHandle);
if (result != 0)
{
StopRegistryMonitor();
return;
}
// Listen for changes.
result = NativeMethods.RegNotifyChangeKeyValue(
s_regHandle,
true,
NativeMethods.REG_NOTIFY_CHANGE_NAME | NativeMethods.REG_NOTIFY_CHANGE_LAST_SET,
s_notifyEvent.SafeWaitHandle,
true);
if (result != 0)
{
StopRegistryMonitor();
}
}
}
private static Tag FindMatchingTag(string name, bool exact) {
List<Tag> tags = s_tags;
// Look for exact match first
foreach (Tag tag in tags) {
if (StringEqualsIgnoreCase(name, tag.Name)) {
return tag;
}
}
if (exact) {
return null;
}
Tag longestTag = null;
int longestPrefix = -1;
foreach (Tag tag in tags) {
if ( tag.PrefixLength > longestPrefix &&
0 == string.Compare(name, 0, tag.Name, 0, tag.PrefixLength, StringComparison.OrdinalIgnoreCase)) {
longestTag = tag;
longestPrefix = tag.PrefixLength;
}
}
return longestTag;
}
private static TagValue GetTagValue(string name) {
Tag tag = FindMatchingTag(name, false);
if (tag != null) {
return tag.Value;
}
else {
return TagValue.Disabled;
}
}
private static bool TraceBreak(string tagName, string message, Exception e, bool includePrefix) {
EnsureInit();
TagValue tagValue = GetTagValue(tagName);
if (tagValue == TagValue.Disabled) {
return false;
}
bool isAssert = object.ReferenceEquals(tagName, TAG_ASSERT);
if (isAssert) {
tagName = "";
}
string exceptionMessage = null;
if (e != null) {
string httpCode = null;
string errorCode = null;
if (e is ExternalException) {
// note that HttpExceptions are ExternalExceptions
errorCode = "_hr=0x" + ((ExternalException)e).ErrorCode.ToString("x", CultureInfo.InvariantCulture);
}
// Use e.ToString() in order to get inner exception
if (errorCode != null) {
exceptionMessage = "Exception " + e.ToString() + "\n" + httpCode + errorCode;
}
else {
exceptionMessage = "Exception " + e.ToString();
}
}
if (string.IsNullOrEmpty(message) & exceptionMessage != null) {
message = exceptionMessage;
exceptionMessage = null;
}
string traceFormat;
int idThread = 0;
int idProcess = 0;
if (!includePrefix || !s_includePrefix) {
traceFormat = "{4}\n{5}";
}
else {
if (s_includeThreadPrefix) {
idThread = Thread.CurrentThread.ManagedThreadId;
using(var process = Process.GetCurrentProcess())
{
idProcess = process.Id;
}
traceFormat = "[0x{0:x}.{1:x} {2} {3}] {4}\n{5}";
}
else {
traceFormat = "[{2} {3}] {4}\n{5}";
}
}
string suffix = "";
if (exceptionMessage != null) {
suffix += exceptionMessage + "\n";
}
bool doBreak = (tagValue == TagValue.Break);
if (doBreak && !isAssert) {
suffix += "Breaking into debugger...\n";
}
string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, idProcess, idThread, COMPONENT, tagName, message, suffix);
Debug.WriteLine(traceMessage);
return doBreak;
}
//private class MBResult {
// internal int Result;
//}
static bool DoAssert(string message) {
if (!s_assert) {
return false;
}
// Skip 2 frames - one for this function, one for
// the public Assert function that called this function.
StackFrame frame = new StackFrame(2, true);
StackTrace trace = new StackTrace(2, true);
string fileName = frame.GetFileName();
int lineNumber = frame.GetFileLineNumber();
string traceFormat;
if (!string.IsNullOrEmpty(fileName)) {
traceFormat = "ASSERTION FAILED: {0}\nFile: {1}:{2}\nStack trace:\n{3}";
}
else {
traceFormat = "ASSERTION FAILED: {0}\nStack trace:\n{3}";
}
string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, message, fileName, lineNumber, trace.ToString());
if (!TraceBreak(TAG_ASSERT, traceMessage, null, true)) {
// If the value of "Assert" is not TagValue.Break, then don't even ask user.
return false;
}
if (s_assertBreak) {
// If "AssertBreak" is enabled, then always break.
return true;
}
string dialogFormat;
if (!string.IsNullOrEmpty(fileName)) {
dialogFormat =
@"Failed expression: {0}
File: {1}:{2}
Component: {3}
PID={4} TID={5}
Stack trace:
{6}
A=Exit process R=Debug I=Continue";
}
else {
dialogFormat =
@"Failed expression: {0}
(no file information available)
Component: {3}
PID={4} TID={5}
Stack trace:
{6}
A=Exit process R=Debug I=Continue";
}
int idProcess = 0;
using (var process = Process.GetCurrentProcess())
{
idProcess = process.Id;
}
string dialogMessage = string.Format(
CultureInfo.InvariantCulture,
dialogFormat,
message,
fileName, lineNumber,
COMPONENT,
idProcess, Thread.CurrentThread.ManagedThreadId,
trace.ToString());
Debug.Fail(dialogMessage);
return true;
}
#endif
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[Conditional("DEBUG")]
internal static void Trace(string tagName, string message)
{
#if DEBUG
if (TraceBreak(tagName, message, null, true)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[Conditional("DEBUG")]
internal static void Trace(string tagName, string message, bool includePrefix)
{
#if DEBUG
if (TraceBreak(tagName, message, null, includePrefix)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[Conditional("DEBUG")]
internal static void Trace(string tagName, string message, Exception e)
{
#if DEBUG
if (TraceBreak(tagName, message, e, true)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[Conditional("DEBUG")]
internal static void Trace(string tagName, Exception e)
{
#if DEBUG
if (TraceBreak(tagName, null, e, true)) {
Break();
}
#endif
}
//
// Sends the message to the debugger if the tag is enabled.
// Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
//
[Conditional("DEBUG")]
internal static void Trace(string tagName, string message, Exception e, bool includePrefix)
{
#if DEBUG
if (TraceBreak(tagName, message, e, includePrefix)) {
Break();
}
#endif
}
#if DEBUG
#endif
[Conditional("DEBUG")]
public static void TraceException(string tagName, Exception e)
{
#if DEBUG
if (TraceBreak(tagName, null, e, true)) {
Break();
}
#endif
}
//
// If the assertion is false and the 'Assert' tag is enabled:
// * Send a message to the debugger.
// * If the 'AssertBreak' tag is enabled, immediately break into the debugger
// * Else display a dialog box asking the user to Abort, Retry (break), or Ignore
//
[Conditional("DEBUG")]
internal static void Assert(bool assertion, string message)
{
#if DEBUG
EnsureInit();
if (assertion == false) {
if (DoAssert(message)) {
Break();
}
}
#endif
}
//
// If the assertion is false and the 'Assert' tag is enabled:
// * Send a message to the debugger.
// * If the 'AssertBreak' tag is enabled, immediately break into the debugger
// * Else display a dialog box asking the user to Abort, Retry (break), or Ignore
//
[Conditional("DEBUG")]
internal static void Assert(bool assertion)
{
#if DEBUG
EnsureInit();
if (assertion == false) {
if (DoAssert(null)) {
Break();
}
}
#endif
}
//
// Like Assert, but the assertion is always considered to be false.
//
[Conditional("DEBUG")]
internal static void Fail(string message)
{
#if DEBUG
Assert(false, message);
#endif
}
//
// Returns true if the tag is enabled, false otherwise.
// Note that the tag needn't be an exact match.
//
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")]
internal static bool IsTagEnabled(string tagName)
{
#if DEBUG
EnsureInit();
return GetTagValue(tagName) != TagValue.Disabled;
#else
return false;
#endif
}
//
// Returns true if the tag present.
// This function chekcs for an exact match.
//
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")]
internal static bool IsTagPresent(string tagName)
{
#if DEBUG
EnsureInit();
return FindMatchingTag(tagName, true) != null;
#else
return false;
#endif
}
//
// Breaks into the debugger, or launches one if not yet attached.
//
[Conditional("DEBUG")]
internal static void Break()
{
#if DEBUG
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && NativeMethods.IsDebuggerPresent())
{
NativeMethods.DebugBreak();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !Debugger.IsAttached)
{
Debugger.Launch();
}
else
{
Debugger.Break();
}
#endif
}
//
// Tells the debug system to always validate calls for a
// particular tag. This is useful for temporarily enabling
// validation in stress tests or other situations where you
// may not have control over the debug tags that are enabled
// on a particular machine.
//
[Conditional("DEBUG")]
internal static void AlwaysValidate(string tagName)
{
#if DEBUG
EnsureInit();
s_tableAlwaysValidate[tagName] = tagName;
#endif
}
//
// Throws an exception if the assertion is not valid.
// Use this function from a DebugValidate method where
// you would otherwise use Assert.
//
[Conditional("DEBUG")]
internal static void CheckValid(bool assertion, string message)
{
#if DEBUG
if (!assertion) {
throw new Exception(message);
}
#endif
}
//
// Calls DebugValidate on an object if such a method exists.
//
// This method should be used from implementations of DebugValidate
// where it is unknown whether an object has a DebugValidate method.
// For example, the DoubleLink class uses it to validate the
// item of type Object which it points to.
//
// This method should NOT be used when code wants to conditionally
// validate an object and have a failed validation caught in an assert.
// Use Debug.Validate(tagName, obj) for that purpose.
//
[Conditional("DEBUG")]
internal static void Validate(object obj)
{
#if DEBUG
Type type;
MethodInfo mi;
if (obj != null) {
type = obj.GetType();
mi = type.GetMethod(
"DebugValidate",
BindingFlags.NonPublic | BindingFlags.Instance,
null,
s_ValidateArgs,
null);
if (mi != null) {
object[] tempIndex = null;
mi.Invoke(obj, tempIndex);
}
}
#endif
}
//
// Validates an object is the "Validate" tag is enabled, or when
// the "Validate" tag is not disabled and the given 'tag' is enabled.
// An Assertion is made if the validation fails.
//
[Conditional("DEBUG")]
internal static void Validate(string tagName, object obj)
{
#if DEBUG
EnsureInit();
if ( obj != null
&& ( IsTagEnabled("Validate")
|| ( !IsTagPresent("Validate")
&& ( s_tableAlwaysValidate[tagName] != null
|| IsTagEnabled(tagName))))) {
try {
Validate(obj);
}
catch (Exception e) {
Assert(false, "Validate failed: " + e.InnerException.Message);
}
#pragma warning disable 1058
catch {
Assert(false, "Validate failed. Non-CLS compliant exception caught.");
}
#pragma warning restore 1058
}
#endif
}
#if DEBUG
//
// Calls DebugDescription on an object to get its description.
//
// This method should only be used in implementations of DebugDescription
// where it is not known whether a nested objects has an implementation
// of DebugDescription. For example, the double linked list class uses
// GetDescription to get the description of the item it points to.
//
// This method should NOT be used when you want to conditionally
// dump an object. Use Debug.Dump instead.
//
// @param obj The object to call DebugDescription on. May be null.
// @param indent A prefix for each line in the description. This is used
// to allow the nested display of objects within other objects.
// The indent is usually a multiple of four spaces.
//
// @return The description.
//
internal static string GetDescription(Object obj, string indent) {
string description;
Type type;
MethodInfo mi;
Object[] parameters;
if (obj == null) {
description = "\n";
}
else {
type = obj.GetType();
mi = type.GetMethod(
"DebugDescription",
BindingFlags.NonPublic | BindingFlags.Instance,
null,
s_DumpArgs,
null);
if (mi == null || mi.ReturnType != typeof(string)) {
description = indent + obj.ToString();
}
else {
parameters = new Object[1] {(Object) indent};
description = (string) mi.Invoke(obj, parameters);
}
}
return description;
}
#endif
//
// Dumps an object to the debugger if the "Dump" tag is enabled,
// or if the "Dump" tag is not present and the 'tag' is enabled.
//
// @param tagName The tag to Dump with.
// @param obj The object to dump.
//
[Conditional("DEBUG")]
internal static void Dump(string tagName, object obj)
{
#if DEBUG
EnsureInit();
string description;
string traceTag = null;
bool dumpEnabled, dumpPresent;
if (obj != null) {
dumpEnabled = IsTagEnabled("Dump");
dumpPresent = IsTagPresent("Dump");
if (dumpEnabled || !dumpPresent) {
if (IsTagEnabled(tagName)) {
traceTag = tagName;
}
else if (dumpEnabled) {
traceTag = "Dump";
}
if (traceTag != null) {
description = GetDescription(obj, string.Empty);
Trace(traceTag, "Dump\n" + description);
}
}
}
#endif
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")]
static internal string FormatLocalDate(DateTime localTime)
{
#if DEBUG
return localTime.ToString(DATE_FORMAT, CultureInfo.InvariantCulture);
#else
return string.Empty;
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient.
/// </summary>
internal class SNIProxy
{
private const int DefaultSqlServerPort = 1433;
private const int DefaultSqlServerDacPort = 1434;
private const string SqlServerSpnHeader = "MSSQLSvc";
internal class SspiClientContextResult
{
internal const uint OK = 0;
internal const uint Failed = 1;
internal const uint KerberosTicketMissing = 2;
}
public static readonly SNIProxy Singleton = new SNIProxy();
/// <summary>
/// Terminate SNI
/// </summary>
public void Terminate()
{
}
/// <summary>
/// Enable MARS support on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint EnableMars(SNIHandle handle)
{
if (SNIMarsManager.Singleton.CreateMarsConnection(handle) == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return TdsEnums.SNI_SUCCESS;
}
return TdsEnums.SNI_ERROR;
}
/// <summary>
/// Enable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint EnableSsl(SNIHandle handle, uint options)
{
try
{
return handle.EnableSsl(options);
}
catch (Exception e)
{
return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e);
}
}
/// <summary>
/// Disable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint DisableSsl(SNIHandle handle)
{
handle.DisableSsl();
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Generate SSPI context
/// </summary>
/// <param name="handle">SNI connection handle</param>
/// <param name="receivedBuff">Receive buffer</param>
/// <param name="receivedLength">Received length</param>
/// <param name="sendBuff">Send buffer</param>
/// <param name="sendLength">Send length</param>
/// <param name="serverName">Service Principal Name buffer</param>
/// <param name="serverNameLength">Length of Service Principal Name</param>
/// <returns>SNI error code</returns>
public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName)
{
SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext;
ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags;
SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;
string securityPackage = NegotiationInfoClass.Negotiate;
if (securityContext == null)
{
credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false);
}
SecurityBuffer[] inSecurityBufferArray = null;
if (receivedBuff != null)
{
inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) };
}
else
{
inSecurityBufferArray = new SecurityBuffer[] { };
}
int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage);
SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN);
ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
| ContextFlagsPal.Confidentiality
| ContextFlagsPal.MutualAuth;
string serverSPN = System.Text.Encoding.UTF8.GetString(serverName);
SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
credentialsHandle,
ref securityContext,
serverSPN,
requestedContextFlags,
inSecurityBufferArray,
outSecurityBuffer,
ref contextFlags);
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
{
inSecurityBufferArray = new SecurityBuffer[] { outSecurityBuffer };
statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray);
outSecurityBuffer.token = null;
}
sendBuff = outSecurityBuffer.token;
if (sendBuff == null)
{
sendBuff = Array.Empty<byte>();
}
sspiClientContextStatus.SecurityContext = securityContext;
sspiClientContextStatus.ContextFlags = contextFlags;
sspiClientContextStatus.CredentialsHandle = credentialsHandle;
if (IsErrorStatus(statusCode.ErrorCode))
{
// Could not access Kerberos Ticket.
//
// SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException,
// so we don't need to check for a GssApiException here.
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError)
{
throw new Exception(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
}
else
{
throw new Exception(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
}
}
}
private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode)
{
return errorCode != SecurityStatusPalErrorCode.NotSet &&
errorCode != SecurityStatusPalErrorCode.OK &&
errorCode != SecurityStatusPalErrorCode.ContinueNeeded &&
errorCode != SecurityStatusPalErrorCode.CompleteNeeded &&
errorCode != SecurityStatusPalErrorCode.CompAndContinue &&
errorCode != SecurityStatusPalErrorCode.ContextExpired &&
errorCode != SecurityStatusPalErrorCode.CredentialsNeeded &&
errorCode != SecurityStatusPalErrorCode.Renegotiate;
}
/// <summary>
/// Initialize SSPI
/// </summary>
/// <param name="maxLength">Max length of SSPI packet</param>
/// <returns>SNI error code</returns>
public uint InitializeSspiPackage(ref uint maxLength)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Set connection buffer size
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="bufferSize">Buffer size</param>
/// <returns>SNI error code</returns>
public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize)
{
handle.SetBufferSize((int)bufferSize);
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="inBuff">Buffer</param>
/// <param name="dataSize">Data size</param>
/// <returns>SNI error status</returns>
public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize)
{
int dataSizeInt = 0;
packet.GetData(inBuff, ref dataSizeInt);
dataSize = (uint)dataSizeInt;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Read synchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="timeout">Timeout</param>
/// <returns>SNI error status</returns>
public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout)
{
return handle.Receive(out packet, timeout);
}
/// <summary>
/// Get SNI connection ID
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="clientConnectionId">Client connection ID</param>
/// <returns>SNI error status</returns>
public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId)
{
clientConnectionId = handle.ConnectionId;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Send a packet
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="sync">true if synchronous, false if asynchronous</param>
/// <returns>SNI error status</returns>
public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync)
{
if (sync)
{
return handle.Send(packet.Clone());
}
else
{
return handle.SendAsync(packet.Clone());
}
}
/// <summary>
/// Create a SNI connection handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="fullServerName">Full server name from connection string</param>
/// <param name="ignoreSniOpenTimeout">Ignore open timeout</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="instanceName">Instance name</param>
/// <param name="spnBuffer">SPN</param>
/// <param name="flushCache">Flush packet cache</param>
/// <param name="async">Asynchronous connection</param>
/// <param name="parallel">Attempt parallel connects</param>
/// <returns>SNI handle</returns>
public SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity)
{
instanceName = new byte[1];
bool errorWithLocalDBProcessing;
string localDBDataSource = GetLocalDBDataSource(fullServerName, out errorWithLocalDBProcessing);
if (errorWithLocalDBProcessing)
{
return null;
}
// If a localDB Data source is available, we need to use it.
fullServerName = localDBDataSource ?? fullServerName;
DataSource details = DataSource.ParseServerName(fullServerName);
if (details == null)
{
return null;
}
SNIHandle sniHandle = null;
switch (details.ConnectionProtocol)
{
case DataSource.Protocol.Admin:
case DataSource.Protocol.None: // default to using tcp if no protocol is provided
case DataSource.Protocol.TCP:
sniHandle = CreateTcpHandle(details, timerExpire, callbackObject, parallel);
break;
case DataSource.Protocol.NP:
sniHandle = CreateNpHandle(details, timerExpire, callbackObject, parallel);
break;
default:
Debug.Fail($"Unexpected connection protocol: {details.ConnectionProtocol}");
break;
}
if (isIntegratedSecurity)
{
try
{
spnBuffer = GetSqlServerSPN(details);
}
catch (Exception e)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, SNICommon.ErrorSpnLookup, e);
}
}
return sniHandle;
}
private static byte[] GetSqlServerSPN(DataSource dataSource)
{
Debug.Assert(!string.IsNullOrWhiteSpace(dataSource.ServerName));
string hostName = dataSource.ServerName;
string postfix = null;
if (dataSource.Port != -1)
{
postfix = dataSource.Port.ToString();
}
else if (!string.IsNullOrWhiteSpace(dataSource.InstanceName))
{
postfix = dataSource.InstanceName;
}
// For handling tcp:<hostname> format
else if (dataSource.ConnectionProtocol == DataSource.Protocol.TCP)
{
postfix = DefaultSqlServerPort.ToString();
}
return GetSqlServerSPN(hostName, postfix);
}
private static byte[] GetSqlServerSPN(string hostNameOrAddress, string portOrInstanceName)
{
Debug.Assert(!string.IsNullOrWhiteSpace(hostNameOrAddress));
IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);
string fullyQualifiedDomainName = hostEntry.HostName;
string serverSpn = SqlServerSpnHeader + "/" + fullyQualifiedDomainName;
if (!string.IsNullOrWhiteSpace(portOrInstanceName))
{
serverSpn += ":" + portOrInstanceName;
}
return Encoding.UTF8.GetBytes(serverSpn);
}
/// <summary>
/// Creates an SNITCPHandle object
/// </summary>
/// <param name="fullServerName">Server string. May contain a comma delimited port number.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used</param>
/// <returns>SNITCPHandle</returns>
private SNITCPHandle CreateTcpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel)
{
// TCP Format:
// tcp:<host name>\<instance name>
// tcp:<host name>,<TCP/IP port number>
string hostName = details.ServerName;
if (string.IsNullOrWhiteSpace(hostName))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
int port = -1;
bool isAdminConnection = details.ConnectionProtocol == DataSource.Protocol.Admin;
if (details.IsSsrpRequired)
{
try
{
port = isAdminConnection ?
SSRP.GetDacPortByInstanceName(hostName, details.InstanceName) :
SSRP.GetPortByInstanceName(hostName, details.InstanceName);
}
catch (SocketException se)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, se);
return null;
}
}
else if (details.Port != -1)
{
port = details.Port;
}
else
{
port = isAdminConnection ? DefaultSqlServerDacPort : DefaultSqlServerPort;
}
return new SNITCPHandle(hostName, port, timerExpire, callbackObject, parallel);
}
/// <summary>
/// Creates an SNINpHandle object
/// </summary>
/// <param name="fullServerName">Server string representing a UNC pipe path.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param>
/// <returns>SNINpHandle</returns>
private SNINpHandle CreateNpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel)
{
if (parallel)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty);
return null;
}
return new SNINpHandle(details.PipeHostName, details.PipeName, timerExpire, callbackObject);
}
/// <summary>
/// Create MARS handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="physicalConnection">SNI connection handle</param>
/// <param name="defaultBufferSize">Default buffer size</param>
/// <param name="async">Asynchronous connection</param>
/// <returns>SNI error status</returns>
public SNIHandle CreateMarsHandle(object callbackObject, SNIHandle physicalConnection, int defaultBufferSize, bool async)
{
SNIMarsConnection connection = SNIMarsManager.Singleton.GetConnection(physicalConnection);
return connection.CreateSession(callbackObject, async);
}
/// <summary>
/// Read packet asynchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">Packet</param>
/// <returns>SNI error status</returns>
public uint ReadAsync(SNIHandle handle, out SNIPacket packet)
{
packet = new SNIPacket(null);
return handle.ReceiveAsync(ref packet);
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void PacketSetData(SNIPacket packet, byte[] data, int length)
{
packet.SetData(data, length);
}
/// <summary>
/// Release packet
/// </summary>
/// <param name="packet">SNI packet</param>
public void PacketRelease(SNIPacket packet)
{
packet.Release();
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public uint CheckConnection(SNIHandle handle)
{
return handle.CheckConnection();
}
/// <summary>
/// Get last SNI error on this thread
/// </summary>
/// <returns></returns>
public SNIError GetLastError()
{
return SNILoadHandle.SingletonInstance.LastError;
}
/// <summary>
/// Gets the Local db Named pipe data source if the input is a localDB server.
/// </summary>
/// <param name="fullServerName">The data source</param>
/// <param name="error">Set true when an error occured while getting LocalDB up</param>
/// <returns></returns>
private string GetLocalDBDataSource(string fullServerName, out bool error)
{
string localDBConnectionString = null;
bool isBadLocalDBDataSource;
string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out isBadLocalDBDataSource);
if (isBadLocalDBDataSource)
{
error = true;
return null;
}
else if (!string.IsNullOrEmpty(localDBInstance))
{
// We have successfully received a localDBInstance which is valid.
Debug.Assert(!string.IsNullOrWhiteSpace(localDBInstance), "Local DB Instance name cannot be empty.");
localDBConnectionString = LocalDB.GetLocalDBConnectionString(localDBInstance);
if (fullServerName == null)
{
// The Last error is set in LocalDB.GetLocalDBConnectionString. We don't need to set Last here.
error = true;
return null;
}
}
error = false;
return localDBConnectionString;
}
}
internal class DataSource
{
private const char CommaSeparator = ',';
private const char BackSlashSeparator = '\\';
private const string DefaultHostName = "localhost";
private const string DefaultSqlServerInstanceName = "mssqlserver";
private const string PipeBeginning = @"\\";
private const string PipeToken = "pipe";
private const string LocalDbHost = "(localdb)";
private const string NamedPipeInstanceNameHeader = "mssql$";
private const string DefaultPipeName = "sql\\query";
internal enum Protocol { TCP, NP, None, Admin };
internal Protocol ConnectionProtocol = Protocol.None;
/// <summary>
/// Provides the HostName of the server to connect to for TCP protocol.
/// This information is also used for finding the SPN of SqlServer
/// </summary>
internal string ServerName { get; private set; }
/// <summary>
/// Provides the port on which the TCP connection should be made if one was specified in Data Source
/// </summary>
internal int Port { get; private set; } = -1;
/// <summary>
/// Provides the inferred Instance Name from Server Data Source
/// </summary>
public string InstanceName { get; internal set; }
/// <summary>
/// Provides the pipe name in case of Named Pipes
/// </summary>
public string PipeName { get; internal set; }
/// <summary>
/// Provides the HostName to connect to in case of Named pipes Data Source
/// </summary>
public string PipeHostName { get; internal set; }
private string _workingDataSource;
private string _dataSourceAfterTrimmingProtocol;
internal bool IsBadDataSource { get; private set; } = false;
internal bool IsSsrpRequired { get; private set; } = false;
private DataSource(string dataSource)
{
// Remove all whitespaces from the datasource and all operations will happen on lower case.
_workingDataSource = dataSource.Trim().ToLowerInvariant();
int firstIndexOfColon = _workingDataSource.IndexOf(':');
PopulateProtocol();
_dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && ConnectionProtocol != DataSource.Protocol.None
? _workingDataSource.Substring(firstIndexOfColon + 1).Trim() : _workingDataSource;
if (_dataSourceAfterTrimmingProtocol.Contains("/")) // Pipe paths only allow back slashes
{
if (ConnectionProtocol == DataSource.Protocol.None)
ReportSNIError(SNIProviders.INVALID_PROV);
else if (ConnectionProtocol == DataSource.Protocol.NP)
ReportSNIError(SNIProviders.NP_PROV);
else if (ConnectionProtocol == DataSource.Protocol.TCP)
ReportSNIError(SNIProviders.TCP_PROV);
}
}
private void PopulateProtocol()
{
string[] splitByColon = _workingDataSource.Split(':');
if (splitByColon.Length <= 1)
{
ConnectionProtocol = DataSource.Protocol.None;
}
else
{
// We trim before switching because " tcp : server , 1433 " is a valid data source
switch (splitByColon[0].Trim())
{
case TdsEnums.TCP:
ConnectionProtocol = DataSource.Protocol.TCP;
break;
case TdsEnums.NP:
ConnectionProtocol = DataSource.Protocol.NP;
break;
case TdsEnums.ADMIN:
ConnectionProtocol = DataSource.Protocol.Admin;
break;
default:
// None of the supported protocols were found. This may be a IPv6 address
ConnectionProtocol = DataSource.Protocol.None;
break;
}
}
}
public static string GetLocalDBInstance(string dataSource, out bool error)
{
string instanceName = null;
string workingDataSource = dataSource.ToLowerInvariant();
string[] tokensByBackSlash = workingDataSource.Split(BackSlashSeparator);
error = false;
// All LocalDb endpoints are of the format host\instancename where host is always (LocalDb) (case-insensitive)
if (tokensByBackSlash.Length == 2 && LocalDbHost.Equals(tokensByBackSlash[0].TrimStart()))
{
if (!string.IsNullOrWhiteSpace(tokensByBackSlash[1]))
{
instanceName = tokensByBackSlash[1].Trim();
}
else
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBNoInstanceName, string.Empty);
error = true;
return null;
}
}
return instanceName;
}
public static DataSource ParseServerName(string dataSource)
{
DataSource details = new DataSource(dataSource);
if (details.IsBadDataSource)
{
return null;
}
if (details.InferNamedPipesInformation())
{
return details;
}
if (details.IsBadDataSource)
{
return null;
}
if (details.InferConnectionDetails())
{
return details;
}
return null;
}
private void InferLocalServerName()
{
// If Server name is empty or localhost, then use "localhost"
if (string.IsNullOrEmpty(ServerName) || IsLocalHost(ServerName))
{
ServerName = ConnectionProtocol == DataSource.Protocol.Admin ?
Environment.MachineName : DefaultHostName;
}
}
private bool InferConnectionDetails()
{
string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator, ',');
ServerName = tokensByCommaAndSlash[0].Trim();
int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(',');
int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(BackSlashSeparator);
// Check the parameters. The parameters are Comma separated in the Data Source. The parameter we really care about is the port
// If Comma exists, the try to get the port number
if (commaIndex > -1)
{
string parameter = backSlashIndex > -1
? ((commaIndex > backSlashIndex) ? tokensByCommaAndSlash[2].Trim() : tokensByCommaAndSlash[1].Trim())
: tokensByCommaAndSlash[1].Trim();
// Bad Data Source like "server, "
if (string.IsNullOrEmpty(parameter))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
// For Tcp and Only Tcp are parameters allowed.
if (ConnectionProtocol == DataSource.Protocol.None)
{
ConnectionProtocol = DataSource.Protocol.TCP;
}
else if (ConnectionProtocol != DataSource.Protocol.TCP)
{
// Parameter has been specified for non-TCP protocol. This is not allowed.
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
int port;
if (!int.TryParse(parameter, out port))
{
ReportSNIError(SNIProviders.TCP_PROV);
return false;
}
// If the user explicitly specified a invalid port in the connection string.
if (port < 1)
{
ReportSNIError(SNIProviders.TCP_PROV);
return false;
}
Port = port;
}
// Instance Name Handling. Only if we found a '\' and we did not find a port in the Data Source
else if (backSlashIndex > -1)
{
// This means that there will not be any part separated by comma.
InstanceName = tokensByCommaAndSlash[1].Trim();
if (string.IsNullOrWhiteSpace(InstanceName))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
if (DefaultSqlServerInstanceName.Equals(InstanceName))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
IsSsrpRequired = true;
}
InferLocalServerName();
return true;
}
private void ReportSNIError(SNIProviders provider)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, 0, SNICommon.InvalidConnStringError, string.Empty);
IsBadDataSource = true;
}
private bool InferNamedPipesInformation()
{
// If we have a datasource beginning with a pipe or we have already determined that the protocol is Named Pipe
if (_dataSourceAfterTrimmingProtocol.StartsWith(PipeBeginning) || ConnectionProtocol == Protocol.NP)
{
// If the data source is "np:servername"
if (!_dataSourceAfterTrimmingProtocol.Contains(BackSlashSeparator))
{
PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol;
InferLocalServerName();
PipeName = SNINpHandle.DefaultPipePath;
return true;
}
try
{
string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator);
// The datasource is of the format \\host\pipe\sql\query [0]\[1]\[2]\[3]\[4]\[5]
// It would at least have 6 parts.
// Another valid Sql named pipe for an named instance is \\.\pipe\MSSQL$MYINSTANCE\sql\query
if (tokensByBackSlash.Length < 6)
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
string host = tokensByBackSlash[2];
if (string.IsNullOrEmpty(host))
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
//Check if the "pipe" keyword is the first part of path
if (!PipeToken.Equals(tokensByBackSlash[3]))
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
if (tokensByBackSlash[4].StartsWith(NamedPipeInstanceNameHeader))
{
InstanceName = tokensByBackSlash[4].Substring(NamedPipeInstanceNameHeader.Length);
}
StringBuilder pipeNameBuilder = new StringBuilder();
for (int i = 4; i < tokensByBackSlash.Length - 1; i++)
{
pipeNameBuilder.Append(tokensByBackSlash[i]);
pipeNameBuilder.Append(Path.DirectorySeparatorChar);
}
// Append the last part without a "/"
pipeNameBuilder.Append(tokensByBackSlash[tokensByBackSlash.Length - 1]);
PipeName = pipeNameBuilder.ToString();
if (string.IsNullOrWhiteSpace(InstanceName) && !DefaultPipeName.Equals(PipeName))
{
InstanceName = PipeToken + PipeName;
}
ServerName = IsLocalHost(host) ? Environment.MachineName : host;
// Pipe hostname is the hostname after leading \\ which should be passed down as is to open Named Pipe.
// For Named Pipes the ServerName makes sense for SPN creation only.
PipeHostName = host;
}
catch (UriFormatException)
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
// DataSource is something like "\\pipename"
if (ConnectionProtocol == DataSource.Protocol.None)
{
ConnectionProtocol = DataSource.Protocol.NP;
}
else if (ConnectionProtocol != DataSource.Protocol.NP)
{
// In case the path began with a "\\" and protocol was not Named Pipes
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
return true;
}
return false;
}
private static bool IsLocalHost(string serverName)
=> ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName);
}
}
| |
/*
* 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.
*/
/*
* Created on May 21, 2005
*
*/
namespace NPOI.SS.Formula.Functions
{
using System;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*
* This class Is a functon library for common fiscal functions.
* <b>Glossary of terms/abbreviations:</b>
* <br/>
* <ul>
* <li><em>FV:</em> Future Value</li>
* <li><em>PV:</em> Present Value</li>
* <li><em>NPV:</em> Net Present Value</li>
* <li><em>PMT:</em> (Periodic) Payment</li>
*
* </ul>
* For more info on the terms/abbreviations please use the references below
* (hyperlinks are subject to Change):
* <br/>Online References:
* <ol>
* <li>GNU Emacs Calc 2.02 Manual: http://theory.uwinnipeg.ca/gnu/calc/calc_203.html</li>
* <li>Yahoo Financial Glossary: http://biz.yahoo.com/f/g/nn.html#y</li>
* <li>MS Excel function reference: http://office.microsoft.com/en-us/assistance/CH062528251033.aspx</li>
* </ol>
* <h3>Implementation Notes:</h3>
* Symbols used in the formulae that follow:<br/>
* <ul>
* <li>p: present value</li>
* <li>f: future value</li>
* <li>n: number of periods</li>
* <li>y: payment (in each period)</li>
* <li>r: rate</li>
* <li>^: the power operator (NOT the java bitwise XOR operator!)</li>
* </ul>
* [From MS Excel function reference] Following are some of the key formulas
* that are used in this implementation:
* <pre>
* p(1+r)^n + y(1+rt)((1+r)^n-1)/r + f=0 ...{when r!=0}
* ny + p + f=0 ...{when r=0}
* </pre>
*/
internal class FinanceLib
{
// constants for default values
private FinanceLib() { }
/**
* Future value of an amount given the number of payments, rate, amount
* of individual payment, present value and bool value indicating whether
* payments are due at the beginning of period
* (false => payments are due at end of period)
* @param r rate
* @param n num of periods
* @param y pmt per period
* @param p future value
* @param t type (true=pmt at end of period, false=pmt at begining of period)
*/
public static double fv(double r, double n, double y, double p, bool t)
{
double retval = 0;
if (r == 0)
{
retval = -1 * (p + (n * y));
}
else
{
double r1 = r + 1;
retval = ((1 - Math.Pow(r1, n)) * (t ? r1 : 1) * y) / r
-
p * Math.Pow(r1, n);
}
return retval;
}
/**
* Present value of an amount given the number of future payments, rate, amount
* of individual payment, future value and bool value indicating whether
* payments are due at the beginning of period
* (false => payments are due at end of period)
* @param r
* @param n
* @param y
* @param f
* @param t
*/
public static double pv(double r, double n, double y, double f, bool t)
{
double retval = 0;
if (r == 0)
{
retval = -1 * ((n * y) + f);
}
else
{
double r1 = r + 1;
retval = (((1 - Math.Pow(r1, n)) / r) * (t ? r1 : 1) * y - f)
/
Math.Pow(r1, n);
}
return retval;
}
/**
* calculates the Net Present Value of a principal amount
* given the disCount rate and a sequence of cash flows
* (supplied as an array). If the amounts are income the value should
* be positive, else if they are payments and not income, the
* value should be negative.
* @param r
* @param cfs cashflow amounts
*/
public static double npv(double r, double[] cfs)
{
double npv = 0;
double r1 = r + 1;
double trate = r1;
for (int i = 0, iSize = cfs.Length; i < iSize; i++)
{
npv += cfs[i] / trate;
trate *= r1;
}
return npv;
}
/**
*
* @param r
* @param n
* @param p
* @param f
* @param t
*/
public static double pmt(double r, double n, double p, double f, bool t)
{
double retval = 0;
if (r == 0)
{
retval = -1 * (f + p) / n;
}
else
{
double r1 = r + 1;
retval = (f + p * Math.Pow(r1, n)) * r
/
((t ? r1 : 1) * (1 - Math.Pow(r1, n)));
}
return retval;
}
/**
*
* @param r
* @param y
* @param p
* @param f
* @param t
*/
public static double nper(double r, double y, double p, double f, bool t)
{
double retval = 0;
if (r == 0)
{
retval = -1 * (f + p) / y;
}
else
{
double r1 = r + 1;
double ryr = (t ? r1 : 1) * y / r;
double a1 = ((ryr - f) < 0)
? Math.Log(f - ryr)
: Math.Log(ryr - f);
double a2 = ((ryr - f) < 0)
? Math.Log(-p - ryr)
: Math.Log(p + ryr);
double a3 = Math.Log(r1);
retval = (a1 - a2) / a3;
}
return retval;
}
}
}
| |
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.IO;
namespace Lucene.Net.Analysis
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AlreadyClosedException = Lucene.Net.Store.AlreadyClosedException;
/// <summary>
/// An Analyzer builds TokenStreams, which analyze text. It thus represents a
/// policy for extracting index terms from text.
/// <p>
/// In order to define what analysis is done, subclasses must define their
/// <seealso cref="TokenStreamComponents TokenStreamComponents"/> in <seealso cref="#createComponents(String, Reader)"/>.
/// The components are then reused in each call to <seealso cref="#tokenStream(String, Reader)"/>.
/// <p>
/// Simple example:
/// <pre class="prettyprint">
/// Analyzer analyzer = new Analyzer() {
/// {@literal @Override}
/// protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
/// Tokenizer source = new FooTokenizer(reader);
/// TokenStream filter = new FooFilter(source);
/// filter = new BarFilter(filter);
/// return new TokenStreamComponents(source, filter);
/// }
/// };
/// </pre>
/// For more examples, see the <seealso cref="Lucene.Net.Analysis Analysis package documentation"/>.
/// <p>
/// For some concrete implementations bundled with Lucene, look in the analysis modules:
/// <ul>
/// <li><a href="{@docRoot}/../analyzers-common/overview-summary.html">Common</a>:
/// Analyzers for indexing content in different languages and domains.
/// <li><a href="{@docRoot}/../analyzers-icu/overview-summary.html">ICU</a>:
/// Exposes functionality from ICU to Apache Lucene.
/// <li><a href="{@docRoot}/../analyzers-kuromoji/overview-summary.html">Kuromoji</a>:
/// Morphological analyzer for Japanese text.
/// <li><a href="{@docRoot}/../analyzers-morfologik/overview-summary.html">Morfologik</a>:
/// Dictionary-driven lemmatization for the Polish language.
/// <li><a href="{@docRoot}/../analyzers-phonetic/overview-summary.html">Phonetic</a>:
/// Analysis for indexing phonetic signatures (for sounds-alike search).
/// <li><a href="{@docRoot}/../analyzers-smartcn/overview-summary.html">Smart Chinese</a>:
/// Analyzer for Simplified Chinese, which indexes words.
/// <li><a href="{@docRoot}/../analyzers-stempel/overview-summary.html">Stempel</a>:
/// Algorithmic Stemmer for the Polish Language.
/// <li><a href="{@docRoot}/../analyzers-uima/overview-summary.html">UIMA</a>:
/// Analysis integration with Apache UIMA.
/// </ul>
/// </summary>
public abstract class Analyzer : IDisposable
{
private readonly ReuseStrategy _reuseStrategy;
// non final as it gets nulled if closed; pkg private for access by ReuseStrategy's final helper methods:
internal IDisposableThreadLocal<object> StoredValue = new IDisposableThreadLocal<object>();
/// <summary>
/// Create a new Analyzer, reusing the same set of components per-thread
/// across calls to <seealso cref="#tokenStream(String, Reader)"/>.
/// </summary>
protected Analyzer()
: this(GLOBAL_REUSE_STRATEGY)
{
}
/// <summary>
/// Expert: create a new Analyzer with a custom <seealso cref="ReuseStrategy"/>.
/// <p>
/// NOTE: if you just want to reuse on a per-field basis, its easier to
/// use a subclass of <seealso cref="AnalyzerWrapper"/> such as
/// <a href="{@docRoot}/../analyzers-common/Lucene.Net.Analysis/miscellaneous/PerFieldAnalyzerWrapper.html">
/// PerFieldAnalyerWrapper</a> instead.
/// </summary>
protected Analyzer(ReuseStrategy reuseStrategy)
{
this._reuseStrategy = reuseStrategy;
}
/// <summary>
/// Creates a new <seealso cref="TokenStreamComponents"/> instance for this analyzer.
/// </summary>
/// <param name="fieldName">
/// the name of the fields content passed to the
/// <seealso cref="TokenStreamComponents"/> sink as a reader </param>
/// <param name="reader">
/// the reader passed to the <seealso cref="Tokenizer"/> constructor </param>
/// <returns> the <seealso cref="TokenStreamComponents"/> for this analyzer. </returns>
public abstract TokenStreamComponents CreateComponents(string fieldName, TextReader reader);
/// <summary>
/// Returns a TokenStream suitable for <code>fieldName</code>, tokenizing
/// the contents of <code>text</code>.
/// <p>
/// this method uses <seealso cref="#createComponents(String, Reader)"/> to obtain an
/// instance of <seealso cref="TokenStreamComponents"/>. It returns the sink of the
/// components and stores the components internally. Subsequent calls to this
/// method will reuse the previously stored components after resetting them
/// through <seealso cref="TokenStreamComponents#setReader(Reader)"/>.
/// <p>
/// <b>NOTE:</b> After calling this method, the consumer must follow the
/// workflow described in <seealso cref="TokenStream"/> to properly consume its contents.
/// See the <seealso cref="Lucene.Net.Analysis Analysis package documentation"/> for
/// some examples demonstrating this.
/// </summary>
/// <param name="fieldName"> the name of the field the created TokenStream is used for </param>
/// <param name="text"> the String the streams source reads from </param>
/// <returns> TokenStream for iterating the analyzed content of <code>reader</code> </returns>
/// <exception cref="AlreadyClosedException"> if the Analyzer is closed. </exception>
/// <exception cref="IOException"> if an i/o error occurs (may rarely happen for strings). </exception>
/// <seealso cref= #tokenStream(String, Reader) </seealso>
public TokenStream TokenStream(string fieldName, TextReader reader)
{
TokenStreamComponents components = _reuseStrategy.GetReusableComponents(this, fieldName);
TextReader r = InitReader(fieldName, reader);
if (components == null)
{
components = CreateComponents(fieldName, r);
_reuseStrategy.SetReusableComponents(this, fieldName, components);
}
else
{
components.Reader = r;// LUCENENET TODO new TextReaderWrapper(r);
}
return components.TokenStream;
}
public TokenStream TokenStream(string fieldName, string text)
{
TokenStreamComponents components = _reuseStrategy.GetReusableComponents(this, fieldName);
ReusableStringReader strReader =
(components == null || components.ReusableStringReader == null)
? new ReusableStringReader()
: components.ReusableStringReader;
strReader.Value = text;
var r = InitReader(fieldName, strReader);
if (components == null)
{
components = CreateComponents(fieldName, r);
_reuseStrategy.SetReusableComponents(this, fieldName, components);
}
else
{
components.Reader = r;
}
components.ReusableStringReader = strReader;
return components.TokenStream;
}
/// <summary>
/// Override this if you want to add a CharFilter chain.
/// <p>
/// The default implementation returns <code>reader</code>
/// unchanged.
/// </summary>
/// <param name="fieldName"> IndexableField name being indexed </param>
/// <param name="reader"> original Reader </param>
/// <returns> reader, optionally decorated with CharFilter(s) </returns>
public virtual TextReader InitReader(string fieldName, TextReader reader)
{
return reader;
}
/// <summary>
/// Invoked before indexing a IndexableField instance if
/// terms have already been added to that field. this allows custom
/// analyzers to place an automatic position increment gap between
/// IndexbleField instances using the same field name. The default value
/// position increment gap is 0. With a 0 position increment gap and
/// the typical default token position increment of 1, all terms in a field,
/// including across IndexableField instances, are in successive positions, allowing
/// exact PhraseQuery matches, for instance, across IndexableField instance boundaries.
/// </summary>
/// <param name="fieldName"> IndexableField name being indexed. </param>
/// <returns> position increment gap, added to the next token emitted from <seealso cref="#tokenStream(String,Reader)"/>.
/// this value must be {@code >= 0}. </returns>
public virtual int GetPositionIncrementGap(string fieldName)
{
return 0;
}
/// <summary>
/// Just like <seealso cref="#getPositionIncrementGap"/>, except for
/// Token offsets instead. By default this returns 1.
/// this method is only called if the field
/// produced at least one token for indexing.
/// </summary>
/// <param name="fieldName"> the field just indexed </param>
/// <returns> offset gap, added to the next token emitted from <seealso cref="#tokenStream(String,Reader)"/>.
/// this value must be {@code >= 0}. </returns>
public virtual int GetOffsetGap(string fieldName)
{
return 1;
}
/// <summary>
/// Returns the used <seealso cref="ReuseStrategy"/>.
/// </summary>
public ReuseStrategy Strategy
{
get
{
return _reuseStrategy;
}
}
/// <summary>
/// Frees persistent resources used by this Analyzer </summary>
public void Dispose()
{
if (StoredValue != null)
{
StoredValue.Dispose();
StoredValue = null;
}
}
/// <summary>
/// this class encapsulates the outer components of a token stream. It provides
/// access to the source (<seealso cref="Tokenizer"/>) and the outer end (sink), an
/// instance of <seealso cref="TokenFilter"/> which also serves as the
/// <seealso cref="TokenStream"/> returned by
/// <seealso cref="Analyzer#tokenStream(String, Reader)"/>.
/// </summary>
public class TokenStreamComponents
{
/// <summary>
/// Original source of the tokens.
/// </summary>
protected internal readonly Tokenizer Source;
/// <summary>
/// Sink tokenstream, such as the outer tokenfilter decorating
/// the chain. this can be the source if there are no filters.
/// </summary>
protected internal readonly TokenStream Sink;
/// <summary>
/// Internal cache only used by <seealso cref="Analyzer#tokenStream(String, String)"/>. </summary>
[NonSerialized]
internal ReusableStringReader ReusableStringReader;
/// <summary>
/// Creates a new <seealso cref="TokenStreamComponents"/> instance.
/// </summary>
/// <param name="source">
/// the analyzer's tokenizer </param>
/// <param name="result">
/// the analyzer's resulting token stream </param>
public TokenStreamComponents(Tokenizer source, TokenStream result)
{
this.Source = source;
this.Sink = result;
}
/// <summary>
/// Creates a new <seealso cref="TokenStreamComponents"/> instance.
/// </summary>
/// <param name="source">
/// the analyzer's tokenizer </param>
public TokenStreamComponents(Tokenizer source)
{
this.Source = source;
this.Sink = source;
}
/// <summary>
/// Resets the encapsulated components with the given reader. If the components
/// cannot be reset, an Exception should be thrown.
/// </summary>
/// <param name="reader">
/// a reader to reset the source component </param>
/// <exception cref="IOException">
/// if the component's reset method throws an <seealso cref="IOException"/> </exception>
protected internal virtual TextReader Reader
{
set
{
Source.Reader = value;
}
}
/// <summary>
/// Returns the sink <seealso cref="TokenStream"/>
/// </summary>
/// <returns> the sink <seealso cref="TokenStream"/> </returns>
public virtual TokenStream TokenStream
{
get
{
return Sink;
}
}
/// <summary>
/// Returns the component's <seealso cref="Tokenizer"/>
/// </summary>
/// <returns> Component's <seealso cref="Tokenizer"/> </returns>
public virtual Tokenizer Tokenizer
{
get
{
return Source;
}
}
}
/// <summary>
/// Strategy defining how TokenStreamComponents are reused per call to
/// <seealso cref="Analyzer#tokenStream(String, java.io.Reader)"/>.
/// </summary>
public abstract class ReuseStrategy
{
/// <summary>
/// Gets the reusable TokenStreamComponents for the field with the given name.
/// </summary>
/// <param name="analyzer"> Analyzer from which to get the reused components. Use
/// <seealso cref="#getStoredValue(Analyzer)"/> and <seealso cref="#setStoredValue(Analyzer, Object)"/>
/// to access the data on the Analyzer. </param>
/// <param name="fieldName"> Name of the field whose reusable TokenStreamComponents
/// are to be retrieved </param>
/// <returns> Reusable TokenStreamComponents for the field, or {@code null}
/// if there was no previous components for the field </returns>
public abstract TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName);
/// <summary>
/// Stores the given TokenStreamComponents as the reusable components for the
/// field with the give name.
/// </summary>
/// <param name="fieldName"> Name of the field whose TokenStreamComponents are being set </param>
/// <param name="components"> TokenStreamComponents which are to be reused for the field </param>
public abstract void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components);
/// <summary>
/// Returns the currently stored value.
/// </summary>
/// <returns> Currently stored value or {@code null} if no value is stored </returns>
/// <exception cref="AlreadyClosedException"> if the Analyzer is closed. </exception>
protected internal object GetStoredValue(Analyzer analyzer)
{
if (analyzer.StoredValue == null)
{
throw new AlreadyClosedException("this Analyzer is closed");
}
return analyzer.StoredValue.Get();
}
/// <summary>
/// Sets the stored value.
/// </summary>
/// <param name="storedValue"> Value to store </param>
/// <exception cref="AlreadyClosedException"> if the Analyzer is closed. </exception>
protected internal void SetStoredValue(Analyzer analyzer, object storedValue)
{
if (analyzer.StoredValue == null)
{
throw new AlreadyClosedException("this Analyzer is closed");
}
analyzer.StoredValue.Set(storedValue);
}
}
/// <summary>
/// A predefined <seealso cref="ReuseStrategy"/> that reuses the same components for
/// every field.
/// </summary>
public static readonly ReuseStrategy GLOBAL_REUSE_STRATEGY = new GlobalReuseStrategy();
/// <summary>
/// Implementation of <seealso cref="ReuseStrategy"/> that reuses the same components for
/// every field. </summary>
/// @deprecated this implementation class will be hidden in Lucene 5.0.
/// Use <seealso cref="Analyzer#GLOBAL_REUSE_STRATEGY"/> instead!
[Obsolete("this implementation class will be hidden in Lucene 5.0.")]
public sealed class GlobalReuseStrategy : ReuseStrategy
/// <summary>
/// Sole constructor. (For invocation by subclass constructors, typically implicit.) </summary>
/// @deprecated Don't create instances of this class, use <seealso cref="Analyzer#GLOBAL_REUSE_STRATEGY"/>
{
public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName)
{
return (TokenStreamComponents)GetStoredValue(analyzer);
}
public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components)
{
SetStoredValue(analyzer, components);
}
}
/// <summary>
/// A predefined <seealso cref="ReuseStrategy"/> that reuses components per-field by
/// maintaining a Map of TokenStreamComponent per field name.
/// </summary>
public static readonly ReuseStrategy PER_FIELD_REUSE_STRATEGY = new PerFieldReuseStrategy();
/// <summary>
/// Implementation of <seealso cref="ReuseStrategy"/> that reuses components per-field by
/// maintaining a Map of TokenStreamComponent per field name. </summary>
/// @deprecated this implementation class will be hidden in Lucene 5.0.
/// Use <seealso cref="Analyzer#PER_FIELD_REUSE_STRATEGY"/> instead!
[Obsolete("this implementation class will be hidden in Lucene 5.0.")]
public class PerFieldReuseStrategy : ReuseStrategy
/// <summary>
/// Sole constructor. (For invocation by subclass constructors, typically implicit.) </summary>
/// @deprecated Don't create instances of this class, use <seealso cref="Analyzer#PER_FIELD_REUSE_STRATEGY"/>
{
public PerFieldReuseStrategy()
{
}
public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName)
{
var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer);
if (componentsPerField != null)
{
TokenStreamComponents ret;
componentsPerField.TryGetValue(fieldName, out ret);
return ret;
}
return null;
}
public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components)
{
var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer);
if (componentsPerField == null)
{
componentsPerField = new Dictionary<string, TokenStreamComponents>();
SetStoredValue(analyzer, componentsPerField);
}
componentsPerField[fieldName] = components;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Concurrency;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using Orleans.Serialization;
using UnitTests.GrainInterfaces;
using Xunit;
using Orleans.Storage;
namespace UnitTests.Grains
{
internal static class TestRuntimeEnvironmentUtility
{
public static string CaptureRuntimeEnvironment()
{
var callStack = Utils.GetStackTrace(1); // Don't include this method in stack trace
return String.Format(
" TaskScheduler={0}" + Environment.NewLine
+ " RuntimeContext={1}" + Environment.NewLine
+ " WorkerPoolThread={2}" + Environment.NewLine
+ " Thread.CurrentThread.ManagedThreadId={4}" + Environment.NewLine
+ " StackTrace=" + Environment.NewLine
+ " {5}",
TaskScheduler.Current,
RuntimeContext.Current,
Thread.CurrentThread.Name,
Thread.CurrentThread.ManagedThreadId,
callStack);
}
}
[Serializable]
[GenerateSerializer]
public class PersistenceTestGrainState
{
public PersistenceTestGrainState()
{
SortedDict = new SortedDictionary<int, int>();
}
[Id(0)]
public int Field1 { get; set; }
[Id(1)]
public string Field2 { get; set; }
[Id(2)]
public SortedDictionary<int, int> SortedDict { get; set; }
}
[Serializable]
[GenerateSerializer]
public class PersistenceGenericGrainState<T>
{
[Id(0)]
public T Field1 { get; set; }
[Id(1)]
public string Field2 { get; set; }
[Id(2)]
public SortedDictionary<T, T> SortedDict { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceTestGrain : Grain<PersistenceTestGrainState>, IPersistenceTestGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<bool> CheckStateInit()
{
Assert.NotNull(State);
Assert.Equal(0, State.Field1);
Assert.Null(State.Field2);
//Assert.NotNull(State.Field3, "Null Field3");
//Assert.AreEqual(0, State.Field3.Count, "Field3 = {0}", String.Join("'", State.Field3));
Assert.NotNull(State.SortedDict);
return Task.FromResult(true);
}
public Task<string> CheckProviderType()
{
IGrainStorage grainStorage = this.GetGrainStorage(this.ServiceProvider);
Assert.NotNull(grainStorage);
return Task.FromResult(grainStorage.GetType().FullName);
}
public Task DoSomething()
{
return Task.CompletedTask;
}
public Task DoWrite(int val)
{
State.Field1 = val;
State.SortedDict[val] = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync();
return State.Field1;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public async Task DoDelete()
{
await ClearStateAsync();
}
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceTestGenericGrain<T> : PersistenceTestGrain, IPersistenceTestGenericGrain<T>
{
//...
}
[Orleans.Providers.StorageProvider(ProviderName = "ErrorInjector")]
public class PersistenceProviderErrorGrain : Grain<PersistenceTestGrainState>, IPersistenceProviderErrorGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync();
return State.Field1;
}
public Task<string> GetActivationId() => Task.FromResult(this.Data.ActivationId.ToString());
}
[Orleans.Providers.StorageProvider(ProviderName = "ErrorInjector")]
public class PersistenceUserHandledErrorGrain : Grain<PersistenceTestGrainState>, IPersistenceUserHandledErrorGrain
{
private readonly ILogger logger;
private readonly DeepCopier<PersistenceTestGrainState> copier;
public PersistenceUserHandledErrorGrain(ILoggerFactory loggerFactory, DeepCopier<PersistenceTestGrainState> copier)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
this.copier = copier;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public async Task DoWrite(int val, bool recover)
{
var original = this.copier.Copy(State);
try
{
State.Field1 = val;
await WriteStateAsync();
}
catch (Exception exc)
{
if (!recover) throw;
this.logger.Warn(0, "Grain is handling error in DoWrite - Resetting value to " + original, exc);
State = (PersistenceTestGrainState)original;
}
}
public async Task<int> DoRead(bool recover)
{
var original = this.copier.Copy(State);
try
{
await ReadStateAsync();
}
catch (Exception exc)
{
if (!recover) throw;
this.logger.Warn(0, "Grain is handling error in DoRead - Resetting value to " + original, exc);
State = (PersistenceTestGrainState)original;
}
return State.Field1;
}
}
public class PersistenceProviderErrorProxyGrain : Grain, IPersistenceProviderErrorProxyGrain
{
public Task<int> GetValue(IPersistenceProviderErrorGrain other) => other.GetValue();
public Task DoWrite(int val, IPersistenceProviderErrorGrain other) => other.DoWrite(val);
public Task<int> DoRead(IPersistenceProviderErrorGrain other) => other.DoRead();
public Task<string> GetActivationId() => Task.FromResult(this.Data.ActivationId.ToString());
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceErrorGrain : Grain<PersistenceTestGrainState>, IPersistenceErrorGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task DoWriteError(int val, bool errorBeforeUpdate)
{
if (errorBeforeUpdate) throw new ApplicationException("Before Update");
State.Field1 = val;
await WriteStateAsync();
throw new ApplicationException("After Update");
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public async Task<int> DoReadError(bool errorBeforeRead)
{
if (errorBeforeRead) throw new ApplicationException("Before Read");
await ReadStateAsync(); // Attempt to re-read state from store
throw new ApplicationException("After Read");
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MissingProvider")]
public class BadProviderTestGrain : Grain<PersistenceTestGrainState>, IBadProviderTestGrain
{
private readonly ILogger logger;
public BadProviderTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.logger.Warn(1, "OnActivateAsync");
return Task.CompletedTask;
}
public Task DoSomething()
{
this.logger.Warn(1, "DoSomething");
throw new ApplicationException(
"BadProviderTestGrain.DoSomething should never get called when provider is missing");
}
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceNoStateTestGrain : Grain, IPersistenceNoStateTestGrain
{
private readonly ILogger logger;
public PersistenceNoStateTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.logger.Info(1, "OnActivateAsync");
return Task.CompletedTask;
}
public Task DoSomething()
{
this.logger.Info(1, "DoSomething");
return Task.CompletedTask;
}
}
public class ServiceIdGrain : Grain, IServiceIdGrain
{
private readonly IOptions<ClusterOptions> clusterOptions;
public ServiceIdGrain(IOptions<ClusterOptions> clusterOptions)
{
this.clusterOptions = clusterOptions;
}
public Task<string> GetServiceId()
{
return Task.FromResult(clusterOptions.Value.ServiceId);
}
}
[Orleans.Providers.StorageProvider(ProviderName = "GrainStorageForTest")]
public class GrainStorageTestGrain : Grain<PersistenceTestGrainState>,
IGrainStorageTestGrain, IGrainStorageTestGrain_LongKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "GrainStorageForTest")]
public class GrainStorageGenericGrain<T> : Grain<PersistenceGenericGrainState<T>>,
IGrainStorageGenericGrain<T>
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<T> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(T val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<T> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "GrainStorageForTest")]
public class GrainStorageTestGrainExtendedKey : Grain<PersistenceTestGrainState>,
IGrainStorageTestGrain_GuidExtendedKey, IGrainStorageTestGrain_LongExtendedKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task<string> GetExtendedKeyValue()
{
string extKey;
_ = this.GetPrimaryKey(out extKey);
return Task.FromResult(extKey);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "DDBStore")]
public class AWSStorageTestGrain : Grain<PersistenceTestGrainState>,
IAWSStorageTestGrain, IAWSStorageTestGrain_LongKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task<string> GetActivationId() => Task.FromResult(this.Data.ActivationId.ToString());
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "DDBStore")]
public class AWSStorageGenericGrain<T> : Grain<PersistenceGenericGrainState<T>>,
IAWSStorageGenericGrain<T>
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<T> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(T val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<T> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "DDBStore")]
public class AWSStorageTestGrainExtendedKey : Grain<PersistenceTestGrainState>,
IAWSStorageTestGrain_GuidExtendedKey, IAWSStorageTestGrain_LongExtendedKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task<string> GetExtendedKeyValue()
{
string extKey;
_ = this.GetPrimaryKey(out extKey);
return Task.FromResult(extKey);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
//[Orleans.Providers.StorageProvider(ProviderName = "AzureStorageEmulator")]
public class MemoryStorageTestGrain : Grain<MemoryStorageTestGrain.NestedPersistenceTestGrainState>,
IMemoryStorageTestGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync();
}
[Serializable]
[GenerateSerializer]
public class NestedPersistenceTestGrainState
{
[Id(0)]
public int Field1 { get; set; }
[Id(1)]
public string Field2 { get; set; }
[Id(2)]
public SortedDictionary<int, int> SortedDict { get; set; }
}
}
[Serializable]
[GenerateSerializer]
public class UserState
{
public UserState()
{
Friends = new List<IUser>();
}
[Id(0)]
public string Name { get; set; }
[Id(1)]
public string Status { get; set; }
[Id(2)]
public List<IUser> Friends { get; set; }
}
[Serializable]
[GenerateSerializer]
public class DerivedUserState : UserState
{
[Id(0)]
public int Field1 { get; set; }
[Id(1)]
public int Field2 { get; set; }
}
/// <summary>
/// Orleans grain implementation class.
/// </summary>
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
//[Orleans.Providers.StorageProvider(ProviderName = "AzureStore")]
//[Orleans.Providers.StorageProvider(ProviderName = "AzureStorageEmulator")]
public class UserGrain : Grain<DerivedUserState>, IUser
{
public Task SetName(string name)
{
State.Name = name;
return WriteStateAsync();
}
public Task<string> GetStatus()
{
return Task.FromResult(String.Format("{0} : {1}", State.Name, State.Status));
}
public Task<string> GetName()
{
return Task.FromResult(State.Name);
}
public Task UpdateStatus(string status)
{
State.Status = status;
return WriteStateAsync();
}
public Task AddFriend(IUser friend)
{
if (!State.Friends.Contains(friend))
State.Friends.Add(friend);
else
throw new Exception("Already a friend.");
return Task.CompletedTask;
}
public Task<List<IUser>> GetFriends()
{
return Task.FromResult(State.Friends);
}
public async Task<string> GetFriendsStatuses()
{
var sb = new StringBuilder();
var promises = new List<Task<string>>();
foreach (var friend in State.Friends)
promises.Add(friend.GetStatus());
var friends = await Task.WhenAll(promises);
foreach (var f in friends)
{
sb.AppendLine(f);
}
return sb.ToString();
}
}
[Serializable]
[GenerateSerializer]
public class StateForIReentrentGrain
{
public StateForIReentrentGrain()
{
DictOne = new Dictionary<string, int>();
DictTwo = new Dictionary<string, int>();
}
[Id(0)]
public int One { get; set; }
[Id(1)]
public int Two { get; set; }
[Id(2)]
public Dictionary<string, int> DictOne { get; set; }
[Id(3)]
public Dictionary<string, int> DictTwo { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
[Reentrant]
public class ReentrentGrainWithState : Grain<StateForIReentrentGrain>, IReentrentGrainWithState
{
private const int Multiple = 100;
private IReentrentGrainWithState _other;
private IGrainContext _context;
private TaskScheduler _scheduler;
private ILogger logger;
private bool executing;
private Task outstandingWriteStateOperation;
public ReentrentGrainWithState(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
_context = RuntimeContext.CurrentGrainContext;
_scheduler = TaskScheduler.Current;
executing = false;
return base.OnActivateAsync();
}
// When reentrant grain is doing WriteStateAsync, etag violations are posssible due to concurent writes.
// The solution is to serialize all writes, and make sure only a single write is outstanind at any moment in time.
// No deadlocks are posssible with that approach, since all WriteStateAsync go to the store, which does not issue call into grains,
// thus cycle of calls is not posssible.
// Implementaton: need to use While and not if, due to the same "early check becomes later invalid" standard problem, like in conditional variables.
private async Task PerformSerializedStateUpdate()
{
while (outstandingWriteStateOperation != null)
{
await outstandingWriteStateOperation;
}
outstandingWriteStateOperation = WriteStateAsync();
await outstandingWriteStateOperation;
outstandingWriteStateOperation = null;
}
public Task Setup(IReentrentGrainWithState other)
{
logger.Info("Setup");
_other = other;
return Task.CompletedTask;
}
public async Task SetOne(int val)
{
logger.Info("SetOne Start");
CheckRuntimeEnvironment();
var iStr = val.ToString(CultureInfo.InvariantCulture);
State.One = val;
State.DictOne[iStr] = val;
State.DictTwo[iStr] = val;
CheckRuntimeEnvironment();
await PerformSerializedStateUpdate();
CheckRuntimeEnvironment();
}
public async Task SetTwo(int val)
{
logger.Info("SetTwo Start");
CheckRuntimeEnvironment();
var iStr = val.ToString(CultureInfo.InvariantCulture);
State.Two = val;
State.DictTwo[iStr] = val;
State.DictOne[iStr] = val;
CheckRuntimeEnvironment();
await PerformSerializedStateUpdate();
CheckRuntimeEnvironment();
}
public async Task Test1()
{
logger.Info(" ==================================== Test1 Started");
CheckRuntimeEnvironment();
for (var i = 1*Multiple; i < 2*Multiple; i++)
{
var t1 = SetOne(i);
await t1;
CheckRuntimeEnvironment();
var t2 = PerformSerializedStateUpdate();
await t2;
CheckRuntimeEnvironment();
var t3 = _other.SetTwo(i);
await t3;
CheckRuntimeEnvironment();
var t4 = PerformSerializedStateUpdate();
await t4;
CheckRuntimeEnvironment();
}
CheckRuntimeEnvironment();
logger.Info(" ==================================== Test1 Done");
}
public async Task Test2()
{
logger.Info("==================================== Test2 Started");
CheckRuntimeEnvironment();
for (var i = 2*Multiple; i < 3*Multiple; i++)
{
var t1 = _other.SetOne(i);
await t1;
CheckRuntimeEnvironment();
var t2 = PerformSerializedStateUpdate();
await t2;
CheckRuntimeEnvironment();
var t3 = SetTwo(i);
await t3;
CheckRuntimeEnvironment();
var t4 = PerformSerializedStateUpdate();
await t4;
CheckRuntimeEnvironment();
}
CheckRuntimeEnvironment();
logger.Info(" ==================================== Test2 Done");
}
public async Task Task_Delay(bool doStart)
{
var wrapper = new Task(async () =>
{
logger.Info("Before Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(1);
logger.Info("After Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(2);
logger.Info("After Task.Delay #2 TaskScheduler.Current=" + TaskScheduler.Current);
});
if (doStart)
{
wrapper.Start(); // THIS IS THE KEY STEP!
}
await wrapper;
}
private async Task DoDelay(int i)
{
logger.Info("Before Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
await Task.Delay(1);
logger.Info("After Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
}
private void CheckRuntimeEnvironment()
{
if (executing)
{
var errorMsg = "Found out that this grain is already in the middle of execution."
+ " Single threaded-ness violation!\n" +
TestRuntimeEnvironmentUtility.CaptureRuntimeEnvironment();
this.logger.Error(1, "\n\n\n\n" + errorMsg + "\n\n\n\n");
throw new Exception(errorMsg);
//Environment.Exit(1);
}
if (RuntimeContext.CurrentGrainContext == null)
{
var errorMsg = "Found RuntimeContext.Current == null.\n" + TestRuntimeEnvironmentUtility.CaptureRuntimeEnvironment();
this.logger.Error(1, "\n\n\n\n" + errorMsg + "\n\n\n\n");
throw new Exception(errorMsg);
//Environment.Exit(1);
}
var context = RuntimeContext.CurrentGrainContext;
var scheduler = TaskScheduler.Current;
executing = true;
Assert.Equal(_scheduler, scheduler);
Assert.Equal(_context, context);
Assert.NotNull(context);
executing = false;
}
}
internal class NonReentrentStressGrainWithoutState : Grain, INonReentrentStressGrainWithoutState
{
private readonly OrleansTaskScheduler scheduler;
private const int Multiple = 100;
private ILogger logger;
private bool executing;
private const int LEVEL = 2; // level 2 is enough to repro the problem.
private static int _counter = 1;
private int _id;
// HACK for testing
private readonly Tuple<string, Severity>[] overridesOn =
{
new Tuple<string, Severity>("Scheduler", Severity.Verbose),
new Tuple<string, Severity>("Scheduler.ActivationTaskScheduler", Severity.Verbose3)
};
private readonly Tuple<string, Severity>[] overridesOff =
{
new Tuple<string, Severity>("Scheduler", Severity.Info),
new Tuple<string, Severity>("Scheduler.ActivationTaskScheduler", Severity.Info)
};
public NonReentrentStressGrainWithoutState(OrleansTaskScheduler scheduler)
{
this.scheduler = scheduler;
}
public override Task OnActivateAsync()
{
_id = _counter++;
var loggerFactory = this.ServiceProvider?.GetService<ILoggerFactory>();
//if grain created outside a cluster
if (loggerFactory == null)
loggerFactory = NullLoggerFactory.Instance;
logger = loggerFactory.CreateLogger($"NonReentrentStressGrainWithoutState-{_id}");
executing = false;
Log("--> OnActivateAsync");
//#if DEBUG
// // HACK for testing
// Logger.SetTraceLevelOverrides(overridesOn.ToList());
//#endif
Log("<-- OnActivateAsync");
return base.OnActivateAsync();
}
private async Task SetOne(int iter, int level)
{
Log(String.Format("---> SetOne {0}-{1}_0", iter, level));
CheckRuntimeEnvironment("SetOne");
if (level > 0)
{
Log("SetOne {0}-{1}_1. Before await Task.Done.", iter, level);
await Task.CompletedTask;
Log("SetOne {0}-{1}_2. After await Task.Done.", iter, level);
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_3", iter, level));
Log("SetOne {0}-{1}_4. Before await Task.Delay.", iter, level);
await Task.Delay(TimeSpan.FromMilliseconds(10));
Log("SetOne {0}-{1}_5. After await Task.Delay.", iter, level);
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_6", iter, level));
var nextLevel = level - 1;
await SetOne(iter, nextLevel);
Log("SetOne {0}-{1}_7 => {2}. After await SetOne call.", iter, level, nextLevel);
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_8", iter, level));
Log("SetOne {0}-{1}_9. Finished SetOne.", iter, level);
}
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_10", iter, level));
Log("<--- SetOne {0}-{1}_11", iter, level);
}
public async Task Test1()
{
Log(String.Format("Test1.Start"));
CheckRuntimeEnvironment("Test1.BeforeLoop");
var tasks = new List<Task>();
for (var i = 0; i < Multiple; i++)
{
Log("Test1_ ------>" + i);
CheckRuntimeEnvironment(String.Format("Test1_{0}_0", i));
var task = SetOne(i, LEVEL);
Log("After SetOne call " + i);
CheckRuntimeEnvironment(String.Format("Test1_{0}_1", i));
tasks.Add(task);
CheckRuntimeEnvironment(String.Format("Test1_{0}_2", i));
Log("Test1_ <------" + i);
}
CheckRuntimeEnvironment("Test1.AfterLoop");
Log(String.Format("Test1_About to WhenAll"));
await Task.WhenAll(tasks);
Log(String.Format("Test1.Finish"));
CheckRuntimeEnvironment("Test1.Finish-CheckRuntimeEnvironment");
//#if DEBUG
// // HACK for testing
// Logger.SetTraceLevelOverrides(overridesOff.ToList());
//#endif
}
public async Task Task_Delay(bool doStart)
{
var wrapper = new Task(async () =>
{
logger.Info("Before Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(1);
logger.Info("After Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(2);
logger.Info("After Task.Delay #2 TaskScheduler.Current=" + TaskScheduler.Current);
});
if (doStart)
{
wrapper.Start(); // THIS IS THE KEY STEP!
}
await wrapper;
}
private async Task DoDelay(int i)
{
logger.Info("Before Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
await Task.Delay(1);
logger.Info("After Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
}
private void CheckRuntimeEnvironment(string str)
{
var callStack = new StackTrace();
//Log("CheckRuntimeEnvironment - {0} Executing={1}", str, executing);
if (executing)
{
var errorMsg = string.Format(
"Found out that grain {0} is already in the middle of execution."
+ "\n Single threaded-ness violation!"
+ "\n {1} \n Call Stack={2}",
this._id,
TestRuntimeEnvironmentUtility.CaptureRuntimeEnvironment(),
callStack);
this.logger.Error(1, "\n\n\n\n" + errorMsg + "\n\n\n\n");
this.scheduler.DumpSchedulerStatus();
//Environment.Exit(1);
throw new Exception(errorMsg);
}
//Assert.IsFalse(executing, "Found out that this grain is already in the middle of execution. Single threaded-ness violation!");
executing = true;
//Log("CheckRuntimeEnvironment - Start sleep " + str);
Thread.Sleep(10);
executing = false;
//Log("CheckRuntimeEnvironment - End sleep " + str);
}
private void Log(string fmt, params object[] args)
{
var msg = fmt; // +base.CaptureRuntimeEnvironment();
logger.Info(msg, args);
}
}
[Serializable]
[GenerateSerializer]
public class InternalGrainStateData
{
[Id(0)]
public int One { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
internal class InternalGrainWithState : Grain<InternalGrainStateData>, IInternalGrainWithState
{
private ILogger logger;
public InternalGrainWithState(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public Task SetOne(int val)
{
logger.Info("SetOne");
State.One = val;
return Task.CompletedTask;
}
}
public interface IBaseStateData // Note: I am deliberately not using IGrainState here.
{
int Field1 { get; set; }
}
[Serializable]
[GenerateSerializer]
public class StateInheritanceTestGrainData : IBaseStateData
{
[Id(0)]
private int Field2 { get; set; }
[Id(1)]
public int Field1 { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
public class StateInheritanceTestGrain : Grain<StateInheritanceTestGrainData>, IStateInheritanceTestGrain
{
private ILogger logger;
public StateInheritanceTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
return base.OnActivateAsync();
}
public Task<int> GetValue()
{
var val = State.Field1;
logger.Info("GetValue {0}", val);
return Task.FromResult(val);
}
public Task SetValue(int val)
{
State.Field1 = val;
logger.Info("SetValue {0}", val);
return WriteStateAsync();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
/// <summary>
/// Static class containing the WinHttp global callback and associated routines.
/// </summary>
internal static class WinHttpRequestCallback
{
public static Interop.WinHttp.WINHTTP_STATUS_CALLBACK StaticCallbackDelegate =
new Interop.WinHttp.WINHTTP_STATUS_CALLBACK(WinHttpCallback);
public static void WinHttpCallback(
IntPtr handle,
IntPtr context,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
if (NetEventSource.IsEnabled) WinHttpTraceHelper.TraceCallbackStatus(null, handle, context, internetStatus);
if (Environment.HasShutdownStarted)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Environment.HasShutdownStarted returned True");
return;
}
if (context == IntPtr.Zero)
{
return;
}
WinHttpRequestState state = WinHttpRequestState.FromIntPtr(context);
Debug.Assert(state != null, "WinHttpCallback must have a non-null state object");
RequestCallback(handle, state, internetStatus, statusInformation, statusInformationLength);
}
private static void RequestCallback(
IntPtr handle,
WinHttpRequestState state,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
try
{
switch (internetStatus)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
OnRequestHandleClosing(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
OnRequestSendRequestComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
Debug.Assert(statusInformationLength == sizeof(int));
int bytesAvailable = Marshal.ReadInt32(statusInformation);
OnRequestDataAvailable(state, bytesAvailable);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
OnRequestReadComplete(state, statusInformationLength);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
OnRequestWriteComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
OnRequestReceiveResponseHeadersComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT:
string redirectUriString = Marshal.PtrToStringUni(statusInformation);
var redirectUri = new Uri(redirectUriString);
OnRequestRedirect(state, redirectUri);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
OnRequestSendingRequest(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
Debug.Assert(
statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(),
"RequestCallback: statusInformationLength=" + statusInformationLength +
" must be sizeof(WINHTTP_ASYNC_RESULT)=" + Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>());
var asyncResult = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(statusInformation);
OnRequestError(state, asyncResult);
return;
default:
return;
}
}
catch (Exception ex)
{
state.SavedException = ex;
if (state.RequestHandle != null)
{
// Since we got a fatal error processing the request callback,
// we need to close the WinHttp request handle in order to
// abort the currently executing WinHttp async operation.
//
// We must always call Dispose() against the SafeWinHttpHandle
// wrapper and never close directly the raw WinHttp handle.
// The SafeWinHttpHandle wrapper is thread-safe and guarantees
// calling the underlying WinHttpCloseHandle() function only once.
state.RequestHandle.Dispose();
}
}
}
private static void OnRequestHandleClosing(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null");
// This is the last notification callback that WinHTTP will send. Therefore, we can
// now explicitly dispose the state object which will free its corresponding GCHandle.
// This will then allow the state object to be garbage collected.
state.Dispose();
}
private static void OnRequestSendRequestComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null");
Debug.Assert(state.LifecycleAwaitable != null, "OnRequestSendRequestComplete: LifecycleAwaitable is null");
state.LifecycleAwaitable.SetResult(1);
}
private static void OnRequestDataAvailable(WinHttpRequestState state, int bytesAvailable)
{
Debug.Assert(state != null, "OnRequestDataAvailable: state is null");
state.LifecycleAwaitable.SetResult(bytesAvailable);
}
private static void OnRequestReadComplete(WinHttpRequestState state, uint bytesRead)
{
Debug.Assert(state != null, "OnRequestReadComplete: state is null");
// If we read to the end of the stream and we're using 'Content-Length' semantics on the response body,
// then verify we read at least the number of bytes required.
if (bytesRead == 0
&& state.ExpectedBytesToRead.HasValue
&& state.CurrentBytesRead < state.ExpectedBytesToRead.Value)
{
state.LifecycleAwaitable.SetException(new IOException(SR.Format(
SR.net_http_io_read_incomplete,
state.ExpectedBytesToRead.Value,
state.CurrentBytesRead)));
}
else
{
state.CurrentBytesRead += (long)bytesRead;
state.LifecycleAwaitable.SetResult((int)bytesRead);
}
}
private static void OnRequestWriteComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestWriteComplete: state is null");
Debug.Assert(state.TcsInternalWriteDataToRequestStream != null, "TcsInternalWriteDataToRequestStream is null");
Debug.Assert(!state.TcsInternalWriteDataToRequestStream.Task.IsCompleted, "TcsInternalWriteDataToRequestStream.Task is completed");
state.TcsInternalWriteDataToRequestStream.TrySetResult(true);
}
private static void OnRequestReceiveResponseHeadersComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestReceiveResponseHeadersComplete: state is null");
Debug.Assert(state.LifecycleAwaitable != null, "LifecycleAwaitable is null");
state.LifecycleAwaitable.SetResult(1);
}
private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri)
{
Debug.Assert(state != null, "OnRequestRedirect: state is null");
Debug.Assert(redirectUri != null, "OnRequestRedirect: redirectUri is null");
// If we're manually handling cookies, we need to reset them based on the new URI.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
// Add any cookies that may have arrived with redirect response.
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
// Reset cookie request headers based on redirectUri.
WinHttpCookieContainerAdapter.ResetCookieRequestHeaders(state, redirectUri);
}
state.RequestMessage.RequestUri = redirectUri;
// Redirection to a new uri may require a new connection through a potentially different proxy.
// If so, we will need to respond to additional 407 proxy auth demands and re-attach any
// proxy credentials. The ProcessResponse() method looks at the state.LastStatusCode
// before attaching proxy credentials and marking the HTTP request to be re-submitted.
// So we need to reset the LastStatusCode remembered. Otherwise, it will see additional 407
// responses as an indication that proxy auth failed and won't retry the HTTP request.
if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
state.LastStatusCode = 0;
}
// For security reasons, we drop the server credential if it is a
// NetworkCredential. But we allow credentials in a CredentialCache
// since they are specifically tied to URI's.
if (!(state.ServerCredentials is CredentialCache))
{
state.ServerCredentials = null;
}
// Similarly, we need to clear any Auth headers that were added to the request manually or
// through the default headers.
ResetAuthRequestHeaders(state);
}
private static void OnRequestSendingRequest(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendingRequest: state is null");
Debug.Assert(state.RequestHandle != null, "OnRequestSendingRequest: state.RequestHandle is null");
if (state.RequestMessage.RequestUri.Scheme != UriScheme.Https)
{
// Not SSL/TLS.
return;
}
// Grab the channel binding token (CBT) information from the request handle and put it into
// the TransportContext object.
state.TransportContext.SetChannelBinding(state.RequestHandle);
if (state.ServerCertificateValidationCallback != null)
{
IntPtr certHandle = IntPtr.Zero;
uint certHandleSize = (uint)IntPtr.Size;
if (!Interop.WinHttp.WinHttpQueryOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_SERVER_CERT_CONTEXT,
ref certHandle,
ref certHandleSize))
{
int lastError = Marshal.GetLastWin32Error();
if (NetEventSource.IsEnabled) NetEventSource.Error(state, $"Error getting WINHTTP_OPTION_SERVER_CERT_CONTEXT, {lastError}");
if (lastError == Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE)
{
// Not yet an SSL/TLS connection. This occurs while connecting thru a proxy where the
// CONNECT verb hasn't yet been processed due to the proxy requiring authentication.
// We need to ignore this notification. Another notification will be sent once the final
// connection thru the proxy is completed.
return;
}
throw WinHttpException.CreateExceptionUsingError(lastError, "WINHTTP_CALLBACK_STATUS_SENDING_REQUEST/WinHttpQueryOption");
}
// Get any additional certificates sent from the remote server during the TLS/SSL handshake.
X509Certificate2Collection remoteCertificateStore =
UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(certHandle);
// Create a managed wrapper around the certificate handle. Since this results in duplicating
// the handle, we will close the original handle after creating the wrapper.
var serverCertificate = new X509Certificate2(certHandle);
Interop.Crypt32.CertFreeCertificateContext(certHandle);
X509Chain chain = null;
SslPolicyErrors sslPolicyErrors;
bool result = false;
try
{
WinHttpCertificateHelper.BuildChain(
serverCertificate,
remoteCertificateStore,
state.RequestMessage.RequestUri.Host,
state.CheckCertificateRevocationList,
out chain,
out sslPolicyErrors);
result = state.ServerCertificateValidationCallback(
state.RequestMessage,
serverCertificate,
chain,
sslPolicyErrors);
}
catch (Exception ex)
{
throw WinHttpException.CreateExceptionUsingError(
(int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE, "X509Chain.Build", ex);
}
finally
{
if (chain != null)
{
chain.Dispose();
}
serverCertificate.Dispose();
}
if (!result)
{
throw WinHttpException.CreateExceptionUsingError(
(int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE, "ServerCertificateValidationCallback");
}
}
}
private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult)
{
Debug.Assert(state != null, "OnRequestError: state is null");
if (NetEventSource.IsEnabled) WinHttpTraceHelper.TraceAsyncError(state, asyncResult);
Exception innerException = WinHttpException.CreateExceptionUsingError(unchecked((int)asyncResult.dwError), "WINHTTP_CALLBACK_STATUS_REQUEST_ERROR");
switch (unchecked((uint)asyncResult.dwResult.ToInt32()))
{
case Interop.WinHttp.API_SEND_REQUEST:
state.LifecycleAwaitable.SetException(innerException);
break;
case Interop.WinHttp.API_RECEIVE_RESPONSE:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST)
{
state.RetryRequest = true;
state.LifecycleAwaitable.SetResult(0);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED)
{
// WinHttp will automatically drop any client SSL certificates that we
// have pre-set into the request handle including the NULL certificate
// (which means we have no certs to send). For security reasons, we don't
// allow the certificate to be re-applied. But we need to tell WinHttp
// explicitly that we don't have any certificate to send.
Debug.Assert(state.RequestHandle != null, "OnRequestError: state.RequestHandle is null");
WinHttpHandler.SetNoClientCertificate(state.RequestHandle);
state.RetryRequest = true;
state.LifecycleAwaitable.SetResult(0);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
state.LifecycleAwaitable.SetCanceled(state.CancellationToken);
}
else
{
state.LifecycleAwaitable.SetException(innerException);
}
break;
case Interop.WinHttp.API_QUERY_DATA_AVAILABLE:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
if (NetEventSource.IsEnabled) NetEventSource.Error(state, "QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED");
state.LifecycleAwaitable.SetCanceled();
}
else
{
state.LifecycleAwaitable.SetException(
new IOException(SR.net_http_io_read, innerException));
}
break;
case Interop.WinHttp.API_READ_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
if (NetEventSource.IsEnabled) NetEventSource.Error(state, "API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.LifecycleAwaitable.SetCanceled();
}
else
{
state.LifecycleAwaitable.SetException(new IOException(SR.net_http_io_read, innerException));
}
break;
case Interop.WinHttp.API_WRITE_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's WriteAsync() call into the TrySetCanceled().
if (NetEventSource.IsEnabled) NetEventSource.Error(state, "API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.TcsInternalWriteDataToRequestStream.TrySetCanceled();
}
else
{
state.TcsInternalWriteDataToRequestStream.TrySetException(
new IOException(SR.net_http_io_write, innerException));
}
break;
default:
Debug.Fail(
"OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.",
"Error code: " + asyncResult.dwError + " (" + innerException.Message + ")");
break;
}
}
private static void ResetAuthRequestHeaders(WinHttpRequestState state)
{
const string AuthHeaderNameWithColon = "Authorization:";
SafeWinHttpHandle requestHandle = state.RequestHandle;
// Clear auth headers.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
AuthHeaderNameWithColon,
(uint)AuthHeaderNameWithColon.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_REPLACE))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
throw WinHttpException.CreateExceptionUsingError(lastError, "WINHTTP_CALLBACK_STATUS_REDIRECT/WinHttpAddRequestHeaders");
}
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Construction;
using Microsoft.DotNet.Tools.Test.Utilities;
using System.IO;
using System.Linq;
using Xunit;
using FluentAssertions;
using Microsoft.DotNet.ProjectJsonMigration.Rules;
using System;
namespace Microsoft.DotNet.ProjectJsonMigration.Tests
{
public class GivenThatIWantToMigratePackOptions : TestBase
{
[Fact]
public void It_does_not_migrate_Summary()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""summary"": ""Some not important summary""
}
}");
EmitsOnlyAlwaysEmittedPackOptionsProperties(mockProj);
}
[Fact]
public void It_does_not_migrate_Owner()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""owner"": ""Some not important owner""
}
}");
EmitsOnlyAlwaysEmittedPackOptionsProperties(mockProj);
}
[Fact]
public void Migrating__empty_tags_does_not_populate_PackageTags()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""tags"": []
}
}");
mockProj.Properties.Count(p => p.Name == "PackageTags").Should().Be(0);
}
[Fact]
public void Migrating_tags_populates_PackageTags_semicolon_delimited()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""tags"": [""hyperscale"", ""cats""]
}
}");
mockProj.Properties.Count(p => p.Name == "PackageTags").Should().Be(1);
mockProj.Properties.First(p => p.Name == "PackageTags").Value.Should().Be("hyperscale;cats");
}
[Fact]
public void Migrating_ReleaseNotes_populates_PackageReleaseNotes()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""releaseNotes"": ""Some release notes value.""
}
}");
mockProj.Properties.Count(p => p.Name == "PackageReleaseNotes").Should().Be(1);
mockProj.Properties.First(p => p.Name == "PackageReleaseNotes").Value.Should()
.Be("Some release notes value.");
}
[Fact]
public void Migrating_IconUrl_populates_PackageIconUrl()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""iconUrl"": ""http://www.mylibrary.gov/favicon.ico""
}
}");
mockProj.Properties.Count(p => p.Name == "PackageIconUrl").Should().Be(1);
mockProj.Properties.First(p => p.Name == "PackageIconUrl").Value.Should()
.Be("http://www.mylibrary.gov/favicon.ico");
}
[Fact]
public void Migrating_ProjectUrl_populates_PackageProjectUrl()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""projectUrl"": ""http://www.url.to.library.com""
}
}");
mockProj.Properties.Count(p => p.Name == "PackageProjectUrl").Should().Be(1);
mockProj.Properties.First(p => p.Name == "PackageProjectUrl").Value.Should()
.Be("http://www.url.to.library.com");
}
[Fact]
public void Migrating_LicenseUrl_populates_PackageLicenseUrl()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""licenseUrl"": ""http://www.url.to.library.com/licence""
}
}");
mockProj.Properties.Count(p => p.Name == "PackageLicenseUrl").Should().Be(1);
mockProj.Properties.First(p => p.Name == "PackageLicenseUrl").Value.Should()
.Be("http://www.url.to.library.com/licence");
}
[Fact]
public void Migrating_RequireLicenseAcceptance_populates_PackageRequireLicenseAcceptance()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""requireLicenseAcceptance"": ""true""
}
}");
mockProj.Properties.Count(p => p.Name == "PackageRequireLicenseAcceptance").Should().Be(1);
mockProj.Properties.First(p => p.Name == "PackageRequireLicenseAcceptance").Value.Should().Be("true");
}
[Fact]
public void Migrating_RequireLicenseAcceptance_populates_PackageRequireLicenseAcceptance_even_if_its_value_is_false()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""requireLicenseAcceptance"": ""false""
}
}");
mockProj.Properties.Count(p => p.Name == "PackageRequireLicenseAcceptance").Should().Be(1);
mockProj.Properties.First(p => p.Name == "PackageRequireLicenseAcceptance").Value.Should().Be("false");
}
[Fact]
public void Migrating_Repository_Type_populates_RepositoryType()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""repository"": {
""type"": ""git""
}
}
}");
mockProj.Properties.Count(p => p.Name == "RepositoryType").Should().Be(1);
mockProj.Properties.First(p => p.Name == "RepositoryType").Value.Should().Be("git");
}
[Fact]
public void Migrating_Repository_Url_populates_RepositoryUrl()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""repository"": {
""url"": ""http://github.com/dotnet/cli""
}
}
}");
mockProj.Properties.Count(p => p.Name == "RepositoryUrl").Should().Be(1);
mockProj.Properties.First(p => p.Name == "RepositoryUrl").Value.Should().Be("http://github.com/dotnet/cli");
}
[Fact]
public void Migrating_Files_without_mappings_populates_content_with_same_path_as_include_and_pack_true()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""files"": {
""include"": [""path/to/some/file.cs"", ""path/to/some/other/file.cs""]
}
}
}");
var contentItems = mockProj.Items
.Where(item => item.ItemType.Equals("Content", StringComparison.Ordinal))
.Where(item => item.GetMetadataWithName("Pack").Value == "true");
contentItems.Count().Should().Be(1);
contentItems.First().Include.Should().Be(@"path\to\some\file.cs;path\to\some\other\file.cs");
}
[Fact]
public void Migrating_Files_with_mappings_populates_content_PackagePath_metadata()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""files"": {
""include"": [""path/to/some/file.cs""],
""mappings"": {
""some/other/path/file.cs"": ""path/to/some/file.cs""
}
}
}
}");
var contentItems = mockProj.Items
.Where(item => item.ItemType.Equals("Content", StringComparison.Ordinal))
.Where(item =>
item.GetMetadataWithName("Pack").Value == "true" &&
item.GetMetadataWithName("PackagePath") != null);
contentItems.Count().Should().Be(1);
contentItems.First().Include.Should().Be(@"path\to\some\file.cs");
contentItems.First().GetMetadataWithName("PackagePath").Value.Should().Be(
Path.Combine("some", "other", "path"));
}
[Fact]
public void Migrating_Files_with_mappings_to_root_populates_content_PackagePath_metadata_but_leaves_it_empty()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""files"": {
""include"": [""path/to/some/file.cs""],
""mappings"": {
"".file.cs"": ""path/to/some/file.cs""
}
}
}
}");
var contentItems = mockProj.Items
.Where(item => item.ItemType.Equals("Content", StringComparison.Ordinal))
.Where(item =>
item.GetMetadataWithName("Pack").Value == "true" &&
item.GetMetadataWithName("PackagePath") != null);
contentItems.Count().Should().Be(1);
contentItems.First().Include.Should().Be(@"path\to\some\file.cs");
contentItems.First().GetMetadataWithName("PackagePath").Value.Should().BeEmpty();
}
[Fact]
public void Migrating_same_file_with_multiple_mappings_string_joins_the_mappings_in_PackagePath()
{
var mockProj = RunPackOptionsRuleOnPj(@"
{
""packOptions"": {
""files"": {
""include"": [""path/to/some/file.cs""],
""mappings"": {
""other/path/file.cs"": ""path/to/some/file.cs"",
""different/path/file1.cs"": ""path/to/some/file.cs""
}
}
}
}");
var expectedPackagePath = string.Join(
";",
new [] {
Path.Combine("different", "path"),
Path.Combine("other", "path")
});
var contentItems = mockProj.Items
.Where(item => item.ItemType.Equals("Content", StringComparison.Ordinal))
.Where(item =>
item.GetMetadataWithName("Pack").Value == "true" &&
item.GetMetadataWithName("PackagePath") != null);
contentItems.Count().Should().Be(1);
contentItems.First().Include.Should().Be(@"path\to\some\file.cs");
contentItems.First().GetMetadataWithName("PackagePath").Value.Should().Be(expectedPackagePath);
}
private ProjectRootElement RunPackOptionsRuleOnPj(string packOptions, string testDirectory = null)
{
testDirectory = testDirectory ?? Temp.CreateDirectory().Path;
return TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[]
{
new MigratePackOptionsRule()
}, packOptions, testDirectory);
}
private void EmitsOnlyAlwaysEmittedPackOptionsProperties(ProjectRootElement project)
{
project.Properties.Count().Should().Be(1);
project.Properties.All(p => p.Name == "PackageRequireLicenseAcceptance").Should().BeTrue();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TinderChallenge.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
namespace Orleans.Runtime.Messaging
{
internal class Gateway
{
private readonly MessageCenter messageCenter;
private readonly GatewayClientCleanupAgent dropper;
// clients is the main authorative collection of all connected clients.
// Any client currently in the system appears in this collection.
// In addition, we use clientConnections collection for fast retrival of ClientState.
// Anything that appears in those 2 collections should also appear in the main clients collection.
private readonly ConcurrentDictionary<ClientGrainId, ClientState> clients;
private readonly ConcurrentDictionary<GatewayInboundConnection, ClientState> clientConnections;
private readonly SiloAddress gatewayAddress;
private readonly GatewaySender sender;
private readonly ClientsReplyRoutingCache clientsReplyRoutingCache;
private ClientObserverRegistrar clientRegistrar;
private readonly object lockable;
private readonly ILogger logger;
private readonly ILoggerFactory loggerFactory;
private readonly SiloMessagingOptions messagingOptions;
public Gateway(
MessageCenter msgCtr,
ILocalSiloDetails siloDetails,
MessageFactory messageFactory,
ILoggerFactory loggerFactory,
IOptions<SiloMessagingOptions> options)
{
this.messagingOptions = options.Value;
this.loggerFactory = loggerFactory;
messageCenter = msgCtr;
this.logger = this.loggerFactory.CreateLogger<Gateway>();
dropper = new GatewayClientCleanupAgent(this, loggerFactory, messagingOptions.ClientDropTimeout);
clients = new ConcurrentDictionary<ClientGrainId, ClientState>();
clientConnections = new ConcurrentDictionary<GatewayInboundConnection, ClientState>();
clientsReplyRoutingCache = new ClientsReplyRoutingCache(messagingOptions.ResponseTimeout);
this.gatewayAddress = siloDetails.GatewayAddress;
this.sender = new GatewaySender(this, msgCtr, messageFactory, loggerFactory.CreateLogger<GatewaySender>());
lockable = new object();
}
internal void Start(ClientObserverRegistrar clientRegistrar)
{
this.clientRegistrar = clientRegistrar;
this.clientRegistrar.SetGateway(this);
dropper.Start();
}
internal void Stop()
{
dropper.Stop();
}
internal ICollection<ClientGrainId> GetConnectedClients()
{
return clients.Keys;
}
internal void RecordOpenedConnection(GatewayInboundConnection connection, ClientGrainId clientId)
{
lock (lockable)
{
logger.LogInformation((int)ErrorCode.GatewayClientOpenedSocket, "Recorded opened connection from endpoint {EndPoint}, client ID {ClientId}.", connection.RemoteEndPoint, clientId);
ClientState clientState;
if (clients.TryGetValue(clientId, out clientState))
{
var oldSocket = clientState.Connection;
if (oldSocket != null)
{
// The old socket will be closed by itself later.
clientConnections.TryRemove(oldSocket, out _);
}
}
else
{
clientState = new ClientState(clientId, messagingOptions.ClientDropTimeout);
clients[clientId] = clientState;
MessagingStatisticsGroup.ConnectedClientCount.Increment();
}
clientState.RecordConnection(connection);
clientConnections[connection] = clientState;
clientRegistrar.ClientAdded(clientId);
}
}
internal void RecordClosedConnection(GatewayInboundConnection connection)
{
if (connection == null) return;
lock (lockable)
{
if (!clientConnections.TryGetValue(connection, out var clientState)) return;
clientConnections.TryRemove(connection, out _);
clientState.RecordDisconnection();
logger.LogInformation(
(int)ErrorCode.GatewayClientClosedSocket,
"Recorded closed socket from endpoint {Endpoint}, client ID {clientId}.",
connection.RemoteEndPoint?.ToString() ?? "null",
clientState.Id);
}
}
internal SiloAddress TryToReroute(Message msg)
{
// ** Special routing rule for system target here **
// When a client make a request/response to/from a SystemTarget, the TargetSilo can be set to either
// - the GatewayAddress of the target silo (for example, when the client want get the cluster typemap)
// - the "internal" Silo-to-Silo address, if the client want to send a message to a specific SystemTarget
// activation that is on a silo on which there is no gateway available (or if the client is not
// connected to that gateway)
// So, if the TargetGrain is a SystemTarget we always trust the value from Message.TargetSilo and forward
// it to this address...
// EXCEPT if the value is equal to the current GatewayAdress: in this case we will return
// null and the local dispatcher will forward the Message to a local SystemTarget activation
if (msg.TargetGrain.IsSystemTarget() && !IsTargetingLocalGateway(msg.TargetSilo))
return msg.TargetSilo;
// for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back.
if (!msg.SendingGrain.IsClient() || !msg.TargetGrain.IsClient()) return null;
if (msg.Direction != Message.Directions.Response) return null;
SiloAddress gateway;
return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null;
}
internal void DropDisconnectedClients()
{
lock (lockable)
{
List<ClientState> clientsToDrop = clients.Values.Where(cs => cs.ReadyToDrop()).ToList();
foreach (ClientState client in clientsToDrop)
DropClient(client);
}
}
internal void DropExpiredRoutingCachedEntries()
{
lock (lockable)
{
clientsReplyRoutingCache.DropExpiredEntries();
}
}
private bool IsTargetingLocalGateway(SiloAddress siloAddress)
{
// Special case if the address used by the client was loopback
return this.gatewayAddress.Matches(siloAddress)
|| (IPAddress.IsLoopback(siloAddress.Endpoint.Address)
&& siloAddress.Endpoint.Port == this.gatewayAddress.Endpoint.Port
&& siloAddress.Generation == this.gatewayAddress.Generation);
}
// This function is run under global lock
// There is NO need to acquire individual ClientState lock, since we only access client Id (immutable) and close an older socket.
private void DropClient(ClientState client)
{
logger.Info(ErrorCode.GatewayDroppingClient, "Dropping client {0}, {1} after disconnect with no reconnect",
client.Id, DateTime.UtcNow.Subtract(client.DisconnectedSince));
clients.TryRemove(client.Id, out _);
clientRegistrar.ClientDropped(client.Id);
GatewayInboundConnection oldConnection = client.Connection;
if (oldConnection != null)
{
// this will not happen, since we drop only already disconnected clients, for socket is already null. But leave this code just to be sure.
client.RecordDisconnection();
clientConnections.TryRemove(oldConnection, out _);
oldConnection.Close();
}
MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1);
}
/// <summary>
/// See if this message is intended for a grain we're proxying, and queue it for delivery if so.
/// </summary>
/// <param name="msg"></param>
/// <returns>true if the message should be delivered to a proxied grain, false if not.</returns>
internal bool TryDeliverToProxy(Message msg)
{
// See if it's a grain we're proxying.
ClientState client;
var targetGrain = msg.TargetGrain;
if (!ClientGrainId.TryParse(targetGrain, out var clientId))
{
return false;
}
if (!clients.TryGetValue(clientId, out client))
{
return false;
}
// when this Gateway receives a message from client X to client addressale object Y
// it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to)
// it will use this Gateway to re-route the REPLY from Y back to X.
if (msg.SendingGrain.IsClient())
{
clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo);
}
msg.TargetSilo = null;
// Override the SendingSilo only if the sending grain is not
// a system target
if (!msg.SendingGrain.IsSystemTarget())
{
msg.SendingSilo = gatewayAddress;
}
QueueRequest(client, msg);
return true;
}
private void QueueRequest(ClientState clientState, Message msg) => this.sender.Send(clientState, msg);
private class ClientState
{
private readonly TimeSpan clientDropTimeout;
internal Queue<Message> PendingToSend { get; private set; }
internal GatewayInboundConnection Connection { get; private set; }
internal DateTime DisconnectedSince { get; private set; }
internal ClientGrainId Id { get; private set; }
internal bool IsConnected => this.Connection != null;
internal ClientState(ClientGrainId id, TimeSpan clientDropTimeout)
{
Id = id;
this.clientDropTimeout = clientDropTimeout;
PendingToSend = new Queue<Message>();
}
internal void RecordDisconnection()
{
if (Connection == null) return;
DisconnectedSince = DateTime.UtcNow;
Connection = null;
}
internal void RecordConnection(GatewayInboundConnection connection)
{
Connection = connection;
DisconnectedSince = DateTime.MaxValue;
}
internal bool ReadyToDrop()
{
return !IsConnected &&
(DateTime.UtcNow.Subtract(DisconnectedSince) >= clientDropTimeout);
}
}
private class GatewayClientCleanupAgent : TaskSchedulerAgent
{
private readonly Gateway gateway;
private readonly TimeSpan clientDropTimeout;
internal GatewayClientCleanupAgent(Gateway gateway, ILoggerFactory loggerFactory, TimeSpan clientDropTimeout)
: base(loggerFactory)
{
this.gateway = gateway;
this.clientDropTimeout = clientDropTimeout;
}
protected override async Task Run()
{
while (!Cts.IsCancellationRequested)
{
gateway.DropDisconnectedClients();
gateway.DropExpiredRoutingCachedEntries();
await Task.Delay(clientDropTimeout);
}
}
}
// this cache is used to record the addresses of Gateways from which clients connected to.
// it is used to route replies to clients from client addressable objects
// without this cache this Gateway will not know how to route the reply back to the client
// (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined).
private class ClientsReplyRoutingCache
{
// for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway.
private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes;
private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
internal ClientsReplyRoutingCache(TimeSpan responseTimeout)
{
clientRoutes = new ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>>();
TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = responseTimeout.Multiply(5);
}
internal void RecordClientRoute(GrainId client, SiloAddress gateway)
{
var now = DateTime.UtcNow;
clientRoutes.AddOrUpdate(client, new Tuple<SiloAddress, DateTime>(gateway, now), (k, v) => new Tuple<SiloAddress, DateTime>(gateway, now));
}
internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway)
{
gateway = null;
Tuple<SiloAddress, DateTime> tuple;
bool ret = clientRoutes.TryGetValue(client, out tuple);
if (ret)
gateway = tuple.Item1;
return ret;
}
internal void DropExpiredEntries()
{
List<GrainId> clientsToDrop = clientRoutes.Where(route => Expired(route.Value.Item2)).Select(kv => kv.Key).ToList();
foreach (GrainId client in clientsToDrop)
{
Tuple<SiloAddress, DateTime> tuple;
clientRoutes.TryRemove(client, out tuple);
}
}
private bool Expired(DateTime lastUsed)
{
return DateTime.UtcNow.Subtract(lastUsed) >= TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
}
}
private sealed class GatewaySender
{
private readonly Gateway gateway;
private readonly MessageCenter messageCenter;
private readonly MessageFactory messageFactory;
private readonly ILogger<GatewaySender> log;
private readonly CounterStatistic gatewaySends;
internal GatewaySender(Gateway gateway, MessageCenter messageCenter, MessageFactory messageFactory, ILogger<GatewaySender> log)
{
this.gateway = gateway;
this.messageCenter = messageCenter;
this.messageFactory = messageFactory;
this.log = log;
this.gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT);
}
public void Send(ClientState clientState, Message msg)
{
// This should never happen -- but make sure to handle it reasonably, just in case
if (clientState == null)
{
if (msg == null) return;
this.log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), msg.TargetGrain);
MessagingStatisticsGroup.OnFailedSentMessage(msg);
// Message for unrecognized client -- reject it
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = this.messageFactory.CreateRejectionResponse(
msg,
Message.RejectionTypes.Unrecoverable,
"Unknown client " + msg.TargetGrain);
messageCenter.SendMessage(error);
}
else
{
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
return;
}
lock (clientState.PendingToSend)
{
// if disconnected - queue for later.
if (!clientState.IsConnected)
{
if (msg == null) return;
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain);
clientState.PendingToSend.Enqueue(msg);
return;
}
// if the queue is non empty - drain it first.
if (clientState.PendingToSend.Count > 0)
{
if (msg != null)
clientState.PendingToSend.Enqueue(msg);
// For now, drain in-line, although in the future this should happen in yet another asynch agent
Drain(clientState);
return;
}
// the queue was empty AND we are connected.
// If the request includes a message to send, send it (or enqueue it for later)
if (msg == null) return;
if (!Send(msg, clientState))
{
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain);
clientState.PendingToSend.Enqueue(msg);
}
else
{
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent message {0} to client {1}", msg, msg.TargetGrain);
}
}
}
private void Drain(ClientState clientState)
{
lock (clientState.PendingToSend)
{
while (clientState.PendingToSend.Count > 0)
{
var m = clientState.PendingToSend.Peek();
if (Send(m, clientState))
{
if (this.log.IsEnabled(LogLevel.Trace)) this.log.Trace("Sent queued message {0} to client {1}", m, clientState.Id);
clientState.PendingToSend.Dequeue();
}
else
{
return;
}
}
}
}
private bool Send(Message msg, ClientState client)
{
var connection = client.Connection;
if (connection is null) return false;
try
{
connection.Send(msg);
gatewaySends.Increment();
return true;
}
catch (Exception exception)
{
gateway.RecordClosedConnection(connection);
connection.Abort(new ConnectionAbortedException("Exception posting a message to sender. See InnerException for details.", exception));
return false;
}
}
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class JobType : IEquatable<JobType>
{
/// <summary>
/// Initializes a new instance of the <see cref="JobType" /> class.
/// Initializes a new instance of the <see cref="JobType" />class.
/// </summary>
/// <param name="Name">Name (required).</param>
/// <param name="Description">Description.</param>
/// <param name="JobCode">JobCode.</param>
/// <param name="IsActive">IsActive (default to false).</param>
/// <param name="CustomFields">CustomFields.</param>
public JobType(string Name = null, string Description = null, string JobCode = null, bool? IsActive = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "Name" is required (not null)
if (Name == null)
{
throw new InvalidDataException("Name is a required property for JobType and cannot be null");
}
else
{
this.Name = Name;
}
this.Description = Description;
this.JobCode = JobCode;
// use default value if no "IsActive" provided
if (IsActive == null)
{
this.IsActive = false;
}
else
{
this.IsActive = IsActive;
}
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets ClientId
/// </summary>
[DataMember(Name="clientId", EmitDefaultValue=false)]
public int? ClientId { get; private set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets JobCode
/// </summary>
[DataMember(Name="jobCode", EmitDefaultValue=false)]
public string JobCode { get; set; }
/// <summary>
/// Gets or Sets IsActive
/// </summary>
[DataMember(Name="isActive", EmitDefaultValue=false)]
public bool? IsActive { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { 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 JobType {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" ClientId: ").Append(ClientId).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" JobCode: ").Append(JobCode).Append("\n");
sb.Append(" IsActive: ").Append(IsActive).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as JobType);
}
/// <summary>
/// Returns true if JobType instances are equal
/// </summary>
/// <param name="other">Instance of JobType to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(JobType other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.ClientId == other.ClientId ||
this.ClientId != null &&
this.ClientId.Equals(other.ClientId)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.JobCode == other.JobCode ||
this.JobCode != null &&
this.JobCode.Equals(other.JobCode)
) &&
(
this.IsActive == other.IsActive ||
this.IsActive != null &&
this.IsActive.Equals(other.IsActive)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.ClientId != null)
hash = hash * 59 + this.ClientId.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.JobCode != null)
hash = hash * 59 + this.JobCode.GetHashCode();
if (this.IsActive != null)
hash = hash * 59 + this.IsActive.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// CertificatesOperations operations.
/// </summary>
public partial interface ICertificatesOperations
{
/// <summary>
/// Get all certificates for a subscription
/// </summary>
/// Get all certificates for a subscription
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Certificate>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificates for a subscription in the specified resource
/// group.
/// </summary>
/// Get certificates for a subscription in the specified resource
/// group.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Certificate>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a certificate by certificate name for a subscription in the
/// specified resource group.
/// </summary>
/// Get a certificate by certificate name for a subscription in the
/// specified resource group.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Certificate>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or modifies an existing certificate.
/// </summary>
/// Creates or modifies an existing certificate.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='certificateEnvelope'>
/// Details of certificate if it exists already.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Certificate>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, Certificate certificateEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a certificate by name in a specificed subscription and
/// resourcegroup.
/// </summary>
/// Delete a certificate by name in a specificed subscription and
/// resourcegroup.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate to be deleted.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<object>> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or modifies an existing certificate.
/// </summary>
/// Creates or modifies an existing certificate.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='certificateEnvelope'>
/// Details of certificate if it exists already.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Certificate>> UpdateWithHttpMessagesAsync(string resourceGroupName, string name, Certificate certificateEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the certificate signing requests for a subscription in the
/// specified resource group
/// </summary>
/// Gets the certificate signing requests for a subscription in the
/// specified resource group
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IList<Csr>>> ListCsrsWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a certificate signing request by certificate name for a
/// subscription in the specified resource group
/// </summary>
/// Gets a certificate signing request by certificate name for a
/// subscription in the specified resource group
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Csr>> GetCsrWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or modifies an existing certificate signing request.
/// </summary>
/// Creates or modifies an existing certificate signing request.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='csrEnvelope'>
/// Details of certificate signing request if it exists already.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Csr>> CreateOrUpdateCsrWithHttpMessagesAsync(string resourceGroupName, string name, Csr csrEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the certificate signing request.
/// </summary>
/// Delete the certificate signing request.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate signing request.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<object>> DeleteCsrWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or modifies an existing certificate signing request.
/// </summary>
/// Creates or modifies an existing certificate signing request.
/// <param name='resourceGroupName'>
/// Name of the resource group
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='csrEnvelope'>
/// Details of certificate signing request if it exists already.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Csr>> UpdateCsrWithHttpMessagesAsync(string resourceGroupName, string name, Csr csrEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all certificates for a subscription
/// </summary>
/// Get all certificates for a subscription
/// <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>
Task<AzureOperationResponse<IPage<Certificate>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificates for a subscription in the specified resource
/// group.
/// </summary>
/// Get certificates for a subscription in the specified resource
/// group.
/// <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>
Task<AzureOperationResponse<IPage<Certificate>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using IxMilia.BCad.Entities;
using IxMilia.BCad.Extensions;
using IxMilia.BCad.Helpers;
using IxMilia.BCad.Primitives;
namespace IxMilia.BCad.Utilities
{
public static class EditUtilities
{
private static object rotateCacheLock = new object();
private static Vector cachedRotateOffset;
private static double cachedRotateAngle;
private static Matrix4 cachedRotateMatrix;
private static Matrix4 GetRotateMatrix(Vector offset, double angleInDegrees)
{
lock (rotateCacheLock)
{
// it will be common to re-use a specific rotation multiple times in a row
if (offset != cachedRotateOffset || angleInDegrees != cachedRotateAngle)
{
cachedRotateOffset = offset;
cachedRotateAngle = angleInDegrees;
cachedRotateMatrix = Matrix4.CreateTranslate(offset)
* Matrix4.RotateAboutZ(-angleInDegrees)
* Matrix4.CreateTranslate(-offset);
}
return cachedRotateMatrix;
}
}
public static Entity Rotate(Entity entity, Vector offset, double angleInDegrees)
{
var transform = GetRotateMatrix(offset, angleInDegrees);
var inSitu = GetRotateMatrix(Vector.Zero, angleInDegrees);
switch (entity.Kind)
{
case EntityKind.Arc:
var arc = (Arc)entity;
return arc.Update(
center: transform.Transform(arc.Center),
startAngle: MathHelper.CorrectAngleDegrees(arc.StartAngle + angleInDegrees),
endAngle: MathHelper.CorrectAngleDegrees(arc.EndAngle + angleInDegrees));
case EntityKind.Circle:
var circ = (Circle)entity;
return circ.Update(center: transform.Transform(circ.Center));
case EntityKind.Ellipse:
var el = (Ellipse)entity;
return el.Update(center: transform.Transform(el.Center),
majorAxis: inSitu.Transform(el.MajorAxis));
case EntityKind.Line:
var line = (Line)entity;
return line.Update(p1: transform.Transform(line.P1), p2: transform.Transform(line.P2));
case EntityKind.Location:
var loc = (Location)entity;
return loc.Update(point: transform.Transform(loc.Point));
default:
throw new ArgumentException("Unsupported entity type " + entity.Kind);
}
}
public static void Trim(SelectedEntity entityToTrim, IEnumerable<IPrimitive> boundaryPrimitives, out IEnumerable<Entity> removed, out IEnumerable<Entity> added)
{
var selectionPrimitives = entityToTrim.Entity.GetPrimitives();
// find all intersection points
var intersectionPoints = boundaryPrimitives
.SelectMany(b => selectionPrimitives.Select(sel => b.IntersectionPoints(sel)))
.WhereNotNull()
.SelectMany(b => b)
.WhereNotNull();
if (intersectionPoints.Any())
{
// perform the trim operation
switch (entityToTrim.Entity.Kind)
{
case EntityKind.Line:
TrimLine((Line)entityToTrim.Entity, entityToTrim.SelectionPoint, intersectionPoints, out removed, out added);
break;
case EntityKind.Arc:
case EntityKind.Circle:
case EntityKind.Ellipse:
TrimEllipse(entityToTrim.Entity, entityToTrim.SelectionPoint, intersectionPoints, out removed, out added);
break;
default:
Debug.Assert(false, "unsupported trim entity: " + entityToTrim.Entity.Kind);
removed = new List<Entity>();
added = new List<Entity>();
break;
}
}
else
{
removed = new List<Entity>();
added = new List<Entity>();
}
}
public static void Extend(SelectedEntity entityToExtend, IEnumerable<IPrimitive> boundaryPrimitives, out IEnumerable<Entity> removed, out IEnumerable<Entity> added)
{
var selectionPrimitives = entityToExtend.Entity.GetPrimitives();
// find all intersection points on boundary primitives but not on the entity to extend
var intersectionPoints = boundaryPrimitives
.SelectMany(b => selectionPrimitives.Select(sel => b.IntersectionPoints(sel, withinBounds: false)))
.WhereNotNull()
.SelectMany(b => b)
.WhereNotNull()
.Where(p => boundaryPrimitives.Any(b => b.IsPointOnPrimitive(p)) && !selectionPrimitives.Any(b => b.IsPointOnPrimitive(p)));
if (intersectionPoints.Any())
{
switch (entityToExtend.Entity.Kind)
{
case EntityKind.Arc:
case EntityKind.Circle:
case EntityKind.Ellipse:
ExtendEllipse(entityToExtend.Entity, entityToExtend.SelectionPoint, intersectionPoints, out removed, out added);
break;
case EntityKind.Line:
ExtendLine((Line)entityToExtend.Entity, entityToExtend.SelectionPoint, intersectionPoints, out removed, out added);
break;
default:
Debug.Assert(false, "unsupported extend entity: " + entityToExtend.Entity.Kind);
removed = new List<Entity>();
added = new List<Entity>();
break;
}
}
else
{
removed = new List<Entity>();
added = new List<Entity>();
}
}
public static bool CanOffsetEntity(Entity entityToOffset)
{
switch (entityToOffset.Kind)
{
case EntityKind.Arc:
case EntityKind.Circle:
case EntityKind.Ellipse:
case EntityKind.Line:
return true;
case EntityKind.Aggregate:
case EntityKind.Location:
case EntityKind.Polyline:
case EntityKind.Text:
return false;
default:
throw new ArgumentException("entityToOffset.Kind");
}
}
public static IPrimitive Offset(Plane drawingPlane, IPrimitive primitive, Point offsetDirection, double offsetDistance)
{
if (!drawingPlane.Contains(offsetDirection))
return null;
IPrimitive result;
switch (primitive.Kind)
{
case PrimitiveKind.Ellipse:
var el = (PrimitiveEllipse)primitive;
var projection = el.FromUnitCircle.Inverse();
var isInside = projection.Transform((Vector)offsetDirection).LengthSquared <= 1.0;
var majorLength = el.MajorAxis.Length;
if (isInside && (offsetDistance > majorLength * el.MinorAxisRatio)
|| (offsetDistance >= majorLength))
{
result = null;
}
else
{
Vector newMajor;
if (isInside)
{
newMajor = el.MajorAxis.Normalize() * (majorLength - offsetDistance);
}
else
{
newMajor = el.MajorAxis.Normalize() * (majorLength + offsetDistance);
}
result = new PrimitiveEllipse(
center: el.Center,
majorAxis: newMajor,
normal: el.Normal,
minorAxisRatio: el.MinorAxisRatio,
startAngle: el.StartAngle,
endAngle: el.EndAngle,
color: el.Color);
}
break;
case PrimitiveKind.Line:
// find what side the offset occured on and move both end points
var line = (PrimitiveLine)primitive;
// normalize to XY plane
var picked = drawingPlane.ToXYPlane(offsetDirection);
var p1 = drawingPlane.ToXYPlane(line.P1);
var p2 = drawingPlane.ToXYPlane(line.P2);
var pline = new PrimitiveLine(p1, p2);
var perpendicular = new PrimitiveLine(picked, pline.PerpendicularSlope());
var intersection = pline.IntersectionPoint(perpendicular, false);
if (intersection.HasValue && intersection.Value != picked)
{
var offsetVector = (picked - intersection.Value).Normalize() * offsetDistance;
offsetVector = drawingPlane.FromXYPlane(offsetVector);
result = new PrimitiveLine(
p1: line.P1 + offsetVector,
p2: line.P2 + offsetVector,
color: line.Color);
}
else
{
// the selected point was directly on the line
result = null;
}
break;
case PrimitiveKind.Point:
var point = (PrimitivePoint)primitive;
var pointOffsetVector = (offsetDirection - point.Location).Normalize() * offsetDistance;
result = new PrimitivePoint(point.Location + pointOffsetVector, point.Color);
break;
case PrimitiveKind.Text:
result = null;
break;
default:
throw new ArgumentException("primitive.Kind");
}
return result;
}
public static Entity Offset(IWorkspace workspace, Entity entityToOffset, Point offsetDirection, double offsetDistance)
{
switch (entityToOffset.Kind)
{
case EntityKind.Arc:
case EntityKind.Circle:
case EntityKind.Ellipse:
case EntityKind.Line:
var primitive = entityToOffset.GetPrimitives().Single();
var thickness = primitive.GetThickness();
var offset = Offset(
workspace.DrawingPlane,
primitive,
offsetDirection,
offsetDistance);
var entity = offset?.ToEntity();
if (entity != null)
{
entity = entity.WithThickness(thickness);
}
return entity;
case EntityKind.Aggregate:
case EntityKind.Location:
case EntityKind.Polyline:
case EntityKind.Text:
return null;
default:
throw new ArgumentException("entityToOffset.Kind");
}
}
public static PrimitiveEllipse Ttr(Plane drawingPlane, SelectedEntity firstEntity, SelectedEntity secondEntity, double radius)
{
var first = firstEntity.Entity;
var second = secondEntity.Entity;
if (!CanOffsetEntity(first) || !CanOffsetEntity(second))
return null;
if (!drawingPlane.Contains(first) || !drawingPlane.Contains(second))
return null;
// offset each entity both possible directions, intersect everything, and take the closest
// point to be the center
var firstOffsets = OffsetBothDirections(
drawingPlane: drawingPlane,
primitive: first.GetPrimitives().First(),
distance: radius);
var secondOffsets = OffsetBothDirections(
drawingPlane: drawingPlane,
primitive: second.GetPrimitives().First(),
distance: radius);
var candidatePoints = (from f in firstOffsets
from s in secondOffsets
where f != null && s != null
select f.IntersectionPoints(s, false))
.SelectMany(x => x);
if (candidatePoints.Any())
{
var center = candidatePoints.OrderBy(x =>
{
return (x - firstEntity.SelectionPoint).LengthSquared
* (x - secondEntity.SelectionPoint).LengthSquared;
}).First();
return new PrimitiveEllipse(center, radius, drawingPlane.Normal);
}
return null;
}
public static Entity Move(Entity entity, Vector offset)
{
switch (entity.Kind)
{
case EntityKind.Aggregate:
var agg = (AggregateEntity)entity;
return agg.Update(location: agg.Location + offset);
case EntityKind.Arc:
var arc = (Arc)entity;
return arc.Update(center: arc.Center + offset);
case EntityKind.Circle:
var circle = (Circle)entity;
return circle.Update(center: circle.Center + offset);
case EntityKind.Ellipse:
var el = (Ellipse)entity;
return el.Update(center: el.Center + offset);
case EntityKind.Line:
var line = (Line)entity;
return line.Update(p1: line.P1 + offset, p2: line.P2 + offset);
case EntityKind.Location:
var location = (Location)entity;
return location.Update(point: location.Point + offset);
case EntityKind.Polyline:
var poly = (Polyline)entity;
return poly.Update(vertices: poly.Vertices.Select(v => new Vertex(v.Location + offset, v.IncludedAngle, v.Direction)));
case EntityKind.Text:
var text = (Text)entity;
return text.Update(location: text.Location + offset);
default:
throw new ArgumentException("entity.Kind");
}
}
private static IEnumerable<IPrimitive> OffsetBothDirections(Plane drawingPlane, IPrimitive primitive, double distance)
{
switch (primitive.Kind)
{
case PrimitiveKind.Ellipse:
var el = (PrimitiveEllipse)primitive;
return new[]
{
Offset(drawingPlane, el, el.Center, distance),
Offset(drawingPlane, el, el.Center + (el.MajorAxis * 2.0), distance)
};
case PrimitiveKind.Line:
var line = (PrimitiveLine)primitive;
var lineVector = line.P2 - line.P1;
if (lineVector.IsZeroVector)
{
return Enumerable.Empty<IPrimitive>();
}
var offsetVector = lineVector.Cross(drawingPlane.Normal);
return new[]
{
Offset(drawingPlane, line, line.P1 + offsetVector, distance),
Offset(drawingPlane, line, line.P1 - offsetVector, distance)
};
case PrimitiveKind.Point:
return Enumerable.Empty<IPrimitive>();
case PrimitiveKind.Text:
return Enumerable.Empty<IPrimitive>();
default:
throw new ArgumentException("primitive.Kind");
}
}
private static void TrimLine(Line lineToTrim, Point pivot, IEnumerable<Point> intersectionPoints, out IEnumerable<Entity> removed, out IEnumerable<Entity> added)
{
var removedList = new List<Entity>();
var addedList = new List<Entity>();
// split intersection points based on which side of the selection point they are
var left = new List<Point>();
var right = new List<Point>();
var pivotDist = (pivot - lineToTrim.P1).LengthSquared;
var fullDist = (lineToTrim.P2 - lineToTrim.P1).LengthSquared;
foreach (var point in intersectionPoints)
{
var isectDist = (point - lineToTrim.P1).LengthSquared;
if (MathHelper.BetweenNarrow(0.0, pivotDist, isectDist))
{
left.Add(point);
}
else if (MathHelper.BetweenNarrow(pivotDist, fullDist, isectDist))
{
right.Add(point);
}
}
// find the closest points on each side. these are the new endpoints
var leftPoints = left.OrderBy(p => (p - pivot).LengthSquared);
var rightPoints = right.OrderBy(p => (p - pivot).LengthSquared);
if (leftPoints.Any() || rightPoints.Any())
{
// remove the original line
removedList.Add(lineToTrim);
// add the new shorted lines where appropriate
if (leftPoints.Any())
{
addedList.Add(lineToTrim.Update(p1: lineToTrim.P1, p2: leftPoints.First()));
}
if (rightPoints.Any())
{
addedList.Add(lineToTrim.Update(p1: rightPoints.First(), p2: lineToTrim.P2));
}
}
removed = removedList;
added = addedList;
}
private static void TrimEllipse(Entity entityToTrim, Point pivot, IEnumerable<Point> intersectionPoints, out IEnumerable<Entity> removed, out IEnumerable<Entity> added)
{
var addedList = new List<Entity>();
var removedList = new List<Entity>();
// prep common variables
double startAngle, endAngle;
bool isClosed;
if (entityToTrim.Kind == EntityKind.Arc)
{
startAngle = ((Arc)entityToTrim).StartAngle;
endAngle = ((Arc)entityToTrim).EndAngle;
isClosed = false;
}
else if (entityToTrim.Kind == EntityKind.Ellipse)
{
startAngle = ((Ellipse)entityToTrim).StartAngle;
endAngle = ((Ellipse)entityToTrim).EndAngle;
isClosed = MathHelper.CloseTo(0.0, startAngle) && MathHelper.CloseTo(360.0, endAngle);
}
else
{
startAngle = 0.0;
endAngle = 360.0;
isClosed = true;
}
// convert points to angles
var inverse = entityToTrim.GetUnitCircleProjection().Inverse();
var angles = intersectionPoints
.Select(p => inverse.Transform(p))
.Select(p => (Math.Atan2(p.Y, p.X) * MathHelper.RadiansToDegrees).CorrectAngleDegrees())
.Where(a => isClosed || (!MathHelper.CloseTo(a, startAngle) && !MathHelper.CloseTo(a, endAngle)))
.OrderBy(a => a)
.ToList();
var unitPivot = inverse.Transform(pivot);
var selectionAngle = (Math.Atan2(unitPivot.Y, unitPivot.X) * MathHelper.RadiansToDegrees).CorrectAngleDegrees();
var selectionAfterIndex = angles.Where(a => a < selectionAngle).Count() - 1;
if (selectionAfterIndex < 0)
selectionAfterIndex = angles.Count - 1;
var previousIndex = selectionAfterIndex;
var nextIndex = previousIndex + 1;
if (nextIndex >= angles.Count)
nextIndex = 0;
// prepare normalized angles (for arc trimming)
List<double> normalizedAngles;
double normalizedSelectionAngle;
if (startAngle > endAngle)
{
normalizedAngles = angles.Select(a => a >= startAngle ? a - 360.0 : a).ToList();
normalizedSelectionAngle = selectionAngle >= startAngle ? selectionAngle - 360.0 : selectionAngle;
}
else
{
normalizedAngles = angles;
normalizedSelectionAngle = selectionAngle;
}
var lesserAngles = normalizedAngles.Where(a => a < normalizedSelectionAngle).ToList();
var greaterAngles = normalizedAngles.Where(a => a > normalizedSelectionAngle).ToList();
switch (entityToTrim.Kind)
{
case EntityKind.Arc:
var arc = (Arc)entityToTrim;
if (lesserAngles.Any() || greaterAngles.Any())
{
removedList.Add(entityToTrim);
if (lesserAngles.Any())
{
addedList.Add(arc.Update(endAngle: lesserAngles.Max().CorrectAngleDegrees()));
}
if (greaterAngles.Any())
{
addedList.Add(arc.Update(startAngle: greaterAngles.Min().CorrectAngleDegrees()));
}
}
break;
case EntityKind.Circle:
var circle = (Circle)entityToTrim;
if (angles.Count >= 2)
{
// 2 cutting edges required
removedList.Add(entityToTrim);
addedList.Add(new Arc(
circle.Center,
circle.Radius,
angles[nextIndex],
angles[previousIndex],
circle.Normal,
circle.Color));
}
break;
case EntityKind.Ellipse:
var el = (Ellipse)entityToTrim;
if (el.StartAngle == 0.0 && el.EndAngle == 360.0)
{
// treat like a circle
if (angles.Count >= 2)
{
removedList.Add(entityToTrim);
addedList.Add(el.Update(startAngle: angles[nextIndex], endAngle: angles[previousIndex]));
}
}
else
{
// tread like an arc
if (lesserAngles.Any() || greaterAngles.Any())
{
removedList.Add(entityToTrim);
if (lesserAngles.Any())
{
addedList.Add(el.Update(endAngle: lesserAngles.Max().CorrectAngleDegrees()));
}
if (greaterAngles.Any())
{
addedList.Add(el.Update(startAngle: greaterAngles.Min().CorrectAngleDegrees()));
}
}
}
break;
default:
throw new ArgumentException("This should never happen", "entityToTrim.Kind");
}
added = addedList;
removed = removedList;
}
private static void ExtendLine(Line lineToExtend, Point selectionPoint, IEnumerable<Point> intersectionPoints, out IEnumerable<Entity> removed, out IEnumerable<Entity> added)
{
var removedList = new List<Entity>();
var addedList = new List<Entity>();
// find closest intersection point to the selection
var closestRealPoints = intersectionPoints.OrderBy(p => (p - selectionPoint).LengthSquared);
if (closestRealPoints.Any())
{
var closestRealPoint = closestRealPoints.First();
// find closest end point to the selection
var closestEndPoint = (lineToExtend.P1 - selectionPoint).LengthSquared < (lineToExtend.P2 - selectionPoint).LengthSquared
? lineToExtend.P1
: lineToExtend.P2;
// if closest intersection point and closest end point are on the same side of the midpoint, do extend
var midPoint = lineToExtend.MidPoint();
var selectionVector = (closestRealPoint - midPoint).Normalize();
var endVector = (closestEndPoint - midPoint).Normalize();
if (selectionVector.CloseTo(endVector))
{
removedList.Add(lineToExtend);
if (closestEndPoint.CloseTo(lineToExtend.P1))
{
// replace p1
addedList.Add(lineToExtend.Update(p1: closestRealPoint));
}
else
{
// replace p2
addedList.Add(lineToExtend.Update(p2: closestRealPoint));
}
}
}
removed = removedList;
added = addedList;
}
private static void ExtendEllipse(Entity ellipseToExtend, Point selectionPoint, IEnumerable<Point> intersectionPoints, out IEnumerable<Entity> removed, out IEnumerable<Entity> added)
{
var removedList = new List<Entity>();
var addedList = new List<Entity>();
// get primitive ellipse object
var primitives = ellipseToExtend.GetPrimitives();
Debug.Assert(primitives.Count() == 1);
var primitive = primitives.Single();
Debug.Assert(primitive.Kind == PrimitiveKind.Ellipse);
var ellipse = (PrimitiveEllipse)primitive;
// prepare transformation matrix
var fromUnitMatrix = ellipse.FromUnitCircle;
var toUnitMatrix = fromUnitMatrix.Inverse();
var selectionUnit = toUnitMatrix.Transform(selectionPoint);
// find closest intersection point to the selection
var closestRealPoints = intersectionPoints.OrderBy(p => (p - selectionPoint).LengthSquared);
if (closestRealPoints.Any())
{
var closestRealPoint = closestRealPoints.First();
var closestUnitPoint = toUnitMatrix.Transform(closestRealPoint);
var newAngle = (Math.Atan2(closestUnitPoint.Y, closestUnitPoint.X) * MathHelper.RadiansToDegrees).CorrectAngleDegrees();
// find the closest end point to the selection
var startPoint = toUnitMatrix.Transform(ellipse.StartPoint());
var endPoint = toUnitMatrix.Transform(ellipse.EndPoint());
var startAngle = ellipse.StartAngle;
var endAngle = ellipse.EndAngle;
if ((startPoint - selectionUnit).LengthSquared < (endPoint - selectionUnit).LengthSquared)
{
// start point should get replaced
startAngle = newAngle;
}
else
{
// end point should get replaced
endAngle = newAngle;
}
// remove the old ellipse
removedList.Add(ellipseToExtend);
// create the new ellipse
Entity entityToAdd;
if (MathHelper.CloseTo(1.0, ellipse.MinorAxisRatio))
{
// circle or arc
if (MathHelper.CloseTo(0.0, startAngle) && MathHelper.CloseTo(360.0, endAngle))
{
// circle
entityToAdd = new Circle(ellipse.Center, ellipse.MajorAxis.Length, ellipse.Normal, ellipse.Color);
}
else
{
// arc
entityToAdd = new Arc(ellipse.Center, ellipse.MajorAxis.Length, startAngle, endAngle, ellipse.Normal, ellipse.Color);
}
}
else
{
// ellipse
entityToAdd = new Ellipse(ellipse.Center, ellipse.MajorAxis, ellipse.MinorAxisRatio, startAngle, endAngle, ellipse.Normal, ellipse.Color);
}
addedList.Add(entityToAdd);
}
removed = removedList;
added = addedList;
}
}
}
| |
// 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.Internal;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace System.Reflection.Metadata.Ecma335
{
internal struct StringHeap
{
private static string[] s_virtualValues;
internal readonly MemoryBlock Block;
private VirtualHeap _lazyVirtualHeap;
internal StringHeap(MemoryBlock block, MetadataKind metadataKind)
{
_lazyVirtualHeap = null;
if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335)
{
// Note:
// Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent
// when comparing to a text that ends with a high surrogate.
var values = new string[(int)StringHandle.VirtualIndex.Count];
values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime";
values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime";
values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel";
values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml";
values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime";
values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors";
values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose";
values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets";
values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute";
values[(int)StringHandle.VirtualIndex.Color] = "Color";
values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius";
values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset";
values[(int)StringHandle.VirtualIndex.Duration] = "Duration";
values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType";
values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1";
values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken";
values[(int)StringHandle.VirtualIndex.Exception] = "Exception";
values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition";
values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength";
values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType";
values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand";
values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2";
values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable";
values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable";
values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1";
values[(int)StringHandle.VirtualIndex.IList] = "IList";
values[(int)StringHandle.VirtualIndex.IList1] = "IList`1";
values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged";
values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged";
values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2";
values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1";
values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime";
values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2";
values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix";
values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D";
values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2";
values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs";
values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler";
values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1";
values[(int)StringHandle.VirtualIndex.Plane] = "Plane";
values[(int)StringHandle.VirtualIndex.Point] = "Point";
values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs";
values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler";
values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion";
values[(int)StringHandle.VirtualIndex.Rect] = "Rect";
values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior";
values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType";
values[(int)StringHandle.VirtualIndex.Size] = "Size";
values[(int)StringHandle.VirtualIndex.System] = "System";
values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections";
values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic";
values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized";
values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel";
values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics";
values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input";
values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness";
values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan";
values[(int)StringHandle.VirtualIndex.Type] = "Type";
values[(int)StringHandle.VirtualIndex.Uri] = "Uri";
values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2";
values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3";
values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4";
values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation";
values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation";
values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D";
s_virtualValues = values;
AssertFilled();
}
this.Block = TrimEnd(block);
}
[Conditional("DEBUG")]
private static void AssertFilled()
{
for (int i = 0; i < s_virtualValues.Length; i++)
{
Debug.Assert(s_virtualValues[i] != null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i);
}
}
// Trims the alignment padding of the heap.
// See StgStringPool::InitOnMem in ndp\clr\src\Utilcode\StgPool.cpp.
// This is especially important for EnC.
private static MemoryBlock TrimEnd(MemoryBlock block)
{
if (block.Length == 0)
{
return block;
}
int i = block.Length - 1;
while (i >= 0 && block.PeekByte(i) == 0)
{
i--;
}
// this shouldn't happen in valid metadata:
if (i == block.Length - 1)
{
return block;
}
// +1 for terminating \0
return block.GetMemoryBlockAt(0, i + 2);
}
internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder)
{
return handle.IsVirtual ? GetVirtualHandleString(handle, utf8Decoder) : GetNonVirtualString(handle, utf8Decoder, prefixOpt: null);
}
internal MemoryBlock GetMemoryBlock(StringHandle handle)
{
return handle.IsVirtual ? GetVirtualHandleMemoryBlock(handle) : GetNonVirtualStringMemoryBlock(handle);
}
internal static string GetVirtualString(StringHandle.VirtualIndex index)
{
return s_virtualValues[(int)index];
}
private string GetNonVirtualString(StringHandle handle, MetadataStringDecoder utf8Decoder, byte[] prefixOpt)
{
Debug.Assert(handle.StringKind != StringKind.Virtual);
int bytesRead;
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return Block.PeekUtf8NullTerminated(handle.GetHeapOffset(), prefixOpt, utf8Decoder, out bytesRead, otherTerminator);
}
private unsafe MemoryBlock GetNonVirtualStringMemoryBlock(StringHandle handle)
{
Debug.Assert(handle.StringKind != StringKind.Virtual);
int bytesRead;
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
int offset = handle.GetHeapOffset();
int length = Block.GetUtf8NullTerminatedLength(offset, out bytesRead, otherTerminator);
return new MemoryBlock(Block.Pointer + offset, length);
}
private unsafe byte[] GetNonVirtualStringBytes(StringHandle handle, byte[] prefix)
{
Debug.Assert(handle.StringKind != StringKind.Virtual);
var block = GetNonVirtualStringMemoryBlock(handle);
var bytes = new byte[prefix.Length + block.Length];
Buffer.BlockCopy(prefix, 0, bytes, 0, prefix.Length);
Marshal.Copy((IntPtr)block.Pointer, bytes, prefix.Length, block.Length);
return bytes;
}
private string GetVirtualHandleString(StringHandle handle, MetadataStringDecoder utf8Decoder)
{
Debug.Assert(handle.IsVirtual);
return handle.StringKind switch
{
StringKind.Virtual => GetVirtualString(handle.GetVirtualIndex()),
StringKind.WinRTPrefixed => GetNonVirtualString(handle, utf8Decoder, MetadataReader.WinRTPrefix),
_ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind),
};
}
private MemoryBlock GetVirtualHandleMemoryBlock(StringHandle handle)
{
Debug.Assert(handle.IsVirtual);
var heap = VirtualHeap.GetOrCreateVirtualHeap(ref _lazyVirtualHeap);
lock (heap)
{
if (!heap.TryGetMemoryBlock(handle.RawValue, out var block))
{
byte[] bytes = handle.StringKind switch
{
StringKind.Virtual => Encoding.UTF8.GetBytes(GetVirtualString(handle.GetVirtualIndex())),
StringKind.WinRTPrefixed => GetNonVirtualStringBytes(handle, MetadataReader.WinRTPrefix),
_ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind),
};
block = heap.AddBlob(handle.RawValue, bytes);
}
return block;
}
}
internal BlobReader GetBlobReader(StringHandle handle)
{
return new BlobReader(GetMemoryBlock(handle));
}
internal StringHandle GetNextHandle(StringHandle handle)
{
if (handle.IsVirtual)
{
return default(StringHandle);
}
int terminator = this.Block.IndexOf(0, handle.GetHeapOffset());
if (terminator == -1 || terminator == Block.Length - 1)
{
return default(StringHandle);
}
return StringHandle.FromOffset(terminator + 1);
}
internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase)
{
Debug.Assert(value != null);
if (handle.IsVirtual)
{
// TODO: This can allocate unnecessarily for <WinRT> prefixed handles.
return string.Equals(GetString(handle, utf8Decoder), value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
if (handle.IsNil)
{
return value.Length == 0;
}
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.Utf8NullTerminatedEquals(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase);
}
internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase)
{
Debug.Assert(value != null);
if (handle.IsVirtual)
{
// TODO: This can allocate unnecessarily for <WinRT> prefixed handles.
return GetString(handle, utf8Decoder).StartsWith(value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
if (handle.IsNil)
{
return value.Length == 0;
}
char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0';
return this.Block.Utf8NullTerminatedStartsWith(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase);
}
/// <summary>
/// Returns true if the given raw (non-virtual) handle represents the same string as given ASCII string.
/// </summary>
internal bool EqualsRaw(StringHandle rawHandle, string asciiString)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.GetHeapOffset(), asciiString) == 0;
}
/// <summary>
/// Returns the heap index of the given ASCII character or -1 if not found prior null terminator or end of heap.
/// </summary>
internal int IndexOfRaw(int startIndex, char asciiChar)
{
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
return this.Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar);
}
/// <summary>
/// Returns true if the given raw (non-virtual) handle represents a string that starts with given ASCII prefix.
/// </summary>
internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.Utf8NullTerminatedStringStartsWithAsciiPrefix(rawHandle.GetHeapOffset(), asciiPrefix);
}
/// <summary>
/// Equivalent to Array.BinarySearch, searches for given raw (non-virtual) handle in given array of ASCII strings.
/// </summary>
internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle)
{
Debug.Assert(!rawHandle.IsVirtual);
Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported");
return this.Block.BinarySearch(asciiKeys, rawHandle.GetHeapOffset());
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCRPC
{
/// <summary>
/// Organizes the const values
/// </summary>
public static class ConstValues
{
/// <summary>
/// Size of Guid in byte
/// </summary>
public const int GuidByteSize = 16;
/// <summary>
/// Size of GlobalCounter field in byte
/// </summary>
public const int GlobalCounterByteSize = 6;
/// <summary>
/// MaximumByteCount field is present when ByteCount is equal to 0xBABE(47806)
/// </summary>
public const ushort MaximumByteCountIndicator = 0xbabe;
/// <summary>
/// The size of AUX_HEADER.
/// </summary>
public const int AuxHeaderByteSize = 4;
/// <summary>
/// The maximum value of RowCount field in RopQueryRows request
/// </summary>
public const ushort QueryRowsRequestRowCountMax = 0xffff;
/// <summary>
/// The size of sample tags.
/// </summary>
public const int SampleTagsByteSize = 6;
/// <summary>
/// Indicate the MessageId field in Message ROPs with value 0x00000000000000000.
/// </summary>
public const ulong MessageIdZeroValue = 0x00000000000000000;
/// <summary>
/// The payload length in ROP input buffer for null ROP request
/// </summary>
public const int RequestBufferPayloadLength = 2;
/// <summary>
/// The RopSize value in ROP input buffer for null ROP request
/// </summary>
public const ushort RequestBufferRopSize = 2;
/// <summary>
/// Size of property which type is PytpTime in byte
/// </summary>
public const int PtypTimeByteSize = 8;
/// <summary>
/// Size of Version field in RPC_HEADER_EXT
/// </summary>
public const int RpcHeaderExtVersionByteSize = 2;
/// <summary>
/// Size of Flags field in RPC_HEADER_EXT
/// </summary>
public const int RpcHeaderExtFlagsByteSize = 2;
/// <summary>
/// Size of Size field in RPC_HEADER_EXT
/// </summary>
public const int RpcHeaderExtSizeByteSize = 2;
/// <summary>
/// A Default value for Locale. 1033 indicates "en-us".
/// </summary>
public const uint DefaultLocale = 0x00000409;
/// <summary>
/// The base number of product major version in three WORD version.
/// </summary>
public const long OffsetProductMajorVersion = 0x100000000;
/// <summary>
/// The base number of build major number in three WORD version.
/// </summary>
public const int OffsetBuildMajorNumber = 0x10000;
/// <summary>
/// The size of RopSize in ROP input and output buffer structure.
/// </summary>
public const int RopSizeInRopInputOutputBufferSize = 2;
/// <summary>
/// 96 is an arbitrary initial size for Buffer
/// </summary>
public const int ArbitraryInitialSizeForBuffer = 96;
/// <summary>
/// The size of Size field in AUX_HEADER.
/// </summary>
public const int AuxHeaderSizeByteSize = 2;
/// <summary>
/// The size of Version field in AUX_HEADER.
/// </summary>
public const int AuxHeaderVersionByteSize = 1;
/// <summary>
/// The size of Type field in AUX_HEADER.
/// </summary>
public const int AuxHeaderTypeByteSize = 1;
/// <summary>
/// The size of AUX_HEADER.
/// </summary>
public const int AuxHeaderSize = AuxHeaderSizeByteSize + AuxHeaderVersionByteSize + AuxHeaderTypeByteSize;
/// <summary>
/// The size of normalized version.
/// </summary>
public const int NormalizedVersionSize = 4;
/// <summary>
/// The mask to get the high-bit of WORD.
/// </summary>
public const ushort HighBitMask = 0x8000;
/// <summary>
/// The high-order BYTE of the first WORD in Version.
/// </summary>
public const ushort HighByteMask = 0xFF00;
/// <summary>
/// The low-order BYTE of the first WORD in Version.
/// </summary>
public const ushort LowByteMask = 0x00FF;
/// <summary>
/// The step distance of one byte.
/// </summary>
public const int StepDistanceOfOneByte = 8;
/// <summary>
/// TableFlags of ConversationMembers.
/// </summary>
public const int ConversationMemberTableFlag = 0x80;
/// <summary>
/// The GID length.
/// </summary>
public const int GidLength = 22;
/// <summary>
/// The size of Pad field.
/// </summary>
public const int PadFieldByteSize = 2;
/// <summary>
/// Value of Version field in RPC_HEADER_EXT
/// </summary>
public const ushort RpcHeaderExtVersionValue = 0x0000;
/// <summary>
/// Code page id used in RopLogon
/// </summary>
public const ushort LogonCodePageId = 0x0FFF;
/// <summary>
/// The endmark of a string.
/// </summary>
public const char StringEndMark = '\0';
/// <summary>
/// The default value for server output object handle.
/// </summary>
public const uint DefaultOutputHandle = 0xFFFFFFFF;
/// <summary>
/// Indicate the OutputHandleIndex field.
/// </summary>
public const uint OutputHandleIndexForOneRop = 1;
/// <summary>
/// Indicate a value that is not zero.
/// </summary>
public const bool NonZero = true;
/// <summary>
/// An unsigned integer indicates an invalid value of pcbAuxOut that that should be larger than 4104 (0x00001008), as specified by EcDoConnectEx method and EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint TooBigpcbAuxOut = 4105;
/// <summary>
/// An unsigned integer indicates a valid value of pcbAuxOut, as specified by EcDoConnectEx method and EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint ValidpcbAuxOut = 4104;
/// <summary>
/// An unsigned integer indicates an invalid value of cbAuxIn that should be larger than 4104 (0x00001008), as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint TooBigcbAuxIn = 4105;
/// <summary>
/// An unsigned integer indicates an invalid value of cbAuxIn that should be larger than 0 and less than 8 (0x00000008), as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint TooSmallcbAuxIn = 7;
/// <summary>
/// An unsigned integer indicates an invalid value of cbIn that should be larger than 32775 (0x00008007) and less than 262144 (0x00040000), as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint BigcbIn = 32776;
/// <summary>
/// An unsigned integer indicates an invalid value of cbIn that should be larger than 262144 (0x00040000) for Exchange 2010 and 2013, as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint TooBigcbIn = 262145;
/// <summary>
/// An unsigned integer indicates an invalid value of cbIn that should be less than 8 (0x00000008), as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint TooSmallcbIn = 7;
/// <summary>
/// An unsigned integer indicates an invalid value of pcbOut that should be less than 8 (0x00000008), as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint TooSmallpcbOut = 7;
/// <summary>
/// An unsigned integer indicates an invalid value of pcbOut that should be larger than 8 (0x00000008) and less than 32775 (0x00008007), as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint SmallpcbOut = 32768;
/// <summary>
/// An unsigned integer indicates a valid value of pcbOut, as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint ValidpcbOut = 262144;
/// <summary>
/// An integer indicates an invalid value of pcbOut that should be larger than 262144 (0x00040000), as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const uint TooBigpcbOut = 262145;
/// <summary>
/// InvalidPcxh specify an invalid session context handle, as specified by EcDoRpcExt2 method in [MS-OXCRPC].
/// </summary>
public const int InvalidPcxh = 1;
/// <summary>
/// An unsigned integer indicates a client-derived 32-bit hash value of the User's distinguished name, as specified by EcDoConnectEx method in [MS-OXCRPC].
/// </summary>
public const uint ConnectionMod = 3409270;
/// <summary>
/// An unsigned integer indicates the code page in which text data is sent if Unicode format is not requested by the client on subsequent calls using this Session Context, as specified by EcDoConnectEx method in [MS-OXCRPC].
/// </summary>
public const uint CodePageId = 1252;
/// <summary>
/// An unsigned short indicates an arbitrary invalid value for picxr, as specified by EcDoConnectEx method in [MS-OXCRPC].
/// </summary>
public const ushort Invalidpicxr = 171;
/// <summary>
/// An unsigned long indicates a value of RowCount field in RopQueryRows request, as specified by RopQueryRows ROP in [MS-OXCROPS].
/// </summary>
public const ulong MaximumRowCount = 65535;
/// <summary>
/// An unsigned long indicates a small value of MaximumByteCount field in RopReadStream request, as specified by RopReadStream ROP in [MS-OXCROPS].
/// </summary>
public const ulong RequestedByteCount = 32;
/// <summary>
/// An integer indicates a value of MaximumBufferSize field in RopFastTransferSourceGetBuffer request, as specified by RopFastTransferSourceGetBuffer ROP in [MS-OXCROPS].
/// </summary>
public const ulong MaximumBufferSize = 65535;
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using HalconDotNet;
namespace ViewROI
{
/// <summary>
/// This class allows you to print a function into a Windows.Forms.Control.
/// The function must be supplied as an array of either double, float or
/// int values. When initializing the class you must provide the control that
/// actually draws the function plot. During the initialization you
/// can also decide whether the mouse event is used to return the (x,y)
/// coordinates of the plotted function. The scaling
/// of the x-y axis is performed automatically and depent on the length
/// of the function as well as the settings for the y-axis scaling:
/// * AXIS_RANGE_FIXED
/// * AXIS_RANGE_INCREASING
/// * AXIS_RANGE_ADAPTING
///
/// Constraints of the function plot class:
/// So far only functions containing a positive range of y-values can
/// be plotted correctly. Also only a positive and ascending x-range
/// can be plotted. The origin of the coordinate system is set to
/// be in the lower left corner of the control. Another definition
/// of the origin and hence the direction of the coordinate axis
/// is not implemented yet.
/// </summary>
public class FunctionPlot
{
// panels for display
private Graphics gPanel, backBuffer;
// graphical settings
private Pen pen, penCurve, penCursor;
private SolidBrush brushCS, brushFuncPanel;
private Font drawFont;
private StringFormat format;
private Bitmap functionMap;
// dimensions of panels
private float panelWidth;
private float panelHeight;
private float margin;
// origin
private float originX;
private float originY;
private PointF[] points;
private HFunction1D func;
// axis
private int axisAdaption;
private float axisXLength;
private float axisYLength;
private float scaleX, scaleY;
public const int AXIS_RANGE_FIXED = 3;
public const int AXIS_RANGE_INCREASING = 4;
public const int AXIS_RANGE_ADAPTING = 5;
int PreX, BorderRight, BorderTop;
/// <summary>
/// Initializes a FunctionPlot instance by providing a GUI control
/// and a flag specifying the mouse interaction mode.
/// The control is used to determine the available space to draw
/// the axes and to plot the supplied functions. Depending on the
/// available space, the values of the function as well as the axis
/// steps are adjusted (scaled) to fit into the visible part of the
/// control.
/// </summary>
/// <param name="panel">
/// An instance of the Windows.Forms.Control to plot the
/// supplied functions in
/// </param>
/// <param name="useMouseHandle">
/// Flag that specifies whether or not mouse interaction should
/// be used to create a navigation bar for the plotted function
/// </param>
public FunctionPlot(Control panel, bool useMouseHandle)
{
gPanel = panel.CreateGraphics();
panelWidth = panel.Size.Width - 32;
panelHeight = panel.Size.Height - 22;
originX = 32;
originY = panel.Size.Height - 22;
margin = 5.0f;
BorderRight = (int)(panelWidth + originX - margin);
BorderTop = (int)panelHeight;
PreX = 0;
scaleX = scaleY = 0.0f;
//default setting for axis scaling
axisAdaption = AXIS_RANGE_ADAPTING;
axisXLength = 10.0f;
axisYLength = 10.0f;
pen = new Pen(System.Drawing.Color.DarkGray, 1);
penCurve = new Pen(System.Drawing.Color.Blue, 1);
penCursor = new Pen(System.Drawing.Color.LightSteelBlue, 1);
penCursor.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
brushCS = new SolidBrush(Color.Black);
brushFuncPanel = new SolidBrush(Color.White);
drawFont = new Font("Arial", 6);
format = new StringFormat();
format.Alignment = StringAlignment.Far;
functionMap = new Bitmap(panel.Size.Width, panel.Size.Height);
backBuffer = Graphics.FromImage(functionMap);
resetPlot();
panel.Paint += new System.Windows.Forms.PaintEventHandler(this.paint);
if (useMouseHandle)
panel.MouseMove += new System.Windows.Forms.MouseEventHandler(this.mouseMoved);
}
/// <summary>
/// Convenience method for constructor call. For this case the
/// useMouseHandle flag is set to false by default.
/// </summary>
/// <param name="panel">
/// An instance of the Windows.Forms.Control to plot the
/// supplied function in.
/// </param>
public FunctionPlot(Control panel)
: this(panel, false)
{
}
/// <summary>
/// Changes the origin of the coordinate system to be
/// at the control positions x and y.
/// </summary>
/// <param name="x">
/// X position within the control coordinate system
/// </param>
/// <param name="y">
/// Y position within the control coordinate system.
/// </param>
public void setOrigin(int x, int y)
{
float tmpX;
if (x < 1 || y < 1)
return;
tmpX = originX;
originX = x;
originY = y;
panelWidth = panelWidth + tmpX - originX;
panelHeight = originY;
BorderRight = (int)(panelWidth + originX - margin);
BorderTop = (int)panelHeight;
}
/// <summary>
/// Sets the type of scaling for the y-axis. If the
/// y-axis is defined to be of fixed size, then the upper
/// limit has to be provided with val. Otherwise,
/// an 8-bit image is assumed, so the fixed size is set
/// to be 255.
/// </summary>
/// <param name="mode">
/// Class constant starting with AXIS_RANGE_*
/// </param>
/// <param name="val">
/// For the mode AXIS_RANGE_FIXED the value
/// val must be positive, otherwise
/// it has no meaning.
/// </param>
public void setAxisAdaption(int mode, float val)
{
switch (mode)
{
case AXIS_RANGE_FIXED:
axisAdaption = mode;
axisYLength = (val > 0) ? val : 255.0f;
break;
default:
axisAdaption = mode;
break;
}
}
public void setAxisAdaption(int mode)
{
setAxisAdaption(mode, -1.0f);
}
/// <summary>
/// Plots a function of double values.
/// </summary>
/// <param name="grayValues">
/// Y-values defined as an array of doubles
/// </param>
public void plotFunction(double[] grayValues)
{
drawFunction(new HTuple(grayValues));
}
/// <summary>
/// Plots a function of float values.
/// </summary>
/// <param name="grayValues">
/// Y-values defined as an array of floats
/// </param>
public void plotFunction(float[] grayValues)
{
drawFunction(new HTuple(grayValues));
}
/// <summary>
/// Plots a function of integer values.
/// </summary>
/// <param name="grayValues">
/// Y-values defined as an array of integers
/// </param>
public void plotFunction(int[] grayValues)
{
drawFunction(new HTuple(grayValues));
}
/// <summary>Plots a function provided as an HTuple</summary>
private void drawFunction(HTuple tuple)
{
HTuple val;
int maxY,maxX;
float stepOffset;
if (tuple.Length == 0)
{
resetPlot();
return;
}
val = tuple.TupleSortIndex();
maxX = tuple.Length - 1;
maxY = (int)tuple[val[val.Length - 1].I].D;
axisXLength = maxX;
switch (axisAdaption)
{
case AXIS_RANGE_ADAPTING:
axisYLength = maxY;
break;
case AXIS_RANGE_INCREASING:
axisYLength = (maxY > axisYLength) ? maxY : axisYLength;
break;
}
backBuffer.Clear(System.Drawing.Color.WhiteSmoke);
backBuffer.FillRectangle(brushFuncPanel, originX, 0, panelWidth, panelHeight);
stepOffset = drawXYLabels();
drawLineCurve(tuple, stepOffset);
backBuffer.Flush();
gPanel.DrawImageUnscaled(functionMap, 0, 0);
gPanel.Flush();
}
/// <summary>
/// Clears the panel and displays only the coordinate axes.
/// </summary>
public void resetPlot()
{
backBuffer.Clear(System.Drawing.Color.WhiteSmoke);
backBuffer.FillRectangle(brushFuncPanel, originX, 0, panelWidth, panelHeight);
func = null;
drawXYLabels();
backBuffer.Flush();
repaint();
}
/// <summary>
/// Puts (=flushes) the current content of the graphics object on screen
/// again.
/// </summary>
private void repaint()
{
gPanel.DrawImageUnscaled(functionMap, 0, 0);
gPanel.Flush();
}
/// <summary>Plots the points of the function.</summary>
private void drawLineCurve(HTuple tuple, float stepOffset)
{
int length;
if (stepOffset > 1)
points = scaleDispValue(tuple);
else
points = scaleDispBlockValue(tuple);
length = points.Length;
func = new HFunction1D(tuple);
for (int i = 0; i < length - 1; i++)
backBuffer.DrawLine(penCurve, points[i], points[i + 1]);
}
/// <summary>
/// Scales the function to the dimension of the graphics object
/// (provided by the control).
/// </summary>
/// <param name="tup">
/// Function defined as a tuple of y-values
/// </param>
/// <returns>
/// Array of PointF values, containing the scaled function data
/// </returns>
private PointF[] scaleDispValue(HTuple tup)
{
PointF [] pVals;
float xMax, yMax, yV, x, y;
int length;
xMax = axisXLength;
yMax = axisYLength;
scaleX = (xMax != 0.0f) ? ((panelWidth - margin) / xMax) : 0.0f;
scaleY = (yMax != 0.0f) ? ((panelHeight - margin) / yMax) : 0.0f;
length = tup.Length;
pVals = new PointF[length];
for (int j=0; j < length; j++)
{
yV = (float)tup[j].D;
x = originX + (float)j * scaleX;
y = panelHeight - (yV * scaleY);
pVals[j] = new PointF(x, y);
}
return pVals;
}
/// <summary>
/// Scales the function to the dimension of the graphics object
/// (provided by the control). If the stepsize for the x-axis is
/// 1, the points are scaled in a block shape.
/// </summary>
/// <param name="tup">
/// Function defined as a tuple of y-values
/// </param>
/// <returns>
/// Array of PointF values, containing the scaled function data
/// </returns>
private PointF[] scaleDispBlockValue(HTuple tup)
{
PointF [] pVals;
float xMax, yMax, yV,x,y;
int length, idx;
xMax = axisXLength;
yMax = axisYLength;
scaleX = (xMax != 0.0f) ? ((panelWidth - margin) / xMax) : 0.0f;
scaleY = (yMax != 0.0f) ? ((panelHeight - margin) / yMax) : 0.0f;
length = tup.Length;
pVals = new PointF[length * 2];
y = 0;
idx = 0;
for (int j=0; j < length; j++)
{
yV = (float)tup[j].D;
x = originX + (float)j * scaleX - (scaleX / 2.0f);
y = panelHeight - (yV * scaleY);
pVals[idx] = new PointF(x, y);
idx++;
x = originX + (float)j * scaleX + (scaleX / 2.0f);
pVals[idx] = new PointF(x, y);
idx++;
}
//trim the end points of the curve
idx--;
x = originX + (float)(length - 1) * scaleX;
pVals[idx] = new PointF(x, y);
idx = 0;
yV = (float)tup[idx].D;
x = originX;
y = panelHeight - (yV * scaleY);
pVals[idx] = new PointF(x, y);
return pVals;
}
/// <summary>Draws x- and y-axis and its labels.</summary>
/// <returns>Step size used for the x-axis</returns>
private float drawXYLabels()
{
float pX,pY,length, XStart,YStart;
float YCoord, XCoord, XEnd, YEnd, offset, offsetString, offsetStep;
float scale = 0.0f;
offsetString = 5;
XStart = originX;
YStart = originY;
//prepare scale data for x-axis
pX = axisXLength;
if (pX != 0.0)
scale = (panelWidth - margin) / pX;
if (scale > 10.0)
offset = 1.0f;
else if (scale > 2)
offset = 10.0f;
else if (scale > 0.2)
offset = 100.0f;
else
offset = 1000.0f;
/*************** draw X-Axis ***************/
XCoord = 0.0f;
YCoord = YStart;
XEnd = (scale * pX);
backBuffer.DrawLine(pen, XStart, YStart, XStart + panelWidth - margin, YStart);
backBuffer.DrawLine(pen, XStart + XCoord, YCoord, XStart + XCoord, YCoord + 6);
backBuffer.DrawString(0 + "", drawFont, brushCS, XStart + XCoord + 4, YCoord + 8, format);
backBuffer.DrawLine(pen, XStart + XEnd, YCoord, XStart + XEnd, YCoord + 6);
backBuffer.DrawString(((int)pX + ""), drawFont, brushCS, XStart + XEnd + 4, YCoord + 8, format);
length = (int)(pX / offset);
length = (offset == 10) ? length - 1 : length;
for (int i=1; i <= length; i++)
{
XCoord = (float)(offset * i * scale);
if ((XEnd - XCoord) < 20)
continue;
backBuffer.DrawLine(pen, XStart + XCoord, YCoord, XStart + XCoord, YCoord + 6);
backBuffer.DrawString(((int)(i * offset) + ""), drawFont, brushCS, XStart + XCoord + 5, YCoord + 8, format);
}
offsetStep = offset;
//prepare scale data for y-axis
pY = axisYLength;
if (pY != 0.0)
scale = ((panelHeight - margin) / pY);
if (scale > 10.0)
offset = 1.0f;
else if (scale > 2)
offset = 10.0f;
else if (scale > 0.8)
offset = 50.0f;
else if (scale > 0.12)
offset = 100.0f;
else
offset = 1000.0f;
/*************** draw Y-Axis ***************/
XCoord = XStart;
YCoord = 5.0f;
YEnd = YStart - (scale * pY);
backBuffer.DrawLine(pen, XStart, YStart, XStart, YStart - (panelHeight - margin));
backBuffer.DrawLine(pen, XCoord, YStart, XCoord - 10, YStart);
backBuffer.DrawString(0 + "", drawFont, brushCS, XCoord - 12, YStart - offsetString, format);
backBuffer.DrawLine(pen, XCoord, YEnd, XCoord - 10, YEnd);
backBuffer.DrawString(pY + "", drawFont, brushCS, XCoord - 12, YEnd - offsetString, format);
length = (int)(pY / offset);
length = (offset == 10) ? length - 1 : length;
for (int i=1; i <= length; i++)
{
YCoord = (YStart - ((float)offset * i * scale));
if ((YCoord - YEnd) < 10)
continue;
backBuffer.DrawLine(pen, XCoord, YCoord, XCoord - 10, YCoord);
backBuffer.DrawString(((int)(i * offset) + ""), drawFont, brushCS, XCoord - 12, YCoord - offsetString, format);
}
return offsetStep;
}
/// <summary>
/// Action call for the Mouse-Move event. For the x-coordinate
/// supplied by the MouseEvent, the unscaled x and y coordinates
/// of the plotted function are determined and displayed
/// on the control.
/// </summary>
private void mouseMoved(object sender, MouseEventArgs e)
{
int Xh, Xc;
HTuple Ytup;
float Yh, Yc;
Xh = e.X;
if (PreX == Xh || Xh < originX || Xh > BorderRight || func == null)
return;
PreX = Xh;
Xc = (int)Math.Round((Xh - originX) / scaleX);
Ytup = func.GetYValueFunct1d(new HTuple(Xc), "zero");
Yc = (float)Ytup[0].D;
Yh = panelHeight - (Yc * scaleY);
gPanel.DrawImageUnscaled(functionMap, 0, 0);
gPanel.DrawLine(penCursor, Xh, 0, Xh, BorderTop);
gPanel.DrawLine(penCursor, originX, Yh, BorderRight + margin, Yh);
gPanel.DrawString(("X = " + Xc), drawFont, brushCS, panelWidth - margin, 10);
gPanel.DrawString(("Y = " + (int)Yc), drawFont, brushCS, panelWidth - margin, 20);
gPanel.Flush();
}
/// <summary>
/// Action call for the Paint event of the control to trigger the
/// repainting of the function plot.
/// </summary>
private void paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
repaint();
}
}//end of class
}//end of namespace
| |
/*===-----------------------------* C# *---------------------------------===//
//
// THIS FILE IS GENERATED BY INVAR. DO NOT EDIT !!!
//
//===----------------------------------------------------------------------===*/
namespace Test.Abc {
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
/// Test comments.
public sealed class Info
: Invar.BinaryDecode
, Invar.BinaryEncode
, Invar.JSONEncode
, Invar.XMLEncode
{
public const uint CRC32 = 0x120FDCDB;
private Int32 key = 123;
private SByte number01 = -1;
private Int16 number02 = -1;
private Int32 number03 = -1;
private Int64 number04 = -1L; // Test field comments.
private Byte number05 = 0;
private UInt16 number06 = 0;
private UInt32 number07 = 0;
private UInt64 number08 = 0L;
private Single number09 = 0.0F;
private Double number10 = 0.00;
private Boolean isReal = false;
private String s = "hello"; // a string.
private List<String> world = new List<String>();
private Gender gender = Gender.NONE;
private Info next = null;
private Test.Abc.Conflict conflict = new Test.Abc.Conflict();
private List<Test.Xyz.Conflict> conflicts = new List<Test.Xyz.Conflict>();
private List<Double> numbers = new List<Double>();
private Dictionary<Info,Gender> mapInfoG = new Dictionary<Info,Gender>();
private Dictionary<Gender,Info> mapGenderInfo = new Dictionary<Gender,Info>();
private Dictionary<Int32,Double> mapDouble = new Dictionary<Int32,Double>();
private Dictionary<String,String> hotfix = null; // [AutoAdd] Hotfix.
/// .
[Invar.InvarRule("int32", "f0")]
public Int32 GetKey() { return this.key; }
/// .
[Invar.InvarRule("int8", "f1")]
public SByte GetNumber01() { return this.number01; }
/// .
[Invar.InvarRule("int16", "f2")]
public Int16 GetNumber02() { return this.number02; }
/// .
[Invar.InvarRule("int32", "f3")]
public Int32 GetNumber03() { return this.number03; }
/// Test field comments.
[Invar.InvarRule("int64", "f4")]
public Int64 GetNumber04() { return this.number04; }
/// .
[Invar.InvarRule("uint8", "f5")]
public Byte GetNumber05() { return this.number05; }
/// .
[Invar.InvarRule("uint16", "f6")]
public UInt16 GetNumber06() { return this.number06; }
/// .
[Invar.InvarRule("uint32", "f7")]
public UInt32 GetNumber07() { return this.number07; }
/// .
[Invar.InvarRule("uint64", "f8")]
public UInt64 GetNumber08() { return this.number08; }
/// .
[Invar.InvarRule("float", "f9")]
public Single GetNumber09() { return this.number09; }
/// .
[Invar.InvarRule("double", "f10")]
public Double GetNumber10() { return this.number10; }
/// .
[Invar.InvarRule("bool", "f11")]
public Boolean GetIsReal() { return this.isReal; }
/// a string.
[Invar.InvarRule("string", "f12")]
public String GetS() { return this.s; }
/// .
[Invar.InvarRule("vec<string>", "f13")]
public List<String> GetWorld() { return this.world; }
/// .
[Invar.InvarRule("Test.Abc.Gender", "f14")]
public Gender GetGender() { return this.gender; }
/// .
[Invar.InvarRule("Test.Abc.Info", "f15")]
public Info GetNext() { return this.next; }
/// .
[Invar.InvarRule("Test.Abc.Conflict", "f16")]
public Test.Abc.Conflict GetConflict() { return this.conflict; }
/// .
[Invar.InvarRule("vec<Test.Xyz.Conflict>", "f17")]
public List<Test.Xyz.Conflict> GetConflicts() { return this.conflicts; }
/// .
[Invar.InvarRule("vec<double>", "f18")]
public List<Double> GetNumbers() { return this.numbers; }
/// .
[Invar.InvarRule("map<Test.Abc.Info,Test.Abc.Gender>", "f19")]
public Dictionary<Info,Gender> GetMapInfoG() { return this.mapInfoG; }
/// .
[Invar.InvarRule("map<Test.Abc.Gender,Test.Abc.Info>", "f20")]
public Dictionary<Gender,Info> GetMapGenderInfo() { return this.mapGenderInfo; }
/// .
[Invar.InvarRule("map<int32,double>", "f21")]
public Dictionary<Int32,Double> GetMapDouble() { return this.mapDouble; }
/// [AutoAdd] Hotfix.
[Invar.InvarRule("map<string,string>", "f22")]
public Dictionary<String,String> GetHotfix() { return this.hotfix; }
/// .
[Invar.InvarRule("int32", "f0")]
public Info SetKey(Int32 value) { this.key = value; return this; }
/// .
[Invar.InvarRule("int8", "f1")]
public Info SetNumber01(SByte value) { this.number01 = value; return this; }
/// .
[Invar.InvarRule("int16", "f2")]
public Info SetNumber02(Int16 value) { this.number02 = value; return this; }
/// .
[Invar.InvarRule("int32", "f3")]
public Info SetNumber03(Int32 value) { this.number03 = value; return this; }
/// Test field comments.
[Invar.InvarRule("int64", "f4")]
public Info SetNumber04(Int64 value) { this.number04 = value; return this; }
/// .
[Invar.InvarRule("uint8", "f5")]
public Info SetNumber05(Byte value) { this.number05 = value; return this; }
/// .
[Invar.InvarRule("uint16", "f6")]
public Info SetNumber06(UInt16 value) { this.number06 = value; return this; }
/// .
[Invar.InvarRule("uint32", "f7")]
public Info SetNumber07(UInt32 value) { this.number07 = value; return this; }
/// .
[Invar.InvarRule("uint64", "f8")]
public Info SetNumber08(UInt64 value) { this.number08 = value; return this; }
/// .
[Invar.InvarRule("float", "f9")]
public Info SetNumber09(Single value) { this.number09 = value; return this; }
/// .
[Invar.InvarRule("double", "f10")]
public Info SetNumber10(Double value) { this.number10 = value; return this; }
/// .
[Invar.InvarRule("bool", "f11")]
public Info SetIsReal(Boolean value) { this.isReal = value; return this; }
/// a string.
[Invar.InvarRule("string", "f12")]
public Info SetS(String value) { this.s = value; return this; }
/// .
[Invar.InvarRule("Test.Abc.Gender", "f14")]
public Info SetGender(Gender value) { this.gender = value; return this; }
/// .
[Invar.InvarRule("Test.Abc.Info", "f15")]
public Info SetNext(Info value) { this.next = value; return this; }
/// .
[Invar.InvarRule("Test.Abc.Conflict", "f16")]
public Info SetConflict(Test.Abc.Conflict value) { this.conflict = value; return this; }
/// [AutoAdd] Hotfix.
[Invar.InvarRule("map<string,string>", "f22")]
public Info SetHotfix(Dictionary<String,String> value) { this.hotfix = value; return this; }
public Info Reuse()
{
this.key = 123;
this.number01 = -1;
this.number02 = -1;
this.number03 = -1;
this.number04 = -1L;
this.number05 = 0;
this.number06 = 0;
this.number07 = 0;
this.number08 = 0L;
this.number09 = 0.0F;
this.number10 = 0.00;
this.isReal = false;
this.s = "hello";
this.world.Clear();
this.gender = Gender.NONE;
if (this.next != null) { this.next.Reuse(); }
this.conflict.Reuse();
this.conflicts.Clear();
this.numbers.Clear();
this.mapInfoG.Clear();
this.mapGenderInfo.Clear();
this.mapDouble.Clear();
if (this.hotfix != null) { this.hotfix.Clear(); }
return this;
} //Info::Reuse()
public Info Copy(Info from_)
{
if (null == from_ || this == from_) {
return this;
}
this.key = from_.key;
this.number01 = from_.number01;
this.number02 = from_.number02;
this.number03 = from_.number03;
this.number04 = from_.number04;
this.number05 = from_.number05;
this.number06 = from_.number06;
this.number07 = from_.number07;
this.number08 = from_.number08;
this.number09 = from_.number09;
this.number10 = from_.number10;
this.isReal = from_.isReal;
this.s = from_.s;
this.world.Clear();
this.world.AddRange(from_.world);
this.gender = from_.gender;
if (null == from_.next) {
this.next = null;
} else {
if (null == this.next) { this.next = new Info(); }
this.next.Copy(from_.next);
}
this.conflict.Copy(from_.conflict);
this.conflicts.Clear();
this.conflicts.AddRange(from_.conflicts);
this.numbers.Clear();
this.numbers.AddRange(from_.numbers);
this.mapInfoG.Clear();
foreach (var mapInfoGIter in from_.mapInfoG) {
this.mapInfoG.Add(mapInfoGIter.Key, mapInfoGIter.Value);
}
this.mapGenderInfo.Clear();
foreach (var mapGenderInfoIter in from_.mapGenderInfo) {
this.mapGenderInfo.Add(mapGenderInfoIter.Key, mapGenderInfoIter.Value);
}
this.mapDouble.Clear();
foreach (var mapDoubleIter in from_.mapDouble) {
this.mapDouble.Add(mapDoubleIter.Key, mapDoubleIter.Value);
}
if (null == from_.hotfix) {
this.hotfix = null;
} else {
if (null == this.hotfix) { this.hotfix = new Dictionary<String,String>(); }
else { this.hotfix.Clear(); }
foreach (var hotfixIter in from_.hotfix) {
this.hotfix.Add(hotfixIter.Key, hotfixIter.Value);
}
}
return this;
} //Info::Copy(...)
public void Read(BinaryReader r)
{
this.key = r.ReadInt32();
this.number01 = r.ReadSByte();
this.number02 = r.ReadInt16();
this.number03 = r.ReadInt32();
this.number04 = r.ReadInt64();
this.number05 = r.ReadByte();
this.number06 = r.ReadUInt16();
this.number07 = r.ReadUInt32();
this.number08 = r.ReadUInt64();
this.number09 = r.ReadSingle();
this.number10 = r.ReadDouble();
this.isReal = r.ReadBoolean();
this.s = Encoding.UTF8.GetString(r.ReadBytes(r.ReadInt32()));
UInt32 lenWorld = r.ReadUInt32();
for (UInt32 iWorld = 0; iWorld < lenWorld; iWorld++) {
String n1 = Encoding.UTF8.GetString(r.ReadBytes(r.ReadInt32()));
this.world.Add(n1);
}
this.gender = (Gender)Enum.ToObject(typeof(Gender), r.ReadInt32());
sbyte nextExists = r.ReadSByte();
if ((sbyte)0x01 == nextExists) {
if (this.next == null) { this.next = new Info(); }
this.next.Read(r);
}
else if ((sbyte)0x00 == nextExists) { this.next = null; }
else { throw new IOException("Protoc read error: The value of 'nextExists' is invalid.", 497); }
this.conflict.Read(r);
UInt32 lenConflicts = r.ReadUInt32();
for (UInt32 iConflicts = 0; iConflicts < lenConflicts; iConflicts++) {
Test.Xyz.Conflict n1 = new Test.Xyz.Conflict();
n1.Read(r);
this.conflicts.Add(n1);
}
UInt32 lenNumbers = r.ReadUInt32();
for (UInt32 iNumbers = 0; iNumbers < lenNumbers; iNumbers++) {
Double n1 = r.ReadDouble();
this.numbers.Add(n1);
}
UInt32 lenMapInfoG = r.ReadUInt32();
for (UInt32 iMapInfoG = 0; iMapInfoG < lenMapInfoG; iMapInfoG++) {
Info k1 = new Info();
k1.Read(r);
Gender v1 = (Gender)Enum.ToObject(typeof(Gender), r.ReadInt32());
if (!this.mapInfoG.ContainsKey(k1)) {
this.mapInfoG.Add(k1, v1);
} else {
this.mapInfoG[k1] = v1;
}
}
UInt32 lenMapGenderInfo = r.ReadUInt32();
for (UInt32 iMapGenderInfo = 0; iMapGenderInfo < lenMapGenderInfo; iMapGenderInfo++) {
Gender k1 = (Gender)Enum.ToObject(typeof(Gender), r.ReadInt32());
Info v1 = new Info();
v1.Read(r);
if (!this.mapGenderInfo.ContainsKey(k1)) {
this.mapGenderInfo.Add(k1, v1);
} else {
this.mapGenderInfo[k1] = v1;
}
}
UInt32 lenMapDouble = r.ReadUInt32();
for (UInt32 iMapDouble = 0; iMapDouble < lenMapDouble; iMapDouble++) {
Int32 k1 = r.ReadInt32();
Double v1 = r.ReadDouble();
if (!this.mapDouble.ContainsKey(k1)) {
this.mapDouble.Add(k1, v1);
} else {
this.mapDouble[k1] = v1;
}
}
sbyte hotfixExists = r.ReadSByte();
if ((sbyte)0x01 == hotfixExists) {
if (this.hotfix == null) { this.hotfix = new Dictionary<String,String>(); }
UInt32 lenHotfix = r.ReadUInt32();
for (UInt32 iHotfix = 0; iHotfix < lenHotfix; iHotfix++) {
String k1 = Encoding.UTF8.GetString(r.ReadBytes(r.ReadInt32()));
String v1 = Encoding.UTF8.GetString(r.ReadBytes(r.ReadInt32()));
if (!this.hotfix.ContainsKey(k1)) {
this.hotfix.Add(k1, v1);
} else {
this.hotfix[k1] = v1;
}
}
}
else if ((sbyte)0x00 == hotfixExists) { this.hotfix = null; }
else { throw new IOException("Protoc read error: The value of 'hotfixExists' is invalid.", 498); }
} //Info::Read(...)
public void Write(BinaryWriter w)
{
w.Write(this.key);
w.Write(this.number01);
w.Write(this.number02);
w.Write(this.number03);
w.Write(this.number04);
w.Write(this.number05);
w.Write(this.number06);
w.Write(this.number07);
w.Write(this.number08);
w.Write(this.number09);
w.Write(this.number10);
w.Write(this.isReal);
byte[] sBytes = Encoding.UTF8.GetBytes(this.s);
w.Write(sBytes.Length);
w.Write(sBytes);
w.Write(this.world.Count);
foreach (String n1 in this.world) {
byte[] n1Bytes = Encoding.UTF8.GetBytes(n1);
w.Write(n1Bytes.Length);
w.Write(n1Bytes);
}
w.Write((Int32)this.gender);
if (this.next != null) {
w.Write((sbyte)0x01);
this.next.Write(w);
} else {
w.Write((sbyte)0x00);
}
this.conflict.Write(w);
w.Write(this.conflicts.Count);
foreach (Test.Xyz.Conflict n1 in this.conflicts) {
n1.Write(w);
}
w.Write(this.numbers.Count);
foreach (Double n1 in this.numbers) {
w.Write(n1);
}
w.Write(this.mapInfoG.Count);
foreach (KeyValuePair<Info,Gender> mapInfoGIter in this.mapInfoG) {
Info k1 = mapInfoGIter.Key;
k1.Write(w);
Gender v1 = mapInfoGIter.Value;
w.Write((Int32)v1);
}
w.Write(this.mapGenderInfo.Count);
foreach (KeyValuePair<Gender,Info> mapGenderInfoIter in this.mapGenderInfo) {
Gender k1 = mapGenderInfoIter.Key;
w.Write((Int32)k1);
Info v1 = mapGenderInfoIter.Value;
v1.Write(w);
}
w.Write(this.mapDouble.Count);
foreach (KeyValuePair<Int32,Double> mapDoubleIter in this.mapDouble) {
Int32 k1 = mapDoubleIter.Key;
w.Write(k1);
Double v1 = mapDoubleIter.Value;
w.Write(v1);
}
if (this.hotfix != null) {
w.Write((sbyte)0x01);
w.Write(this.hotfix.Count);
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) {
String k1 = hotfixIter.Key;
byte[] k1Bytes = Encoding.UTF8.GetBytes(k1);
w.Write(k1Bytes.Length);
w.Write(k1Bytes);
String v1 = hotfixIter.Value;
byte[] v1Bytes = Encoding.UTF8.GetBytes(v1);
w.Write(v1Bytes.Length);
w.Write(v1Bytes);
}
} else {
w.Write((sbyte)0x00);
}
} //Info::Write(...)
public override String ToString()
{
StringBuilder result = new StringBuilder();
result.Append('{').Append(' ');
result.Append(GetType().ToString());
result.Append(',').Append(' ').Append("key").Append(':');
result.Append(this.key.ToString());
result.Append(',').Append(' ').Append("number01").Append(':');
result.Append(this.number01.ToString());
result.Append(',').Append(' ').Append("number02").Append(':');
result.Append(this.number02.ToString());
result.Append(',').Append(' ').Append("number03").Append(':');
result.Append(this.number03.ToString());
result.Append(',').Append(' ').Append("number04").Append(':');
result.Append(this.number04.ToString());
result.Append(',').Append(' ').Append("number05").Append(':');
result.Append(this.number05.ToString());
result.Append(',').Append(' ').Append("number06").Append(':');
result.Append(this.number06.ToString());
result.Append(',').Append(' ').Append("number07").Append(':');
result.Append(this.number07.ToString());
result.Append(',').Append(' ').Append("number08").Append(':');
result.Append(this.number08.ToString());
result.Append(',').Append(' ').Append("number09").Append(':');
result.Append(this.number09.ToString());
result.Append(',').Append(' ').Append("number10").Append(':');
result.Append(this.number10.ToString());
result.Append(',').Append(' ').Append("isReal").Append(':');
result.Append(this.isReal.ToString());
result.Append(',').Append(' ').Append("s").Append(':');
result.Append("\"" + this.s + "\"");
result.Append(',').Append(' ').Append("world").Append(':');
result.Append("(" + this.world.Count + ")");
result.Append(',').Append(' ').Append("gender").Append(':');
result.Append(this.gender.ToString());
result.Append(',').Append(' ').Append("next").Append(':');
if (this.next != null) { result.Append("<Info>"); }
else { result.Append("null"); }
result.Append(',').Append(' ').Append("conflict").Append(':');
result.Append("<Test.Abc.Conflict>");
result.Append(',').Append(' ').Append("conflicts").Append(':');
result.Append("(" + this.conflicts.Count + ")");
result.Append(',').Append(' ').Append("numbers").Append(':');
result.Append("(" + this.numbers.Count + ")");
result.Append(',').Append(' ').Append("mapInfoG").Append(':');
result.Append("[" + this.mapInfoG.Count + "]");
result.Append(',').Append(' ').Append("mapGenderInfo").Append(':');
result.Append("[" + this.mapGenderInfo.Count + "]");
result.Append(',').Append(' ').Append("mapDouble").Append(':');
result.Append("[" + this.mapDouble.Count + "]");
result.Append(',').Append(' ').Append("hotfix").Append(':');
if (this.hotfix != null) { result.Append("[" + this.hotfix.Count + "]"); }
else { result.Append("null"); }
result.Append(' ').Append('}');
return result.ToString();
} //Info::ToString()
public StringBuilder ToStringJSON()
{
StringBuilder code = new StringBuilder();
this.WriteJSON(code);
return code;
}
public void WriteJSON(StringBuilder s)
{
s.Append('\n').Append('{');
string comma = null;
s.Append('"').Append("key").Append('"').Append(':'); comma = ","; s.Append(this.key.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number01").Append('"').Append(':'); comma = ","; s.Append(this.number01.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number02").Append('"').Append(':'); comma = ","; s.Append(this.number02.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number03").Append('"').Append(':'); comma = ","; s.Append(this.number03.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number04").Append('"').Append(':'); comma = ","; s.Append(this.number04.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number05").Append('"').Append(':'); comma = ","; s.Append(this.number05.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number06").Append('"').Append(':'); comma = ","; s.Append(this.number06.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number07").Append('"').Append(':'); comma = ","; s.Append(this.number07.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number08").Append('"').Append(':'); comma = ","; s.Append(this.number08.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number09").Append('"').Append(':'); comma = ","; s.Append(this.number09.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("number10").Append('"').Append(':'); comma = ","; s.Append(this.number10.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("isReal").Append('"').Append(':'); comma = ","; s.Append(this.isReal.ToString().ToLower());
bool sExists = !String.IsNullOrEmpty(this.s);
if (!String.IsNullOrEmpty(comma) && sExists) { s.Append(comma); comma = null; }
if (sExists) {
s.Append('"').Append("s").Append('"').Append(':'); comma = ","; s.Append('"').Append(this.s.ToString()).Append('"');
}
bool worldExists = (null != this.world && this.world.Count > 0);
if (!String.IsNullOrEmpty(comma) && worldExists) { s.Append(comma); comma = null; }
if (worldExists) { s.Append('"').Append("world").Append('"').Append(':'); comma = ","; }
int worldSize = (null == this.world ? 0 : this.world.Count);
if (worldSize > 0) {
s.Append('\n').Append('[');
int worldIdx = 0;
foreach (String n1 in this.world) { /* vec.for: this.world */
++worldIdx;
s.Append('"').Append(n1.ToString()).Append('"');
if (worldIdx != worldSize) { s.Append(','); }
}
s.Append(']');
}
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append('"').Append("gender").Append('"').Append(':'); comma = ","; s.Append((int)this.gender);;
bool nextExists = (null != this.next);
if (!String.IsNullOrEmpty(comma) && nextExists) { s.Append(comma); comma = null; }
if (nextExists) {
s.Append('"').Append("next").Append('"').Append(':'); comma = ","; this.next.WriteJSON(s);
}
bool conflictExists = (null != this.conflict);
if (!String.IsNullOrEmpty(comma) && conflictExists) { s.Append(comma); comma = null; }
if (conflictExists) {
s.Append('"').Append("conflict").Append('"').Append(':'); comma = ","; this.conflict.WriteJSON(s);
}
bool conflictsExists = (null != this.conflicts && this.conflicts.Count > 0);
if (!String.IsNullOrEmpty(comma) && conflictsExists) { s.Append(comma); comma = null; }
if (conflictsExists) { s.Append('"').Append("conflicts").Append('"').Append(':'); comma = ","; }
int conflictsSize = (null == this.conflicts ? 0 : this.conflicts.Count);
if (conflictsSize > 0) {
s.Append('\n').Append('[');
int conflictsIdx = 0;
foreach (Test.Xyz.Conflict n1 in this.conflicts) { /* vec.for: this.conflicts */
++conflictsIdx;
n1.WriteJSON(s);
if (conflictsIdx != conflictsSize) { s.Append(','); }
}
s.Append(']');
}
bool numbersExists = (null != this.numbers && this.numbers.Count > 0);
if (!String.IsNullOrEmpty(comma) && numbersExists) { s.Append(comma); comma = null; }
if (numbersExists) { s.Append('"').Append("numbers").Append('"').Append(':'); comma = ","; }
int numbersSize = (null == this.numbers ? 0 : this.numbers.Count);
if (numbersSize > 0) {
s.Append('\n').Append('[');
int numbersIdx = 0;
foreach (Double n1 in this.numbers) { /* vec.for: this.numbers */
++numbersIdx;
s.Append(n1.ToString());
if (numbersIdx != numbersSize) { s.Append(','); }
}
s.Append(']');
}
bool mapInfoGExists = (null != this.mapInfoG && this.mapInfoG.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapInfoGExists) { s.Append(comma); comma = null; }
if (mapInfoGExists) { s.Append('"').Append("mapInfoG").Append('"').Append(':'); comma = ","; }
int mapInfoGSize = (null == this.mapInfoG ? 0 : this.mapInfoG.Count);
if (mapInfoGSize > 0) {
s.Append('\n').Append('{');
int mapInfoGIdx = 0;
foreach (KeyValuePair<Info,Gender> mapInfoGIter in this.mapInfoG) { /* map.for: this.mapInfoG */
++mapInfoGIdx;
Info k1 = mapInfoGIter.Key; /* nest.k */
s.Append('"'); k1.WriteJSON(s); s.Append('"').Append(':');
Gender v1 = mapInfoGIter.Value; /* nest.v */
s.Append((int)v1);;
if (mapInfoGIdx != mapInfoGSize) { s.Append(','); }
}
s.Append('}');
}
bool mapGenderInfoExists = (null != this.mapGenderInfo && this.mapGenderInfo.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapGenderInfoExists) { s.Append(comma); comma = null; }
if (mapGenderInfoExists) { s.Append('"').Append("mapGenderInfo").Append('"').Append(':'); comma = ","; }
int mapGenderInfoSize = (null == this.mapGenderInfo ? 0 : this.mapGenderInfo.Count);
if (mapGenderInfoSize > 0) {
s.Append('\n').Append('{');
int mapGenderInfoIdx = 0;
foreach (KeyValuePair<Gender,Info> mapGenderInfoIter in this.mapGenderInfo) { /* map.for: this.mapGenderInfo */
++mapGenderInfoIdx;
Gender k1 = mapGenderInfoIter.Key; /* nest.k */
s.Append('"'); s.Append((int)k1);; s.Append('"').Append(':');
Info v1 = mapGenderInfoIter.Value; /* nest.v */
v1.WriteJSON(s);
if (mapGenderInfoIdx != mapGenderInfoSize) { s.Append(','); }
}
s.Append('}');
}
bool mapDoubleExists = (null != this.mapDouble && this.mapDouble.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapDoubleExists) { s.Append(comma); comma = null; }
if (mapDoubleExists) { s.Append('"').Append("mapDouble").Append('"').Append(':'); comma = ","; }
int mapDoubleSize = (null == this.mapDouble ? 0 : this.mapDouble.Count);
if (mapDoubleSize > 0) {
s.Append('\n').Append('{');
int mapDoubleIdx = 0;
foreach (KeyValuePair<Int32,Double> mapDoubleIter in this.mapDouble) { /* map.for: this.mapDouble */
++mapDoubleIdx;
Int32 k1 = mapDoubleIter.Key; /* nest.k */
s.Append('"'); s.Append(k1.ToString()); s.Append('"').Append(':');
Double v1 = mapDoubleIter.Value; /* nest.v */
s.Append(v1.ToString());
if (mapDoubleIdx != mapDoubleSize) { s.Append(','); }
}
s.Append('}');
}
bool hotfixExists = (null != this.hotfix && this.hotfix.Count > 0);
if (!String.IsNullOrEmpty(comma) && hotfixExists) { s.Append(comma); comma = null; }
if (hotfixExists) {
int hotfixSize = (null == this.hotfix ? 0 : this.hotfix.Count);
if (hotfixSize > 0) {
s.Append('\n').Append('{');
int hotfixIdx = 0;
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) { /* map.for: this.hotfix */
++hotfixIdx;
String k1 = hotfixIter.Key; /* nest.k */
s.Append('"'); s.Append('"').Append(k1.ToString()).Append('"'); s.Append('"').Append(':');
String v1 = hotfixIter.Value; /* nest.v */
s.Append('"').Append(v1.ToString()).Append('"');
if (hotfixIdx != hotfixSize) { s.Append(','); }
}
s.Append('}');
} comma = ",";
}
s.Append('}').Append('\n');
} //Info::WriteJSON(...)
public StringBuilder ToStringLua()
{
StringBuilder code = new StringBuilder();
code.Append("-- Info.CRC32: 0x");
code.Append(CRC32.ToString("X2")).Append(" --").Append('\n');
code.Append("local table=");
this.WriteLua(code); code.Append(';');
return code;
}
public void WriteLua(StringBuilder s)
{
s.Append('\n').Append('{');
string comma = null;
s.Append("key").Append('='); comma = ","; s.Append(this.key.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number01").Append('='); comma = ","; s.Append(this.number01.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number02").Append('='); comma = ","; s.Append(this.number02.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number03").Append('='); comma = ","; s.Append(this.number03.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number04").Append('='); comma = ","; s.Append(this.number04.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number05").Append('='); comma = ","; s.Append(this.number05.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number06").Append('='); comma = ","; s.Append(this.number06.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number07").Append('='); comma = ","; s.Append(this.number07.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number08").Append('='); comma = ","; s.Append(this.number08.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number09").Append('='); comma = ","; s.Append(this.number09.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("number10").Append('='); comma = ","; s.Append(this.number10.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("isReal").Append('='); comma = ","; s.Append(this.isReal.ToString().ToLower());
bool sExists = !String.IsNullOrEmpty(this.s);
if (!String.IsNullOrEmpty(comma) && sExists) { s.Append(comma); comma = null; }
if (sExists) {
s.Append("s").Append('='); comma = ","; s.Append('"').Append(this.s.ToString()).Append('"');
}
bool worldExists = (null != this.world && this.world.Count > 0);
if (!String.IsNullOrEmpty(comma) && worldExists) { s.Append(comma); comma = null; }
if (worldExists) { s.Append("world").Append('='); comma = ","; }
int worldSize = (null == this.world ? 0 : this.world.Count);
if (worldSize > 0) {
s.Append('\n').Append('{');
int worldIdx = 0;
foreach (String n1 in this.world) { /* vec.for: this.world */
++worldIdx;
s.Append('"').Append(n1.ToString()).Append('"');
if (worldIdx != worldSize) { s.Append(','); }
s.Append('}');
}
}
if (!String.IsNullOrEmpty(comma)) { s.Append(comma); comma = null; }
s.Append("gender").Append('='); comma = ","; s.Append((int)this.gender);;
bool nextExists = (null != this.next);
if (!String.IsNullOrEmpty(comma) && nextExists) { s.Append(comma); comma = null; }
if (nextExists) {
s.Append("next").Append('='); comma = ","; this.next.WriteLua(s);
}
bool conflictExists = (null != this.conflict);
if (!String.IsNullOrEmpty(comma) && conflictExists) { s.Append(comma); comma = null; }
if (conflictExists) {
s.Append("conflict").Append('='); comma = ","; this.conflict.WriteLua(s);
}
bool conflictsExists = (null != this.conflicts && this.conflicts.Count > 0);
if (!String.IsNullOrEmpty(comma) && conflictsExists) { s.Append(comma); comma = null; }
if (conflictsExists) { s.Append("conflicts").Append('='); comma = ","; }
int conflictsSize = (null == this.conflicts ? 0 : this.conflicts.Count);
if (conflictsSize > 0) {
s.Append('\n').Append('{');
int conflictsIdx = 0;
foreach (Test.Xyz.Conflict n1 in this.conflicts) { /* vec.for: this.conflicts */
++conflictsIdx;
n1.WriteLua(s);
if (conflictsIdx != conflictsSize) { s.Append(','); }
s.Append('}');
}
}
bool numbersExists = (null != this.numbers && this.numbers.Count > 0);
if (!String.IsNullOrEmpty(comma) && numbersExists) { s.Append(comma); comma = null; }
if (numbersExists) { s.Append("numbers").Append('='); comma = ","; }
int numbersSize = (null == this.numbers ? 0 : this.numbers.Count);
if (numbersSize > 0) {
s.Append('\n').Append('{');
int numbersIdx = 0;
foreach (Double n1 in this.numbers) { /* vec.for: this.numbers */
++numbersIdx;
s.Append(n1.ToString());
if (numbersIdx != numbersSize) { s.Append(','); }
s.Append('}');
}
}
bool mapInfoGExists = (null != this.mapInfoG && this.mapInfoG.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapInfoGExists) { s.Append(comma); comma = null; }
if (mapInfoGExists) { s.Append("mapInfoG").Append('='); comma = ","; }
int mapInfoGSize = (null == this.mapInfoG ? 0 : this.mapInfoG.Count);
if (mapInfoGSize > 0) {
s.Append('\n').Append('{');
int mapInfoGIdx = 0;
foreach (KeyValuePair<Info,Gender> mapInfoGIter in this.mapInfoG) { /* map.for: this.mapInfoG */
++mapInfoGIdx;
Info k1 = mapInfoGIter.Key; /* nest.k */
k1.WriteLua(s); s.Append('=');
Gender v1 = mapInfoGIter.Value; /* nest.v */
s.Append((int)v1);;
if (mapInfoGIdx != mapInfoGSize) { s.Append(','); }
s.Append('}');
}
}
bool mapGenderInfoExists = (null != this.mapGenderInfo && this.mapGenderInfo.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapGenderInfoExists) { s.Append(comma); comma = null; }
if (mapGenderInfoExists) { s.Append("mapGenderInfo").Append('='); comma = ","; }
int mapGenderInfoSize = (null == this.mapGenderInfo ? 0 : this.mapGenderInfo.Count);
if (mapGenderInfoSize > 0) {
s.Append('\n').Append('{');
int mapGenderInfoIdx = 0;
foreach (KeyValuePair<Gender,Info> mapGenderInfoIter in this.mapGenderInfo) { /* map.for: this.mapGenderInfo */
++mapGenderInfoIdx;
Gender k1 = mapGenderInfoIter.Key; /* nest.k */
s.Append('['); s.Append((int)k1);; s.Append(']').Append('=');
Info v1 = mapGenderInfoIter.Value; /* nest.v */
v1.WriteLua(s);
if (mapGenderInfoIdx != mapGenderInfoSize) { s.Append(','); }
s.Append('}');
}
}
bool mapDoubleExists = (null != this.mapDouble && this.mapDouble.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapDoubleExists) { s.Append(comma); comma = null; }
if (mapDoubleExists) { s.Append("mapDouble").Append('='); comma = ","; }
int mapDoubleSize = (null == this.mapDouble ? 0 : this.mapDouble.Count);
if (mapDoubleSize > 0) {
s.Append('\n').Append('{');
int mapDoubleIdx = 0;
foreach (KeyValuePair<Int32,Double> mapDoubleIter in this.mapDouble) { /* map.for: this.mapDouble */
++mapDoubleIdx;
Int32 k1 = mapDoubleIter.Key; /* nest.k */
s.Append('['); s.Append(k1.ToString()); s.Append(']').Append('=');
Double v1 = mapDoubleIter.Value; /* nest.v */
s.Append(v1.ToString());
if (mapDoubleIdx != mapDoubleSize) { s.Append(','); }
s.Append('}');
}
}
bool hotfixExists = (null != this.hotfix && this.hotfix.Count > 0);
if (!String.IsNullOrEmpty(comma) && hotfixExists) { s.Append(comma); comma = null; }
if (hotfixExists) {
int hotfixSize = (null == this.hotfix ? 0 : this.hotfix.Count);
if (hotfixSize > 0) {
s.Append('\n').Append('{');
int hotfixIdx = 0;
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) { /* map.for: this.hotfix */
++hotfixIdx;
String k1 = hotfixIter.Key; /* nest.k */
s.Append('"').Append(k1.ToString()).Append('"'); s.Append('=');
String v1 = hotfixIter.Value; /* nest.v */
s.Append('"').Append(v1.ToString()).Append('"');
if (hotfixIdx != hotfixSize) { s.Append(','); }
s.Append('}');
}
} comma = ",";
}
s.Append('}').Append('\n');
}
public StringBuilder ToStringPHP()
{
StringBuilder code = new StringBuilder();
code.Append("<?php ").Append("/* Info.CRC32: 0x");
code.Append(CRC32.ToString("X2")).Append(" */").Append('\n');
code.Append('\n').Append("return ");
this.WritePHP(code); code.Append(';').Append('\n');
return code;
}
public void WritePHP(StringBuilder s)
{
s.Append("array").Append('(').Append('\n');
string comma = null;
s.Append('\'').Append("key").Append('\'').Append("=>"); comma = ","; s.Append(this.key.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number01").Append('\'').Append("=>"); comma = ","; s.Append(this.number01.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number02").Append('\'').Append("=>"); comma = ","; s.Append(this.number02.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number03").Append('\'').Append("=>"); comma = ","; s.Append(this.number03.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number04").Append('\'').Append("=>"); comma = ","; s.Append(this.number04.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number05").Append('\'').Append("=>"); comma = ","; s.Append(this.number05.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number06").Append('\'').Append("=>"); comma = ","; s.Append(this.number06.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number07").Append('\'').Append("=>"); comma = ","; s.Append(this.number07.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number08").Append('\'').Append("=>"); comma = ","; s.Append(this.number08.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number09").Append('\'').Append("=>"); comma = ","; s.Append(this.number09.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("number10").Append('\'').Append("=>"); comma = ","; s.Append(this.number10.ToString());
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("isReal").Append('\'').Append("=>"); comma = ","; s.Append(this.isReal.ToString().ToLower());
bool sExists = !String.IsNullOrEmpty(this.s);
if (!String.IsNullOrEmpty(comma) && sExists) { s.Append(comma).Append('\n'); comma = null; }
if (sExists) {
s.Append('\'').Append("s").Append('\'').Append("=>"); comma = ","; s.Append('\'').Append(this.s.ToString()).Append('\'');
}
bool worldExists = (null != this.world && this.world.Count > 0);
if (!String.IsNullOrEmpty(comma) && worldExists) { s.Append(comma).Append('\n'); comma = null; }
if (worldExists) { s.Append('\'').Append("world").Append('\'').Append("=>"); comma = ","; }
int worldSize = (null == this.world ? 0 : this.world.Count);
if (worldSize > 0) {
s.Append("array").Append('(').Append('\n');
int worldIdx = 0;
foreach (String n1 in this.world) { /* vec.for: this.world */
++worldIdx;
s.Append('\'').Append(n1.ToString()).Append('\'');
if (worldIdx != worldSize) { s.Append(',').Append('\n'); }
}
s.Append("/* vec size: ").Append(this.world.Count).Append(" */").Append(')');
}
if (!String.IsNullOrEmpty(comma)) { s.Append(comma).Append('\n'); comma = null; }
s.Append('\'').Append("gender").Append('\'').Append("=>"); comma = ","; s.Append((int)this.gender);
s.Append("/*Gender::").Append(this.gender.ToString()).Append("*/");
bool nextExists = (null != this.next);
if (!String.IsNullOrEmpty(comma) && nextExists) { s.Append(comma).Append('\n'); comma = null; }
if (nextExists) {
s.Append('\'').Append("next").Append('\'').Append("=>"); comma = ","; this.next.WritePHP(s);
}
bool conflictExists = (null != this.conflict);
if (!String.IsNullOrEmpty(comma) && conflictExists) { s.Append(comma).Append('\n'); comma = null; }
if (conflictExists) {
s.Append('\'').Append("conflict").Append('\'').Append("=>"); comma = ","; this.conflict.WritePHP(s);
}
bool conflictsExists = (null != this.conflicts && this.conflicts.Count > 0);
if (!String.IsNullOrEmpty(comma) && conflictsExists) { s.Append(comma).Append('\n'); comma = null; }
if (conflictsExists) { s.Append('\'').Append("conflicts").Append('\'').Append("=>"); comma = ","; }
int conflictsSize = (null == this.conflicts ? 0 : this.conflicts.Count);
if (conflictsSize > 0) {
s.Append("array").Append('(').Append('\n');
int conflictsIdx = 0;
foreach (Test.Xyz.Conflict n1 in this.conflicts) { /* vec.for: this.conflicts */
++conflictsIdx;
n1.WritePHP(s);
if (conflictsIdx != conflictsSize) { s.Append(',').Append('\n'); }
}
s.Append("/* vec size: ").Append(this.conflicts.Count).Append(" */").Append(')');
}
bool numbersExists = (null != this.numbers && this.numbers.Count > 0);
if (!String.IsNullOrEmpty(comma) && numbersExists) { s.Append(comma).Append('\n'); comma = null; }
if (numbersExists) { s.Append('\'').Append("numbers").Append('\'').Append("=>"); comma = ","; }
int numbersSize = (null == this.numbers ? 0 : this.numbers.Count);
if (numbersSize > 0) {
s.Append("array").Append('(').Append('\n');
int numbersIdx = 0;
foreach (Double n1 in this.numbers) { /* vec.for: this.numbers */
++numbersIdx;
s.Append(n1.ToString());
if (numbersIdx != numbersSize) { s.Append(',').Append('\n'); }
}
s.Append("/* vec size: ").Append(this.numbers.Count).Append(" */").Append(')');
}
bool mapInfoGExists = (null != this.mapInfoG && this.mapInfoG.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapInfoGExists) { s.Append(comma).Append('\n'); comma = null; }
if (mapInfoGExists) { s.Append('\'').Append("mapInfoG").Append('\'').Append("=>"); comma = ","; }
int mapInfoGSize = (null == this.mapInfoG ? 0 : this.mapInfoG.Count);
if (mapInfoGSize > 0) {
s.Append("array").Append('(').Append('\n');
int mapInfoGIdx = 0;
foreach (KeyValuePair<Info,Gender> mapInfoGIter in this.mapInfoG) { /* map.for: this.mapInfoG */
++mapInfoGIdx;
Info k1 = mapInfoGIter.Key; /* nest.k */
k1.WritePHP(s); s.Append("=>");
Gender v1 = mapInfoGIter.Value; /* nest.v */
s.Append((int)v1);
s.Append("/*Gender::").Append(v1.ToString()).Append("*/");
if (mapInfoGIdx != mapInfoGSize) { s.Append(','); s.Append('\n'); }
}
s.Append("/* map size: ").Append(this.mapInfoG.Count).Append(" */").Append(')');
}
bool mapGenderInfoExists = (null != this.mapGenderInfo && this.mapGenderInfo.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapGenderInfoExists) { s.Append(comma).Append('\n'); comma = null; }
if (mapGenderInfoExists) { s.Append('\'').Append("mapGenderInfo").Append('\'').Append("=>"); comma = ","; }
int mapGenderInfoSize = (null == this.mapGenderInfo ? 0 : this.mapGenderInfo.Count);
if (mapGenderInfoSize > 0) {
s.Append("array").Append('(').Append('\n');
int mapGenderInfoIdx = 0;
foreach (KeyValuePair<Gender,Info> mapGenderInfoIter in this.mapGenderInfo) { /* map.for: this.mapGenderInfo */
++mapGenderInfoIdx;
Gender k1 = mapGenderInfoIter.Key; /* nest.k */
s.Append((int)k1);
s.Append("/*Gender::").Append(k1.ToString()).Append("*/"); s.Append("=>");
Info v1 = mapGenderInfoIter.Value; /* nest.v */
v1.WritePHP(s);
if (mapGenderInfoIdx != mapGenderInfoSize) { s.Append(','); s.Append('\n'); }
}
s.Append("/* map size: ").Append(this.mapGenderInfo.Count).Append(" */").Append(')');
}
bool mapDoubleExists = (null != this.mapDouble && this.mapDouble.Count > 0);
if (!String.IsNullOrEmpty(comma) && mapDoubleExists) { s.Append(comma).Append('\n'); comma = null; }
if (mapDoubleExists) { s.Append('\'').Append("mapDouble").Append('\'').Append("=>"); comma = ","; }
int mapDoubleSize = (null == this.mapDouble ? 0 : this.mapDouble.Count);
if (mapDoubleSize > 0) {
s.Append("array").Append('(').Append('\n');
int mapDoubleIdx = 0;
foreach (KeyValuePair<Int32,Double> mapDoubleIter in this.mapDouble) { /* map.for: this.mapDouble */
++mapDoubleIdx;
Int32 k1 = mapDoubleIter.Key; /* nest.k */
s.Append(k1.ToString()); s.Append("=>");
Double v1 = mapDoubleIter.Value; /* nest.v */
s.Append(v1.ToString());
if (mapDoubleIdx != mapDoubleSize) { s.Append(','); s.Append('\n'); }
}
s.Append("/* map size: ").Append(this.mapDouble.Count).Append(" */").Append(')');
}
bool hotfixExists = (null != this.hotfix && this.hotfix.Count > 0);
if (!String.IsNullOrEmpty(comma) && hotfixExists) { s.Append(comma).Append('\n'); comma = null; }
if (hotfixExists) {
int hotfixSize = (null == this.hotfix ? 0 : this.hotfix.Count);
if (hotfixSize > 0) {
s.Append("array").Append('(').Append('\n');
int hotfixIdx = 0;
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) { /* map.for: this.hotfix */
++hotfixIdx;
String k1 = hotfixIter.Key; /* nest.k */
s.Append('\'').Append(k1.ToString()).Append('\''); s.Append("=>");
String v1 = hotfixIter.Value; /* nest.v */
s.Append('\'').Append(v1.ToString()).Append('\'');
if (hotfixIdx != hotfixSize) { s.Append(','); s.Append('\n'); }
}
s.Append("/* map size: ").Append(this.hotfix.Count).Append(" */").Append(')');
} comma = ",";
}
s.Append("/* ").Append(GetType().ToString()).Append(" */");
s.Append(')');
}
public StringBuilder ToStringXML()
{
StringBuilder code = new StringBuilder();
code.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
code.Append('\n').Append("<!-- ").Append("Info").Append(".CRC32: 0x");
code.Append(CRC32.ToString("X2")).Append(" -->");
this.WriteXML(code, "Info");
return code;
}
public void WriteXML(StringBuilder s, String name)
{
StringBuilder attrs = new StringBuilder();
StringBuilder nodes = new StringBuilder();
attrs.Append(' ').Append("key").Append('=').Append('"').Append(this.key.ToString()).Append('"');
attrs.Append(' ').Append("number01").Append('=').Append('"').Append(this.number01.ToString()).Append('"');
attrs.Append(' ').Append("number02").Append('=').Append('"').Append(this.number02.ToString()).Append('"');
attrs.Append(' ').Append("number03").Append('=').Append('"').Append(this.number03.ToString()).Append('"');
attrs.Append(' ').Append("number04").Append('=').Append('"').Append(this.number04.ToString()).Append('"');
attrs.Append(' ').Append("number05").Append('=').Append('"').Append(this.number05.ToString()).Append('"');
attrs.Append(' ').Append("number06").Append('=').Append('"').Append(this.number06.ToString()).Append('"');
attrs.Append(' ').Append("number07").Append('=').Append('"').Append(this.number07.ToString()).Append('"');
attrs.Append(' ').Append("number08").Append('=').Append('"').Append(this.number08.ToString()).Append('"');
attrs.Append(' ').Append("number09").Append('=').Append('"').Append(this.number09.ToString()).Append('"');
attrs.Append(' ').Append("number10").Append('=').Append('"').Append(this.number10.ToString()).Append('"');
attrs.Append(' ').Append("isReal").Append('=').Append('"').Append(this.isReal.ToString()).Append('"');
attrs.Append(' ').Append("s").Append('=').Append('"').Append(this.s).Append('"');
if (this.world.Count > 0) {
nodes.Append('\n').Append('<').Append("world").Append('>');
foreach (String n1 in this.world) {
nodes.Append('<').Append("n1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(n1);
nodes.Append('"').Append('/').Append('>');
}
nodes.Append('<').Append('/').Append("world").Append('>');
}
attrs.Append(' ').Append("gender").Append('=').Append('"').Append(this.gender.ToString()).Append('"');
if (this.next != null) {
this.next.WriteXML(nodes, "next");
}
this.conflict.WriteXML(nodes, "conflict");
if (this.conflicts.Count > 0) {
nodes.Append('\n').Append('<').Append("conflicts").Append('>');
foreach (Test.Xyz.Conflict n1 in this.conflicts) {
n1.WriteXML(nodes, "n1");
}
nodes.Append('<').Append('/').Append("conflicts").Append('>');
}
if (this.numbers.Count > 0) {
nodes.Append('\n').Append('<').Append("numbers").Append('>');
foreach (Double n1 in this.numbers) {
nodes.Append('<').Append("n1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(n1.ToString());
nodes.Append('"').Append('/').Append('>');
}
nodes.Append('<').Append('/').Append("numbers").Append('>');
}
if (this.mapInfoG.Count > 0) {
nodes.Append('\n').Append('<').Append("mapInfoG").Append('>');
foreach (KeyValuePair<Info,Gender> mapInfoGIter in this.mapInfoG) {
nodes.Append('\n');
Info k1 = mapInfoGIter.Key;
k1.WriteXML(nodes, "k1");
Gender v1 = mapInfoGIter.Value;
nodes.Append('<').Append("v1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(v1.ToString());
nodes.Append('"').Append('/').Append('>');
}
nodes.Append('<').Append('/').Append("mapInfoG").Append('>');
}
if (this.mapGenderInfo.Count > 0) {
nodes.Append('\n').Append('<').Append("mapGenderInfo").Append('>');
foreach (KeyValuePair<Gender,Info> mapGenderInfoIter in this.mapGenderInfo) {
nodes.Append('\n');
Gender k1 = mapGenderInfoIter.Key;
nodes.Append('<').Append("k1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(k1.ToString());
nodes.Append('"').Append('/').Append('>');
Info v1 = mapGenderInfoIter.Value;
v1.WriteXML(nodes, "v1");
}
nodes.Append('<').Append('/').Append("mapGenderInfo").Append('>');
}
if (this.mapDouble.Count > 0) {
nodes.Append('\n').Append('<').Append("mapDouble").Append('>');
foreach (KeyValuePair<Int32,Double> mapDoubleIter in this.mapDouble) {
nodes.Append('\n');
Int32 k1 = mapDoubleIter.Key;
nodes.Append('<').Append("k1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(k1.ToString());
nodes.Append('"').Append('/').Append('>');
Double v1 = mapDoubleIter.Value;
nodes.Append('<').Append("v1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(v1.ToString());
nodes.Append('"').Append('/').Append('>');
}
nodes.Append('<').Append('/').Append("mapDouble").Append('>');
}
if (this.hotfix != null && this.hotfix.Count > 0) {
nodes.Append('\n').Append('<').Append("hotfix").Append('>');
foreach (KeyValuePair<String,String> hotfixIter in this.hotfix) {
nodes.Append('\n');
String k1 = hotfixIter.Key;
nodes.Append('<').Append("k1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(k1);
nodes.Append('"').Append('/').Append('>');
String v1 = hotfixIter.Value;
nodes.Append('<').Append("v1").Append(' ').Append("value").Append('=').Append('"');
nodes.Append(v1);
nodes.Append('"').Append('/').Append('>');
}
nodes.Append('<').Append('/').Append("hotfix").Append('>');
}
s.Append('\n').Append('<').Append(name).Append(attrs);
if (nodes.Length == 0) {
s.Append('/').Append('>');
} else {
s.Append('>').Append(nodes);
s.Append('<').Append('/').Append(name).Append('>');
}
} //Info::WriteXML(...)
} /* class: Info */
/*
[email protected]/int32/int8/int16/int32/int64/uint8/uint16/uint32/uint64/float/double/bool/string/vec
-string/int32/test.abc.Info/test.abc.Conflict/vec-test.xyz.Conflict/vec-double/map-test.abc.Info-i
nt32/map-int32-test.abc.Info/map-int32-double/map-string-string
[email protected]/int32/string/vec-int8/map-string-string
[email protected]/double/map-string-string
*/
} //namespace: Test.Abc
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Reflection;
using System.Threading;
using NUnit.Compatibility;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
using NUnit.Framework.Internal.Execution;
using NUnit.Framework.Internal.Abstractions;
namespace NUnit.TestUtilities
{
/// <summary>
/// Utility Class used to build and run NUnit tests used as test data
/// </summary>
internal static class TestBuilder
{
#region Build Tests
public static TestSuite MakeSuite(string name)
{
return new TestSuite(name);
}
public static TestSuite MakeFixture(Type type)
{
return (TestSuite)new DefaultSuiteBuilder().BuildFrom(new TypeWrapper(type));
}
public static TestSuite MakeFixture(object fixture)
{
TestSuite suite = MakeFixture(fixture.GetType());
suite.Fixture = fixture;
return suite;
}
public static TestSuite MakeParameterizedMethodSuite(Type type, string methodName)
{
var suite = MakeTestFromMethod(type, methodName) as TestSuite;
Assert.NotNull(suite, "Unable to create parameterized suite - most likely there is no data provided");
return suite;
}
public static TestMethod MakeTestCase(Type type, string methodName)
{
var test = MakeTestFromMethod(type, methodName) as TestMethod;
Assert.NotNull(test, "Unable to create TestMethod from {0}", methodName);
return test;
}
// Will return either a ParameterizedMethodSuite or an NUnitTestMethod
// depending on whether the method takes arguments or not
internal static Test MakeTestFromMethod(Type type, string methodName)
{
var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (method == null)
Assert.Fail("Method not found: " + methodName);
return new DefaultTestCaseBuilder().BuildFrom(new MethodWrapper(type, method));
}
#endregion
#region Create WorkItems
public static WorkItem CreateWorkItem(Type type)
{
return CreateWorkItem(MakeFixture(type));
}
public static WorkItem CreateWorkItem(Type type, string methodName)
{
return CreateWorkItem(MakeTestFromMethod(type, methodName));
}
public static WorkItem CreateWorkItem(Test test)
{
var context = new TestExecutionContext();
context.Dispatcher = new SuperSimpleDispatcher();
return CreateWorkItem(test, context);
}
public static WorkItem CreateWorkItem(Test test, object testObject, IDebugger debugger = null)
{
var context = new TestExecutionContext
{
TestObject = testObject,
Dispatcher = new SuperSimpleDispatcher()
};
return CreateWorkItem(test, context, debugger);
}
public static WorkItem CreateWorkItem(Test test, TestExecutionContext context, IDebugger debugger = null)
{
var work = WorkItemBuilder.CreateWorkItem(test, TestFilter.Empty, debugger ?? new DebuggerProxy(), true);
work.InitializeContext(context);
return work;
}
#endregion
#region Run Tests
public static ITestResult RunTestFixture(Type type)
{
return RunTest(MakeFixture(type), null);
}
public static ITestResult RunTestFixture(object fixture)
{
return RunTest(MakeFixture(fixture), fixture);
}
public static ITestResult RunParameterizedMethodSuite(Type type, string methodName)
{
var suite = MakeParameterizedMethodSuite(type, methodName);
object testObject = null;
if (!type.IsStatic())
testObject = Reflect.Construct(type);
return RunTest(suite, testObject);
}
public static ITestResult RunTestCase(Type type, string methodName)
{
var testMethod = MakeTestCase(type, methodName);
object testObject = null;
if (!type.IsStatic())
testObject = Reflect.Construct(type);
return RunTest(testMethod, testObject);
}
public static ITestResult RunTestCase(object fixture, string methodName)
{
var testMethod = MakeTestCase(fixture.GetType(), methodName);
return RunTest(testMethod, fixture);
}
public static ITestResult RunAsTestCase(Action action)
{
var method = action.GetMethodInfo();
var testMethod = MakeTestCase(method.DeclaringType, method.Name);
return RunTest(testMethod);
}
public static ITestResult RunTest(Test test)
{
return RunTest(test, null);
}
public static ITestResult RunTest(Test test, object testObject, IDebugger debugger = null)
{
return ExecuteWorkItem(CreateWorkItem(test, testObject, debugger ?? new DebuggerProxy()));
}
public static ITestResult ExecuteWorkItem(WorkItem work)
{
work.Execute();
// TODO: Replace with an event - but not while method is static
while (work.State != WorkItemState.Complete)
{
Thread.Sleep(1);
}
return work.Result;
}
#endregion
#region Nested TestDispatcher Class
/// <summary>
/// SuperSimpleDispatcher merely executes the work item.
/// It is needed particularly when running suites, since
/// the child items require a dispatcher in the context.
/// </summary>
class SuperSimpleDispatcher : IWorkItemDispatcher
{
public int LevelOfParallelism { get { return 0; } }
public void Start(WorkItem topLevelWorkItem)
{
topLevelWorkItem.Execute();
}
public void Dispatch(WorkItem work)
{
work.Execute();
}
public void CancelRun(bool force)
{
throw new NotImplementedException();
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using NHibernate;
using NHibernate.Cache;
using NHibernate.Cache.Entry;
using NHibernate.Engine;
using NHibernate.Id;
using NHibernate.Metadata;
using NHibernate.Persister.Entity;
using NHibernate.Tuple.Entity;
using NHibernate.Type;
namespace FluentNHibernate.Testing.FluentInterfaceTests
{
internal class SecondCustomPersister : CustomPersister
{}
internal class CustomPersister : IEntityPersister
{
public void PostInstantiate()
{}
public bool IsSubclassEntityName(string entityName)
{
return false;
}
public IType GetPropertyType(string propertyName)
{
return null;
}
public int[] FindDirty(object[] currentState, object[] previousState, object entity, ISessionImplementor session)
{
return new int[] {};
}
public int[] FindModified(object[] old, object[] current, object entity, ISessionImplementor session)
{
return new int[] {};
}
public object[] GetNaturalIdentifierSnapshot(object id, ISessionImplementor session)
{
return new object[] {};
}
public object Load(object id, object optionalObject, LockMode lockMode, ISessionImplementor session)
{
return null;
}
public void Lock(object id, object version, object obj, LockMode lockMode, ISessionImplementor session)
{}
public void Insert(object id, object[] fields, object obj, ISessionImplementor session)
{}
public object Insert(object[] fields, object obj, ISessionImplementor session)
{
return null;
}
public void Delete(object id, object version, object obj, ISessionImplementor session)
{}
public void Update(object id, object[] fields, int[] dirtyFields, bool hasDirtyCollection, object[] oldFields, object oldVersion, object obj, object rowId, ISessionImplementor session)
{}
public object[] GetDatabaseSnapshot(object id, ISessionImplementor session)
{
return new object[] {};
}
public object GetCurrentVersion(object id, ISessionImplementor session)
{
return null;
}
public object ForceVersionIncrement(object id, object currentVersion, ISessionImplementor session)
{
return null;
}
public EntityMode? GuessEntityMode(object obj)
{
return null;
}
public bool IsInstrumented(EntityMode entityMode)
{
return false;
}
public void AfterInitialize(object entity, bool lazyPropertiesAreUnfetched, ISessionImplementor session)
{}
public void AfterReassociate(object entity, ISessionImplementor session)
{}
public object CreateProxy(object id, ISessionImplementor session)
{
return null;
}
public bool? IsTransient(object obj, ISessionImplementor session)
{
return null;
}
public object[] GetPropertyValuesToInsert(object obj, IDictionary mergeMap, ISessionImplementor session)
{
return new object[] {};
}
public void ProcessInsertGeneratedProperties(object id, object entity, object[] state, ISessionImplementor session)
{}
public void ProcessUpdateGeneratedProperties(object id, object entity, object[] state, ISessionImplementor session)
{}
public Type GetMappedClass(EntityMode entityMode)
{
return null;
}
public bool ImplementsLifecycle(EntityMode entityMode)
{
return false;
}
public bool ImplementsValidatable(EntityMode entityMode)
{
return false;
}
public Type GetConcreteProxyClass(EntityMode entityMode)
{
return null;
}
public void SetPropertyValues(object obj, object[] values, EntityMode entityMode)
{}
public void SetPropertyValue(object obj, int i, object value, EntityMode entityMode)
{}
public object[] GetPropertyValues(object obj, EntityMode entityMode)
{
return new object[] {};
}
public object GetPropertyValue(object obj, int i, EntityMode entityMode)
{
return null;
}
public object GetPropertyValue(object obj, string name, EntityMode entityMode)
{
return null;
}
public object GetIdentifier(object obj, EntityMode entityMode)
{
return null;
}
public void SetIdentifier(object obj, object id, EntityMode entityMode)
{}
public object GetVersion(object obj, EntityMode entityMode)
{
return null;
}
public object Instantiate(object id, EntityMode entityMode)
{
return null;
}
public bool IsInstance(object entity, EntityMode entityMode)
{
return false;
}
public bool HasUninitializedLazyProperties(object obj, EntityMode entityMode)
{
return false;
}
public void ResetIdentifier(object entity, object currentId, object currentVersion, EntityMode entityMode)
{}
public IEntityPersister GetSubclassEntityPersister(object instance, ISessionFactoryImplementor factory, EntityMode entityMode)
{
return null;
}
public bool? IsUnsavedVersion(object version)
{
return null;
}
public ISessionFactoryImplementor Factory
{
get { return null; }
}
public string RootEntityName
{
get { return null; }
}
public string EntityName
{
get { return null; }
}
public EntityMetamodel EntityMetamodel
{
get { return null; }
}
public string[] PropertySpaces
{
get { return new string[] {}; }
}
public string[] QuerySpaces
{
get { return new string[] {}; }
}
public bool IsMutable
{
get { return false; }
}
public bool IsInherited
{
get { return false; }
}
public bool IsIdentifierAssignedByInsert
{
get { return false; }
}
bool IEntityPersister.IsVersioned
{
get { return false; }
}
public IVersionType VersionType
{
get { return null; }
}
public int VersionProperty
{
get { return 0; }
}
public int[] NaturalIdentifierProperties
{
get { return new int[] {}; }
}
public IIdentifierGenerator IdentifierGenerator
{
get { return null; }
}
public IType[] PropertyTypes
{
get { return new IType[] {}; }
}
public string[] PropertyNames
{
get { return new string[] {}; }
}
public bool[] PropertyInsertability
{
get { return new bool[] {}; }
}
public ValueInclusion[] PropertyInsertGenerationInclusions
{
get { return new ValueInclusion[] {}; }
}
public ValueInclusion[] PropertyUpdateGenerationInclusions
{
get { return new ValueInclusion[] {}; }
}
public bool[] PropertyCheckability
{
get { return new bool[] {}; }
}
public bool[] PropertyNullability
{
get { return new bool[] {}; }
}
public bool[] PropertyVersionability
{
get { return new bool[] {}; }
}
public bool[] PropertyLaziness
{
get { return new bool[] {}; }
}
public CascadeStyle[] PropertyCascadeStyles
{
get { return new CascadeStyle[] {}; }
}
public IType IdentifierType
{
get { return null; }
}
public string IdentifierPropertyName
{
get { return null; }
}
public bool IsCacheInvalidationRequired
{
get { return false; }
}
public bool IsLazyPropertiesCacheable
{
get { return false; }
}
public ICacheConcurrencyStrategy Cache
{
get { return null; }
}
public ICacheEntryStructure CacheEntryStructure
{
get { return null; }
}
public IClassMetadata ClassMetadata
{
get { return null; }
}
public bool IsBatchLoadable
{
get { return false; }
}
public bool IsSelectBeforeUpdateRequired
{
get { return false; }
}
public bool IsVersionPropertyGenerated
{
get { return false; }
}
public bool HasProxy
{
get { return false; }
}
public bool HasCollections
{
get { return false; }
}
public bool HasMutableProperties
{
get { return false; }
}
public bool HasSubselectLoadableCollections
{
get { return false; }
}
public bool HasCascades
{
get { return false; }
}
public bool HasIdentifierProperty
{
get { return false; }
}
public bool CanExtractIdOutOfEntity
{
get { return false; }
}
public bool HasNaturalIdentifier
{
get { return false; }
}
public bool HasLazyProperties
{
get { return false; }
}
public bool[] PropertyUpdateability
{
get { return new bool[] {}; }
}
public bool HasCache
{
get { return false; }
}
public bool HasInsertGeneratedProperties
{
get { return false; }
}
public bool HasUpdateGeneratedProperties
{
get { return false; }
}
bool IOptimisticCacheSource.IsVersioned
{
get { return false; }
}
public IComparer VersionComparator
{
get { return null; }
}
}
}
| |
//==================================================================
// C# OpenGL Framework (http://www.csharpopenglframework.com)
// Copyright (c) 2005-2006 devDept (http://www.devdept.com)
// All rights reserved.
//
// For more information on this program, please visit:
// http://www.csharpopenglframework.com
//
// For licensing information, please visit:
// http://www.csharpopenglframework.com/licensing.html
//==================================================================
using System.Drawing;
using System.Windows.Forms;
using OpenGL;
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace openglFramework
{
public partial class OpenGLControl : UserControl
{
// Zoom/Pan/Rotate
const float rotationScale = 4.0f;
// Buttons
private bool zoomButtonDown = false;
private bool panButtonDown = false;
private bool rotateButtonDown = false;
private bool zoomWindowButtonDown = false;
// Cursors
Cursor zoomCursor;
Cursor panCursor;
Cursor rotateCursor;
protected Quaternion cameraQuat; // camera quaternion
protected Vector lastPoint;
protected Vector curPoint;
protected float rotAngle;
protected Vector rotAxis;
protected int panDeltaX;
protected int panDeltaY;
protected enum actionType
{
None,
Zoom,
Pan,
Rotate,
ZoomWindow,
SelectByPick,
SelectByBox
}
protected actionType action;
#region Properties
[CategoryAttribute("ZPR")]
public bool ZoomButtonDown
{
get { return zoomButtonDown; }
set { zoomButtonDown = value; }
}
[CategoryAttribute("ZPR")]
public bool PanButtonDown
{
get { return panButtonDown; }
set{panButtonDown = value; }
}
[CategoryAttribute("ZPR")]
public bool RotateButtonDown
{
get { return rotateButtonDown; }
set{ rotateButtonDown = value; }
}
[CategoryAttribute("ZPR")]
public bool ZoomWindowButtonDown
{
get { return zoomWindowButtonDown; }
set { zoomWindowButtonDown = value; }
}
#endregion
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && zoomWindowButtonDown)
{
action = actionType.ZoomWindow;
curPoint.x = e.X;
curPoint.y = e.Y;
lastPoint.x = curPoint.x;
lastPoint.y = curPoint.y;
}
else if ((e.Button == MouseButtons.Middle && (Control.ModifierKeys & Keys.Shift) == Keys.Shift) ||
zoomButtonDown)
{
action = actionType.Zoom;
Cursor = zoomCursor;
lastPoint.x = e.X;
lastPoint.y = e.Y;
}
else if ((e.Button == MouseButtons.Middle && (Control.ModifierKeys & Keys.Control) == Keys.Control) ||
panButtonDown)
{
action = actionType.Pan;
Cursor = panCursor;
lastPoint.x = e.X;
lastPoint.y = e.Y;
}
else if (e.Button == MouseButtons.Middle || rotateButtonDown)
{
action = actionType.Rotate;
Cursor = rotateCursor;
lastPoint = TrackBallMapping(e.X, e.Y, this.Width, this.Height);
}
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
Vector direction;
float pixelDiff;
float ratio = prevZoomRect.Width / viewportRect.Width;
switch (action)
{
case actionType.Rotate: curPoint = TrackBallMapping(e.X, e.Y, this.Width, this.Height);
direction = curPoint - lastPoint;
float velocity = (float)direction.Length();
if (velocity > 0.0001f)
{
rotAxis = Vector.Cross(lastPoint, curPoint);
rotAxis.Normalize(); // needed from UpdateCameraQuat
rotAngle = velocity * rotationScale;
UpdateCameraQuat(true);
AxisAndAngleOnStatusBar();
Invalidate();
}
lastPoint = curPoint;
break;
case actionType.Zoom : pixelDiff = lastPoint.y - e.Y;
if (aspect > 1)
{
zoomRect.Width += pixelDiff * ratio;
zoomRect.X -= (pixelDiff / 2) * ratio;
float prevHeight = zoomRect.Height;
zoomRect.Height = zoomRect.Width / aspect;
zoomRect.Y -= (zoomRect.Height - prevHeight) / 2;
}
else
{
zoomRect.Height += pixelDiff * ratio;
zoomRect.Y -= (pixelDiff / 2) * ratio;
float prevWidth = zoomRect.Width;
zoomRect.Width = zoomRect.Height * aspect;
zoomRect.X -= (zoomRect.Width - prevWidth) / 2;
}
// Set the current point, so the lastPoint will be saved properly below.
curPoint.x = (float) e.X;
curPoint.y = (float) e.Y;
Invalidate();
lastPoint = curPoint;
break;
case actionType.Pan:
zoomRect.X += (int)+ ((lastPoint.x - e.X) * ratio);
zoomRect.Y += (int)- ((lastPoint.y - e.Y) * ratio);
// Set the current point, so the lastPoint will be saved properly below.
curPoint.x = (float) e.X;
curPoint.y = (float) e.Y;
Invalidate();
lastPoint = curPoint;
break;
case actionType.ZoomWindow:
curPoint.x = e.X;
curPoint.y = e.Y;
Invalidate();
break;
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (action == actionType.ZoomWindow)
ZoomWindow((int) lastPoint.x, (int) (this.Height - lastPoint.y),
(int) curPoint.x, (int) (this.Height - curPoint.y));
action = actionType.None;
Invalidate();
Cursor = Cursors.Arrow;
((MainForm)this.Parent).StatusText("");
base.OnMouseUp(e);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
float ratio = prevZoomRect.Width / viewportRect.Width;
int amount = (int) ((e.Delta / 5) * ratio);
if (aspect > 1)
{
zoomRect.Width += amount;
zoomRect.X -= amount / 2;
float prevHeight = zoomRect.Height;
zoomRect.Height = zoomRect.Width / aspect;
zoomRect.Y -= (zoomRect.Height - prevHeight) / 2;
}
else
{
zoomRect.Height += amount;
zoomRect.Y -= amount / 2;
float prevWidth = zoomRect.Width;
zoomRect.Width = zoomRect.Height * aspect;
zoomRect.X -= (zoomRect.Width - prevWidth) / 2;
}
Invalidate();
base.OnMouseWheel(e);
}
protected virtual void DrawSelectionBox()
{
}
protected void AxisAndAngleOnStatusBar()
{
((MainForm)this.Parent).StatusText("Axis: (" + rotAxis.x.ToString("f2") + ", " + rotAxis.y.ToString("f2") + ", " + rotAxis.z.ToString("f2") + ") Angle: " + MU.radToDeg(rotAngle).ToString("f2") + " deg");
}
protected void SelectionBoxOnStatusBar()
{
((MainForm)this.Parent).StatusText("Box: (" + lastPoint.x.ToString() + ", " + (this.Height - lastPoint.y).ToString() + ") (" + curPoint.x.ToString() + ", " + (this.Height - curPoint.y).ToString() + ")");
}
protected void PanOnStatusBar()
{
((MainForm)this.Parent).StatusText("Position: (" + panDeltaX.ToString() + ", " + panDeltaY.ToString() + ")");
}
protected void DrawZoomWindowBox()
{
int firstX = (int) curPoint.x;
int firstY = (int)(this.Height - curPoint.y);
int secondX = (int)lastPoint.x;
int secondY = (int)(this.Height - lastPoint.y);
NormalizeBox(ref firstX, ref firstY, ref secondX, ref secondY);
gl.Color3ub(255, 255, 255);
gl.Begin(gl.LINE_LOOP);
DrawBox(firstX, firstY, secondX, secondY, 0);
gl.End();
}
protected void UpdateCameraQuat(bool additive)
{
Quaternion axisQuat; // quaternion from the rotation axis
Quaternion tempQuat; // temp quaternion
axisQuat = new Quaternion(0, 0, 0, 1.0f);
axisQuat.AxisToQuat(rotAxis, rotAngle); // build the quaternion representing the quaternion change
tempQuat = cameraQuat; // copy temp quaternion as the *= operator does not
if (additive)
cameraQuat = tempQuat * axisQuat;
else
cameraQuat = axisQuat;
cameraQuat.GetAxisAngle(ref rotAxis, ref rotAngle); // get angle axis representation
}
Vector TrackBallMapping(int x, int y, int width, int height)
{
Vector result;
result.x = (2.0f * x - width) / width;
result.y = (height - 2.0f * y) / height;
result.z = 0;
float d;
d = (float)result.Length();
d = (d < 1.0f) ? d : 1.0f;
result.z = (float)Math.Sqrt(1.001f - d * d);
result.Normalize();
return result;
}
}
}
| |
/*
* Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details.
*/using UnityEngine;
using System.Collections.Generic;
public class MPLevelConfigGeneratorServer : ILevelConfigGenerator {
MPLevelConfig[] lvlArr;
int counter;
int[] minBoardDims;
int[] maxBoardDims;
string[] potentialItems;
string instruction = "";
public string getInstruction(){ return instruction;}
public int getConfigCount() { if(lvlArr == null) { return -1; } else { return lvlArr.Length; } }
public void reboot(){
counter = 0;
}
public MPLevelConfigGeneratorServer(ActivityServerCommunication para_serverCommunication)
{
List<PackagedNextWord> list = null;
LevelParameters level = new LevelParameters("");
if(para_serverCommunication!=null){
list = para_serverCommunication.loadWords();
level = new LevelParameters(para_serverCommunication.getLevel());
instruction = LocalisationMang.instructions(para_serverCommunication.getDifficulty()[0],para_serverCommunication.getLevel(),ApplicationID.MOVING_PATHWAYS);
}
if (list==null){
WorldViewServerCommunication.setError("Did not find words");
return;
}else if(list.Count==0){
WorldViewServerCommunication.setError("List of words is empty");
return;
}else{
foreach(PackagedNextWord w in list){
if (w.getAnnotatedWord().getWordProblems().Count==0){
WorldViewServerCommunication.setError("Word '"+w.getAnnotatedWord().getWord()+"' do not have problems");
return;
}else if(w.getAnnotatedWord().getWordProblems()[0].matched.Length==0){
WorldViewServerCommunication.setError("Word '"+w.getAnnotatedWord().getWord()+"' do not have problems");
return;
}
}
}
int num_levels = level.accuracy;
lvlArr = new MPLevelConfig[num_levels];
List<string> correctItems = new List<string>();
List<string> fillerItems = new List<string>();
string pattern = "";
bool isSound = (level.ttsType == TtsType.SPOKEN2WRITTEN);
if((WorldViewServerCommunication.tts==null))
isSound = false;
try{
int lA = list[0].getAnnotatedWord().getWordProblems()[0].category;
int diff = list[0].getAnnotatedWord().getWordProblems()[0].index;
string description = WorldViewServerCommunication.userProfile.userProblems.getDifficultiesDescription().getDifficulties()[lA][diff].getDescriptionsToString();
foreach(PackagedNextWord word in list){
if(!word.getFiller()){
lA = word.getAnnotatedWord().getWordProblems()[0].category;
diff = word.getAnnotatedWord().getWordProblems()[0].index;
description = WorldViewServerCommunication.userProfile.userProblems.getDifficultiesDescription().getDifficulties()[lA][diff].getDescriptionsToString();
}
}
if(level.mode==0){//DEPRECATED
string phoneme = "";
foreach(string desc in description.Split (',')){
if (desc.Contains("-")){
if (phoneme=="")
phoneme += desc.Split('-')[1];
else
phoneme += " / "+desc.Split('-')[1];
}
}
if(phoneme==""){
isSound = false;
pattern = description;
}else
pattern = "/"+phoneme+"/";
for (int i=0;i<list.Count;i++){
lA = list[i].getAnnotatedWord().getWordProblems()[0].category;
diff = list[i].getAnnotatedWord().getWordProblems()[0].index;
string grapheme =WorldViewServerCommunication.userProfile.userProblems.getDifficultiesDescription().getDifficulties()[lA][diff].descriptions[0].Split('-')[0];
if(list[i].getFiller()){
Debug.Log(grapheme);
fillerItems.Add(grapheme);
}else{
correctItems.Add(grapheme);
}
}
}else if(level.mode==1){//confusing//consonants/vowels Greek, letter to letter and confusin EN
if(para_serverCommunication.language==LanguageCode.EN){
string a = description.Split('/')[0];
string b = description.Split('/')[1];
if(Random.Range(0.0f,1.0f)>0.5){
correctItems.Add(a);
fillerItems.Add (b);
pattern = a;
}else{
correctItems.Add(b);
fillerItems.Add (a);
pattern = b;
}
if(isSound)
if(!WorldViewServerCommunication.tts.test(pattern)){//Letter name
isSound = false;
}
}else{
for (int i=0;i<list.Count;i++){
MatchedData problem = list[i].getAnnotatedWord().getWordProblems()[0].matched[0];
string grapheme = list[i].getAnnotatedWord().getWord().Substring(problem.start,problem.end-problem.start);
if(list[i].getFiller()){
fillerItems.Add(grapheme);
}else{
correctItems.Add(grapheme);
}
}
pattern = correctItems[0];
if(isSound)
if(!WorldViewServerCommunication.tts.test(pattern)){//Letter name
isSound = false;
}
}
}else if(level.mode==2){//EN (vowels & consonants) GR (consonants & letter similarity)
if(para_serverCommunication.language==LanguageCode.EN){
string phoneme = "";
foreach(string desc in description.Split (',')){
if (desc.Contains("-")){
if (phoneme=="")
phoneme += desc.Split('-')[1];
else
phoneme += " / "+desc.Split('-')[1];
}
}
if(!isSound){
GhostbookManagerLight gbMang = GhostbookManagerLight.getInstance();
pattern = gbMang.createExplanation(lA,diff);//Human readable description
}else{
if(phoneme==""){
isSound = false;
GhostbookManagerLight gbMang = GhostbookManagerLight.getInstance();
pattern = gbMang.createExplanation(lA,diff);//Human readable description
}else{
pattern = "/"+phoneme+"/";
if(!WorldViewServerCommunication.tts.test(pattern)){//Phonemes are prerecorded
isSound = false;
GhostbookManagerLight gbMang = GhostbookManagerLight.getInstance();
pattern = gbMang.createExplanation(lA,diff);//Human readable description
}
}
}
for (int i=0;i<list.Count;i++){
if(list[i].getFiller()){
fillerItems.Add(list[i].getAnnotatedWord().getWord());
}else{
correctItems.Add(list[i].getAnnotatedWord().getWord());
}
}
}else{
for (int i=0;i<list.Count;i++){
if(list[i].getFiller()){
fillerItems.Add(list[i].getAnnotatedWord().getWord());
}else{
correctItems.Add(list[i].getAnnotatedWord().getWord());
//pattern = "/"+list[i].getAnnotatedWord().getGraphemesPhonemes()[0].phoneme+"/";
}
}
pattern = correctItems[0].Substring(0,1);//first letter
if(isSound){
if(!WorldViewServerCommunication.tts.test(pattern)){//Letter ma,e
isSound = false;
}
}
}
}else if(level.mode==3){//GP correspondence, GR
for (int i=0;i<list.Count;i++){
if(list[i].getFiller()){
fillerItems.Add(list[i].getAnnotatedWord().getWord());
}else{
correctItems.Add(list[i].getAnnotatedWord().getWord());
MatchedData problem = list[i].getAnnotatedWord().getWordProblems()[0].matched[0];
string grapheme = list[i].getAnnotatedWord().getWord().Substring(problem.start,problem.end-problem.start);
pattern = grapheme;
}
}
if(isSound){
if(!WorldViewServerCommunication.tts.test(pattern)){//TODO: probably should record the phonemes
isSound = false;
}
}
}else if(level.mode==4){//Greek vowels, contain letter
for (int i=0;i<list.Count;i++){
if(list[i].getFiller()){
fillerItems.Add(list[i].getAnnotatedWord().getWord());
}else{
correctItems.Add(list[i].getAnnotatedWord().getWord());
//pattern = "/"+list[i].getAnnotatedWord().getGraphemesPhonemes()[0].phoneme+"/";
MatchedData problem = list[i].getAnnotatedWord().getWordProblems()[0].matched[0];
pattern = list[i].getAnnotatedWord().getWord().Substring(problem.start,problem.end-problem.start);
}
}
if(isSound){
if(!WorldViewServerCommunication.tts.test(pattern)){//TODO: needs phonemes prerecorded
isSound = false;
}
}
}
int[] chosenBoardDim = new int[2];
if(level.speed==0){
chosenBoardDim[0] = 5;
chosenBoardDim[1] = 5;
}else if(level.speed==1){
chosenBoardDim[0] = 8;
chosenBoardDim[1] = 8;
}else{
chosenBoardDim[0] = 12;
chosenBoardDim[1] = 12;
}
if(isSound){//This should be handled above, additional precaution
if(WorldViewServerCommunication.tts!=null){
if(!WorldViewServerCommunication.tts.test(pattern))
isSound = false;
}
}
for (int j = 0;j<num_levels;j++){
//Debug.Log(j);
lvlArr[j] = new MPLevelConfig(chosenBoardDim,correctItems.ToArray(),fillerItems.ToArray(),pattern,isSound,list[0].getAnnotatedWord().getWordProblems()[0].category,list[0].getAnnotatedWord().getWordProblems()[0].index);
}
}catch(System.Exception e){
WorldViewServerCommunication.setError(e.Message);
return;
}
counter = 0;
}
public ILevelConfig getNextLevelConfig(System.Object para_extraInfo)
{
int reqIndex = counter % lvlArr.Length;
MPLevelConfig reqConfig = lvlArr[reqIndex];
counter++;
return reqConfig;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.