context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace SqlStreamStore.InMemory
{
using System;
using System.Collections.Generic;
using System.Linq;
using SqlStreamStore.Infrastructure;
using SqlStreamStore.Streams;
internal class InMemoryStream
{
private readonly string _streamId;
private readonly InMemoryAllStream _inMemoryAllStream;
private readonly GetUtcNow _getUtcNow;
private readonly Action _onStreamAppended;
private readonly Func<int> _getNextPosition;
private readonly List<InMemoryStreamMessage> _messages = new List<InMemoryStreamMessage>();
private readonly Dictionary<Guid, InMemoryStreamMessage> _messagesById = new Dictionary<Guid, InMemoryStreamMessage>();
internal InMemoryStream(
string streamId,
InMemoryAllStream inMemoryAllStream,
GetUtcNow getUtcNow,
Action onStreamAppended,
Func<int> getNextPosition)
{
_streamId = streamId;
_inMemoryAllStream = inMemoryAllStream;
_getUtcNow = getUtcNow;
_onStreamAppended = onStreamAppended;
_getNextPosition = getNextPosition;
}
internal IReadOnlyList<InMemoryStreamMessage> Messages => _messages;
internal int CurrentVersion { get; private set; } = -1;
internal int CurrentPosition { get; private set; } = -1;
internal void AppendToStream(int expectedVersion, NewStreamMessage[] newMessages)
{
switch(expectedVersion)
{
case ExpectedVersion.Any:
AppendToStreamExpectedVersionAny(expectedVersion, newMessages);
return;
case ExpectedVersion.NoStream:
AppendToStreamExpectedVersionNoStream(expectedVersion, newMessages);
return;
default:
AppendToStreamExpectedVersion(expectedVersion, newMessages);
return;
}
}
private void AppendToStreamExpectedVersion(int expectedVersion, NewStreamMessage[] newMessages)
{
// Need to do optimistic concurrency check...
if(expectedVersion > CurrentVersion)
{
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
if(CurrentVersion >= 0 && expectedVersion < CurrentVersion)
{
// expectedVersion < currentVersion, Idempotency test
for(int i = 0; i < newMessages.Length; i++)
{
int index = expectedVersion + i + 1;
if(index >= _messages.Count)
{
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
if(_messages[index].MessageId != newMessages[i].MessageId)
{
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
}
return;
}
// expectedVersion == currentVersion)
if(newMessages.Any(newmessage => _messagesById.ContainsKey(newmessage.MessageId)))
{
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
AppendEvents(newMessages);
}
private void AppendToStreamExpectedVersionAny(int expectedVersion, NewStreamMessage[] newMessages)
{
// idemponcy check - how many newMessages have already been written?
var newEventIds = new HashSet<Guid>(newMessages.Select(e => e.MessageId));
newEventIds.ExceptWith(_messagesById.Keys);
if(newEventIds.Count == 0)
{
// All Messages have already been written, we're idempotent
return;
}
if(newEventIds.Count != newMessages.Length)
{
// Some of the Messages have already been written, bad request
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
// None of the Messages were written previously...
AppendEvents(newMessages);
}
private void AppendToStreamExpectedVersionNoStream(int expectedVersion, NewStreamMessage[] newMessages)
{
if(_messages.Count > 0)
{
//Already committed Messages, do idempotency check
if(newMessages.Length > _messages.Count)
{
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
if(newMessages.Where((message, index) => _messages[index].MessageId != message.MessageId).Any())
{
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
return;
}
// None of the Messages were written previously...
AppendEvents(newMessages);
}
private void AppendEvents(NewStreamMessage[] newMessages)
{
foreach(var newmessage in newMessages)
{
var position = _getNextPosition();
CurrentVersion++;
CurrentPosition = position;
var inMemorymessage = new InMemoryStreamMessage(
_streamId,
newmessage.MessageId,
CurrentVersion,
position,
_getUtcNow(),
newmessage.Type,
newmessage.JsonData,
newmessage.JsonMetadata);
_messages.Add(inMemorymessage);
_messagesById.Add(newmessage.MessageId, inMemorymessage);
_inMemoryAllStream.AddAfter(_inMemoryAllStream.Last, inMemorymessage);
}
_onStreamAppended();
}
internal void DeleteAllEvents(int expectedVersion)
{
if (expectedVersion > 0 && expectedVersion != CurrentVersion)
{
throw new WrongExpectedVersionException(
ErrorMessages.AppendFailedWrongExpectedVersion(_streamId, expectedVersion));
}
foreach (var inMemorymessage in _messages)
{
_inMemoryAllStream.Remove(inMemorymessage);
}
_messages.Clear();
_messagesById.Clear();
}
internal bool DeleteEvent(Guid eventId)
{
InMemoryStreamMessage inMemoryStreamMessage;
if(!_messagesById.TryGetValue(eventId, out inMemoryStreamMessage))
{
return false;
}
_messages.Remove(inMemoryStreamMessage);
_inMemoryAllStream.Remove(inMemoryStreamMessage);
_messagesById.Remove(eventId);
return true;
}
internal string GetMessageData(Guid messageId)
{
InMemoryStreamMessage message;
return _messagesById.TryGetValue(messageId, out message) ? message.JsonData : string.Empty;
}
}
}
| |
using NUnit.Framework;
using VkNet.Enums.Filters;
using VkNet.Enums.SafetyEnums;
namespace VkNet.Tests.Enum.SafetyEnums
{
[TestFixture]
public class SafetyEnumsTest
{
[Test]
public void AppFilterTest()
{
// get test
Assert.That(actual: AppFilter.Installed.ToString(), expression: Is.EqualTo(expected: "installed"));
Assert.That(actual: AppFilter.Featured.ToString(), expression: Is.EqualTo(expected: "featured"));
// parse test
Assert.That(actual: AppFilter.FromJsonString(response: "installed"), expression: Is.EqualTo(expected: AppFilter.Installed));
Assert.That(actual: AppFilter.FromJsonString(response: "featured"), expression: Is.EqualTo(expected: AppFilter.Featured));
}
[Test]
public void AppPlatformsTest()
{
// get test
Assert.That(actual: AppPlatforms.Ios.ToString(), expression: Is.EqualTo(expected: "ios"));
Assert.That(actual: AppPlatforms.Android.ToString(), expression: Is.EqualTo(expected: "android"));
Assert.That(actual: AppPlatforms.WinPhone.ToString(), expression: Is.EqualTo(expected: "winphone"));
Assert.That(actual: AppPlatforms.Web.ToString(), expression: Is.EqualTo(expected: "web"));
// parse test
Assert.That(actual: AppPlatforms.FromJsonString(response: "ios"), expression: Is.EqualTo(expected: AppPlatforms.Ios));
Assert.That(actual: AppPlatforms.FromJsonString(response: "android"), expression: Is.EqualTo(expected: AppPlatforms.Android));
Assert.That(actual: AppPlatforms.FromJsonString(response: "winphone"), expression: Is.EqualTo(expected: AppPlatforms.WinPhone));
Assert.That(actual: AppPlatforms.FromJsonString(response: "web"), expression: Is.EqualTo(expected: AppPlatforms.Web));
}
[Test]
public void AppRatingTypeTest()
{
// get test
Assert.That(actual: AppRatingType.Level.ToString(), expression: Is.EqualTo(expected: "level"));
Assert.That(actual: AppRatingType.Points.ToString(), expression: Is.EqualTo(expected: "points"));
// parse test
Assert.That(actual: AppRatingType.FromJsonString(response: "level"), expression: Is.EqualTo(expected: AppRatingType.Level));
Assert.That(actual: AppRatingType.FromJsonString(response: "points"), expression: Is.EqualTo(expected: AppRatingType.Points));
}
[Test]
public void AppRequestTypeTest()
{
// get test
Assert.That(actual: AppRequestType.Invite.ToString(), expression: Is.EqualTo(expected: "invite"));
Assert.That(actual: AppRequestType.Request.ToString(), expression: Is.EqualTo(expected: "request"));
// parse test
Assert.That(actual: AppRequestType.FromJsonString(response: "invite"), expression: Is.EqualTo(expected: AppRequestType.Invite));
Assert.That(actual: AppRequestType.FromJsonString(response: "request")
, expression: Is.EqualTo(expected: AppRequestType.Request));
}
[Test]
public void AppSortTest()
{
// get test
Assert.That(actual: AppSort.PopularToday.ToString(), expression: Is.EqualTo(expected: "popular_today"));
Assert.That(actual: AppSort.Visitors.ToString(), expression: Is.EqualTo(expected: "visitors"));
Assert.That(actual: AppSort.CreateDate.ToString(), expression: Is.EqualTo(expected: "create_date"));
Assert.That(actual: AppSort.GrowthRate.ToString(), expression: Is.EqualTo(expected: "growth_rate"));
Assert.That(actual: AppSort.PopularWeek.ToString(), expression: Is.EqualTo(expected: "popular_week"));
// parse test
Assert.That(actual: AppSort.FromJsonString(response: "popular_today"), expression: Is.EqualTo(expected: AppSort.PopularToday));
Assert.That(actual: AppSort.FromJsonString(response: "visitors"), expression: Is.EqualTo(expected: AppSort.Visitors));
Assert.That(actual: AppSort.FromJsonString(response: "create_date"), expression: Is.EqualTo(expected: AppSort.CreateDate));
Assert.That(actual: AppSort.FromJsonString(response: "growth_rate"), expression: Is.EqualTo(expected: AppSort.GrowthRate));
Assert.That(actual: AppSort.FromJsonString(response: "popular_week"), expression: Is.EqualTo(expected: AppSort.PopularWeek));
}
[Test]
public void ChangeNameStatusTest()
{
// get test
Assert.That(actual: ChangeNameStatus.Processing.ToString(), expression: Is.EqualTo(expected: "processing"));
Assert.That(actual: ChangeNameStatus.Declined.ToString(), expression: Is.EqualTo(expected: "declined"));
Assert.That(actual: ChangeNameStatus.Success.ToString(), expression: Is.EqualTo(expected: "success"));
Assert.That(actual: ChangeNameStatus.WasAccepted.ToString(), expression: Is.EqualTo(expected: "was_accepted"));
Assert.That(actual: ChangeNameStatus.WasDeclined.ToString(), expression: Is.EqualTo(expected: "was_declined"));
// parse test
Assert.That(actual: ChangeNameStatus.FromJsonString(response: "processing")
, expression: Is.EqualTo(expected: ChangeNameStatus.Processing));
Assert.That(actual: ChangeNameStatus.FromJsonString(response: "declined")
, expression: Is.EqualTo(expected: ChangeNameStatus.Declined));
Assert.That(actual: ChangeNameStatus.FromJsonString(response: "success")
, expression: Is.EqualTo(expected: ChangeNameStatus.Success));
Assert.That(actual: ChangeNameStatus.FromJsonString(response: "was_accepted")
, expression: Is.EqualTo(expected: ChangeNameStatus.WasAccepted));
Assert.That(actual: ChangeNameStatus.FromJsonString(response: "was_declined")
, expression: Is.EqualTo(expected: ChangeNameStatus.WasDeclined));
}
[Test]
public void CommentObjectTypeTest()
{
// get test
Assert.That(actual: CommentObjectType.Post.ToString(), expression: Is.EqualTo(expected: "post"));
Assert.That(actual: CommentObjectType.Photo.ToString(), expression: Is.EqualTo(expected: "photo"));
Assert.That(actual: CommentObjectType.Video.ToString(), expression: Is.EqualTo(expected: "video"));
Assert.That(actual: CommentObjectType.Topic.ToString(), expression: Is.EqualTo(expected: "topic"));
Assert.That(actual: CommentObjectType.Note.ToString(), expression: Is.EqualTo(expected: "note"));
// parse test
Assert.That(actual: CommentObjectType.FromJsonString(response: "post")
, expression: Is.EqualTo(expected: CommentObjectType.Post));
Assert.That(actual: CommentObjectType.FromJsonString(response: "photo")
, expression: Is.EqualTo(expected: CommentObjectType.Photo));
Assert.That(actual: CommentObjectType.FromJsonString(response: "video")
, expression: Is.EqualTo(expected: CommentObjectType.Video));
Assert.That(actual: CommentObjectType.FromJsonString(response: "topic")
, expression: Is.EqualTo(expected: CommentObjectType.Topic));
Assert.That(actual: CommentObjectType.FromJsonString(response: "note")
, expression: Is.EqualTo(expected: CommentObjectType.Note));
}
[Test]
public void CommentsSortTest()
{
// get test
Assert.That(actual: CommentsSort.Asc.ToString(), expression: Is.EqualTo(expected: "asc"));
Assert.That(actual: CommentsSort.Desc.ToString(), expression: Is.EqualTo(expected: "desc"));
// parse test
Assert.That(actual: CommentsSort.FromJsonString(response: "asc"), expression: Is.EqualTo(expected: CommentsSort.Asc));
Assert.That(actual: CommentsSort.FromJsonString(response: "desc"), expression: Is.EqualTo(expected: CommentsSort.Desc));
}
[Test]
public void DeactivatedTest()
{
// get test
Assert.That(actual: Deactivated.Deleted.ToString(), expression: Is.EqualTo(expected: "deleted"));
Assert.That(actual: Deactivated.Banned.ToString(), expression: Is.EqualTo(expected: "banned"));
Assert.That(actual: Deactivated.Activated.ToString(), expression: Is.EqualTo(expected: "activated"));
// parse test
Assert.That(actual: Deactivated.FromJsonString(response: "deleted"), expression: Is.EqualTo(expected: Deactivated.Deleted));
Assert.That(actual: Deactivated.FromJsonString(response: "banned"), expression: Is.EqualTo(expected: Deactivated.Banned));
Assert.That(actual: Deactivated.FromJsonString(response: "activated"), expression: Is.EqualTo(expected: Deactivated.Activated));
}
[Test]
public void DisplayTest()
{
// get test
Assert.That(actual: Display.Page.ToString(), expression: Is.EqualTo(expected: "page"));
Assert.That(actual: Display.Popup.ToString(), expression: Is.EqualTo(expected: "popup"));
Assert.That(actual: Display.Mobile.ToString(), expression: Is.EqualTo(expected: "mobile"));
// parse test
Assert.That(actual: Display.FromJsonString(response: "page"), expression: Is.EqualTo(expected: Display.Page));
Assert.That(actual: Display.FromJsonString(response: "popup"), expression: Is.EqualTo(expected: Display.Popup));
Assert.That(actual: Display.FromJsonString(response: "mobile"), expression: Is.EqualTo(expected: Display.Mobile));
}
[Test]
public void FeedTypeTest()
{
// get test
Assert.That(actual: FeedType.Photo.ToString(), expression: Is.EqualTo(expected: "photo"));
Assert.That(actual: FeedType.PhotoTag.ToString(), expression: Is.EqualTo(expected: "photo_tag"));
// parse test
Assert.That(actual: FeedType.FromJsonString(response: "photo"), expression: Is.EqualTo(expected: FeedType.Photo));
Assert.That(actual: FeedType.FromJsonString(response: "photo_tag"), expression: Is.EqualTo(expected: FeedType.PhotoTag));
}
[Test]
public void FriendsFilterTest()
{
// get test
Assert.That(actual: FriendsFilter.Mutual.ToString(), expression: Is.EqualTo(expected: "mutual"));
Assert.That(actual: FriendsFilter.Contacts.ToString(), expression: Is.EqualTo(expected: "contacts"));
Assert.That(actual: FriendsFilter.MutualContacts.ToString(), expression: Is.EqualTo(expected: "mutual_contacts"));
// parse test
Assert.That(actual: FriendsFilter.FromJsonString(response: "mutual"), expression: Is.EqualTo(expected: FriendsFilter.Mutual));
Assert.That(actual: FriendsFilter.FromJsonString(response: "contacts")
, expression: Is.EqualTo(expected: FriendsFilter.Contacts));
Assert.That(actual: FriendsFilter.FromJsonString(response: "mutual_contacts")
, expression: Is.EqualTo(expected: FriendsFilter.MutualContacts));
}
[Test]
public void FriendsOrderTest()
{
// get test
Assert.That(actual: FriendsOrder.Name.ToString(), expression: Is.EqualTo(expected: "name"));
Assert.That(actual: FriendsOrder.Hints.ToString(), expression: Is.EqualTo(expected: "hints"));
Assert.That(actual: FriendsOrder.Random.ToString(), expression: Is.EqualTo(expected: "random"));
// parse test
Assert.That(actual: FriendsOrder.FromJsonString(response: "name"), expression: Is.EqualTo(expected: FriendsOrder.Name));
Assert.That(actual: FriendsOrder.FromJsonString(response: "hints"), expression: Is.EqualTo(expected: FriendsOrder.Hints));
Assert.That(actual: FriendsOrder.FromJsonString(response: "random"), expression: Is.EqualTo(expected: FriendsOrder.Random));
}
[Test]
public void GroupsSortTest()
{
// get test
Assert.That(actual: GroupsSort.IdAsc.ToString(), expression: Is.EqualTo(expected: "id_asc"));
Assert.That(actual: GroupsSort.IdDesc.ToString(), expression: Is.EqualTo(expected: "id_desc"));
Assert.That(actual: GroupsSort.TimeAsc.ToString(), expression: Is.EqualTo(expected: "time_asc"));
Assert.That(actual: GroupsSort.TimeDesc.ToString(), expression: Is.EqualTo(expected: "time_desc"));
// parse test
Assert.That(actual: GroupsSort.FromJsonString(response: "id_asc"), expression: Is.EqualTo(expected: GroupsSort.IdAsc));
Assert.That(actual: GroupsSort.FromJsonString(response: "id_desc"), expression: Is.EqualTo(expected: GroupsSort.IdDesc));
Assert.That(actual: GroupsSort.FromJsonString(response: "time_asc"), expression: Is.EqualTo(expected: GroupsSort.TimeAsc));
Assert.That(actual: GroupsSort.FromJsonString(response: "time_desc"), expression: Is.EqualTo(expected: GroupsSort.TimeDesc));
}
[Test]
public void GroupTypeTest()
{
// get test
Assert.That(actual: GroupType.Page.ToString(), expression: Is.EqualTo(expected: "page"));
Assert.That(actual: GroupType.Group.ToString(), expression: Is.EqualTo(expected: "group"));
Assert.That(actual: GroupType.Event.ToString(), expression: Is.EqualTo(expected: "event"));
Assert.That(actual: GroupType.Undefined.ToString(), expression: Is.EqualTo(expected: "undefined"));
// parse test
Assert.That(actual: GroupType.FromJsonString(response: "page"), expression: Is.EqualTo(expected: GroupType.Page));
Assert.That(actual: GroupType.FromJsonString(response: "group"), expression: Is.EqualTo(expected: GroupType.Group));
Assert.That(actual: GroupType.FromJsonString(response: "event"), expression: Is.EqualTo(expected: GroupType.Event));
Assert.That(actual: GroupType.FromJsonString(response: "undefined"), expression: Is.EqualTo(expected: GroupType.Undefined));
}
[Test]
public void LikeObjectTypeTest()
{
// get test
Assert.That(actual: LikeObjectType.Post.ToString(), expression: Is.EqualTo(expected: "post"));
Assert.That(actual: LikeObjectType.Comment.ToString(), expression: Is.EqualTo(expected: "comment"));
Assert.That(actual: LikeObjectType.Photo.ToString(), expression: Is.EqualTo(expected: "photo"));
Assert.That(actual: LikeObjectType.Audio.ToString(), expression: Is.EqualTo(expected: "audio"));
Assert.That(actual: LikeObjectType.Video.ToString(), expression: Is.EqualTo(expected: "video"));
Assert.That(actual: LikeObjectType.Note.ToString(), expression: Is.EqualTo(expected: "note"));
Assert.That(actual: LikeObjectType.PhotoComment.ToString(), expression: Is.EqualTo(expected: "photo_comment"));
Assert.That(actual: LikeObjectType.VideoComment.ToString(), expression: Is.EqualTo(expected: "video_comment"));
Assert.That(actual: LikeObjectType.TopicComment.ToString(), expression: Is.EqualTo(expected: "topic_comment"));
Assert.That(actual: LikeObjectType.SitePage.ToString(), expression: Is.EqualTo(expected: "sitepage"));
Assert.That(actual: LikeObjectType.Market.ToString(), expression: Is.EqualTo(expected: "market"));
Assert.That(actual: LikeObjectType.MarketComment.ToString(), expression: Is.EqualTo(expected: "market_comment"));
// parse test
Assert.That(actual: LikeObjectType.FromJsonString(response: "post"), expression: Is.EqualTo(expected: LikeObjectType.Post));
Assert.That(actual: LikeObjectType.FromJsonString(response: "comment")
, expression: Is.EqualTo(expected: LikeObjectType.Comment));
Assert.That(actual: LikeObjectType.FromJsonString(response: "photo"), expression: Is.EqualTo(expected: LikeObjectType.Photo));
Assert.That(actual: LikeObjectType.FromJsonString(response: "audio"), expression: Is.EqualTo(expected: LikeObjectType.Audio));
Assert.That(actual: LikeObjectType.FromJsonString(response: "video"), expression: Is.EqualTo(expected: LikeObjectType.Video));
Assert.That(actual: LikeObjectType.FromJsonString(response: "note"), expression: Is.EqualTo(expected: LikeObjectType.Note));
Assert.That(actual: LikeObjectType.FromJsonString(response: "photo_comment")
, expression: Is.EqualTo(expected: LikeObjectType.PhotoComment));
Assert.That(actual: LikeObjectType.FromJsonString(response: "video_comment")
, expression: Is.EqualTo(expected: LikeObjectType.VideoComment));
Assert.That(actual: LikeObjectType.FromJsonString(response: "topic_comment")
, expression: Is.EqualTo(expected: LikeObjectType.TopicComment));
Assert.That(actual: LikeObjectType.FromJsonString(response: "sitepage")
, expression: Is.EqualTo(expected: LikeObjectType.SitePage));
Assert.That(actual: LikeObjectType.FromJsonString(response: "market"), expression: Is.EqualTo(expected: LikeObjectType.Market));
Assert.That(actual: LikeObjectType.FromJsonString(response: "market_comment")
, expression: Is.EqualTo(expected: LikeObjectType.MarketComment));
}
[Test]
public void LikesFilterTest()
{
// get test
Assert.That(actual: LikesFilter.Likes.ToString(), expression: Is.EqualTo(expected: "likes"));
Assert.That(actual: LikesFilter.Copies.ToString(), expression: Is.EqualTo(expected: "copies"));
// parse test
Assert.That(actual: LikesFilter.FromJsonString(response: "likes"), expression: Is.EqualTo(expected: LikesFilter.Likes));
Assert.That(actual: LikesFilter.FromJsonString(response: "copies"), expression: Is.EqualTo(expected: LikesFilter.Copies));
}
[Test]
public void LinkAccessTypeTest()
{
// get test
Assert.That(actual: LinkAccessType.NotBanned.ToString(), expression: Is.EqualTo(expected: "not_banned"));
Assert.That(actual: LinkAccessType.Banned.ToString(), expression: Is.EqualTo(expected: "banned"));
Assert.That(actual: LinkAccessType.Processing.ToString(), expression: Is.EqualTo(expected: "processing"));
// parse test
Assert.That(actual: LinkAccessType.FromJsonString(response: "not_banned")
, expression: Is.EqualTo(expected: LinkAccessType.NotBanned));
Assert.That(actual: LinkAccessType.FromJsonString(response: "banned"), expression: Is.EqualTo(expected: LinkAccessType.Banned));
Assert.That(actual: LinkAccessType.FromJsonString(response: "processing")
, expression: Is.EqualTo(expected: LinkAccessType.Processing));
}
[Test]
public void MediaTypeTest()
{
// get test
Assert.That(actual: MediaType.Photo.ToString(), expression: Is.EqualTo(expected: "photo"));
Assert.That(actual: MediaType.Video.ToString(), expression: Is.EqualTo(expected: "video"));
Assert.That(actual: MediaType.Audio.ToString(), expression: Is.EqualTo(expected: "audio"));
Assert.That(actual: MediaType.Doc.ToString(), expression: Is.EqualTo(expected: "doc"));
Assert.That(actual: MediaType.Link.ToString(), expression: Is.EqualTo(expected: "link"));
Assert.That(actual: MediaType.Market.ToString(), expression: Is.EqualTo(expected: "market"));
Assert.That(actual: MediaType.Wall.ToString(), expression: Is.EqualTo(expected: "wall"));
Assert.That(actual: MediaType.Share.ToString(), expression: Is.EqualTo(expected: "share"));
// parse test
Assert.That(actual: MediaType.FromJsonString(response: "photo"), expression: Is.EqualTo(expected: MediaType.Photo));
Assert.That(actual: MediaType.FromJsonString(response: "video"), expression: Is.EqualTo(expected: MediaType.Video));
Assert.That(actual: MediaType.FromJsonString(response: "audio"), expression: Is.EqualTo(expected: MediaType.Audio));
Assert.That(actual: MediaType.FromJsonString(response: "doc"), expression: Is.EqualTo(expected: MediaType.Doc));
Assert.That(actual: MediaType.FromJsonString(response: "link"), expression: Is.EqualTo(expected: MediaType.Link));
Assert.That(actual: MediaType.FromJsonString(response: "market"), expression: Is.EqualTo(expected: MediaType.Market));
Assert.That(actual: MediaType.FromJsonString(response: "wall"), expression: Is.EqualTo(expected: MediaType.Wall));
Assert.That(actual: MediaType.FromJsonString(response: "share"), expression: Is.EqualTo(expected: MediaType.Share));
}
[Test]
public void NameCaseTest()
{
// get test
Assert.That(actual: NameCase.Nom.ToString(), expression: Is.EqualTo(expected: "nom"));
Assert.That(actual: NameCase.Gen.ToString(), expression: Is.EqualTo(expected: "gen"));
Assert.That(actual: NameCase.Dat.ToString(), expression: Is.EqualTo(expected: "dat"));
Assert.That(actual: NameCase.Acc.ToString(), expression: Is.EqualTo(expected: "acc"));
Assert.That(actual: NameCase.Ins.ToString(), expression: Is.EqualTo(expected: "ins"));
Assert.That(actual: NameCase.Abl.ToString(), expression: Is.EqualTo(expected: "abl"));
// parse test
Assert.That(actual: NameCase.FromJsonString(response: "nom"), expression: Is.EqualTo(expected: NameCase.Nom));
Assert.That(actual: NameCase.FromJsonString(response: "gen"), expression: Is.EqualTo(expected: NameCase.Gen));
Assert.That(actual: NameCase.FromJsonString(response: "dat"), expression: Is.EqualTo(expected: NameCase.Dat));
Assert.That(actual: NameCase.FromJsonString(response: "acc"), expression: Is.EqualTo(expected: NameCase.Acc));
Assert.That(actual: NameCase.FromJsonString(response: "ins"), expression: Is.EqualTo(expected: NameCase.Ins));
Assert.That(actual: NameCase.FromJsonString(response: "abl"), expression: Is.EqualTo(expected: NameCase.Abl));
}
[Test]
public void NewsObjectTypesTest()
{
// get test
Assert.That(actual: NewsObjectTypes.Wall.ToString(), expression: Is.EqualTo(expected: "wall"));
Assert.That(actual: NewsObjectTypes.Tag.ToString(), expression: Is.EqualTo(expected: "tag"));
Assert.That(actual: NewsObjectTypes.ProfilePhoto.ToString(), expression: Is.EqualTo(expected: "profilephoto"));
Assert.That(actual: NewsObjectTypes.Video.ToString(), expression: Is.EqualTo(expected: "video"));
Assert.That(actual: NewsObjectTypes.Photo.ToString(), expression: Is.EqualTo(expected: "photo"));
Assert.That(actual: NewsObjectTypes.Audio.ToString(), expression: Is.EqualTo(expected: "audio"));
// parse test
Assert.That(actual: NewsObjectTypes.FromJsonString(response: "wall"), expression: Is.EqualTo(expected: NewsObjectTypes.Wall));
Assert.That(actual: NewsObjectTypes.FromJsonString(response: "tag"), expression: Is.EqualTo(expected: NewsObjectTypes.Tag));
Assert.That(actual: NewsObjectTypes.FromJsonString(response: "profilephoto")
, expression: Is.EqualTo(expected: NewsObjectTypes.ProfilePhoto));
Assert.That(actual: NewsObjectTypes.FromJsonString(response: "video"), expression: Is.EqualTo(expected: NewsObjectTypes.Video));
Assert.That(actual: NewsObjectTypes.FromJsonString(response: "photo"), expression: Is.EqualTo(expected: NewsObjectTypes.Photo));
Assert.That(actual: NewsObjectTypes.FromJsonString(response: "audio"), expression: Is.EqualTo(expected: NewsObjectTypes.Audio));
}
[Test]
public void NewsTypesTest()
{
// get test
Assert.That(actual: NewsTypes.Post.ToString(), expression: Is.EqualTo(expected: "post"));
Assert.That(actual: NewsTypes.Photo.ToString(), expression: Is.EqualTo(expected: "photo"));
Assert.That(actual: NewsTypes.PhotoTag.ToString(), expression: Is.EqualTo(expected: "photo_tag"));
Assert.That(actual: NewsTypes.WallPhoto.ToString(), expression: Is.EqualTo(expected: "wall_photo"));
Assert.That(actual: NewsTypes.Friend.ToString(), expression: Is.EqualTo(expected: "friend"));
Assert.That(actual: NewsTypes.Note.ToString(), expression: Is.EqualTo(expected: "note"));
// parse test
Assert.That(actual: NewsTypes.FromJsonString(response: "post"), expression: Is.EqualTo(expected: NewsTypes.Post));
Assert.That(actual: NewsTypes.FromJsonString(response: "photo"), expression: Is.EqualTo(expected: NewsTypes.Photo));
Assert.That(actual: NewsTypes.FromJsonString(response: "photo_tag"), expression: Is.EqualTo(expected: NewsTypes.PhotoTag));
Assert.That(actual: NewsTypes.FromJsonString(response: "wall_photo"), expression: Is.EqualTo(expected: NewsTypes.WallPhoto));
Assert.That(actual: NewsTypes.FromJsonString(response: "friend"), expression: Is.EqualTo(expected: NewsTypes.Friend));
Assert.That(actual: NewsTypes.FromJsonString(response: "note"), expression: Is.EqualTo(expected: NewsTypes.Note));
}
[Test]
public void OccupationTypeTest()
{
// get test
Assert.That(actual: OccupationType.Work.ToString(), expression: Is.EqualTo(expected: "work"));
Assert.That(actual: OccupationType.School.ToString(), expression: Is.EqualTo(expected: "school"));
Assert.That(actual: OccupationType.University.ToString(), expression: Is.EqualTo(expected: "university"));
// parse test
Assert.That(actual: OccupationType.FromJsonString(response: "work"), expression: Is.EqualTo(expected: OccupationType.Work));
Assert.That(actual: OccupationType.FromJsonString(response: "school"), expression: Is.EqualTo(expected: OccupationType.School));
Assert.That(actual: OccupationType.FromJsonString(response: "university")
, expression: Is.EqualTo(expected: OccupationType.University));
}
[Test]
public void PhotoAlbumTypeTest()
{
// get test
Assert.That(actual: PhotoAlbumType.Wall.ToString(), expression: Is.EqualTo(expected: "wall"));
Assert.That(actual: PhotoAlbumType.Profile.ToString(), expression: Is.EqualTo(expected: "profile"));
Assert.That(actual: PhotoAlbumType.Saved.ToString(), expression: Is.EqualTo(expected: "saved"));
// parse test
Assert.That(actual: PhotoAlbumType.FromJsonString(response: "wall"), expression: Is.EqualTo(expected: PhotoAlbumType.Wall));
Assert.That(actual: PhotoAlbumType.FromJsonString(response: "profile")
, expression: Is.EqualTo(expected: PhotoAlbumType.Profile));
Assert.That(actual: PhotoAlbumType.FromJsonString(response: "saved"), expression: Is.EqualTo(expected: PhotoAlbumType.Saved));
}
[Test]
public void PhotoFeedTypeTest()
{
// get test
Assert.That(actual: PhotoFeedType.Photo.ToString(), expression: Is.EqualTo(expected: "photo"));
Assert.That(actual: PhotoFeedType.PhotoTag.ToString(), expression: Is.EqualTo(expected: "photo_tag"));
// parse test
Assert.That(actual: PhotoFeedType.FromJsonString(response: "photo"), expression: Is.EqualTo(expected: PhotoFeedType.Photo));
Assert.That(actual: PhotoFeedType.FromJsonString(response: "photo_tag")
, expression: Is.EqualTo(expected: PhotoFeedType.PhotoTag));
}
[Test]
public void PhotoSearchRadiusTest()
{
// get test
Assert.That(actual: PhotoSearchRadius.Ten.ToString(), expression: Is.EqualTo(expected: "10"));
Assert.That(actual: PhotoSearchRadius.OneHundred.ToString(), expression: Is.EqualTo(expected: "100"));
Assert.That(actual: PhotoSearchRadius.Eighty.ToString(), expression: Is.EqualTo(expected: "800"));
Assert.That(actual: PhotoSearchRadius.SixThousand.ToString(), expression: Is.EqualTo(expected: "6000"));
Assert.That(actual: PhotoSearchRadius.FiftyThousand.ToString(), expression: Is.EqualTo(expected: "50000"));
// parse test
Assert.That(actual: PhotoSearchRadius.FromJsonString(response: "10"), expression: Is.EqualTo(expected: PhotoSearchRadius.Ten));
Assert.That(actual: PhotoSearchRadius.FromJsonString(response: "100")
, expression: Is.EqualTo(expected: PhotoSearchRadius.OneHundred));
Assert.That(actual: PhotoSearchRadius.FromJsonString(response: "800")
, expression: Is.EqualTo(expected: PhotoSearchRadius.Eighty));
Assert.That(actual: PhotoSearchRadius.FromJsonString(response: "6000")
, expression: Is.EqualTo(expected: PhotoSearchRadius.SixThousand));
Assert.That(actual: PhotoSearchRadius.FromJsonString(response: "50000")
, expression: Is.EqualTo(expected: PhotoSearchRadius.FiftyThousand));
}
[Test]
public void PhotoSizeTypeTest()
{
// get test
Assert.That(actual: PhotoSizeType.S.ToString(), expression: Is.EqualTo(expected: "s"));
Assert.That(actual: PhotoSizeType.M.ToString(), expression: Is.EqualTo(expected: "m"));
Assert.That(actual: PhotoSizeType.X.ToString(), expression: Is.EqualTo(expected: "x"));
Assert.That(actual: PhotoSizeType.O.ToString(), expression: Is.EqualTo(expected: "o"));
Assert.That(actual: PhotoSizeType.P.ToString(), expression: Is.EqualTo(expected: "p"));
Assert.That(actual: PhotoSizeType.Q.ToString(), expression: Is.EqualTo(expected: "q"));
Assert.That(actual: PhotoSizeType.R.ToString(), expression: Is.EqualTo(expected: "r"));
Assert.That(actual: PhotoSizeType.Y.ToString(), expression: Is.EqualTo(expected: "y"));
Assert.That(actual: PhotoSizeType.Z.ToString(), expression: Is.EqualTo(expected: "z"));
Assert.That(actual: PhotoSizeType.W.ToString(), expression: Is.EqualTo(expected: "w"));
// parse test
Assert.That(actual: PhotoSizeType.FromJsonString(response: "s"), expression: Is.EqualTo(expected: PhotoSizeType.S));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "m"), expression: Is.EqualTo(expected: PhotoSizeType.M));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "x"), expression: Is.EqualTo(expected: PhotoSizeType.X));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "o"), expression: Is.EqualTo(expected: PhotoSizeType.O));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "p"), expression: Is.EqualTo(expected: PhotoSizeType.P));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "q"), expression: Is.EqualTo(expected: PhotoSizeType.Q));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "r"), expression: Is.EqualTo(expected: PhotoSizeType.R));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "y"), expression: Is.EqualTo(expected: PhotoSizeType.Y));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "z"), expression: Is.EqualTo(expected: PhotoSizeType.Z));
Assert.That(actual: PhotoSizeType.FromJsonString(response: "w"), expression: Is.EqualTo(expected: PhotoSizeType.W));
}
[Test]
public void PlatformTest()
{
// get test
Assert.That(actual: Platform.Android.ToString(), expression: Is.EqualTo(expected: "android"));
Assert.That(actual: Platform.IPhone.ToString(), expression: Is.EqualTo(expected: "iphone"));
Assert.That(actual: Platform.WindowsPhone.ToString(), expression: Is.EqualTo(expected: "wphone"));
// parse test
Assert.That(actual: Platform.FromJsonString(response: "android"), expression: Is.EqualTo(expected: Platform.Android));
Assert.That(actual: Platform.FromJsonString(response: "iphone"), expression: Is.EqualTo(expected: Platform.IPhone));
Assert.That(actual: Platform.FromJsonString(response: "wphone"), expression: Is.EqualTo(expected: Platform.WindowsPhone));
}
[Test]
public void PostSourceTypeTest()
{
// get test
Assert.That(actual: PostSourceType.Vk.ToString(), expression: Is.EqualTo(expected: "vk"));
Assert.That(actual: PostSourceType.Widget.ToString(), expression: Is.EqualTo(expected: "widget"));
Assert.That(actual: PostSourceType.Api.ToString(), expression: Is.EqualTo(expected: "api"));
Assert.That(actual: PostSourceType.Rss.ToString(), expression: Is.EqualTo(expected: "rss"));
Assert.That(actual: PostSourceType.Sms.ToString(), expression: Is.EqualTo(expected: "sms"));
// parse test
Assert.That(actual: PostSourceType.FromJsonString(response: "vk"), expression: Is.EqualTo(expected: PostSourceType.Vk));
Assert.That(actual: PostSourceType.FromJsonString(response: "widget"), expression: Is.EqualTo(expected: PostSourceType.Widget));
Assert.That(actual: PostSourceType.FromJsonString(response: "api"), expression: Is.EqualTo(expected: PostSourceType.Api));
Assert.That(actual: PostSourceType.FromJsonString(response: "rss"), expression: Is.EqualTo(expected: PostSourceType.Rss));
Assert.That(actual: PostSourceType.FromJsonString(response: "sms"), expression: Is.EqualTo(expected: PostSourceType.Sms));
}
[Test]
public void PostTypeOrderTest()
{
// get test
Assert.That(actual: PostTypeOrder.Post.ToString(), expression: Is.EqualTo(expected: "post"));
Assert.That(actual: PostTypeOrder.Copy.ToString(), expression: Is.EqualTo(expected: "copy"));
// parse test
Assert.That(actual: PostTypeOrder.FromJsonString(response: "post"), expression: Is.EqualTo(expected: PostTypeOrder.Post));
Assert.That(actual: PostTypeOrder.FromJsonString(response: "copy"), expression: Is.EqualTo(expected: PostTypeOrder.Copy));
}
[Test]
public void PostTypeTest()
{
// get test
Assert.That(actual: PostType.Post.ToString(), expression: Is.EqualTo(expected: "post"));
Assert.That(actual: PostType.Copy.ToString(), expression: Is.EqualTo(expected: "copy"));
Assert.That(actual: PostType.Reply.ToString(), expression: Is.EqualTo(expected: "reply"));
Assert.That(actual: PostType.Postpone.ToString(), expression: Is.EqualTo(expected: "postpone"));
Assert.That(actual: PostType.Suggest.ToString(), expression: Is.EqualTo(expected: "suggest"));
// parse test
Assert.That(actual: PostType.FromJsonString(response: "post"), expression: Is.EqualTo(expected: PostType.Post));
Assert.That(actual: PostType.FromJsonString(response: "copy"), expression: Is.EqualTo(expected: PostType.Copy));
Assert.That(actual: PostType.FromJsonString(response: "reply"), expression: Is.EqualTo(expected: PostType.Reply));
Assert.That(actual: PostType.FromJsonString(response: "postpone"), expression: Is.EqualTo(expected: PostType.Postpone));
Assert.That(actual: PostType.FromJsonString(response: "suggest"), expression: Is.EqualTo(expected: PostType.Suggest));
}
[Test]
public void PrivacyTest()
{
// get test
Assert.That(actual: Privacy.All.ToString(), expression: Is.EqualTo(expected: "all"));
Assert.That(actual: Privacy.Friends.ToString(), expression: Is.EqualTo(expected: "friends"));
Assert.That(actual: Privacy.FriendsOfFriends.ToString(), expression: Is.EqualTo(expected: "friends_of_friends"));
Assert.That(actual: Privacy.FriendsOfFriendsOnly.ToString(), expression: Is.EqualTo(expected: "friends_of_friends_only"));
Assert.That(actual: Privacy.Nobody.ToString(), expression: Is.EqualTo(expected: "nobody"));
Assert.That(actual: Privacy.OnlyMe.ToString(), expression: Is.EqualTo(expected: "only_me"));
// parse test
Assert.That(actual: Privacy.FromJsonString(response: "all"), expression: Is.EqualTo(expected: Privacy.All));
Assert.That(actual: Privacy.FromJsonString(response: "friends"), expression: Is.EqualTo(expected: Privacy.Friends));
Assert.That(actual: Privacy.FromJsonString(response: "friends_of_friends")
, expression: Is.EqualTo(expected: Privacy.FriendsOfFriends));
Assert.That(actual: Privacy.FromJsonString(response: "friends_of_friends_only")
, expression: Is.EqualTo(expected: Privacy.FriendsOfFriendsOnly));
Assert.That(actual: Privacy.FromJsonString(response: "nobody"), expression: Is.EqualTo(expected: Privacy.Nobody));
Assert.That(actual: Privacy.FromJsonString(response: "only_me"), expression: Is.EqualTo(expected: Privacy.OnlyMe));
}
[Test]
public void RelativeTypeTest()
{
// get test
Assert.That(actual: RelativeType.Sibling.ToString(), expression: Is.EqualTo(expected: "sibling"));
Assert.That(actual: RelativeType.Parent.ToString(), expression: Is.EqualTo(expected: "parent"));
Assert.That(actual: RelativeType.Child.ToString(), expression: Is.EqualTo(expected: "child"));
Assert.That(actual: RelativeType.Grandparent.ToString(), expression: Is.EqualTo(expected: "grandparent"));
Assert.That(actual: RelativeType.Grandchild.ToString(), expression: Is.EqualTo(expected: "grandchild"));
// parse test
Assert.That(actual: RelativeType.FromJsonString(response: "sibling"), expression: Is.EqualTo(expected: RelativeType.Sibling));
Assert.That(actual: RelativeType.FromJsonString(response: "parent"), expression: Is.EqualTo(expected: RelativeType.Parent));
Assert.That(actual: RelativeType.FromJsonString(response: "child"), expression: Is.EqualTo(expected: RelativeType.Child));
Assert.That(actual: RelativeType.FromJsonString(response: "grandparent")
, expression: Is.EqualTo(expected: RelativeType.Grandparent));
Assert.That(actual: RelativeType.FromJsonString(response: "grandchild")
, expression: Is.EqualTo(expected: RelativeType.Grandchild));
}
[Test]
public void ReportTypeTest()
{
// get test
Assert.That(actual: ReportType.Porn.ToString(), expression: Is.EqualTo(expected: "porn"));
Assert.That(actual: ReportType.Spam.ToString(), expression: Is.EqualTo(expected: "spam"));
Assert.That(actual: ReportType.Insult.ToString(), expression: Is.EqualTo(expected: "insult"));
Assert.That(actual: ReportType.Advertisment.ToString(), expression: Is.EqualTo(expected: "advertisment"));
// parse test
Assert.That(actual: ReportType.FromJsonString(response: "porn"), expression: Is.EqualTo(expected: ReportType.Porn));
Assert.That(actual: ReportType.FromJsonString(response: "spam"), expression: Is.EqualTo(expected: ReportType.Spam));
Assert.That(actual: ReportType.FromJsonString(response: "insult"), expression: Is.EqualTo(expected: ReportType.Insult));
Assert.That(actual: ReportType.FromJsonString(response: "advertisment")
, expression: Is.EqualTo(expected: ReportType.Advertisment));
}
[Test]
public void ServicesTest()
{
// get test
Assert.That(actual: Services.Email.ToString(), expression: Is.EqualTo(expected: "email"));
Assert.That(actual: Services.Phone.ToString(), expression: Is.EqualTo(expected: "phone"));
Assert.That(actual: Services.Twitter.ToString(), expression: Is.EqualTo(expected: "twitter"));
Assert.That(actual: Services.Facebook.ToString(), expression: Is.EqualTo(expected: "facebook"));
Assert.That(actual: Services.Odnoklassniki.ToString(), expression: Is.EqualTo(expected: "odnoklassniki"));
Assert.That(actual: Services.Instagram.ToString(), expression: Is.EqualTo(expected: "instagram"));
Assert.That(actual: Services.Google.ToString(), expression: Is.EqualTo(expected: "google"));
// parse test
Assert.That(actual: Services.FromJsonString(response: "email"), expression: Is.EqualTo(expected: Services.Email));
Assert.That(actual: Services.FromJsonString(response: "phone"), expression: Is.EqualTo(expected: Services.Phone));
Assert.That(actual: Services.FromJsonString(response: "twitter"), expression: Is.EqualTo(expected: Services.Twitter));
Assert.That(actual: Services.FromJsonString(response: "facebook"), expression: Is.EqualTo(expected: Services.Facebook));
Assert.That(actual: Services.FromJsonString(response: "odnoklassniki")
, expression: Is.EqualTo(expected: Services.Odnoklassniki));
Assert.That(actual: Services.FromJsonString(response: "instagram"), expression: Is.EqualTo(expected: Services.Instagram));
Assert.That(actual: Services.FromJsonString(response: "google"), expression: Is.EqualTo(expected: Services.Google));
}
[Test]
public void UserSectionTest()
{
// get test
Assert.That(actual: UserSection.Friends.ToString(), expression: Is.EqualTo(expected: "friends"));
Assert.That(actual: UserSection.Subscriptions.ToString(), expression: Is.EqualTo(expected: "subscriptions"));
// parse test
Assert.That(actual: UserSection.FromJsonString(response: "friends"), expression: Is.EqualTo(expected: UserSection.Friends));
Assert.That(actual: UserSection.FromJsonString(response: "subscriptions")
, expression: Is.EqualTo(expected: UserSection.Subscriptions));
}
[Test]
public void VideoCatalogItemTypeTest()
{
// get test
Assert.That(actual: VideoCatalogItemType.Video.ToString(), expression: Is.EqualTo(expected: "video"));
Assert.That(actual: VideoCatalogItemType.Album.ToString(), expression: Is.EqualTo(expected: "album"));
// parse test
Assert.That(actual: VideoCatalogItemType.FromJsonString(response: "video")
, expression: Is.EqualTo(expected: VideoCatalogItemType.Video));
Assert.That(actual: VideoCatalogItemType.FromJsonString(response: "album")
, expression: Is.EqualTo(expected: VideoCatalogItemType.Album));
}
[Test]
public void VideoCatalogTypeTest()
{
// get test
Assert.That(actual: VideoCatalogType.Channel.ToString(), expression: Is.EqualTo(expected: "channel"));
Assert.That(actual: VideoCatalogType.Category.ToString(), expression: Is.EqualTo(expected: "category"));
// parse test
Assert.That(actual: VideoCatalogType.FromJsonString(response: "channel")
, expression: Is.EqualTo(expected: VideoCatalogType.Channel));
Assert.That(actual: VideoCatalogType.FromJsonString(response: "category")
, expression: Is.EqualTo(expected: VideoCatalogType.Category));
}
[Test]
public void WallFilterTest()
{
// get test
Assert.That(actual: WallFilter.Owner.ToString(), expression: Is.EqualTo(expected: "owner"));
Assert.That(actual: WallFilter.Others.ToString(), expression: Is.EqualTo(expected: "others"));
Assert.That(actual: WallFilter.All.ToString(), expression: Is.EqualTo(expected: "all"));
Assert.That(actual: WallFilter.Suggests.ToString(), expression: Is.EqualTo(expected: "suggests"));
Assert.That(actual: WallFilter.Postponed.ToString(), expression: Is.EqualTo(expected: "postponed"));
// parse test
Assert.That(actual: WallFilter.FromJsonString(response: "owner"), expression: Is.EqualTo(expected: WallFilter.Owner));
Assert.That(actual: WallFilter.FromJsonString(response: "others"), expression: Is.EqualTo(expected: WallFilter.Others));
Assert.That(actual: WallFilter.FromJsonString(response: "all"), expression: Is.EqualTo(expected: WallFilter.All));
Assert.That(actual: WallFilter.FromJsonString(response: "suggests"), expression: Is.EqualTo(expected: WallFilter.Suggests));
Assert.That(actual: WallFilter.FromJsonString(response: "postponed"), expression: Is.EqualTo(expected: WallFilter.Postponed));
}
[Test]
public void KeyboardButtonColorTest()
{
// get test
Assert.That(actual: KeyboardButtonColor.Default.ToString(), expression: Is.EqualTo(expected: "default"));
Assert.That(actual: KeyboardButtonColor.Negative.ToString(), expression: Is.EqualTo(expected: "negative"));
Assert.That(actual: KeyboardButtonColor.Positive.ToString(), expression: Is.EqualTo(expected: "positive"));
Assert.That(actual: KeyboardButtonColor.Primary.ToString(), expression: Is.EqualTo(expected: "primary"));
// parse test
Assert.That(actual: KeyboardButtonColor.FromJsonString(response: "default"), expression: Is.EqualTo(expected: KeyboardButtonColor.Default));
Assert.That(actual: KeyboardButtonColor.FromJsonString(response: "negative"), expression: Is.EqualTo(expected: KeyboardButtonColor.Negative));
Assert.That(actual: KeyboardButtonColor.FromJsonString(response: "positive"), expression: Is.EqualTo(expected: KeyboardButtonColor.Positive));
Assert.That(actual: KeyboardButtonColor.FromJsonString(response: "primary"), expression: Is.EqualTo(expected: KeyboardButtonColor.Primary));
}
[Test]
public void KeyboardButtonActionTypeTest()
{
// get test
Assert.That(actual: KeyboardButtonActionType.Text.ToString(), expression: Is.EqualTo(expected: "text"));
// parse test
Assert.That(actual: KeyboardButtonActionType.FromJsonString(response: "text"), expression: Is.EqualTo(expected: KeyboardButtonActionType.Text));
}
[Test]
public void StoryObjectStateTest()
{
// get test
Assert.That(actual: StoryObjectState.Hidden.ToString(), expression: Is.EqualTo(expected: "hidden"));
Assert.That(actual: StoryObjectState.On.ToString(), expression: Is.EqualTo(expected: "on"));
Assert.That(actual: StoryObjectState.Off.ToString(), expression: Is.EqualTo(expected: "off"));
// parse test
Assert.That(actual: StoryObjectState.FromJsonString(response: "hidden"), expression: Is.EqualTo(expected: StoryObjectState.Hidden));
Assert.That(actual: StoryObjectState.FromJsonString(response: "on"), expression: Is.EqualTo(expected: StoryObjectState.On));
Assert.That(actual: StoryObjectState.FromJsonString(response: "off"), expression: Is.EqualTo(expected: StoryObjectState.Off));
}
[Test]
public void StoryLinkTextTest()
{
// get test
Assert.That(actual: StoryLinkText.Book.ToString(), expression: Is.EqualTo(expected: "book"));
Assert.That(actual: StoryLinkText.Buy.ToString(), expression: Is.EqualTo(expected: "buy"));
Assert.That(actual: StoryLinkText.Contact.ToString(), expression: Is.EqualTo(expected: "contact"));
Assert.That(actual: StoryLinkText.Enroll.ToString(), expression: Is.EqualTo(expected: "enroll"));
Assert.That(actual: StoryLinkText.Fill.ToString(), expression: Is.EqualTo(expected: "fill"));
Assert.That(actual: StoryLinkText.GoTo.ToString(), expression: Is.EqualTo(expected: "go_to"));
Assert.That(actual: StoryLinkText.Install.ToString(), expression: Is.EqualTo(expected: "install"));
Assert.That(actual: StoryLinkText.LearnMore.ToString(), expression: Is.EqualTo(expected: "learn_more"));
Assert.That(actual: StoryLinkText.More.ToString(), expression: Is.EqualTo(expected: "more"));
Assert.That(actual: StoryLinkText.Open.ToString(), expression: Is.EqualTo(expected: "open"));
Assert.That(actual: StoryLinkText.Order.ToString(), expression: Is.EqualTo(expected: "order"));
Assert.That(actual: StoryLinkText.Play.ToString(), expression: Is.EqualTo(expected: "play"));
Assert.That(actual: StoryLinkText.Read.ToString(), expression: Is.EqualTo(expected: "read"));
Assert.That(actual: StoryLinkText.Signup.ToString(), expression: Is.EqualTo(expected: "signup"));
Assert.That(actual: StoryLinkText.View.ToString(), expression: Is.EqualTo(expected: "view"));
Assert.That(actual: StoryLinkText.Vote.ToString(), expression: Is.EqualTo(expected: "vote"));
Assert.That(actual: StoryLinkText.Watch.ToString(), expression: Is.EqualTo(expected: "watch"));
Assert.That(actual: StoryLinkText.Write.ToString(), expression: Is.EqualTo(expected: "write"));
// parse test
Assert.That(actual: StoryLinkText.FromJsonString(response: "book"), expression: Is.EqualTo(expected: StoryLinkText.Book));
Assert.That(actual: StoryLinkText.FromJsonString(response: "buy"), expression: Is.EqualTo(expected: StoryLinkText.Buy));
Assert.That(actual: StoryLinkText.FromJsonString(response: "contact"), expression: Is.EqualTo(expected: StoryLinkText.Contact));
Assert.That(actual: StoryLinkText.FromJsonString(response: "enroll"), expression: Is.EqualTo(expected: StoryLinkText.Enroll));
Assert.That(actual: StoryLinkText.FromJsonString(response: "fill"), expression: Is.EqualTo(expected: StoryLinkText.Fill));
Assert.That(actual: StoryLinkText.FromJsonString(response: "go_to"), expression: Is.EqualTo(expected: StoryLinkText.GoTo));
Assert.That(actual: StoryLinkText.FromJsonString(response: "install"), expression: Is.EqualTo(expected: StoryLinkText.Install));
Assert.That(actual: StoryLinkText.FromJsonString(response: "learn_more"), expression: Is.EqualTo(expected: StoryLinkText.LearnMore));
Assert.That(actual: StoryLinkText.FromJsonString(response: "more"), expression: Is.EqualTo(expected: StoryLinkText.More));
Assert.That(actual: StoryLinkText.FromJsonString(response: "open"), expression: Is.EqualTo(expected: StoryLinkText.Open));
Assert.That(actual: StoryLinkText.FromJsonString(response: "order"), expression: Is.EqualTo(expected: StoryLinkText.Order));
Assert.That(actual: StoryLinkText.FromJsonString(response: "play"), expression: Is.EqualTo(expected: StoryLinkText.Play));
Assert.That(actual: StoryLinkText.FromJsonString(response: "read"), expression: Is.EqualTo(expected: StoryLinkText.Read));
Assert.That(actual: StoryLinkText.FromJsonString(response: "signup"), expression: Is.EqualTo(expected: StoryLinkText.Signup));
Assert.That(actual: StoryLinkText.FromJsonString(response: "view"), expression: Is.EqualTo(expected: StoryLinkText.View));
Assert.That(actual: StoryLinkText.FromJsonString(response: "vote"), expression: Is.EqualTo(expected: StoryLinkText.Vote));
Assert.That(actual: StoryLinkText.FromJsonString(response: "watch"), expression: Is.EqualTo(expected: StoryLinkText.Watch));
Assert.That(actual: StoryLinkText.FromJsonString(response: "write"), expression: Is.EqualTo(expected: StoryLinkText.Write));
}
}
}
| |
using System;
using System.Linq;
using System.Net;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using OrchardCore.DisplayManagement.Layout;
using OrchardCore.Environment.Shell;
namespace OrchardCore.DisplayManagement.Notify
{
public class NotifyFilter : IActionFilter, IAsyncResultFilter, IPageFilter
{
public const string CookiePrefix = "orch_notify";
private readonly INotifier _notifier;
private readonly IShapeFactory _shapeFactory;
private readonly ILayoutAccessor _layoutAccessor;
private readonly IDataProtectionProvider _dataProtectionProvider;
private NotifyEntry[] _existingEntries = Array.Empty<NotifyEntry>();
private bool _shouldDeleteCookie;
private string _tenantPath;
private readonly HtmlEncoder _htmlEncoder;
private readonly ILogger _logger;
public NotifyFilter(
INotifier notifier,
ILayoutAccessor layoutAccessor,
IShapeFactory shapeFactory,
ShellSettings shellSettings,
IDataProtectionProvider dataProtectionProvider,
HtmlEncoder htmlEncoder,
ILogger<NotifyFilter> logger)
{
_htmlEncoder = htmlEncoder;
_logger = logger;
_dataProtectionProvider = dataProtectionProvider;
_layoutAccessor = layoutAccessor;
_notifier = notifier;
_shapeFactory = shapeFactory;
_tenantPath = "/" + shellSettings.RequestUrlPrefix;
}
private void OnHandlerExecuting(FilterContext filterContext)
{
var messages = Convert.ToString(filterContext.HttpContext.Request.Cookies[CookiePrefix]);
if (String.IsNullOrEmpty(messages))
{
return;
}
DeserializeNotifyEntries(messages, out var messageEntries);
if (messageEntries == null)
{
// An error occurred during deserialization
_shouldDeleteCookie = true;
return;
}
if (messageEntries.Length == 0)
{
return;
}
// Make the notifications available for the rest of the current request.
_existingEntries = messageEntries;
}
private void OnHandlerExecuted(FilterContext filterContext)
{
var messageEntries = _notifier.List().ToArray();
// Don't touch temp data if there's no work to perform.
if (messageEntries.Length == 0 && _existingEntries.Length == 0)
{
return;
}
// Assign values to the Items collection instead of TempData and
// combine any existing entries added by the previous request with new ones.
_existingEntries = messageEntries.Concat(_existingEntries).Distinct(new NotifyEntryComparer(_htmlEncoder)).ToArray();
object result = filterContext is ActionExecutedContext ace ? ace.Result : ((PageHandlerExecutedContext)filterContext).Result;
// Result is not a view, so assume a redirect and assign values to TemData.
// String data type used instead of complex array to be session-friendly.
if (!(result is ViewResult || result is PageResult) && _existingEntries.Length > 0)
{
filterContext.HttpContext.Response.Cookies.Append(CookiePrefix, SerializeNotifyEntry(_existingEntries), new CookieOptions { HttpOnly = true, Path = _tenantPath });
}
}
#region Interface wrappers
public void OnActionExecuting(ActionExecutingContext filterContext)
{
OnHandlerExecuting(filterContext);
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
OnHandlerExecuted(filterContext);
}
public void OnPageHandlerSelected(PageHandlerSelectedContext context)
{
}
public void OnPageHandlerExecuting(PageHandlerExecutingContext filterContext)
{
OnHandlerExecuting(filterContext);
}
public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
{
OnHandlerExecuted(context);
}
#endregion
public async Task OnResultExecutionAsync(ResultExecutingContext filterContext, ResultExecutionDelegate next)
{
if (_shouldDeleteCookie)
{
DeleteCookies(filterContext);
await next();
return;
}
if (!(filterContext.Result is ViewResult || filterContext.Result is PageResult))
{
await next();
return;
}
if (_existingEntries.Length == 0)
{
await next();
return;
}
var layout = await _layoutAccessor.GetLayoutAsync();
var messagesZone = layout.Zones["Messages"];
if (messagesZone is IShape zone)
{
foreach (var messageEntry in _existingEntries)
{
// Also retrieve the actual zone in case it was only a temporary empty zone created on demand.
zone = await zone.AddAsync(await _shapeFactory.CreateAsync("Message", Arguments.From(messageEntry)));
}
}
DeleteCookies(filterContext);
await next();
}
private void DeleteCookies(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cookies.Delete(CookiePrefix, new CookieOptions { Path = _tenantPath });
}
private string SerializeNotifyEntry(NotifyEntry[] notifyEntries)
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new NotifyEntryConverter(_htmlEncoder));
try
{
var protector = _dataProtectionProvider.CreateProtector(nameof(NotifyFilter));
var signed = protector.Protect(JsonConvert.SerializeObject(notifyEntries, settings));
return WebUtility.UrlEncode(signed);
}
catch
{
return null;
}
}
private void DeserializeNotifyEntries(string value, out NotifyEntry[] messageEntries)
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new NotifyEntryConverter(_htmlEncoder));
try
{
var protector = _dataProtectionProvider.CreateProtector(nameof(NotifyFilter));
var decoded = protector.Unprotect(WebUtility.UrlDecode(value));
messageEntries = JsonConvert.DeserializeObject<NotifyEntry[]>(decoded, settings);
}
catch
{
messageEntries = null;
_logger.LogWarning("The notification entries could not be decrypted");
}
}
}
}
| |
using Content.Shared.ActionBlocker;
using Content.Shared.Acts;
using Content.Shared.Hands.Components;
using Content.Shared.Interaction;
using Content.Shared.Popups;
using Content.Shared.Sound;
using Content.Shared.Verbs;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Player;
using Robust.Shared.Timing;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Content.Shared.Containers.ItemSlots
{
/// <summary>
/// A class that handles interactions related to inserting/ejecting items into/from an item slot.
/// </summary>
public sealed class ItemSlotsSystem : EntitySystem
{
[Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ItemSlotsComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<ItemSlotsComponent, ComponentInit>(Oninitialize);
SubscribeLocalEvent<ItemSlotsComponent, InteractUsingEvent>(OnInteractUsing);
SubscribeLocalEvent<ItemSlotsComponent, InteractHandEvent>(OnInteractHand);
SubscribeLocalEvent<ItemSlotsComponent, UseInHandEvent>(OnUseInHand);
SubscribeLocalEvent<ItemSlotsComponent, GetVerbsEvent<AlternativeVerb>>(AddEjectVerbs);
SubscribeLocalEvent<ItemSlotsComponent, GetVerbsEvent<InteractionVerb>>(AddInteractionVerbsVerbs);
SubscribeLocalEvent<ItemSlotsComponent, BreakageEventArgs>(OnBreak);
SubscribeLocalEvent<ItemSlotsComponent, DestructionEventArgs>(OnBreak);
SubscribeLocalEvent<ItemSlotsComponent, ComponentGetState>(GetItemSlotsState);
SubscribeLocalEvent<ItemSlotsComponent, ComponentHandleState>(HandleItemSlotsState);
}
#region ComponentManagement
/// <summary>
/// Spawn in starting items for any item slots that should have one.
/// </summary>
private void OnMapInit(EntityUid uid, ItemSlotsComponent itemSlots, MapInitEvent args)
{
foreach (var slot in itemSlots.Slots.Values)
{
if (slot.HasItem || string.IsNullOrEmpty(slot.StartingItem))
continue;
var item = EntityManager.SpawnEntity(slot.StartingItem, EntityManager.GetComponent<TransformComponent>(itemSlots.Owner).Coordinates);
slot.ContainerSlot?.Insert(item);
}
}
/// <summary>
/// Ensure item slots have containers.
/// </summary>
private void Oninitialize(EntityUid uid, ItemSlotsComponent itemSlots, ComponentInit args)
{
foreach (var (id, slot) in itemSlots.Slots)
{
slot.ContainerSlot = ContainerHelpers.EnsureContainer<ContainerSlot>(itemSlots.Owner, id);
}
}
/// <summary>
/// Given a new item slot, store it in the <see cref="ItemSlotsComponent"/> and ensure the slot has an item
/// container.
/// </summary>
public void AddItemSlot(EntityUid uid, string id, ItemSlot slot)
{
var itemSlots = EntityManager.EnsureComponent<ItemSlotsComponent>(uid);
slot.ContainerSlot = ContainerHelpers.EnsureContainer<ContainerSlot>(itemSlots.Owner, id);
if (itemSlots.Slots.ContainsKey(id))
Logger.Error($"Duplicate item slot key. Entity: {EntityManager.GetComponent<MetaDataComponent>(itemSlots.Owner).EntityName} ({uid}), key: {id}");
itemSlots.Slots[id] = slot;
}
/// <summary>
/// Remove an item slot. This should generally be called whenever a component that added a slot is being
/// removed.
/// </summary>
public void RemoveItemSlot(EntityUid uid, ItemSlot slot, ItemSlotsComponent? itemSlots = null)
{
if (slot.ContainerSlot == null)
return;
slot.ContainerSlot.Shutdown();
// Don't log missing resolves. when an entity has all of its components removed, the ItemSlotsComponent may
// have been removed before some other component that added an item slot (and is now trying to remove it).
if (!Resolve(uid, ref itemSlots, logMissing: false))
return;
itemSlots.Slots.Remove(slot.ContainerSlot.ID);
if (itemSlots.Slots.Count == 0)
EntityManager.RemoveComponent(uid, itemSlots);
}
#endregion
#region Interactions
/// <summary>
/// Attempt to take an item from a slot, if any are set to EjectOnInteract.
/// </summary>
private void OnInteractHand(EntityUid uid, ItemSlotsComponent itemSlots, InteractHandEvent args)
{
if (args.Handled)
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (slot.Locked || !slot.EjectOnInteract || slot.Item == null)
continue;
args.Handled = true;
TryEjectToHands(uid, slot, args.User);
break;
}
}
/// <summary>
/// Attempt to eject an item from the first valid item slot.
/// </summary>
private void OnUseInHand(EntityUid uid, ItemSlotsComponent itemSlots, UseInHandEvent args)
{
if (args.Handled)
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (slot.Locked || !slot.EjectOnUse || slot.Item == null)
continue;
args.Handled = true;
TryEjectToHands(uid, slot, args.User);
break;
}
}
/// <summary>
/// Tries to insert a held item in any fitting item slot. If a valid slot already contains an item, it will
/// swap it out and place the old one in the user's hand.
/// </summary>
/// <remarks>
/// This only handles the event if the user has an applicable entity that can be inserted. This allows for
/// other interactions to still happen (e.g., open UI, or toggle-open), despite the user holding an item.
/// Maybe this is undesirable.
/// </remarks>
private void OnInteractUsing(EntityUid uid, ItemSlotsComponent itemSlots, InteractUsingEvent args)
{
if (args.Handled)
return;
if (!EntityManager.TryGetComponent(args.User, out SharedHandsComponent hands))
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (!CanInsert(uid, args.Used, slot, swap: slot.Swap, popup: args.User))
continue;
// Drop the held item onto the floor. Return if the user cannot drop.
if (!hands.Drop(args.Used))
return;
if (slot.Item != null)
hands.TryPutInAnyHand(slot.Item.Value);
Insert(uid, slot, args.Used, args.User, excludeUserAudio: args.Predicted);
args.Handled = true;
return;
}
}
#endregion
#region Insert
/// <summary>
/// Insert an item into a slot. This does not perform checks, so make sure to also use <see
/// cref="CanInsert"/> or just use <see cref="TryInsert"/> instead.
/// </summary>
/// <param name="excludeUserAudio">If true, will exclude the user when playing sound. Does nothing client-side.
/// Useful for predicted interactions</param>
private void Insert(EntityUid uid, ItemSlot slot, EntityUid item, EntityUid? user, bool excludeUserAudio = false)
{
slot.ContainerSlot?.Insert(item);
// ContainerSlot automatically raises a directed EntInsertedIntoContainerMessage
PlaySound(uid, slot.InsertSound, slot.SoundOptions, excludeUserAudio ? user : null);
}
/// <summary>
/// Plays a sound
/// </summary>
/// <param name="uid">Source of the sound</param>
/// <param name="sound">The sound</param>
/// <param name="excluded">Optional (server-side) argument used to prevent sending the audio to a specific
/// user. When run client-side, exclusion does nothing.</param>
private void PlaySound(EntityUid uid, SoundSpecifier? sound, AudioParams audioParams, EntityUid? excluded)
{
if (sound == null || !_gameTiming.IsFirstTimePredicted)
return;
var filter = Filter.Pvs(uid);
if (excluded != null)
filter = filter.RemoveWhereAttachedEntity(entity => entity == excluded.Value);
SoundSystem.Play(filter, sound.GetSound(), uid, audioParams);
}
/// <summary>
/// Check whether a given item can be inserted into a slot. Unless otherwise specified, this will return
/// false if the slot is already filled.
/// </summary>
/// <remarks>
/// If a popup entity is given, and if the item slot is set to generate a popup message when it fails to
/// pass the whitelist, then this will generate a popup.
/// </remarks>
public bool CanInsert(EntityUid uid, EntityUid usedUid, ItemSlot slot, bool swap = false, EntityUid? popup = null)
{
if (slot.Locked)
return false;
if (!swap && slot.HasItem)
return false;
if (slot.Whitelist != null && !slot.Whitelist.IsValid(usedUid))
{
if (popup.HasValue && !string.IsNullOrWhiteSpace(slot.WhitelistFailPopup))
_popupSystem.PopupEntity(Loc.GetString(slot.WhitelistFailPopup), uid, Filter.Entities(popup.Value));
return false;
}
return slot.ContainerSlot?.CanInsertIfEmpty(usedUid, EntityManager) ?? false;
}
/// <summary>
/// Tries to insert item into a specific slot.
/// </summary>
/// <returns>False if failed to insert item</returns>
public bool TryInsert(EntityUid uid, string id, EntityUid item, EntityUid? user, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return false;
if (!itemSlots.Slots.TryGetValue(id, out var slot))
return false;
return TryInsert(uid, slot, item, user);
}
/// <summary>
/// Tries to insert item into a specific slot.
/// </summary>
/// <returns>False if failed to insert item</returns>
public bool TryInsert(EntityUid uid, ItemSlot slot, EntityUid item, EntityUid? user)
{
if (!CanInsert(uid, item, slot))
return false;
Insert(uid, slot, item, user);
return true;
}
/// <summary>
/// Tries to insert item into a specific slot from an entity's hand.
/// Does not check action blockers.
/// </summary>
/// <returns>False if failed to insert item</returns>
public bool TryInsertFromHand(EntityUid uid, ItemSlot slot, EntityUid user, SharedHandsComponent? hands = null)
{
if (!Resolve(user, ref hands, false))
return false;
if (!hands.TryGetActiveHeldEntity(out var item))
return false;
var heldItem = item.Value;
if (!CanInsert(uid, item.Value, slot))
return false;
// hands.Drop(item) checks CanDrop action blocker
if (hands.Drop(heldItem))
return false;
Insert(uid, slot, heldItem, user);
return true;
}
#endregion
#region Eject
public bool CanEject(ItemSlot slot)
{
if (slot.Locked || slot.Item == null)
return false;
return slot.ContainerSlot?.CanRemove(slot.Item.Value, EntityManager) ?? false;
}
/// <summary>
/// Eject an item into a slot. This does not perform checks (e.g., is the slot locked?), so you should
/// probably just use <see cref="TryEject"/> instead.
/// </summary>
/// <param name="excludeUserAudio">If true, will exclude the user when playing sound. Does nothing client-side.
/// Useful for predicted interactions</param>
private void Eject(EntityUid uid, ItemSlot slot, EntityUid item, EntityUid? user, bool excludeUserAudio = false)
{
slot.ContainerSlot?.Remove(item);
// ContainerSlot automatically raises a directed EntRemovedFromContainerMessage
PlaySound(uid, slot.EjectSound, slot.SoundOptions, excludeUserAudio ? user : null);
}
/// <summary>
/// Try to eject an item from a slot.
/// </summary>
/// <returns>False if item slot is locked or has no item inserted</returns>
public bool TryEject(EntityUid uid, ItemSlot slot, EntityUid? user, [NotNullWhen(true)] out EntityUid? item, bool excludeUserAudio = false)
{
item = null;
if (!CanEject(slot))
return false;
item = slot.Item;
Eject(uid, slot, item!.Value, user, excludeUserAudio);
return true;
}
/// <summary>
/// Try to eject item from a slot.
/// </summary>
/// <returns>False if the id is not valid, the item slot is locked, or it has no item inserted</returns>
public bool TryEject(EntityUid uid, string id, EntityUid user,
[NotNullWhen(true)] out EntityUid? item, ItemSlotsComponent? itemSlots = null, bool excludeUserAudio = false)
{
item = null;
if (!Resolve(uid, ref itemSlots))
return false;
if (!itemSlots.Slots.TryGetValue(id, out var slot))
return false;
return TryEject(uid, slot, user, out item, excludeUserAudio);
}
/// <summary>
/// Try to eject item from a slot directly into a user's hands. If they have no hands, the item will still
/// be ejected onto the floor.
/// </summary>
/// <returns>
/// False if the id is not valid, the item slot is locked, or it has no item inserted. True otherwise, even
/// if the user has no hands.
/// </returns>
public bool TryEjectToHands(EntityUid uid, ItemSlot slot, EntityUid? user, bool excludeUserAudio = false)
{
if (!TryEject(uid, slot, user, out var item, excludeUserAudio))
return false;
if (user != null && EntityManager.TryGetComponent(user.Value, out SharedHandsComponent? hands))
hands.PutInHand(item.Value);
return true;
}
#endregion
#region Verbs
private void AddEjectVerbs(EntityUid uid, ItemSlotsComponent itemSlots, GetVerbsEvent<AlternativeVerb> args)
{
if (args.Hands == null || !args.CanAccess ||!args.CanInteract ||
!_actionBlockerSystem.CanPickup(args.User))
{
return;
}
foreach (var slot in itemSlots.Slots.Values)
{
if (!CanEject(slot))
continue;
if (slot.EjectOnInteract)
// For this item slot, ejecting/inserting is a primary interaction. Instead of an eject category
// alt-click verb, there will be a "Take item" primary interaction verb.
continue;
var verbSubject = slot.Name != string.Empty
? Loc.GetString(slot.Name)
: EntityManager.GetComponent<MetaDataComponent>(slot.Item!.Value).EntityName ?? string.Empty;
AlternativeVerb verb = new();
verb.IconEntity = slot.Item;
verb.Act = () => TryEjectToHands(uid, slot, args.User, excludeUserAudio: true);
if (slot.EjectVerbText == null)
{
verb.Text = verbSubject;
verb.Category = VerbCategory.Eject;
}
else
{
verb.Text = Loc.GetString(slot.EjectVerbText);
}
args.Verbs.Add(verb);
}
}
private void AddInteractionVerbsVerbs(EntityUid uid, ItemSlotsComponent itemSlots, GetVerbsEvent<InteractionVerb> args)
{
if (args.Hands == null || !args.CanAccess || !args.CanInteract)
return;
// If there are any slots that eject on left-click, add a "Take <item>" verb.
if (_actionBlockerSystem.CanPickup(args.User))
{
foreach (var slot in itemSlots.Slots.Values)
{
if (!slot.EjectOnInteract || !CanEject(slot))
continue;
var verbSubject = slot.Name != string.Empty
? Loc.GetString(slot.Name)
: EntityManager.GetComponent<MetaDataComponent>(slot.Item!.Value).EntityName ?? string.Empty;
InteractionVerb takeVerb = new();
takeVerb.IconEntity = slot.Item;
takeVerb.Act = () => TryEjectToHands(uid, slot, args.User, excludeUserAudio: true);
if (slot.EjectVerbText == null)
takeVerb.Text = Loc.GetString("take-item-verb-text", ("subject", verbSubject));
else
takeVerb.Text = Loc.GetString(slot.EjectVerbText);
args.Verbs.Add(takeVerb);
}
}
// Next, add the insert-item verbs
if (args.Using == null || !_actionBlockerSystem.CanDrop(args.User))
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (!CanInsert(uid, args.Using.Value, slot))
continue;
var verbSubject = slot.Name != string.Empty
? Loc.GetString(slot.Name)
: Name(args.Using.Value) ?? string.Empty;
InteractionVerb insertVerb = new();
insertVerb.IconEntity = args.Using;
insertVerb.Act = () => Insert(uid, slot, args.Using.Value, args.User, excludeUserAudio: true);
if (slot.InsertVerbText != null)
{
insertVerb.Text = Loc.GetString(slot.InsertVerbText);
insertVerb.IconTexture = "/Textures/Interface/VerbIcons/insert.svg.192dpi.png";
}
else if(slot.EjectOnInteract)
{
// Inserting/ejecting is a primary interaction for this entity. Instead of using the insert
// category, we will use a single "Place <item>" verb.
insertVerb.Text = Loc.GetString("place-item-verb-text", ("subject", verbSubject));
insertVerb.IconTexture = "/Textures/Interface/VerbIcons/drop.svg.192dpi.png";
}
else
{
insertVerb.Category = VerbCategory.Insert;
insertVerb.Text = verbSubject;
}
args.Verbs.Add(insertVerb);
}
}
#endregion
/// <summary>
/// Eject items from (some) slots when the entity is destroyed.
/// </summary>
private void OnBreak(EntityUid uid, ItemSlotsComponent component, EntityEventArgs args)
{
foreach (var slot in component.Slots.Values)
{
if (slot.EjectOnBreak && slot.HasItem)
TryEject(uid, slot, null, out var _);
}
}
/// <summary>
/// Get the contents of some item slot.
/// </summary>
public EntityUid? GetItem(EntityUid uid, string id, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return null;
return itemSlots.Slots.GetValueOrDefault(id)?.Item;
}
/// <summary>
/// Lock an item slot. This stops items from being inserted into or ejected from this slot.
/// </summary>
public void SetLock(EntityUid uid, string id, bool locked, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return;
if (!itemSlots.Slots.TryGetValue(id, out var slot))
return;
SetLock(uid, slot, locked, itemSlots);
}
/// <summary>
/// Lock an item slot. This stops items from being inserted into or ejected from this slot.
/// </summary>
public void SetLock(EntityUid uid, ItemSlot slot, bool locked, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return;
slot.Locked = locked;
itemSlots.Dirty();
}
/// <summary>
/// Update the locked state of the managed item slots.
/// </summary>
/// <remarks>
/// Note that the slot's ContainerSlot performs its own networking, so we don't need to send information
/// about the contained entity.
/// </remarks>
private void HandleItemSlotsState(EntityUid uid, ItemSlotsComponent component, ref ComponentHandleState args)
{
if (args.Current is not ItemSlotsComponentState state)
return;
foreach (var (id, locked) in state.SlotLocked)
{
component.Slots[id].Locked = locked;
}
}
private void GetItemSlotsState(EntityUid uid, ItemSlotsComponent component, ref ComponentGetState args)
{
args.State = new ItemSlotsComponentState(component.Slots);
}
}
}
| |
using System;
using System.Globalization;
namespace AbbyyLS.Globalization.Bcp47
{
public static partial class LanguageTagExtensions
{
/// <summary>
/// Converts the value to its equivalent string representation.
/// </summary>
public static string ToText(this Script v)
{
switch (v)
{
case Script.Adlm: return "Adlm";
case Script.Afak: return "Afak";
case Script.Aghb: return "Aghb";
case Script.Ahom: return "Ahom";
case Script.Arab: return "Arab";
case Script.Aran: return "Aran";
case Script.Armi: return "Armi";
case Script.Armn: return "Armn";
case Script.Avst: return "Avst";
case Script.Bali: return "Bali";
case Script.Bamu: return "Bamu";
case Script.Bass: return "Bass";
case Script.Batk: return "Batk";
case Script.Beng: return "Beng";
case Script.Bhks: return "Bhks";
case Script.Blis: return "Blis";
case Script.Bopo: return "Bopo";
case Script.Brah: return "Brah";
case Script.Brai: return "Brai";
case Script.Bugi: return "Bugi";
case Script.Buhd: return "Buhd";
case Script.Cakm: return "Cakm";
case Script.Cans: return "Cans";
case Script.Cari: return "Cari";
case Script.Cham: return "Cham";
case Script.Cher: return "Cher";
case Script.Cirt: return "Cirt";
case Script.Copt: return "Copt";
case Script.Cprt: return "Cprt";
case Script.Cyrl: return "Cyrl";
case Script.Cyrs: return "Cyrs";
case Script.Deva: return "Deva";
case Script.Dsrt: return "Dsrt";
case Script.Dupl: return "Dupl";
case Script.Egyd: return "Egyd";
case Script.Egyh: return "Egyh";
case Script.Egyp: return "Egyp";
case Script.Elba: return "Elba";
case Script.Ethi: return "Ethi";
case Script.Geok: return "Geok";
case Script.Geor: return "Geor";
case Script.Glag: return "Glag";
case Script.Goth: return "Goth";
case Script.Gran: return "Gran";
case Script.Grek: return "Grek";
case Script.Gujr: return "Gujr";
case Script.Guru: return "Guru";
case Script.Hanb: return "Hanb";
case Script.Hang: return "Hang";
case Script.Hani: return "Hani";
case Script.Hano: return "Hano";
case Script.Hans: return "Hans";
case Script.Hant: return "Hant";
case Script.Hatr: return "Hatr";
case Script.Hebr: return "Hebr";
case Script.Hira: return "Hira";
case Script.Hluw: return "Hluw";
case Script.Hmng: return "Hmng";
case Script.Hrkt: return "Hrkt";
case Script.Hung: return "Hung";
case Script.Inds: return "Inds";
case Script.Ital: return "Ital";
case Script.Jamo: return "Jamo";
case Script.Java: return "Java";
case Script.Jpan: return "Jpan";
case Script.Jurc: return "Jurc";
case Script.Kali: return "Kali";
case Script.Kana: return "Kana";
case Script.Khar: return "Khar";
case Script.Khmr: return "Khmr";
case Script.Khoj: return "Khoj";
case Script.Kitl: return "Kitl";
case Script.Kits: return "Kits";
case Script.Knda: return "Knda";
case Script.Kore: return "Kore";
case Script.Kpel: return "Kpel";
case Script.Kthi: return "Kthi";
case Script.Lana: return "Lana";
case Script.Laoo: return "Laoo";
case Script.Latf: return "Latf";
case Script.Latg: return "Latg";
case Script.Latn: return "Latn";
case Script.Leke: return "Leke";
case Script.Lepc: return "Lepc";
case Script.Limb: return "Limb";
case Script.Lina: return "Lina";
case Script.Linb: return "Linb";
case Script.Lisu: return "Lisu";
case Script.Loma: return "Loma";
case Script.Lyci: return "Lyci";
case Script.Lydi: return "Lydi";
case Script.Mahj: return "Mahj";
case Script.Mand: return "Mand";
case Script.Mani: return "Mani";
case Script.Marc: return "Marc";
case Script.Maya: return "Maya";
case Script.Mend: return "Mend";
case Script.Merc: return "Merc";
case Script.Mero: return "Mero";
case Script.Mlym: return "Mlym";
case Script.Modi: return "Modi";
case Script.Mong: return "Mong";
case Script.Moon: return "Moon";
case Script.Mroo: return "Mroo";
case Script.Mtei: return "Mtei";
case Script.Mult: return "Mult";
case Script.Mymr: return "Mymr";
case Script.Narb: return "Narb";
case Script.Nbat: return "Nbat";
case Script.Newa: return "Newa";
case Script.Nkgb: return "Nkgb";
case Script.Nkoo: return "Nkoo";
case Script.Nshu: return "Nshu";
case Script.Ogam: return "Ogam";
case Script.Olck: return "Olck";
case Script.Orkh: return "Orkh";
case Script.Orya: return "Orya";
case Script.Osge: return "Osge";
case Script.Osma: return "Osma";
case Script.Palm: return "Palm";
case Script.Pauc: return "Pauc";
case Script.Perm: return "Perm";
case Script.Phag: return "Phag";
case Script.Phli: return "Phli";
case Script.Phlp: return "Phlp";
case Script.Phlv: return "Phlv";
case Script.Phnx: return "Phnx";
case Script.Piqd: return "Piqd";
case Script.Plrd: return "Plrd";
case Script.Prti: return "Prti";
case Script.Rjng: return "Rjng";
case Script.Roro: return "Roro";
case Script.Runr: return "Runr";
case Script.Samr: return "Samr";
case Script.Sara: return "Sara";
case Script.Sarb: return "Sarb";
case Script.Saur: return "Saur";
case Script.Sgnw: return "Sgnw";
case Script.Shaw: return "Shaw";
case Script.Shrd: return "Shrd";
case Script.Sidd: return "Sidd";
case Script.Sind: return "Sind";
case Script.Sinh: return "Sinh";
case Script.Sora: return "Sora";
case Script.Sund: return "Sund";
case Script.Sylo: return "Sylo";
case Script.Syrc: return "Syrc";
case Script.Syre: return "Syre";
case Script.Syrj: return "Syrj";
case Script.Syrn: return "Syrn";
case Script.Tagb: return "Tagb";
case Script.Takr: return "Takr";
case Script.Tale: return "Tale";
case Script.Talu: return "Talu";
case Script.Taml: return "Taml";
case Script.Tang: return "Tang";
case Script.Tavt: return "Tavt";
case Script.Telu: return "Telu";
case Script.Teng: return "Teng";
case Script.Tfng: return "Tfng";
case Script.Tglg: return "Tglg";
case Script.Thaa: return "Thaa";
case Script.Thai: return "Thai";
case Script.Tibt: return "Tibt";
case Script.Tirh: return "Tirh";
case Script.Ugar: return "Ugar";
case Script.Vaii: return "Vaii";
case Script.Visp: return "Visp";
case Script.Wara: return "Wara";
case Script.Wole: return "Wole";
case Script.Xpeo: return "Xpeo";
case Script.Xsux: return "Xsux";
case Script.Yiii: return "Yiii";
case Script.Zinh: return "Zinh";
case Script.Zmth: return "Zmth";
case Script.Zsye: return "Zsye";
case Script.Zsym: return "Zsym";
case Script.Zxxx: return "Zxxx";
case Script.Zyyy: return "Zyyy";
case Script.Zzzz: return "Zzzz";
default:
throw new NotImplementedException("unexpected value: " + v);
}
}
public static Script? TryParseFromScript(this string text)
{
if(text == null)
return null;
switch (text.ToLower(CultureInfo.InvariantCulture))
{
case "adlm": return Script.Adlm;
case "afak": return Script.Afak;
case "aghb": return Script.Aghb;
case "ahom": return Script.Ahom;
case "arab": return Script.Arab;
case "aran": return Script.Aran;
case "armi": return Script.Armi;
case "armn": return Script.Armn;
case "avst": return Script.Avst;
case "bali": return Script.Bali;
case "bamu": return Script.Bamu;
case "bass": return Script.Bass;
case "batk": return Script.Batk;
case "beng": return Script.Beng;
case "bhks": return Script.Bhks;
case "blis": return Script.Blis;
case "bopo": return Script.Bopo;
case "brah": return Script.Brah;
case "brai": return Script.Brai;
case "bugi": return Script.Bugi;
case "buhd": return Script.Buhd;
case "cakm": return Script.Cakm;
case "cans": return Script.Cans;
case "cari": return Script.Cari;
case "cham": return Script.Cham;
case "cher": return Script.Cher;
case "cirt": return Script.Cirt;
case "copt": return Script.Copt;
case "cprt": return Script.Cprt;
case "cyrl": return Script.Cyrl;
case "cyrs": return Script.Cyrs;
case "deva": return Script.Deva;
case "dsrt": return Script.Dsrt;
case "dupl": return Script.Dupl;
case "egyd": return Script.Egyd;
case "egyh": return Script.Egyh;
case "egyp": return Script.Egyp;
case "elba": return Script.Elba;
case "ethi": return Script.Ethi;
case "geok": return Script.Geok;
case "geor": return Script.Geor;
case "glag": return Script.Glag;
case "goth": return Script.Goth;
case "gran": return Script.Gran;
case "grek": return Script.Grek;
case "gujr": return Script.Gujr;
case "guru": return Script.Guru;
case "hanb": return Script.Hanb;
case "hang": return Script.Hang;
case "hani": return Script.Hani;
case "hano": return Script.Hano;
case "hans": return Script.Hans;
case "hant": return Script.Hant;
case "hatr": return Script.Hatr;
case "hebr": return Script.Hebr;
case "hira": return Script.Hira;
case "hluw": return Script.Hluw;
case "hmng": return Script.Hmng;
case "hrkt": return Script.Hrkt;
case "hung": return Script.Hung;
case "inds": return Script.Inds;
case "ital": return Script.Ital;
case "jamo": return Script.Jamo;
case "java": return Script.Java;
case "jpan": return Script.Jpan;
case "jurc": return Script.Jurc;
case "kali": return Script.Kali;
case "kana": return Script.Kana;
case "khar": return Script.Khar;
case "khmr": return Script.Khmr;
case "khoj": return Script.Khoj;
case "kitl": return Script.Kitl;
case "kits": return Script.Kits;
case "knda": return Script.Knda;
case "kore": return Script.Kore;
case "kpel": return Script.Kpel;
case "kthi": return Script.Kthi;
case "lana": return Script.Lana;
case "laoo": return Script.Laoo;
case "latf": return Script.Latf;
case "latg": return Script.Latg;
case "latn": return Script.Latn;
case "leke": return Script.Leke;
case "lepc": return Script.Lepc;
case "limb": return Script.Limb;
case "lina": return Script.Lina;
case "linb": return Script.Linb;
case "lisu": return Script.Lisu;
case "loma": return Script.Loma;
case "lyci": return Script.Lyci;
case "lydi": return Script.Lydi;
case "mahj": return Script.Mahj;
case "mand": return Script.Mand;
case "mani": return Script.Mani;
case "marc": return Script.Marc;
case "maya": return Script.Maya;
case "mend": return Script.Mend;
case "merc": return Script.Merc;
case "mero": return Script.Mero;
case "mlym": return Script.Mlym;
case "modi": return Script.Modi;
case "mong": return Script.Mong;
case "moon": return Script.Moon;
case "mroo": return Script.Mroo;
case "mtei": return Script.Mtei;
case "mult": return Script.Mult;
case "mymr": return Script.Mymr;
case "narb": return Script.Narb;
case "nbat": return Script.Nbat;
case "newa": return Script.Newa;
case "nkgb": return Script.Nkgb;
case "nkoo": return Script.Nkoo;
case "nshu": return Script.Nshu;
case "ogam": return Script.Ogam;
case "olck": return Script.Olck;
case "orkh": return Script.Orkh;
case "orya": return Script.Orya;
case "osge": return Script.Osge;
case "osma": return Script.Osma;
case "palm": return Script.Palm;
case "pauc": return Script.Pauc;
case "perm": return Script.Perm;
case "phag": return Script.Phag;
case "phli": return Script.Phli;
case "phlp": return Script.Phlp;
case "phlv": return Script.Phlv;
case "phnx": return Script.Phnx;
case "piqd": return Script.Piqd;
case "plrd": return Script.Plrd;
case "prti": return Script.Prti;
case "rjng": return Script.Rjng;
case "roro": return Script.Roro;
case "runr": return Script.Runr;
case "samr": return Script.Samr;
case "sara": return Script.Sara;
case "sarb": return Script.Sarb;
case "saur": return Script.Saur;
case "sgnw": return Script.Sgnw;
case "shaw": return Script.Shaw;
case "shrd": return Script.Shrd;
case "sidd": return Script.Sidd;
case "sind": return Script.Sind;
case "sinh": return Script.Sinh;
case "sora": return Script.Sora;
case "sund": return Script.Sund;
case "sylo": return Script.Sylo;
case "syrc": return Script.Syrc;
case "syre": return Script.Syre;
case "syrj": return Script.Syrj;
case "syrn": return Script.Syrn;
case "tagb": return Script.Tagb;
case "takr": return Script.Takr;
case "tale": return Script.Tale;
case "talu": return Script.Talu;
case "taml": return Script.Taml;
case "tang": return Script.Tang;
case "tavt": return Script.Tavt;
case "telu": return Script.Telu;
case "teng": return Script.Teng;
case "tfng": return Script.Tfng;
case "tglg": return Script.Tglg;
case "thaa": return Script.Thaa;
case "thai": return Script.Thai;
case "tibt": return Script.Tibt;
case "tirh": return Script.Tirh;
case "ugar": return Script.Ugar;
case "vaii": return Script.Vaii;
case "visp": return Script.Visp;
case "wara": return Script.Wara;
case "wole": return Script.Wole;
case "xpeo": return Script.Xpeo;
case "xsux": return Script.Xsux;
case "yiii": return Script.Yiii;
case "zinh": return Script.Zinh;
case "zmth": return Script.Zmth;
case "zsye": return Script.Zsye;
case "zsym": return Script.Zsym;
case "zxxx": return Script.Zxxx;
case "zyyy": return Script.Zyyy;
case "zzzz": return Script.Zzzz;
default: return null;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using Leap;
public class ForceCharacterController : MonoBehaviour {
Controller m_leapController;
float m_lastPushTime = 0.0f;
float m_forcePoints = 0;
bool m_vortexPower = false;
bool m_pullThisFrame = false;
GameObject m_vortexPowerup;
GameObject m_vortexSource = null;
void Start() {
m_leapController = new Controller();
m_vortexPowerup = GameObject.Find("VortexPowerup");
}
public void AddForcePoints(float points) {
m_forcePoints += points;
}
public float GetForcePoints() {
return m_forcePoints;
}
void StageOne(Hand hand) {
if (hand.PalmVelocity.ToUnityScaled().magnitude > 4.0f) return;
Collider [] m_pullObjects = Physics.OverlapSphere(transform.position, 10.0f);
for(int i = 0; i < m_pullObjects.Length; ++i) {
GameObject gObject = m_pullObjects[i].transform.gameObject;
if (gObject.rigidbody == null) continue;
if (gObject.name == "Player") continue;
if (hand.Fingers.Count > 1) continue;
// ignore objects not in the view frustum.
if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(Camera.main), gObject.collider.bounds) == false) continue;
// ignore objects that are occluded from our view.
RaycastHit hit;
if(Physics.Linecast(transform.position, gObject.transform.position, out hit)) {
if (hit.transform != gObject.transform) continue;
}
if (gObject.rigidbody.mass < 1.0f) {
gObject.rigidbody.velocity = Vector3.up * Random.Range(0.5f, 0.8f) * (1.0f + (m_forcePoints / 500.0f));
gObject.rigidbody.AddTorque(new Vector3(Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f)));
}
else if (gObject.rigidbody.mass < 5.0f) {
gObject.rigidbody.velocity = Vector3.up * Random.Range(0.1f, 0.2f) * (1.0f + (m_forcePoints / 500.0f));
}
}
if (m_pullThisFrame == false) {
m_vortexSource = Instantiate(Resources.Load("VortexObject")) as GameObject;
m_vortexSource.transform.position = transform.position + transform.forward * 2.0f;
m_vortexSource.GetComponent<VortexFade>().SetTargetIntensity(1.0f);
m_vortexSource.GetComponent<VortexFade>().SetTargetRadius(1.5f);
}
if (hand.Fingers.Count < 2) {
m_pullThisFrame = true;
} else {
m_pullThisFrame = false;
}
}
void StageTwo(Hand hand) {
if (Time.time - m_lastPushTime < 1.0f) return;
Collider [] m_pullObjects = Physics.OverlapSphere(transform.position, 10.0f);
for(int i = 0; i < m_pullObjects.Length; ++i) {
GameObject gObject = m_pullObjects[i].transform.gameObject;
if (gObject.rigidbody == null) continue;
if (gObject.name == "Player") continue;
// ignore objects not in the view frustum.
if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(Camera.main), gObject.collider.bounds) == false) continue;
// ignore objects that are occluded from our view.
RaycastHit hit;
if(Physics.Linecast(transform.position, gObject.transform.position, out hit)) {
if (hit.transform != gObject.transform) continue;
}
if (hand.Fingers.Count < 2) {
gObject.rigidbody.velocity = Vector3.up * Random.Range(0.5f, 0.8f);
gObject.rigidbody.AddTorque(new Vector3(Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f)));
}
float z = hand.PalmVelocity.ToUnityScaled().z * 0.5f;
float x = hand.PalmVelocity.ToUnityScaled().x * 0.5f;
if (z > 10.0f && hand.PalmPosition.ToUnity().z > -2.0f) {
gObject.rigidbody.velocity += transform.rotation * Vector3.forward * Mathf.Clamp(z, -15.0f, 20.0f);
m_lastPushTime = Time.time;
} else if (Mathf.Abs(x) > 15.0f && hand.Fingers.Count < 2) {
// only allow horizontal throw when fist is closed.
gObject.rigidbody.velocity += transform.rotation * Vector3.right * Mathf.Clamp(x, -10.0f, 10.0f);
m_lastPushTime = Time.time;
}
}
if (m_pullThisFrame == false) {
m_vortexSource = Instantiate(Resources.Load("VortexObject")) as GameObject;
m_vortexSource.transform.position = transform.position + transform.forward * 2.0f;
m_vortexSource.GetComponent<VortexFade>().SetTargetIntensity(1.5f);
m_vortexSource.GetComponent<VortexFade>().SetTargetRadius(3.0f);
}
if (hand.Fingers.Count < 2) {
m_pullThisFrame = true;
} else {
m_pullThisFrame = false;
}
}
void StageThree(Hand hand) {
if (Time.time - m_lastPushTime < 1.0f) return;
Collider [] m_pullObjects = Physics.OverlapSphere(transform.position, 15.0f);
for(int i = 0; i < m_pullObjects.Length; ++i) {
GameObject gObject = m_pullObjects[i].transform.gameObject;
if (gObject.rigidbody == null) continue;
if (gObject.name == "Player") continue;
// ignore objects not in the view frustum.
if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(Camera.main), gObject.collider.bounds) == false) continue;
// ignore objects that are occluded from our view.
RaycastHit hit;
if(Physics.Linecast(transform.position, gObject.transform.position, out hit)) {
if (hit.transform != gObject.transform) continue;
}
if (hand.Fingers.Count < 2) {
gObject.rigidbody.velocity = Vector3.up * Random.Range(0.9f, 1.8f);
gObject.rigidbody.AddTorque(new Vector3(Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f), Random.Range(-0.02f, 0.02f)));
if (m_vortexSource != null) {
Vector3 toVortex = (m_vortexSource.transform.position - gObject.transform.position).normalized * 3.5f;
toVortex.y = 0;
gObject.rigidbody.velocity += toVortex;
float temp = -toVortex.x;
toVortex.x = toVortex.z;
toVortex.z = temp;
gObject.rigidbody.velocity += toVortex;
}
} else if (m_vortexSource) {
// just went from grabbing to not grabbing. "let go" gesture
m_lastPushTime = Time.time;
gObject.rigidbody.velocity = transform.rotation * hand.PalmVelocity.ToUnityScaled() * 0.7f;
}
}
if (m_pullThisFrame == false) {
m_vortexSource = Instantiate(Resources.Load("VortexObject")) as GameObject;
m_vortexSource.light.color = new Color(1, 0, 0, 1);
m_vortexSource.GetComponent<VortexFade>().SetTargetIntensity(2.5f);
m_vortexSource.GetComponent<VortexFade>().SetTargetRadius(15.0f);
}
if (m_vortexSource != null) {
Vector3 handPosBias = transform.rotation * hand.PalmPosition.ToUnityScaled();
handPosBias.y = 0;
Vector3 forwardBias = transform.forward * 5.0f;
forwardBias.y = 0;
m_vortexSource.transform.position = transform.position + forwardBias + handPosBias * 0.8f;
}
if (hand.Fingers.Count < 2) {
m_pullThisFrame = true;
} else {
m_pullThisFrame = false;
}
}
void ControllerUpdate() {
transform.RotateAround(Vector3.up, Input.GetAxis("RightHorizontal") * 0.1f);
transform.RotateAround(transform.right, Input.GetAxis("RightVertical") * 0.1f);
Vector3 view = transform.forward;
view.y = 0;
rigidbody.AddForce(view.normalized * Input.GetAxis("Vertical") * 25.0f);
rigidbody.AddForce(transform.right * Input.GetAxis("Horizontal") * 25.0f);
}
void FixedUpdate () {
ControllerUpdate();
Frame frame = m_leapController.Frame();
for (int i = 0; i < frame.Hands.Count; ++i) {
if (m_vortexPower) StageThree(frame.Hands[i]);
else if (m_forcePoints < 200.0f) StageOne(frame.Hands[i]);
else StageTwo(frame.Hands[i]);
}
// code dealing with the vortex powerup item
if (!m_vortexPower) {
if ((transform.position - m_vortexPowerup.transform.position).magnitude < 5.0f) {
m_vortexPowerup.transform.position = Vector3.Lerp(m_vortexPowerup.transform.position, transform.position, 0.1f);
}
if ((transform.position - m_vortexPowerup.transform.position).magnitude < 0.1f) {
m_vortexPower = true;
GameObject.Destroy(m_vortexPowerup);
m_vortexPowerup = null;
}
}
if (frame.Hands.Count == 0) m_pullThisFrame = false;
if (m_pullThisFrame == false) {
if (m_vortexSource != null) {
// call fade out on m_vortexSource
m_vortexSource.GetComponent<VortexFade>().FadeDestroy();
m_vortexSource = null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Security;
namespace System.Net
{
public sealed unsafe partial class HttpListener
{
public static bool IsSupported => true;
private Dictionary<HttpListenerContext, HttpListenerContext> _listenerContexts = new Dictionary<HttpListenerContext, HttpListenerContext>();
private List<HttpListenerContext> _contextQueue = new List<HttpListenerContext>();
private List<ListenerAsyncResult> _asyncWaitQueue = new List<ListenerAsyncResult>();
private Dictionary<HttpConnection, HttpConnection> _connections = new Dictionary<HttpConnection, HttpConnection>();
public HttpListenerTimeoutManager TimeoutManager
{
get
{
CheckDisposed();
return _timeoutManager;
}
}
private void AddPrefixCore(string uriPrefix) => HttpEndPointManager.AddPrefix(uriPrefix, this);
private void RemovePrefixCore(string uriPrefix) => HttpEndPointManager.RemovePrefix(uriPrefix, this);
public void Start()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
lock (_internalLock)
{
try
{
CheckDisposed();
if (_state == State.Started)
return;
HttpEndPointManager.AddListener(this);
_state = State.Started;
}
catch (Exception exception)
{
_state = State.Closed;
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Start {exception}");
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
}
public bool UnsafeConnectionNtlmAuthentication
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public void Stop()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
lock (_internalLock)
{
CheckDisposed();
if (_state == State.Stopped)
{
return;
}
Close(false);
_state = State.Stopped;
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Stop {exception}");
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public void Abort()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
lock (_internalLock)
{
try
{
if (_state == State.Closed)
{
return;
}
// Just detach and free resources. Don't call Stop (which may throw).
if (_state == State.Started)
{
Close(true);
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Abort {exception}");
throw;
}
finally
{
_state = State.Closed;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
}
private void Dispose()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
lock (_internalLock)
{
try
{
if (_state == State.Closed)
{
return;
}
Close(true);
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Dispose {exception}");
throw;
}
finally
{
_state = State.Closed;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
}
private void Close(bool force)
{
CheckDisposed();
HttpEndPointManager.RemoveListener(this);
Cleanup(force);
}
internal void UnregisterContext(HttpListenerContext context)
{
lock ((_listenerContexts as ICollection).SyncRoot)
{
_listenerContexts.Remove(context);
}
lock ((_contextQueue as ICollection).SyncRoot)
{
int idx = _contextQueue.IndexOf(context);
if (idx >= 0)
_contextQueue.RemoveAt(idx);
}
}
internal void AddConnection(HttpConnection cnc)
{
lock ((_connections as ICollection).SyncRoot)
{
_connections[cnc] = cnc;
}
}
internal void RemoveConnection(HttpConnection cnc)
{
lock ((_connections as ICollection).SyncRoot)
{
_connections.Remove(cnc);
}
}
internal void RegisterContext(HttpListenerContext context)
{
lock ((_listenerContexts as ICollection).SyncRoot)
{
_listenerContexts[context] = context;
}
ListenerAsyncResult ares = null;
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
if (_asyncWaitQueue.Count == 0)
{
lock ((_contextQueue as ICollection).SyncRoot)
_contextQueue.Add(context);
}
else
{
ares = _asyncWaitQueue[0];
_asyncWaitQueue.RemoveAt(0);
}
}
if (ares != null)
{
ares.Complete(context);
}
}
private void Cleanup(bool close_existing)
{
lock ((_listenerContexts as ICollection).SyncRoot)
{
if (close_existing)
{
// Need to copy this since closing will call UnregisterContext
ICollection keys = _listenerContexts.Keys;
var all = new HttpListenerContext[keys.Count];
keys.CopyTo(all, 0);
_listenerContexts.Clear();
for (int i = all.Length - 1; i >= 0; i--)
all[i].Connection.Close(true);
}
lock ((_connections as ICollection).SyncRoot)
{
ICollection keys = _connections.Keys;
var conns = new HttpConnection[keys.Count];
keys.CopyTo(conns, 0);
_connections.Clear();
for (int i = conns.Length - 1; i >= 0; i--)
conns[i].Close(true);
}
lock ((_contextQueue as ICollection).SyncRoot)
{
var ctxs = (HttpListenerContext[])_contextQueue.ToArray();
_contextQueue.Clear();
for (int i = ctxs.Length - 1; i >= 0; i--)
ctxs[i].Connection.Close(true);
}
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
Exception exc = new ObjectDisposedException("listener");
foreach (ListenerAsyncResult ares in _asyncWaitQueue)
{
ares.Complete(exc);
}
_asyncWaitQueue.Clear();
}
}
}
private HttpListenerContext GetContextFromQueue()
{
lock ((_contextQueue as ICollection).SyncRoot)
{
if (_contextQueue.Count == 0)
{
return null;
}
HttpListenerContext context = _contextQueue[0];
_contextQueue.RemoveAt(0);
return context;
}
}
public IAsyncResult BeginGetContext(AsyncCallback callback, Object state)
{
CheckDisposed();
if (_state != State.Started)
{
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "Start()"));
}
ListenerAsyncResult ares = new ListenerAsyncResult(this, callback, state);
// lock wait_queue early to avoid race conditions
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
lock ((_contextQueue as ICollection).SyncRoot)
{
HttpListenerContext ctx = GetContextFromQueue();
if (ctx != null)
{
ares.Complete(ctx, true);
return ares;
}
}
_asyncWaitQueue.Add(ares);
}
return ares;
}
public HttpListenerContext EndGetContext(IAsyncResult asyncResult)
{
CheckDisposed();
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
ListenerAsyncResult ares = asyncResult as ListenerAsyncResult;
if (ares == null || !ReferenceEquals(this, ares._parent))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (ares._endCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetContext)));
}
ares._endCalled = true;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne();
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
int idx = _asyncWaitQueue.IndexOf(ares);
if (idx >= 0)
_asyncWaitQueue.RemoveAt(idx);
}
HttpListenerContext context = ares.GetContext();
context.ParseAuthentication(SelectAuthenticationScheme(context));
return context;
}
internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerContext context)
{
return AuthenticationSchemeSelectorDelegate != null ? AuthenticationSchemeSelectorDelegate(context.Request) : _authenticationScheme;
}
public HttpListenerContext GetContext()
{
CheckDisposed();
if (_state == State.Stopped)
{
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "Start()"));
}
if (_prefixes.Count == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "AddPrefix()"));
}
ListenerAsyncResult ares = (ListenerAsyncResult)BeginGetContext(null, null);
ares._inGet = true;
return EndGetContext(ares);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Tokens
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Selectors;
using System.Xml;
public class SamlAttribute
{
string name;
string nameSpace;
readonly ImmutableCollection<string> attributeValues = new ImmutableCollection<string>();
string originalIssuer;
string attributeValueXsiType = System.Security.Claims.ClaimValueTypes.String;
List<Claim> claims;
string claimType;
bool isReadOnly = false;
public SamlAttribute()
{
}
public SamlAttribute(string attributeNamespace, string attributeName, IEnumerable<string> attributeValues)
{
if (string.IsNullOrEmpty(attributeName))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeNameAttributeRequired));
if (string.IsNullOrEmpty(attributeNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeNamespaceAttributeRequired));
if (attributeValues == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("attributeValues");
this.name = StringUtil.OptimizeString(attributeName);
this.nameSpace = StringUtil.OptimizeString(attributeNamespace);
this.claimType = string.IsNullOrEmpty(this.nameSpace) ? this.name : this.nameSpace + "/" + this.name;
foreach (string value in attributeValues)
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeValueCannotBeNull));
this.attributeValues.Add(value);
}
if (this.attributeValues.Count == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeShouldHaveOneValue));
}
public SamlAttribute(Claim claim)
{
if (claim == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claim");
if (!(claim.Resource is String))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SamlAttributeClaimResourceShouldBeAString));
if (claim.Right != Rights.PossessProperty)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SamlAttributeClaimRightShouldBePossessProperty));
#pragma warning suppress 56506 // claim.CalimType can never be null.
int lastSlashIndex = claim.ClaimType.LastIndexOf('/');
if ((lastSlashIndex == -1) || (lastSlashIndex == 0) || (lastSlashIndex == claim.ClaimType.Length - 1))
{
this.nameSpace = String.Empty;
this.name = claim.ClaimType;
}
else
{
this.nameSpace = StringUtil.OptimizeString(claim.ClaimType.Substring(0, lastSlashIndex));
this.name = StringUtil.OptimizeString(claim.ClaimType.Substring(lastSlashIndex + 1, claim.ClaimType.Length - (lastSlashIndex + 1)));
}
this.claimType = claim.ClaimType;
this.attributeValues.Add(claim.Resource as string);
}
public string Name
{
get { return this.name; }
set
{
if (isReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly)));
if (string.IsNullOrEmpty(value))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeNameAttributeRequired));
this.name = StringUtil.OptimizeString(value);
}
}
public string Namespace
{
get { return this.nameSpace; }
set
{
if (isReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ObjectIsReadOnly)));
if (string.IsNullOrEmpty(value))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeNamespaceAttributeRequired));
this.nameSpace = StringUtil.OptimizeString(value);
}
}
public IList<string> AttributeValues
{
get { return this.attributeValues; }
}
/// <summary>
/// Gets or Sets the string that represents the OriginalIssuer of the SAML Attribute.
/// </summary>
public string OriginalIssuer
{
get { return this.originalIssuer; }
set
{
if (value == String.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID4251));
}
this.originalIssuer = StringUtil.OptimizeString(value);
}
}
/// <summary>
/// Gets or sets the xsi:type of the values contained in the SAML Attribute.
/// </summary>
public string AttributeValueXsiType
{
get { return attributeValueXsiType; }
set
{
if (string.IsNullOrEmpty(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID4254));
}
int indexOfHash = value.IndexOf('#');
if (indexOfHash == -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID4254));
}
string prefix = value.Substring(0, indexOfHash);
if (prefix.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID4254));
}
string suffix = value.Substring(indexOfHash + 1);
if (suffix.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ID4254));
}
attributeValueXsiType = value;
}
}
public bool IsReadOnly
{
get { return this.isReadOnly; }
}
public void MakeReadOnly()
{
if (!this.isReadOnly)
{
this.attributeValues.MakeReadOnly();
this.isReadOnly = true;
}
}
public virtual ReadOnlyCollection<Claim> ExtractClaims()
{
if (this.claims == null)
{
List<Claim> tempClaims = new List<Claim>(this.attributeValues.Count);
for (int i = 0; i < this.attributeValues.Count; i++)
{
if (this.attributeValues[i] == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeValueCannotBeNull));
tempClaims.Add(new Claim(this.claimType, this.attributeValues[i], Rights.PossessProperty));
}
this.claims = tempClaims;
}
return this.claims.AsReadOnly();
}
void CheckObjectValidity()
{
if (string.IsNullOrEmpty(this.name))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeNameAttributeRequired)));
if (string.IsNullOrEmpty(this.nameSpace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeNamespaceAttributeRequired)));
if (this.attributeValues.Count == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeShouldHaveOneValue)));
}
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
if (samlSerializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;
this.name = reader.GetAttribute(dictionary.AttributeName, null);
if (string.IsNullOrEmpty(this.name))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeMissingNameAttributeOnRead)));
this.nameSpace = reader.GetAttribute(dictionary.AttributeNamespace, null);
if (string.IsNullOrEmpty(this.nameSpace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeMissingNamespaceAttributeOnRead)));
this.claimType = string.IsNullOrEmpty(this.nameSpace) ? this.name : this.nameSpace + "/" + this.name;
reader.MoveToContent();
reader.Read();
while (reader.IsStartElement(dictionary.AttributeValue, dictionary.Namespace))
{
// We will load all Attributes as a string value by default.
string attrValue = reader.ReadString();
this.attributeValues.Add(attrValue);
reader.MoveToContent();
reader.ReadEndElement();
}
if (this.attributeValues.Count == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeShouldHaveOneValue)));
reader.MoveToContent();
reader.ReadEndElement();
}
public virtual void WriteXml(XmlDictionaryWriter writer, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer)
{
CheckObjectValidity();
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
if (samlSerializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;
writer.WriteStartElement(dictionary.PreferredPrefix.Value, dictionary.Attribute, dictionary.Namespace);
writer.WriteStartAttribute(dictionary.AttributeName, null);
writer.WriteString(this.name);
writer.WriteEndAttribute();
writer.WriteStartAttribute(dictionary.AttributeNamespace, null);
writer.WriteString(this.nameSpace);
writer.WriteEndAttribute();
for (int i = 0; i < this.attributeValues.Count; i++)
{
if (this.attributeValues[i] == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAttributeValueCannotBeNull));
writer.WriteElementString(dictionary.PreferredPrefix.Value, dictionary.AttributeValue, dictionary.Namespace, this.attributeValues[i]);
}
writer.WriteEndElement();
}
}
}
| |
using System;
using System.Threading;
namespace Lucene.Net.Search
{
using Lucene.Net.Support;
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Counter = Lucene.Net.Util.Counter;
/// <summary>
/// The <seealso cref="TimeLimitingCollector"/> is used to timeout search requests that
/// take longer than the maximum allowed search time limit. After this time is
/// exceeded, the search thread is stopped by throwing a
/// <seealso cref="TimeExceededException"/>.
/// </summary>
public class TimeLimitingCollector : Collector
{
/// <summary>
/// Thrown when elapsed search time exceeds allowed search time. </summary>
public class TimeExceededException : Exception
{
internal long timeAllowed;
internal long timeElapsed;
internal int lastDocCollected;
internal TimeExceededException(long timeAllowed, long timeElapsed, int lastDocCollected)
: base("Elapsed time: " + timeElapsed + "Exceeded allowed search time: " + timeAllowed + " ms.")
{
this.timeAllowed = timeAllowed;
this.timeElapsed = timeElapsed;
this.lastDocCollected = lastDocCollected;
}
/// <summary>
/// Returns allowed time (milliseconds). </summary>
public virtual long TimeAllowed
{
get
{
return timeAllowed;
}
}
/// <summary>
/// Returns elapsed time (milliseconds). </summary>
public virtual long TimeElapsed
{
get
{
return timeElapsed;
}
}
/// <summary>
/// Returns last doc (absolute doc id) that was collected when the search time exceeded. </summary>
public virtual int LastDocCollected
{
get
{
return lastDocCollected;
}
}
}
private long T0 = long.MinValue;
private long Timeout = long.MinValue;
private Collector collector;
private readonly Counter Clock;
private readonly long TicksAllowed;
private bool greedy = false;
private int DocBase;
/// <summary>
/// Create a TimeLimitedCollector wrapper over another <seealso cref="Collector"/> with a specified timeout. </summary>
/// <param name="collector"> the wrapped <seealso cref="Collector"/> </param>
/// <param name="clock"> the timer clock </param>
/// <param name="ticksAllowed"> max time allowed for collecting
/// hits after which <seealso cref="TimeExceededException"/> is thrown </param>
public TimeLimitingCollector(Collector collector, Counter clock, long ticksAllowed)
{
this.collector = collector;
this.Clock = clock;
this.TicksAllowed = ticksAllowed;
}
/// <summary>
/// Sets the baseline for this collector. By default the collectors baseline is
/// initialized once the first reader is passed to the collector.
/// To include operations executed in prior to the actual document collection
/// set the baseline through this method in your prelude.
/// <p>
/// Example usage:
/// <pre class="prettyprint">
/// Counter clock = ...;
/// long baseline = clock.get();
/// // ... prepare search
/// TimeLimitingCollector collector = new TimeLimitingCollector(c, clock, numTicks);
/// collector.setBaseline(baseline);
/// indexSearcher.search(query, collector);
/// </pre>
/// </p> </summary>
/// <seealso cref= #setBaseline() </seealso>
public virtual long Baseline
{
set
{
T0 = value;
Timeout = T0 + TicksAllowed;
}
}
/// <summary>
/// Syntactic sugar for <seealso cref="#setBaseline(long)"/> using <seealso cref="Counter#get()"/>
/// on the clock passed to the constructor.
/// </summary>
public virtual void SetBaseline()
{
Baseline = Clock.Get();
}
/// <summary>
/// Checks if this time limited collector is greedy in collecting the last hit.
/// A non greedy collector, upon a timeout, would throw a <seealso cref="TimeExceededException"/>
/// without allowing the wrapped collector to collect current doc. A greedy one would
/// first allow the wrapped hit collector to collect current doc and only then
/// throw a <seealso cref="TimeExceededException"/>. </summary>
/// <seealso cref= #setGreedy(boolean) </seealso>
public virtual bool Greedy
{
get
{
return greedy;
}
set
{
this.greedy = value;
}
}
/// <summary>
/// Calls <seealso cref="Collector#collect(int)"/> on the decorated <seealso cref="Collector"/>
/// unless the allowed time has passed, in which case it throws an exception.
/// </summary>
/// <exception cref="TimeExceededException">
/// if the time allowed has exceeded. </exception>
public override void Collect(int doc)
{
long time = Clock.Get();
if (Timeout < time)
{
if (greedy)
{
//System.out.println(this+" greedy: before failing, collecting doc: "+(docBase + doc)+" "+(time-t0));
collector.Collect(doc);
}
//System.out.println(this+" failing on: "+(docBase + doc)+" "+(time-t0));
throw new TimeExceededException(Timeout - T0, time - T0, DocBase + doc);
}
//System.out.println(this+" collecting: "+(docBase + doc)+" "+(time-t0));
collector.Collect(doc);
}
public override AtomicReaderContext NextReader
{
set
{
collector.NextReader = value;
this.DocBase = value.DocBase;
if (long.MinValue == T0)
{
SetBaseline();
}
}
}
public override Scorer Scorer
{
set
{
collector.Scorer = value;
}
}
public override bool AcceptsDocsOutOfOrder()
{
return collector.AcceptsDocsOutOfOrder();
}
/// <summary>
/// this is so the same timer can be used with a multi-phase search process such as grouping.
/// We don't want to create a new TimeLimitingCollector for each phase because that would
/// reset the timer for each phase. Once time is up subsequent phases need to timeout quickly.
/// </summary>
/// <param name="collector"> The actual collector performing search functionality </param>
public virtual Collector Collector
{
set
{
this.collector = value;
}
}
/// <summary>
/// Returns the global TimerThreads <seealso cref="Counter"/>
/// <p>
/// Invoking this creates may create a new instance of <seealso cref="TimerThread"/> iff
/// the global <seealso cref="TimerThread"/> has never been accessed before. The thread
/// returned from this method is started on creation and will be alive unless
/// you stop the <seealso cref="TimerThread"/> via <seealso cref="TimerThread#stopTimer()"/>.
/// </p> </summary>
/// <returns> the global TimerThreads <seealso cref="Counter"/>
/// @lucene.experimental </returns>
public static Counter GlobalCounter
{
get
{
return TimerThreadHolder.THREAD.Counter;
}
}
/// <summary>
/// Returns the global <seealso cref="TimerThread"/>.
/// <p>
/// Invoking this creates may create a new instance of <seealso cref="TimerThread"/> iff
/// the global <seealso cref="TimerThread"/> has never been accessed before. The thread
/// returned from this method is started on creation and will be alive unless
/// you stop the <seealso cref="TimerThread"/> via <seealso cref="TimerThread#stopTimer()"/>.
/// </p>
/// </summary>
/// <returns> the global <seealso cref="TimerThread"/>
/// @lucene.experimental </returns>
public static TimerThread GlobalTimerThread
{
get
{
return TimerThreadHolder.THREAD;
}
}
private sealed class TimerThreadHolder
{
internal static readonly TimerThread THREAD;
static TimerThreadHolder()
{
THREAD = new TimerThread(Counter.NewCounter(true));
THREAD.Start();
}
}
/// <summary>
/// Thread used to timeout search requests.
/// Can be stopped completely with <seealso cref="TimerThread#stopTimer()"/>
/// @lucene.experimental
/// </summary>
public sealed class TimerThread : ThreadClass
{
public const string THREAD_NAME = "TimeLimitedCollector timer thread";
public const int DEFAULT_RESOLUTION = 20;
// NOTE: we can avoid explicit synchronization here for several reasons:
// * updates to volatile long variables are atomic
// * only single thread modifies this value
// * use of volatile keyword ensures that it does not reside in
// a register, but in main memory (so that changes are visible to
// other threads).
// * visibility of changes does not need to be instantaneous, we can
// afford losing a tick or two.
//
// See section 17 of the Java Language Specification for details.
internal long Time = 0;
internal volatile bool Stop = false;
internal long resolution;
internal readonly Counter Counter;
public TimerThread(long resolution, Counter counter)
: base(THREAD_NAME)
{
this.resolution = resolution;
this.Counter = counter;
this.SetDaemon(true);
}
public TimerThread(Counter counter)
: this(DEFAULT_RESOLUTION, counter)
{
}
public override void Run()
{
while (!Stop)
{
// TODO: Use System.nanoTime() when Lucene moves to Java SE 5.
Counter.AddAndGet(resolution);
try
{
Thread.Sleep(TimeSpan.FromMilliseconds(Interlocked.Read(ref resolution)));
}
catch (ThreadInterruptedException ie)
{
throw new ThreadInterruptedException("Thread Interrupted Exception", ie);
}
}
}
/// <summary>
/// Get the timer value in milliseconds.
/// </summary>
public long Milliseconds
{
get
{
return Time;
}
}
/// <summary>
/// Stops the timer thread
/// </summary>
public void StopTimer()
{
Stop = true;
}
/// <summary>
/// Return the timer resolution. </summary>
/// <seealso cref= #setResolution(long) </seealso>
public long Resolution
{
get
{
return resolution;
}
set
{
this.resolution = Math.Max(value, 5); // 5 milliseconds is about the minimum reasonable time for a Object.wait(long) call.
}
}
}
}
}
| |
// 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.Symbols;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal enum DisplayClassVariableKind
{
Local,
Parameter,
This,
}
/// <summary>
/// A field in a display class that represents a captured
/// variable: either a local, a parameter, or "this".
/// </summary>
internal sealed class DisplayClassVariable
{
internal readonly string Name;
internal readonly DisplayClassVariableKind Kind;
internal readonly DisplayClassInstance DisplayClassInstance;
internal readonly ConsList<FieldSymbol> DisplayClassFields;
internal DisplayClassVariable(string name, DisplayClassVariableKind kind, DisplayClassInstance displayClassInstance, ConsList<FieldSymbol> displayClassFields)
{
Debug.Assert(displayClassFields.Any());
this.Name = name;
this.Kind = kind;
this.DisplayClassInstance = displayClassInstance;
this.DisplayClassFields = displayClassFields;
// Verify all type parameters are substituted.
Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.Type));
}
internal TypeSymbol Type
{
get { return this.DisplayClassFields.Head.Type; }
}
internal Symbol ContainingSymbol
{
get { return this.DisplayClassInstance.ContainingSymbol; }
}
internal DisplayClassVariable ToOtherMethod(MethodSymbol method, TypeMap typeMap)
{
var otherInstance = this.DisplayClassInstance.ToOtherMethod(method, typeMap);
return SubstituteFields(otherInstance, typeMap);
}
internal BoundExpression ToBoundExpression(CSharpSyntaxNode syntax)
{
var expr = this.DisplayClassInstance.ToBoundExpression(syntax);
var fields = ArrayBuilder<FieldSymbol>.GetInstance();
fields.AddRange(this.DisplayClassFields);
fields.ReverseContents();
foreach (var field in fields)
{
expr = new BoundFieldAccess(syntax, expr, field, constantValueOpt: null) { WasCompilerGenerated = true };
}
fields.Free();
return expr;
}
internal DisplayClassVariable SubstituteFields(DisplayClassInstance otherInstance, TypeMap typeMap)
{
var otherFields = SubstituteFields(this.DisplayClassFields, typeMap);
return new DisplayClassVariable(this.Name, this.Kind, otherInstance, otherFields);
}
private static ConsList<FieldSymbol> SubstituteFields(ConsList<FieldSymbol> fields, TypeMap typeMap)
{
if (!fields.Any())
{
return ConsList<FieldSymbol>.Empty;
}
var head = SubstituteField(fields.Head, typeMap);
var tail = SubstituteFields(fields.Tail, typeMap);
return tail.Prepend(head);
}
private static FieldSymbol SubstituteField(FieldSymbol field, TypeMap typeMap)
{
Debug.Assert(!field.IsStatic);
Debug.Assert(!field.IsReadOnly);
Debug.Assert(field.CustomModifiers.Length == 0);
// CONSIDER: Instead of digging fields out of the unsubstituted type and then performing substitution
// on each one individually, we could dig fields out of the substituted type.
return new EEDisplayClassFieldSymbol(typeMap.SubstituteNamedType(field.ContainingType), field.Name, typeMap.SubstituteType(field.Type));
}
private sealed class EEDisplayClassFieldSymbol : FieldSymbol
{
private readonly NamedTypeSymbol _container;
private readonly string _name;
private readonly TypeSymbol _type;
internal EEDisplayClassFieldSymbol(NamedTypeSymbol container, string name, TypeSymbol type)
{
_container = container;
_name = name;
_type = type;
}
public override Symbol AssociatedSymbol
{
get { throw ExceptionUtilities.Unreachable; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override ImmutableArray<CustomModifier> CustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override Accessibility DeclaredAccessibility
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override bool IsConst
{
get { return false; }
}
public override bool IsReadOnly
{
get { return false; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsVolatile
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override string Name
{
get { return _name; }
}
internal override bool HasRuntimeSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool IsNotSerialized
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override int? TypeLayoutOffset
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes)
{
throw ExceptionUtilities.Unreachable;
}
internal override TypeSymbol GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return _type;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static partial class ParallelQueryCombinationTests
{
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Cast_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int? i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Cast<int?>())
{
Assert.True(i.HasValue);
seen.Add(i.Value);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Cast_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Cast<int?>().ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Concat_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize / 2, DefaultSource)
.Concat(operation.Item(DefaultStart + DefaultSize / 2, DefaultSize / 2, DefaultSource)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Concat_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(
operation.Item(DefaultStart, DefaultSize / 2, DefaultSource)
.Concat(operation.Item(DefaultStart + DefaultSize / 2, DefaultSize / 2, DefaultSource)).ToList(),
x => seen.Add(x)
);
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void DefaultIfEmpty_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).DefaultIfEmpty())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void DefaultIfEmpty_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).DefaultIfEmpty().ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Distinct_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, DefaultSource).Select(x => x / 2).Distinct();
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Distinct_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, DefaultSource).Select(x => x / 2).Distinct();
Assert.All(query.ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Except_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource)
.Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, DefaultSource));
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Except_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource)
.Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, DefaultSource));
Assert.All(query.ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GetEnumerator_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, DefaultSource).GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
seen.Add(current);
Assert.Equal(current, enumerator.Current);
}
seen.AssertComplete();
Assert.Throws<NotSupportedException>(() => enumerator.Reset());
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor))
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor).ToList())
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_ElementSelector_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor, y => -y))
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_ElementSelector_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor, y => -y).ToList())
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupJoin_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, DefaultSize / GroupFactor);
foreach (KeyValuePair<int, IEnumerable<int>> group in operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, DefaultSource)
.GroupJoin(operation.Item(DefaultStart, DefaultSize, DefaultSource), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g)))
{
Assert.True(seenKey.Add(group.Key));
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, GroupFactor);
Assert.All(group.Value, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupJoin_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, DefaultSize / GroupFactor);
foreach (KeyValuePair<int, IEnumerable<int>> group in operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, DefaultSource)
.GroupJoin(operation.Item(DefaultStart, DefaultSize, DefaultSource), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g)).ToList())
{
Assert.True(seenKey.Add(group.Key));
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, GroupFactor);
Assert.All(group.Value, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Intersect_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, DefaultSource)
.Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource));
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Intersect_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, DefaultSource)
.Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource));
Assert.All(query.ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Join_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<KeyValuePair<int, int>> query = operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, DefaultSource)
.Join(operation.Item(DefaultStart, DefaultSize, DefaultSource), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y));
foreach (KeyValuePair<int, int> p in query)
{
Assert.Equal(p.Key, p.Value / GroupFactor);
seen.Add(p.Value);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void Join_Unordered_NotPipelined(Labeled<Operation> source, Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<KeyValuePair<int, int>> query = operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item)
.Join(operation.Item(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y));
foreach (KeyValuePair<int, int> p in query.ToList())
{
Assert.Equal(p.Key, p.Value / GroupFactor);
seen.Add(p.Value);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void OfType_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void OfType_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Select(x => -x))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Select(x => -x).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Index_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Select((x, index) => { indices.Add(index); return -x; }))
{
seen.Add(i);
}
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Index_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Select((x, index) => { indices.Add(index); return -x; }).ToList(), x => seen.Add(x));
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }))
{
seen.Add(i);
}
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => seen.Add(x));
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_ResultSelector_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_ResultSelector_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_ResultSelector_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x))
{
seen.Add(i);
}
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_ResultSelector_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x));
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Skip_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Skip(DefaultSize / 2))
{
seen.Add(i);
count++;
}
Assert.Equal((DefaultSize - 1) / 2 + 1, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Skip_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Skip(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; });
Assert.Equal((DefaultSize - 1) / 2 + 1, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Take_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Take(DefaultSize / 2))
{
seen.Add(i);
count++;
}
Assert.Equal(DefaultSize / 2, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Take_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Take(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; });
Assert.Equal(DefaultSize / 2, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void ToArray_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).ToArray(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Where(x => x < DefaultStart + DefaultSize / 2))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Indexed_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Where((x, index) => x < DefaultStart + DefaultSize / 2))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Indexed_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Where((x, index) => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Zip_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, DefaultSource)
.Zip(operation.Item(0, DefaultSize, DefaultSource), (x, y) => x);
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Zip_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(0, DefaultSize, DefaultSource)
.Zip(operation.Item(DefaultStart, DefaultSize, DefaultSource), (x, y) => y);
Assert.All(query.ToList(), x => seen.Add(x));
seen.AssertComplete();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.ProviderBase
{
internal abstract class DbConnectionInternal
{
internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed);
internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
private readonly bool _allowSetConnectionString;
private readonly bool _hidePassword;
private readonly ConnectionState _state;
private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only)
private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated
private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool)
private bool _connectionIsDoomed; // true when the connection should no longer be used.
private bool _cannotBePooled; // true when the connection should no longer be pooled.
private DateTime _createTime; // when the connection was created.
#if DEBUG
private int _activateCount; // debug only counter to verify activate/deactivates are in sync.
#endif //DEBUG
protected DbConnectionInternal() : this(ConnectionState.Open, true, false)
{
}
// Constructor for internal connections
internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString)
{
_allowSetConnectionString = allowSetConnectionString;
_hidePassword = hidePassword;
_state = state;
}
internal bool AllowSetConnectionString
{
get
{
return _allowSetConnectionString;
}
}
internal bool CanBePooled
{
get
{
bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive);
return flag;
}
}
protected internal bool IsConnectionDoomed
{
get
{
return _connectionIsDoomed;
}
}
internal bool IsEmancipated
{
get
{
// NOTE: There are race conditions between PrePush, PostPop and this
// property getter -- only use this while this object is locked;
// (DbConnectionPool.Clear and ReclaimEmancipatedObjects
// do this for us)
// The functionality is as follows:
//
// _pooledCount is incremented when the connection is pushed into the pool
// _pooledCount is decremented when the connection is popped from the pool
// _pooledCount is set to -1 when the connection is not pooled (just in case...)
//
// That means that:
//
// _pooledCount > 1 connection is in the pool multiple times (This should not happen)
// _pooledCount == 1 connection is in the pool
// _pooledCount == 0 connection is out of the pool
// _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections.
// _pooledCount < -1 connection out of the pool multiple times
//
// Now, our job is to return TRUE when the connection is out
// of the pool and it's owning object is no longer around to
// return it.
bool value = (_pooledCount < 1) && !_owningObject.IsAlive;
return value;
}
}
internal bool IsInPool
{
get
{
Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid");
return (_pooledCount == 1);
}
}
protected internal object Owner
{
// We use a weak reference to the owning object so we can identify when
// it has been garbage collected without thowing exceptions.
get
{
return _owningObject.Target;
}
}
internal DbConnectionPool Pool
{
get
{
return _connectionPool;
}
}
protected internal DbReferenceCollection ReferenceCollection
{
get
{
return _referenceCollection;
}
}
public abstract string ServerVersion
{
get;
}
// this should be abstract but until it is added to all the providers virtual will have to do
public virtual string ServerVersionNormalized
{
get
{
throw ADP.NotSupported();
}
}
public bool ShouldHidePassword
{
get
{
return _hidePassword;
}
}
public ConnectionState State
{
get
{
return _state;
}
}
protected abstract void Activate();
internal void ActivateConnection()
{
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
#if DEBUG
int activateCount = Interlocked.Increment(ref _activateCount);
Debug.Assert(1 == activateCount, "activated multiple times?");
#endif // DEBUG
Activate();
}
internal void AddWeakReference(object value, int tag)
{
if (null == _referenceCollection)
{
_referenceCollection = CreateReferenceCollection();
if (null == _referenceCollection)
{
throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull);
}
}
_referenceCollection.Add(value, tag);
}
public abstract DbTransaction BeginTransaction(IsolationLevel il);
public virtual void ChangeDatabase(string value)
{
throw ADP.MethodNotImplemented();
}
internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
{
// The implementation here is the implementation required for the
// "open" internal connections, since our own private "closed"
// singleton internal connection objects override this method to
// prevent anything funny from happening (like disposing themselves
// or putting them into a connection pool)
//
// Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose
// for cleaning up after DbConnection.Close
// protected override void Deactivate() { // override DbConnectionInternal.Close
// // do derived class connection deactivation for both pooled & non-pooled connections
// }
// public override void Dispose() { // override DbConnectionInternal.Close
// // do derived class cleanup
// base.Dispose();
// }
//
// overriding DbConnection.Close is also possible, but must provider for their own synchronization
// public override void Close() { // override DbConnection.Close
// base.Close();
// // do derived class outer connection for both pooled & non-pooled connections
// // user must do their own synchronization here
// }
//
// if the DbConnectionInternal derived class needs to close the connection it should
// delegate to the DbConnection if one exists or directly call dispose
// DbConnection owningObject = (DbConnection)Owner;
// if (null != owningObject) {
// owningObject.Close(); // force the closed state on the outer object.
// }
// else {
// Dispose();
// }
//
////////////////////////////////////////////////////////////////
// DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING!
////////////////////////////////////////////////////////////////
Debug.Assert(null != owningObject, "null owningObject");
Debug.Assert(null != connectionFactory, "null connectionFactory");
// if an exception occurs after the state change but before the try block
// the connection will be stuck in OpenBusy state. The commented out try-catch
// block doesn't really help because a ThreadAbort during the finally block
// would just revert the connection to a bad state.
// Open->Closed: guarantee internal connection is returned to correct pool
if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this))
{
// Lock to prevent race condition with cancellation
lock (this)
{
object lockToken = ObtainAdditionalLocksForClose();
try
{
PrepareForCloseConnection();
DbConnectionPool connectionPool = Pool;
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
// into the pool.
if (null != connectionPool)
{
connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us...
// NOTE: Before we leave the PutObject call, another
// thread may have already popped the connection from
// the pool, so don't expect to be able to verify it.
}
else
{
Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up...
// To prevent an endless recursion, we need to clear
// the owning object before we call dispose so that
// we can't get here a second time... Ordinarily, I
// would call setting the owner to null a hack, but
// this is safe since we're about to dispose the
// object and it won't have an owner after that for
// certain.
_owningObject.Target = null;
Dispose();
}
}
finally
{
ReleaseAdditionalLocksForClose(lockToken);
// if a ThreadAbort puts us here then its possible the outer connection will not reference
// this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope.
connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
}
}
}
internal virtual void PrepareForReplaceConnection()
{
// By default, there is no preparation required
}
protected virtual void PrepareForCloseConnection()
{
// By default, there is no preparation required
}
protected virtual object ObtainAdditionalLocksForClose()
{
return null; // no additional locks in default implementation
}
protected virtual void ReleaseAdditionalLocksForClose(object lockToken)
{
// no additional locks in default implementation
}
protected virtual DbReferenceCollection CreateReferenceCollection()
{
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject);
}
protected abstract void Deactivate();
internal void DeactivateConnection()
{
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
#if DEBUG
int activateCount = Interlocked.Decrement(ref _activateCount);
Debug.Assert(0 == activateCount, "activated multiple times?");
#endif // DEBUG
if (!_connectionIsDoomed && Pool.UseLoadBalancing)
{
// If we're not already doomed, check the connection's lifetime and
// doom it if it's lifetime has elapsed.
DateTime now = DateTime.UtcNow;
if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks)
{
DoNotPoolThisConnection();
}
}
Deactivate();
}
public virtual void Dispose()
{
_connectionPool = null;
_connectionIsDoomed = true;
}
protected internal void DoNotPoolThisConnection()
{
_cannotBePooled = true;
}
/// <devdoc>Ensure that this connection cannot be put back into the pool.</devdoc>
protected internal void DoomThisConnection()
{
_connectionIsDoomed = true;
}
internal void MakeNonPooledObject(object owningObject)
{
// Used by DbConnectionFactory to indicate that this object IS NOT part of
// a connection pool.
_connectionPool = null;
_owningObject.Target = owningObject;
_pooledCount = -1;
}
internal void MakePooledConnection(DbConnectionPool connectionPool)
{
// Used by DbConnectionFactory to indicate that this object IS part of
// a connection pool.
_createTime = DateTime.UtcNow;
_connectionPool = connectionPool;
}
internal void NotifyWeakReference(int message)
{
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Notify(message);
}
}
internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
{
if (!TryOpenConnection(outerConnection, connectionFactory, null, null))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
/// <devdoc>The default implementation is for the open connection objects, and
/// it simply throws. Our private closed-state connection objects
/// override this and do the correct thing.</devdoc>
// User code should either override DbConnectionInternal.Activate when it comes out of the pool
// or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections
internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
throw ADP.ConnectionAlreadyOpen(State);
}
internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
throw ADP.MethodNotImplemented();
}
protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
// ?->Connecting: prevent set_ConnectionString during Open
if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this))
{
DbConnectionInternal openConnection = null;
try
{
connectionFactory.PermissionDemand(outerConnection);
if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection))
{
return false;
}
}
catch
{
// This should occur for all exceptions, even ADP.UnCatchableExceptions.
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw;
}
if (null == openConnection)
{
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection);
}
return true;
}
internal void PrePush(object expectedOwner)
{
// Called by DbConnectionPool when we're about to be put into it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null == expectedOwner)
{
if (null != _owningObject.Target)
{
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner
}
}
else if (_owningObject.Target != expectedOwner)
{
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner
}
if (0 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time
}
_pooledCount++;
_owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2%
}
internal void PostPop(object newOwner)
{
// Called by DbConnectionPool right after it pulls this from it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
Debug.Assert(!IsEmancipated, "pooled object not in pool");
// When another thread is clearing this pool, it
// will doom all connections in this pool without prejudice which
// causes the following assert to fire, which really mucks up stress
// against checked bits. The assert is benign, so we're commenting
// it out.
//Debug.Assert(CanBePooled, "pooled object is not poolable");
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (null != _owningObject.Target)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner!
}
_owningObject.Target = newOwner;
_pooledCount--;
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null != Pool)
{
if (0 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
else if (-1 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
internal void RemoveWeakReference(object value)
{
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Remove(value);
}
}
/// <summary>
/// When overridden in a derived class, will check if the underlying connection is still actually alive
/// </summary>
/// <param name="throwOnException">If true an exception will be thrown if the connection is dead instead of returning true\false
/// (this allows the caller to have the real reason that the connection is not alive (e.g. network error, etc))</param>
/// <returns>True if the connection is still alive, otherwise false (If not overridden, then always true)</returns>
internal virtual bool IsConnectionAlive(bool throwOnException = false)
{
return true;
}
}
}
| |
// 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.CSharp.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly CodeFixProvider _codeFixProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public static async Task<RenameTrackingTestState> CreateAsync(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = await CreateTestWorkspaceAsync(markup, languageName, TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic());
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public RenameTrackingTestState(
TestWorkspace workspace,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = workspace;
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
var optionService = this.Workspace.Services.GetService<IOptionService>();
// Mock the action taken by the workspace INotificationService
var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback;
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
_historyRegistry,
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService),
Workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp)
{
_codeFixProvider = new CSharpRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else if (languageName == LanguageNames.VisualBasic)
{
_codeFixProvider = new VisualBasicRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid language name: " + languageName, "languageName");
}
}
private static Task<TestWorkspace> CreateTestWorkspaceAsync(string code, string languageName, ExportProvider exportProvider = null)
{
var xml = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code);
return TestWorkspaceFactory.CreateWorkspaceAsync(xml, exportProvider: exportProvider);
}
public void SendEscape()
{
_commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), () => { });
}
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public async Task AssertNoTag()
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
Assert.Equal(0, tags.Count());
}
public async Task<IList<Diagnostic>> GetDocumentDiagnosticsAsync(Document document = null)
{
document = document ?? this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var analyzer = new RenameTrackingDiagnosticAnalyzer();
return (await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(analyzer, document, document.GetSyntaxRootAsync().Result.FullSpan)).ToList();
}
public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var diagnostics = await GetDocumentDiagnosticsAsync(document);
// There should be a single rename tracking diagnostic
Assert.Equal(1, diagnostics.Count);
Assert.Equal(RenameTrackingDiagnosticAnalyzer.DiagnosticId, diagnostics[0].Id);
var actions = new List<CodeAction>();
var context = new CodeFixContext(document, diagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
_codeFixProvider.RegisterCodeFixesAsync(context).Wait();
// There should only be one code action
Assert.Equal(1, actions.Count);
Assert.Equal(string.Format(EditorFeaturesResources.RenameTo, expectedFromName, expectedToName), actions[0].Title);
if (invokeAction)
{
var operations = (await actions[0].GetOperationsAsync(CancellationToken.None)).ToArray();
Assert.Equal(1, operations.Length);
operations[0].Apply(this.Workspace, CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
{
Assert.Null(_notificationMessage);
}
public void AssertNotificationMessage()
{
Assert.NotNull(_notificationMessage);
}
private async Task WaitForAsyncOperationsAsync()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
await waiters.WaitAllAsync();
}
public void Dispose()
{
Workspace.Dispose();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.CoreModules.Framework.EventQueue;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class GroupsModule : ISharedRegionModule, IGroupsModule
{
/// <summary>
/// ; To use this module, you must specify the following in your OpenSim.ini
/// [GROUPS]
/// Enabled = true
///
/// Module = GroupsModule
/// NoticesEnabled = true
/// DebugEnabled = true
///
/// GroupsServicesConnectorModule = XmlRpcGroupsServicesConnector
/// XmlRpcServiceURL = http://osflotsam.org/xmlrpc.php
/// XmlRpcServiceReadKey = 1234
/// XmlRpcServiceWriteKey = 1234
///
/// MessagingModule = GroupsMessagingModule
/// MessagingEnabled = true
///
/// ; Disables HTTP Keep-Alive for Groups Module HTTP Requests, work around for
/// ; a problem discovered on some Windows based region servers. Only disable
/// ; if you see a large number (dozens) of the following Exceptions:
/// ; System.Net.WebException: The request was aborted: The request was canceled.
///
/// XmlRpcDisableKeepAlive = false
/// </summary>
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
private IMessageTransferModule m_msgTransferModule = null;
private IGroupsServicesConnector m_groupData = null;
// Configuration settings
private bool m_groupsEnabled = false;
private bool m_groupNoticesEnabled = true;
private bool m_debugEnabled = true;
#region IRegionModuleBase Members
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false);
if (!m_groupsEnabled)
{
return;
}
if (groupsConfig.GetString("Module", "Default") != Name)
{
m_groupsEnabled = false;
return;
}
m_log.InfoFormat("[GROUPS]: Initializing {0}", this.Name);
m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true);
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
}
}
public void AddRegion(Scene scene)
{
if (m_groupsEnabled)
scene.RegisterModuleInterface<IGroupsModule>(this);
}
public void RegionLoaded(Scene scene)
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
if (m_groupData == null)
{
m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>();
// No Groups Service Connector, then nothing works...
if (m_groupData == null)
{
m_groupsEnabled = false;
m_log.Error("[GROUPS]: Could not get IGroupsServicesConnector");
Close();
return;
}
}
if (m_msgTransferModule == null)
{
m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
// No message transfer module, no notices, group invites, rejects, ejects, etc
if (m_msgTransferModule == null)
{
m_groupsEnabled = false;
m_log.Error("[GROUPS]: Could not get MessageTransferModule");
Close();
return;
}
}
lock (m_sceneList)
{
m_sceneList.Add(scene);
}
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
// The InstantMessageModule itself doesn't do this,
// so lets see if things explode if we don't do it
// scene.EventManager.OnClientClosed += OnClientClosed;
}
public void RemoveRegion(Scene scene)
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
lock (m_sceneList)
{
m_sceneList.Remove(scene);
}
}
public void Close()
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module.");
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "GroupsModule"; }
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region EventHandlers
private void OnNewClient(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest;
client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest;
client.OnDirFindQuery += OnDirFindQuery;
client.OnRequestAvatarProperties += OnRequestAvatarProperties;
// Used for Notices and Group Invites/Accept/Reject
client.OnInstantMessage += OnInstantMessage;
// Send client thier groups information.
SendAgentGroupDataUpdate(client, client.AgentId);
}
private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
//GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetRequestingAgentID(remoteClient), avatarID).ToArray();
GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID);
remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups);
}
/*
* This becomes very problematic in a shared module. In a shared module you may have more then one
* reference to IClientAPI's, one for 0 or 1 root connections, and 0 or more child connections.
* The OnClientClosed event does not provide anything to indicate which one of those should be closed
* nor does it provide what scene it was from so that the specific reference can be looked up.
* The InstantMessageModule.cs does not currently worry about unregistering the handles,
* and it should be an issue, since it's the client that references us not the other way around
* , so as long as we don't keep a reference to the client laying around, the client can still be GC'ed
private void OnClientClosed(UUID AgentId)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
lock (m_ActiveClients)
{
if (m_ActiveClients.ContainsKey(AgentId))
{
IClientAPI client = m_ActiveClients[AgentId];
client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest;
client.OnDirFindQuery -= OnDirFindQuery;
client.OnInstantMessage -= OnInstantMessage;
m_ActiveClients.Remove(AgentId);
}
else
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here.");
}
}
}
*/
void OnDirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart)
{
if (((DirFindFlags)queryFlags & DirFindFlags.Groups) == DirFindFlags.Groups)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: {0} called with queryText({1}) queryFlags({2}) queryStart({3})",
System.Reflection.MethodBase.GetCurrentMethod().Name, queryText, (DirFindFlags)queryFlags, queryStart);
// TODO: This currently ignores pretty much all the query flags including Mature and sort order
remoteClient.SendDirGroupsReply(queryID, m_groupData.FindGroups(GetRequestingAgentID(remoteClient), queryText).ToArray());
}
}
private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID activeGroupID = UUID.Zero;
string activeGroupTitle = string.Empty;
string activeGroupName = string.Empty;
ulong activeGroupPowers = (ulong)GroupPowers.None;
GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient), dataForAgentID);
if (membership != null)
{
activeGroupID = membership.GroupID;
activeGroupTitle = membership.GroupTitle;
activeGroupPowers = membership.GroupPowers;
}
SendAgentDataUpdate(remoteClient, dataForAgentID, activeGroupID, activeGroupName, activeGroupPowers, activeGroupTitle);
SendScenePresenceUpdate(dataForAgentID, activeGroupTitle);
}
private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
string GroupName;
GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null);
if (group != null)
{
GroupName = group.GroupName;
}
else
{
GroupName = "Unknown";
}
remoteClient.SendGroupNameReply(GroupID, GroupName);
}
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Group invitations
if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline))
{
UUID inviteID = new UUID(im.imSessionID);
GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
if (inviteInfo == null)
{
if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Received an Invite IM for an invite that does not exist {0}.", inviteID);
return;
}
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID);
UUID fromAgentID = new UUID(im.fromAgentID);
if ((inviteInfo != null) && (fromAgentID == inviteInfo.AgentID))
{
// Accept
if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice.");
// and the sessionid is the role
m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID);
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = UUID.Zero.Guid;
msg.toAgentID = inviteInfo.AgentID.Guid;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.fromAgentName = "Groups";
msg.message = string.Format("You have been added to the group.");
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox;
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, inviteInfo.AgentID);
UpdateAllClientsWithGroupInfo(inviteInfo.AgentID);
// TODO: If the inviter is still online, they need an agent dataupdate
// and maybe group membership updates for the invitee
m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
}
// Reject
if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice.");
m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID);
}
}
}
// Group notices
if ((im.dialog == (byte)InstantMessageDialog.GroupNotice))
{
if (!m_groupNoticesEnabled)
{
return;
}
UUID GroupID = new UUID(im.toAgentID);
if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null) != null)
{
UUID NoticeID = UUID.Random();
string Subject = im.message.Substring(0, im.message.IndexOf('|'));
string Message = im.message.Substring(Subject.Length + 1);
byte[] bucket;
if ((im.binaryBucket.Length == 1) && (im.binaryBucket[0] == 0))
{
bucket = new byte[19];
bucket[0] = 0; //dunno
bucket[1] = 0; //dunno
GroupID.ToBytes(bucket, 2);
bucket[18] = 0; //dunno
}
else
{
string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket);
binBucket = binBucket.Remove(0, 14).Trim();
if (m_debugEnabled)
{
m_log.WarnFormat("I don't understand a group notice binary bucket of: {0}", binBucket);
OSDMap binBucketOSD = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket);
foreach (string key in binBucketOSD.Keys)
{
if (binBucketOSD.ContainsKey(key))
{
m_log.WarnFormat("{0}: {1}", key, binBucketOSD[key].ToString());
}
}
}
// treat as if no attachment
bucket = new byte[19];
bucket[0] = 0; //dunno
bucket[1] = 0; //dunno
GroupID.ToBytes(bucket, 2);
bucket[18] = 0; //dunno
}
m_groupData.AddGroupNotice(GetRequestingAgentID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket);
if (OnNewGroupNotice != null)
{
OnNewGroupNotice(GroupID, NoticeID);
}
// Send notice out to everyone that wants notices
foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), GroupID))
{
if (m_debugEnabled)
{
UserAccount targetUser = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, member.AgentID);
if (targetUser != null)
{
m_log.DebugFormat("[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUser.FirstName + " " + targetUser.LastName, member.AcceptNotices);
}
else
{
m_log.DebugFormat("[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, member.AgentID, member.AcceptNotices);
}
}
if (member.AcceptNotices)
{
// Build notice IIM
GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice);
msg.toAgentID = member.AgentID.Guid;
OutgoingInstantMessage(msg, member.AgentID);
}
}
}
}
// Interop, received special 210 code for ejecting a group member
// this only works within the comms servers domain, and won't work hypergrid
// TODO:FIXME: Use a presense server of some kind to find out where the
// client actually is, and try contacting that region directly to notify them,
// or provide the notification via xmlrpc update queue
if ((im.dialog == 210))
{
// This is sent from the region that the ejectee was ejected from
// if it's being delivered here, then the ejectee is here
// so we need to send local updates to the agent.
UUID ejecteeID = new UUID(im.toAgentID);
im.dialog = (byte)InstantMessageDialog.MessageFromAgent;
OutgoingInstantMessage(im, ejecteeID);
IClientAPI ejectee = GetActiveClient(ejecteeID);
if (ejectee != null)
{
UUID groupID = new UUID(im.imSessionID);
ejectee.SendAgentDropGroup(groupID);
}
}
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Trigger the above event handler
OnInstantMessage(null, msg);
// If a message from a group arrives here, it may need to be forwarded to a local client
if (msg.fromGroup == true)
{
switch (msg.dialog)
{
case (byte)InstantMessageDialog.GroupInvitation:
case (byte)InstantMessageDialog.GroupNotice:
UUID toAgentID = new UUID(msg.toAgentID);
IClientAPI localClient = GetActiveClient(toAgentID);
if (localClient != null)
{
localClient.SendInstantMessage(msg);
}
break;
}
}
}
#endregion
#region IGroupsModule Members
public event NewGroupNotice OnNewGroupNotice;
public GroupRecord GetGroupRecord(UUID GroupID)
{
return m_groupData.GetGroupRecord(UUID.Zero, GroupID, null);
}
public GroupRecord GetGroupRecord(string name)
{
return m_groupData.GetGroupRecord(UUID.Zero, UUID.Zero, name);
}
public void ActivateGroup(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentActiveGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
// Changing active group changes title, active powers, all kinds of things
// anyone who is in any region that can see this client, should probably be
// updated with new group info. At a minimum, they should get ScenePresence
// updated with new title.
UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient));
}
/// <summary>
/// Get the Role Titles for an Agent, for a specific group
/// </summary>
public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
List<GroupTitlesData> titles = new List<GroupTitlesData>();
foreach (GroupRolesData role in agentRoles)
{
GroupTitlesData title = new GroupTitlesData();
title.Name = role.Name;
if (agentMembership != null)
{
title.Selected = agentMembership.ActiveRole == role.RoleID;
}
title.UUID = role.RoleID;
titles.Add(title);
}
return titles;
}
public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name);
List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID);
if (m_debugEnabled)
{
foreach (GroupMembersData member in data)
{
m_log.DebugFormat("[GROUPS]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner);
}
}
return data;
}
public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID);
return data;
}
public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentID(remoteClient), groupID);
if (m_debugEnabled)
{
foreach (GroupRoleMembersData member in data)
{
m_log.DebugFormat("[GROUPS]: Member({0}) - Role({1})", member.MemberID, member.RoleID);
}
}
return data;
}
public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupProfileData profile = new GroupProfileData();
GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null);
if (groupInfo != null)
{
profile.AllowPublish = groupInfo.AllowPublish;
profile.Charter = groupInfo.Charter;
profile.FounderID = groupInfo.FounderID;
profile.GroupID = groupID;
profile.GroupMembershipCount = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID).Count;
profile.GroupRolesCount = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID).Count;
profile.InsigniaID = groupInfo.GroupPicture;
profile.MaturePublish = groupInfo.MaturePublish;
profile.MembershipFee = groupInfo.MembershipFee;
profile.Money = 0; // TODO: Get this from the currency server?
profile.Name = groupInfo.GroupName;
profile.OpenEnrollment = groupInfo.OpenEnrollment;
profile.OwnerRole = groupInfo.OwnerRoleID;
profile.ShowInList = groupInfo.ShowInList;
}
GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
if (memberInfo != null)
{
profile.MemberTitle = memberInfo.GroupTitle;
profile.PowersMask = memberInfo.GroupPowers;
}
return profile;
}
public GroupMembershipData[] GetMembershipData(UUID agentID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
return m_groupData.GetAgentGroupMemberships(UUID.Zero, agentID).ToArray();
}
public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[GROUPS]: {0} called with groupID={1}, agentID={2}",
System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID);
return m_groupData.GetAgentGroupMembership(UUID.Zero, agentID, groupID);
}
public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Note: Permissions checking for modification rights is handled by the Groups Server/Service
m_groupData.UpdateGroup(GetRequestingAgentID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish);
}
public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile)
{
// Note: Permissions checking for modification rights is handled by the Groups Server/Service
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentGroupInfo(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, acceptNotices, listInProfile);
}
public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name) != null)
{
remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists.");
return UUID.Zero;
}
// is there is a money module present ?
IMoneyModule money = remoteClient.Scene.RequestModuleInterface<IMoneyModule>();
if (money != null)
{
// do the transaction, that is if the agent has got sufficient funds
if (!money.AmountCovered(remoteClient, money.GroupCreationCharge)) {
remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got issuficient funds to create a group.");
return UUID.Zero;
}
money.ApplyCharge(GetRequestingAgentID(remoteClient), money.GroupCreationCharge, "Group Creation");
}
UUID groupID = m_groupData.CreateGroup(GetRequestingAgentID(remoteClient), name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, GetRequestingAgentID(remoteClient));
remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly");
// Update the founder with new group information.
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
return groupID;
}
public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// ToDo: check if agent is a member of group and is allowed to see notices?
return m_groupData.GetGroupNotices(GetRequestingAgentID(remoteClient), groupID).ToArray();
}
/// <summary>
/// Get the title of the agent's current role.
/// </summary>
public string GetGroupTitle(UUID avatarID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero, avatarID);
if (membership != null)
{
return membership.GroupTitle;
}
return string.Empty;
}
/// <summary>
/// Change the current Active Group Role for Agent
/// </summary>
public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentActiveGroupRole(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, titleRoleID);
// TODO: Not sure what all is needed here, but if the active group role change is for the group
// the client currently has set active, then we need to do a scene presence update too
// if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID)
UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient));
}
public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Security Checks are handled in the Groups Service.
switch ((OpenMetaverse.GroupRoleUpdate)updateType)
{
case OpenMetaverse.GroupRoleUpdate.Create:
m_groupData.AddGroupRole(GetRequestingAgentID(remoteClient), groupID, UUID.Random(), name, description, title, powers);
break;
case OpenMetaverse.GroupRoleUpdate.Delete:
m_groupData.RemoveGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID);
break;
case OpenMetaverse.GroupRoleUpdate.UpdateAll:
case OpenMetaverse.GroupRoleUpdate.UpdateData:
case OpenMetaverse.GroupRoleUpdate.UpdatePowers:
if (m_debugEnabled)
{
GroupPowers gp = (GroupPowers)powers;
m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString());
}
m_groupData.UpdateGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID, name, description, title, powers);
break;
case OpenMetaverse.GroupRoleUpdate.NoUpdate:
default:
// No Op
break;
}
// TODO: This update really should send out updates for everyone in the role that just got changed.
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Todo: Security check
switch (changes)
{
case 0:
// Add
m_groupData.AddAgentToGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID);
break;
case 1:
// Remove
m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID);
break;
default:
m_log.ErrorFormat("[GROUPS]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes);
break;
}
// TODO: This update really should send out updates for everyone in the role that just got changed.
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupNoticeInfo data = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), groupNoticeID);
if (data != null)
{
GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), data.GroupID, null);
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = data.GroupID.Guid;
msg.toAgentID = GetRequestingAgentID(remoteClient).Guid;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.fromAgentName = "Group Notice : " + groupInfo == null ? "Unknown" : groupInfo.GroupName;
msg.message = data.noticeData.Subject + "|" + data.Message;
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupNoticeRequested;
msg.fromGroup = true;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
msg.binaryBucket = data.BinaryBucket;
OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient));
}
}
public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.toAgentID = agentID.Guid;
msg.dialog = dialog;
// msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupNotice;
msg.fromGroup = true;
msg.offline = (byte)1; // Allow this message to be stored for offline use
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID, groupNoticeID);
if (info != null)
{
msg.fromAgentID = info.GroupID.Guid;
msg.timestamp = info.noticeData.Timestamp;
msg.fromAgentName = info.noticeData.FromName;
msg.message = info.noticeData.Subject + "|" + info.Message;
msg.binaryBucket = info.BinaryBucket;
}
else
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Group Notice {0} not found, composing empty message.", groupNoticeID);
msg.fromAgentID = UUID.Zero.Guid;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); ;
msg.fromAgentName = string.Empty;
msg.message = string.Empty;
msg.binaryBucket = new byte[0];
}
return msg;
}
public void SendAgentGroupDataUpdate(IClientAPI remoteClient)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Send agent information about his groups
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Should check to see if OpenEnrollment, or if there's an outstanding invitation
m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, UUID.Zero);
remoteClient.SendJoinGroupReply(groupID, true);
// Should this send updates to everyone in the group?
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID);
remoteClient.SendLeaveGroupReply(groupID, true);
remoteClient.SendAgentDropGroup(groupID);
// SL sends out notifcations to the group messaging session that the person has left
// Should this also update everyone who is in the group?
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Todo: Security check?
m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), ejecteeID, groupID);
remoteClient.SendEjectGroupMemberReply(GetRequestingAgentID(remoteClient), groupID, true);
GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null);
UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, ejecteeID);
if ((groupInfo == null) || (account == null))
{
return;
}
// Send Message to Ejectee
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = GetRequestingAgentID(remoteClient).Guid;
// msg.fromAgentID = info.GroupID;
msg.toAgentID = ejecteeID.Guid;
//msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.timestamp = 0;
msg.fromAgentName = remoteClient.Name;
msg.message = string.Format("You have been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName);
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent;
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, ejecteeID);
// Message to ejector
// Interop, received special 210 code for ejecting a group member
// this only works within the comms servers domain, and won't work hypergrid
// TODO:FIXME: Use a presense server of some kind to find out where the
// client actually is, and try contacting that region directly to notify them,
// or provide the notification via xmlrpc update queue
msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = GetRequestingAgentID(remoteClient).Guid;
msg.toAgentID = GetRequestingAgentID(remoteClient).Guid;
msg.timestamp = 0;
msg.fromAgentName = remoteClient.Name;
if (account != null)
{
msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName, account.FirstName + " " + account.LastName);
}
else
{
msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", remoteClient.Name, groupInfo.GroupName, "Unknown member");
}
msg.dialog = (byte)210; //interop
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient));
// SL sends out messages to everyone in the group
// Who all should receive updates and what should they be updated with?
UpdateAllClientsWithGroupInfo(ejecteeID);
}
public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Todo: Security check, probably also want to send some kind of notification
UUID InviteID = UUID.Random();
m_groupData.AddAgentToGroupInvite(GetRequestingAgentID(remoteClient), InviteID, groupID, roleID, invitedAgentID);
// Check to see if the invite went through, if it did not then it's possible
// the remoteClient did not validate or did not have permission to invite.
GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), InviteID);
if (inviteInfo != null)
{
if (m_msgTransferModule != null)
{
Guid inviteUUID = InviteID.Guid;
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = inviteUUID;
// msg.fromAgentID = GetRequestingAgentID(remoteClient).Guid;
msg.fromAgentID = groupID.Guid;
msg.toAgentID = invitedAgentID.Guid;
//msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.timestamp = 0;
msg.fromAgentName = remoteClient.Name;
msg.message = string.Format("{0} has invited you to join a group. There is no cost to join this group.", remoteClient.Name);
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation;
msg.fromGroup = true;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = remoteClient.Scene.RegionInfo.RegionID.Guid;
msg.binaryBucket = new byte[20];
OutgoingInstantMessage(msg, invitedAgentID);
}
}
}
#endregion
#region Client/Update Tools
/// <summary>
/// Try to find an active IClientAPI reference for agentID giving preference to root connections
/// </summary>
private IClientAPI GetActiveClient(UUID agentID)
{
IClientAPI child = null;
// Try root avatar first
foreach (Scene scene in m_sceneList)
{
if (scene.Entities.ContainsKey(agentID) &&
scene.Entities[agentID] is ScenePresence)
{
ScenePresence user = (ScenePresence)scene.Entities[agentID];
if (!user.IsChildAgent)
{
return user.ControllingClient;
}
else
{
child = user.ControllingClient;
}
}
}
// If we didn't find a root, then just return whichever child we found, or null if none
return child;
}
/// <summary>
/// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'.
/// </summary>
private void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, UUID dataForAgentID, GroupMembershipData[] data)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDArray AgentData = new OSDArray(1);
OSDMap AgentDataMap = new OSDMap(1);
AgentDataMap.Add("AgentID", OSD.FromUUID(dataForAgentID));
AgentData.Add(AgentDataMap);
OSDArray GroupData = new OSDArray(data.Length);
OSDArray NewGroupData = new OSDArray(data.Length);
foreach (GroupMembershipData membership in data)
{
if (GetRequestingAgentID(remoteClient) != dataForAgentID)
{
if (!membership.ListInProfile)
{
// If we're sending group info to remoteclient about another agent,
// filter out groups the other agent doesn't want to share.
continue;
}
}
OSDMap GroupDataMap = new OSDMap(6);
OSDMap NewGroupDataMap = new OSDMap(1);
GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID));
GroupDataMap.Add("GroupPowers", OSD.FromULong(membership.GroupPowers));
GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices));
GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture));
GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution));
GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName));
NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile));
GroupData.Add(GroupDataMap);
NewGroupData.Add(NewGroupDataMap);
}
OSDMap llDataStruct = new OSDMap(3);
llDataStruct.Add("AgentData", AgentData);
llDataStruct.Add("GroupData", GroupData);
llDataStruct.Add("NewGroupData", NewGroupData);
if (m_debugEnabled)
{
m_log.InfoFormat("[GROUPS]: {0}", OSDParser.SerializeJsonString(llDataStruct));
}
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
if (queue != null)
{
queue.Enqueue(EventQueueHelper.buildEvent("AgentGroupDataUpdate", llDataStruct), GetRequestingAgentID(remoteClient));
}
}
private void SendScenePresenceUpdate(UUID AgentID, string Title)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Updating scene title for {0} with title: {1}", AgentID, Title);
ScenePresence presence = null;
foreach (Scene scene in m_sceneList)
{
presence = scene.GetScenePresence(AgentID);
if (presence != null)
{
presence.Grouptitle = Title;
// FixMe: Ter suggests a "Schedule" method that I can't find.
presence.SendFullUpdateToAllClients();
}
}
}
/// <summary>
/// Send updates to all clients who might be interested in groups data for dataForClientID
/// </summary>
private void UpdateAllClientsWithGroupInfo(UUID dataForClientID)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Probably isn't nessesary to update every client in every scene.
// Need to examine client updates and do only what's nessesary.
lock (m_sceneList)
{
foreach (Scene scene in m_sceneList)
{
scene.ForEachClient(delegate(IClientAPI client) { SendAgentGroupDataUpdate(client, dataForClientID); });
}
}
}
/// <summary>
/// Update remoteClient with group information about dataForAgentID
/// </summary>
private void SendAgentGroupDataUpdate(IClientAPI remoteClient, UUID dataForAgentID)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name);
// TODO: All the client update functions need to be reexamined because most do too much and send too much stuff
OnAgentDataUpdateRequest(remoteClient, dataForAgentID, UUID.Zero);
// Need to send a group membership update to the client
// UDP version doesn't seem to behave nicely. But we're going to send it out here
// with an empty group membership to hopefully remove groups being displayed due
// to the core Groups Stub
remoteClient.SendGroupMembership(new GroupMembershipData[0]);
GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, dataForAgentID);
SendGroupMembershipInfoViaCaps(remoteClient, dataForAgentID, membershipArray);
remoteClient.SendAvatarGroupsReply(dataForAgentID, membershipArray);
}
/// <summary>
/// Get a list of groups memberships for the agent that are marked "ListInProfile"
/// </summary>
/// <param name="dataForAgentID"></param>
/// <returns></returns>
private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID)
{
List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId, dataForAgentID);
GroupMembershipData[] membershipArray;
if (requestingClient.AgentId != dataForAgentID)
{
Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership)
{
return membership.ListInProfile;
};
membershipArray = membershipData.FindAll(showInProfile).ToArray();
}
else
{
membershipArray = membershipData.ToArray();
}
if (m_debugEnabled)
{
m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId);
foreach (GroupMembershipData membership in membershipArray)
{
m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers);
}
}
return membershipArray;
}
private void SendAgentDataUpdate(IClientAPI remoteClient, UUID dataForAgentID, UUID activeGroupID, string activeGroupName, ulong activeGroupPowers, string activeGroupTitle)
{
if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: All the client update functions need to be reexamined because most do too much and send too much stuff
UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, dataForAgentID);
string firstname, lastname;
if (account != null)
{
firstname = account.FirstName;
lastname = account.LastName;
}
else
{
firstname = "Unknown";
lastname = "Unknown";
}
remoteClient.SendAgentDataUpdate(dataForAgentID, activeGroupID, firstname,
lastname, activeGroupPowers, activeGroupName,
activeGroupTitle);
}
#endregion
#region IM Backed Processes
private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
IClientAPI localClient = GetActiveClient(msgTo);
if (localClient != null)
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is local, delivering directly", localClient.Name);
localClient.SendInstantMessage(msg);
}
else
{
if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo);
m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Message Sent: {0}", success?"Succeeded":"Failed"); });
}
}
public void NotifyChange(UUID groupID)
{
// Notify all group members of a chnge in group roles and/or
// permissions
//
}
#endregion
private UUID GetRequestingAgentID(IClientAPI client)
{
UUID requestingAgentID = UUID.Zero;
if (client != null)
{
requestingAgentID = client.AgentId;
}
return requestingAgentID;
}
}
public class GroupNoticeInfo
{
public GroupNoticeData noticeData = new GroupNoticeData();
public UUID GroupID = UUID.Zero;
public string Message = string.Empty;
public byte[] BinaryBucket = new byte[0];
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/8/2010 10:16:19 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
namespace DotSpatial.Data
{
public class TileCollection : IEnumerable<IImageData>
{
#region Private Variables
private readonly int _tileHeight;
private readonly int _tileWidth;
private int _height;
private IImageData[,] _tiles;
private int _width;
#endregion
#region IEnumerable<IImageData> Members
/// <inheritdoc />
public IEnumerator<IImageData> GetEnumerator()
{
return new TileCollectionEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Nested type: TileCollectionEnumerator
/// <summary>
/// Enumerates the collection of tiles
/// </summary>
private class TileCollectionEnumerator : IEnumerator<IImageData>
{
private readonly IImageData[,] _tiles;
private int _col;
private int _row;
/// <summary>
/// Creates a new instance of hte TileCollectionEnumerator
/// </summary>
/// <param name="parent">The parent tileCollection</param>
public TileCollectionEnumerator(TileCollection parent)
{
_tiles = parent.Tiles;
_row = 0;
_col = -1;
}
#region IEnumerator<IImageData> Members
/// <inheritdoc />
public IImageData Current
{
get { return _tiles[_row, _col]; }
}
/// <inheritdoc />
public void Dispose()
{
// Does nothing
}
object IEnumerator.Current
{
get { return Current; }
}
/// <inheritdoc />
public bool MoveNext()
{
do
{
_col++;
if (_col > _tiles.GetUpperBound(1))
{
_row++;
_col = 0;
}
if (_row > _tiles.GetUpperBound(0)) return false;
} while (_tiles[_row, _col] == null);
return true;
}
/// <inheritdoc />
public void Reset()
{
_row = 0;
_col = 0;
}
#endregion
}
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of TileCollection
/// </summary>
public TileCollection(int width, int height)
{
_tileWidth = 5000;
_tileHeight = 5000;
_width = width;
_height = height;
if (_width < _tileWidth) _tileWidth = width;
if (_height < _tileHeight) _tileHeight = height;
_tiles = new IImageData[NumTilesTall(), NumTilesWide()];
}
/// <summary>
/// Calls a method that calculates the propper image bounds for each of the extents of the tiles,
/// given the affine coefficients for the whole image.
/// </summary>
/// <param name="affine"> x' = A + Bx + Cy; y' = D + Ex + Fy</param>
public void SetTileBounds(double[] affine)
{
double[] tileAffine = new double[6];
for (int i = 0; i < 6; i++)
{
tileAffine[i] = affine[i];
}
if (_tiles == null) return;
for (int row = 0; row < NumTilesTall(); row++)
{
for (int col = 0; col < NumTilesWide(); col++)
{
int h = GetTileHeight(row);
int w = GetTileWidth(col);
// The rotation terms are the same, but the top-left values need to be shifted.
tileAffine[0] = affine[0] + affine[1] * col * _tileWidth + affine[2] * row * _tileHeight;
tileAffine[3] = affine[3] + affine[4] * col * _tileWidth + affine[5] * row * _tileHeight;
_tiles[row, col].Bounds = new RasterBounds(h, w, tileAffine);
}
}
}
#endregion
#region Methods
/// <summary>
/// Gets the width of the tile
/// </summary>
/// <param name="col"></param>
/// <returns></returns>
public int GetTileWidth(int col)
{
if (col < NumTilesWide() - 1) return _tileWidth;
return Width - (NumTilesWide() - 1) * _tileWidth;
}
/// <summary>
/// Gets the height of the tile
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public int GetTileHeight(int row)
{
if (row < NumTilesTall() - 1) return _tileHeight;
return Height - (NumTilesTall() - 1) * _tileHeight;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the integer height in pixels for the combined image at its maximum resolution
/// </summary>
public int Height
{
get { return _height; }
set { _height = value; }
}
/// <summary>
/// Gets or sets the integer pixel width for the combined image at its maximum resolution.
/// </summary>
public int Width
{
get { return _width; }
set { _width = value; }
}
/// <summary>
/// Gets or sets the 2D array of tiles
/// </summary>
public IImageData[,] Tiles
{
get { return _tiles; }
set { _tiles = value; }
}
/// <summary>
/// The width of the standard sized tile (not counting the remainder)
/// </summary>
public int TileWidth
{
get { return _tileWidth; }
}
/// <summary>
/// The height of the standard sized tile, not counting the remainder.
/// </summary>
public int TileHeight
{
get { return _tileHeight; }
}
/// <summary>
/// The total number of tiles
/// </summary>
public int NumTiles
{
get
{
return NumTilesWide() * NumTilesTall();
}
}
/// <summary>
/// Gets the number of tiles in the X direction
/// </summary>
/// <returns></returns>
public int NumTilesWide()
{
return (int)Math.Ceiling(Width / (double)TileWidth);
}
/// <summary>
/// Gets the integer number of tiles in the Y direction
/// </summary>
/// <returns></returns>
public int NumTilesTall()
{
return (int)Math.Ceiling(Height / (double)TileHeight);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Statistics;
using OpenSim.Grid.Communications.OGS1;
using OpenSim.Grid.Framework;
using OpenSim.Grid.UserServer.Modules;
using Nini.Config;
namespace OpenSim.Grid.UserServer
{
/// <summary>
/// Grid user server main class
/// </summary>
public class OpenUser_Main : BaseOpenSimServer, IGridServiceCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected UserConfig Cfg;
protected UserDataBaseService m_userDataBaseService;
public UserManager m_userManager;
protected UserServerAvatarAppearanceModule m_avatarAppearanceModule;
protected UserServerFriendsModule m_friendsModule;
public UserLoginService m_loginService;
public UserLoginAuthService m_loginAuthService;
public MessageServersConnector m_messagesService;
protected GridInfoServiceModule m_gridInfoService;
protected UserServerCommandModule m_consoleCommandModule;
protected UserServerEventDispatchModule m_eventDispatcher;
protected AvatarCreationModule m_appearanceModule;
protected static string m_consoleType = "local";
protected static IConfigSource m_config = null;
protected static string m_configFile = "UserServer_Config.xml";
public static void Main(string[] args)
{
ArgvConfigSource argvSource = new ArgvConfigSource(args);
argvSource.AddSwitch("Startup", "console", "c");
argvSource.AddSwitch("Startup", "xmlfile", "x");
IConfig startupConfig = argvSource.Configs["Startup"];
if (startupConfig != null)
{
m_consoleType = startupConfig.GetString("console", "local");
m_configFile = startupConfig.GetString("xmlfile", "UserServer_Config.xml");
}
m_config = argvSource;
XmlConfigurator.Configure();
m_log.Info("Launching UserServer...");
OpenUser_Main userserver = new OpenUser_Main();
userserver.Startup();
userserver.Work();
}
public OpenUser_Main()
{
switch (m_consoleType)
{
case "rest":
m_console = new RemoteConsole("User");
break;
case "basic":
m_console = new CommandConsole("User");
break;
default:
m_console = new LocalConsole("User");
break;
}
MainConsole.Instance = m_console;
}
public void Work()
{
m_console.Output("Enter help for a list of commands\n");
while (true)
{
m_console.Prompt();
}
}
protected override void StartupSpecific()
{
IInterServiceInventoryServices inventoryService = StartupCoreComponents();
m_stats = StatsManager.StartCollectingUserStats();
//setup services/modules
StartupUserServerModules();
StartOtherComponents(inventoryService);
//PostInitialise the modules
PostInitialiseModules();
//register http handlers and start http server
m_log.Info("[STARTUP]: Starting HTTP process");
RegisterHttpHandlers();
m_httpServer.Start();
base.StartupSpecific();
}
protected virtual IInterServiceInventoryServices StartupCoreComponents()
{
Cfg = new UserConfig("USER SERVER", (Path.Combine(Util.configDir(), m_configFile)));
m_httpServer = new BaseHttpServer(Cfg.HttpPort);
if (m_console is RemoteConsole)
{
RemoteConsole c = (RemoteConsole)m_console;
c.SetServer(m_httpServer);
IConfig netConfig = m_config.AddConfig("Network");
netConfig.Set("ConsoleUser", Cfg.ConsoleUser);
netConfig.Set("ConsolePass", Cfg.ConsolePass);
c.ReadConfig(m_config);
}
RegisterInterface<CommandConsole>(m_console);
RegisterInterface<UserConfig>(Cfg);
//Should be in modules?
IInterServiceInventoryServices inventoryService = new OGS1InterServiceInventoryService(Cfg.InventoryUrl);
// IRegionProfileRouter regionProfileService = new RegionProfileServiceProxy();
RegisterInterface<IInterServiceInventoryServices>(inventoryService);
// RegisterInterface<IRegionProfileRouter>(regionProfileService);
return inventoryService;
}
/// <summary>
/// Start up the user manager
/// </summary>
/// <param name="inventoryService"></param>
protected virtual void StartupUserServerModules()
{
m_log.Info("[STARTUP]: Establishing data connection");
//we only need core components so we can request them from here
IInterServiceInventoryServices inventoryService;
TryGet<IInterServiceInventoryServices>(out inventoryService);
CommunicationsManager commsManager = new UserServerCommsManager(inventoryService);
//setup database access service, for now this has to be created before the other modules.
m_userDataBaseService = new UserDataBaseService(commsManager);
m_userDataBaseService.Initialise(this);
//TODO: change these modules so they fetch the databaseService class in the PostInitialise method
m_userManager = new UserManager(m_userDataBaseService);
m_userManager.Initialise(this);
m_avatarAppearanceModule = new UserServerAvatarAppearanceModule(m_userDataBaseService);
m_avatarAppearanceModule.Initialise(this);
m_friendsModule = new UserServerFriendsModule(m_userDataBaseService);
m_friendsModule.Initialise(this);
m_consoleCommandModule = new UserServerCommandModule();
m_consoleCommandModule.Initialise(this);
m_messagesService = new MessageServersConnector();
m_messagesService.Initialise(this);
m_gridInfoService = new GridInfoServiceModule();
m_gridInfoService.Initialise(this);
}
protected virtual void StartOtherComponents(IInterServiceInventoryServices inventoryService)
{
m_appearanceModule = new AvatarCreationModule(m_userDataBaseService, Cfg, inventoryService);
m_appearanceModule.Initialise(this);
StartupLoginService(inventoryService);
//
// Get the minimum defaultLevel to access to the grid
//
m_loginService.setloginlevel((int)Cfg.DefaultUserLevel);
RegisterInterface<UserLoginService>(m_loginService); //TODO: should be done in the login service
m_eventDispatcher = new UserServerEventDispatchModule(m_userManager, m_messagesService, m_loginService);
m_eventDispatcher.Initialise(this);
}
/// <summary>
/// Start up the login service
/// </summary>
/// <param name="inventoryService"></param>
protected virtual void StartupLoginService(IInterServiceInventoryServices inventoryService)
{
m_loginService = new UserLoginService(
m_userDataBaseService, inventoryService, new LibraryRootFolder(Cfg.LibraryXmlfile), Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy());
if (Cfg.EnableHGLogin)
m_loginAuthService = new UserLoginAuthService(m_userDataBaseService, inventoryService, new LibraryRootFolder(Cfg.LibraryXmlfile),
Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy());
}
protected virtual void PostInitialiseModules()
{
m_consoleCommandModule.PostInitialise(); //it will register its Console command handlers in here
m_userDataBaseService.PostInitialise();
m_messagesService.PostInitialise();
m_eventDispatcher.PostInitialise(); //it will register event handlers in here
m_gridInfoService.PostInitialise();
m_userManager.PostInitialise();
m_avatarAppearanceModule.PostInitialise();
m_friendsModule.PostInitialise();
}
protected virtual void RegisterHttpHandlers()
{
m_loginService.RegisterHandlers(m_httpServer, Cfg.EnableLLSDLogin, true);
if (m_loginAuthService != null)
m_loginAuthService.RegisterHandlers(m_httpServer);
m_userManager.RegisterHandlers(m_httpServer);
m_friendsModule.RegisterHandlers(m_httpServer);
m_avatarAppearanceModule.RegisterHandlers(m_httpServer);
m_messagesService.RegisterHandlers(m_httpServer);
m_gridInfoService.RegisterHandlers(m_httpServer);
}
public override void ShutdownSpecific()
{
m_eventDispatcher.Close();
}
#region IUGAIMCore
protected Dictionary<Type, object> m_moduleInterfaces = new Dictionary<Type, object>();
/// <summary>
/// Register an Module interface.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iface"></param>
public void RegisterInterface<T>(T iface)
{
lock (m_moduleInterfaces)
{
if (!m_moduleInterfaces.ContainsKey(typeof(T)))
{
m_moduleInterfaces.Add(typeof(T), iface);
}
}
}
public bool TryGet<T>(out T iface)
{
if (m_moduleInterfaces.ContainsKey(typeof(T)))
{
iface = (T)m_moduleInterfaces[typeof(T)];
return true;
}
iface = default(T);
return false;
}
public T Get<T>()
{
return (T)m_moduleInterfaces[typeof(T)];
}
public BaseHttpServer GetHttpServer()
{
return m_httpServer;
}
#endregion
public void TestResponse(List<InventoryFolderBase> resp)
{
m_console.Output("response got");
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace DotSpatial.Controls
{
/// <summary>
/// A MapFunction that zooms the map by scrolling the scroll wheel and pans the map by pressing the mouse wheel and moving the mouse.
/// </summary>
public class MapFunctionZoom : MapFunction
{
#region Fields
private Rectangle _client;
private int _direction;
private Point _dragStart;
private bool _isDragging;
private IMapFrame _mapFrame;
private bool _preventDrag;
private double _sensitivity;
private Rectangle _source;
private int _timerInterval;
private Timer _zoomTimer;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MapFunctionZoom"/> class.
/// </summary>
/// <param name="inMap">The map the tool should work on.</param>
public MapFunctionZoom(IMap inMap)
: base(inMap)
{
Configure();
BusySet = false;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether the map function is currently interacting with the map.
/// </summary>
public bool BusySet { get; set; }
/// <summary>
/// Gets or sets a value indicating whether forward zooms in. This controls the sense (direction) of zoom (in or out) as you roll the mouse wheel.
/// </summary>
public bool ForwardZoomsIn
{
get
{
return _direction > 0;
}
set
{
_direction = value ? 1 : -1;
}
}
/// <summary>
/// Gets or sets the wheel zoom sensitivity. Increasing makes it more sensitive. Maximum is 0.5, Minimum is 0.01.
/// </summary>
public double Sensitivity
{
get
{
return 1.0 / _sensitivity;
}
set
{
if (value > 0.5)
value = 0.5;
else if (value < 0.01)
value = 0.01;
_sensitivity = 1.0 / value;
}
}
/// <summary>
/// Gets or sets the full refresh timeout value in milliseconds.
/// </summary>
public int TimerInterval
{
get
{
return _timerInterval;
}
set
{
_timerInterval = value;
_zoomTimer.Interval = _timerInterval;
}
}
#endregion
#region Methods
/// <summary>
/// Handles the actions that the tool controls during the OnMouseDown event.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseDown(GeoMouseArgs e)
{
if (e.Button == MouseButtons.Middle && !_preventDrag)
{
_dragStart = e.Location;
_source = e.Map.MapFrame.View;
}
base.OnMouseDown(e);
}
/// <summary>
/// Handles the mouse move event, changing the viewing extents to match the movements
/// of the mouse if the left mouse button is down.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseMove(GeoMouseArgs e)
{
if (_dragStart != Point.Empty && !_preventDrag)
{
if (!BusySet)
{
Map.IsBusy = true;
BusySet = true;
}
_isDragging = true;
Point diff = new Point
{
X = _dragStart.X - e.X,
Y = _dragStart.Y - e.Y
};
e.Map.MapFrame.View = new Rectangle(_source.X + diff.X, _source.Y + diff.Y, _source.Width, _source.Height);
Map.Invalidate();
}
base.OnMouseMove(e);
}
/// <summary>
/// Mouse Up.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(GeoMouseArgs e)
{
if (e.Button == MouseButtons.Middle && _isDragging)
{
_isDragging = false;
_preventDrag = true;
e.Map.MapFrame.ResetExtents();
_preventDrag = false;
Map.IsBusy = false;
BusySet = false;
}
_dragStart = Point.Empty;
base.OnMouseUp(e);
}
/// <summary>
/// Mouse Wheel.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseWheel(GeoMouseArgs e)
{
// Fix this
_zoomTimer.Stop(); // if the timer was already started, stop it.
if (!(e.Map.IsZoomedToMaxExtent && (_direction * e.Delta < 0)))
{
e.Map.IsZoomedToMaxExtent = false;
Rectangle r = e.Map.MapFrame.View;
// For multiple zoom steps before redrawing, we actually
// want the x coordinate relative to the screen, not
// the x coordinate relative to the previously modified view.
if (_client == Rectangle.Empty) _client = r;
int cw = _client.Width;
int ch = _client.Height;
double w = r.Width;
double h = r.Height;
if (_direction * e.Delta > 0)
{
double inFactor = 2.0 * _sensitivity;
r.Inflate(Convert.ToInt32(-w / inFactor), Convert.ToInt32(-h / inFactor));
// try to keep the mouse cursor in the same geographic position
r.X += Convert.ToInt32((e.X * w / (_sensitivity * cw)) - (w / inFactor));
r.Y += Convert.ToInt32((e.Y * h / (_sensitivity * ch)) - (h / inFactor));
}
else
{
double outFactor = 0.5 * _sensitivity;
r.Inflate(Convert.ToInt32(w / _sensitivity), Convert.ToInt32(h / _sensitivity));
r.X += Convert.ToInt32((w / _sensitivity) - (e.X * w / (outFactor * cw)));
r.Y += Convert.ToInt32((h / _sensitivity) - (e.Y * h / (outFactor * ch)));
}
e.Map.MapFrame.View = r;
e.Map.Invalidate();
_zoomTimer.Start();
_mapFrame = e.Map.MapFrame;
if (!BusySet)
{
Map.IsBusy = true;
BusySet = true;
}
base.OnMouseWheel(e);
}
}
private void Configure()
{
YieldStyle = YieldStyles.Scroll;
_timerInterval = 100;
_zoomTimer = new Timer
{
Interval = _timerInterval
};
_zoomTimer.Tick += ZoomTimerTick;
_client = Rectangle.Empty;
Sensitivity = .30;
ForwardZoomsIn = true;
Name = "ScrollZoom";
}
private void ZoomTimerTick(object sender, EventArgs e)
{
_zoomTimer.Stop();
if (_mapFrame == null) return;
_client = Rectangle.Empty;
_mapFrame.ResetExtents();
Map.IsBusy = false;
BusySet = false;
}
#endregion
}
}
| |
// -------------------------------------
// Domain : Avariceonline.com
// Author : Nicholas Ventimiglia
// Product : Unity3d Foundation
// Published : 2015
// -------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Foundation.Databinding
{
/// <summary>
/// Presents an array, observable collection or other IEnumerable visually.
/// </summary>
/// <remarks>
/// The Prefab (child template) should have a binding context set to Mock binding
/// </remarks>
[AddComponentMenu("Foundation/Databinding/ListBinder")]
public class ListBinder : BindingBase
{
protected List<BindingContext> Children = new List<BindingContext>();
protected IObservableCollection DataList;
public bool DelayLoad;
protected int Index;
protected bool IsInit;
protected bool IsLoaded;
/// <summary>
/// Shown when loading
/// </summary>
public GameObject LoadingMask;
/// <summary>
/// True if this is a static list.
/// The list will only update once.
/// </summary>
public bool OneTime;
/// <summary>
/// Child Item Template
/// </summary>
/// <remarks>
/// The Prefab (child template) should have a binding context set to Mock binding
/// </remarks>
public GameObject Prefab;
protected RectTransform RectTransform;
protected RectTransform RectTransform2;
/// <summary>
/// Bottom Up as opposed to Top Down
/// </summary>
public bool SetAsFirstSibling = false;
[HideInInspector] public BindingInfo SourceBinding = new BindingInfo {BindingName = "DataSource"};
private void Awake()
{
RectTransform = GetComponent<RectTransform>();
RectTransform2 = Prefab.GetComponent<RectTransform>();
Init();
if (Application.isPlaying)
{
if (Prefab)
{
var scale = Prefab.transform.localScale;
Prefab.transform.SetParent(transform.parent);
Prefab.SetActive(false);
Prefab.transform.localScale = scale;
if (Prefab.GetComponent<BindingContext>() == null)
{
Debug.LogError("template item must have an Root.");
enabled = false;
}
}
if (LoadingMask)
LoadingMask.SetActive(false);
}
}
public override void Init()
{
if (IsInit)
return;
IsInit = true;
SourceBinding.Action = UpdateSource;
SourceBinding.Filters = BindingFilter.Properties;
SourceBinding.FilterTypes = new[] {typeof (IEnumerable)};
}
protected void UpdateSource(object value)
{
if (OneTime && IsLoaded)
return;
if (DelayLoad)
StartCoroutine(BindAsync(value));
else
Bind(value);
}
private IEnumerator BindAsync(object data)
{
yield return 1;
Bind(data);
}
/// <summary>
/// Bind the ObservableCollection
/// </summary>
/// <param name="data"></param>
public void Bind(object data)
{
if (DataList != null)
{
DataList.OnObjectAdd -= OnAdd;
DataList.OnObjectInsert -= OnInsert;
DataList.OnClear -= OnClear;
DataList.OnObjectRemove -= OnRemove;
}
foreach (var item in Children)
{
item.DataInstance = null;
Recycle(item.gameObject);
}
DataList = null;
OnClear();
StopAllCoroutines();
if (data is IObservableCollection)
{
DataList = data as IObservableCollection;
StartCoroutine(AddAsync(DataList.GetObjects()));
DataList.OnObjectAdd += OnAdd;
DataList.OnObjectInsert += OnInsert;
DataList.OnClear += OnClear;
DataList.OnObjectRemove += OnRemove;
IsLoaded = true;
}
else if (data is IEnumerable)
{
var a = data as IEnumerable;
StartCoroutine(AddAsync(a.Cast<object>()));
IsLoaded = true;
}
}
private void OnClear()
{
foreach (var item in Children)
{
item.DataInstance = null;
Recycle(item.gameObject);
}
Children.Clear();
IsLoaded = false;
}
private void OnRemove(object obj)
{
var view = Children.FirstOrDefault(o => o.DataInstance == obj);
if (view != null)
{
view.DataInstance = null;
Children.Remove(view);
Recycle(view.gameObject);
}
}
private void OnAdd(object obj)
{
var view = GetNext();
var root = view.GetComponent<BindingContext>();
root.DataInstance = obj;
view.name = "_Item " + Index++;
Children.Add(root);
if (SetAsFirstSibling)
view.transform.SetAsFirstSibling();
}
private void OnInsert(int location, object obj)
{
var view = GetNext();
var root = view.GetComponent<BindingContext>();
root.DataInstance = obj;
view.name = "_Item " + Index++;
Children.Insert(location, root);
if (SetAsFirstSibling)
view.transform.SetSiblingIndex(location);
}
private IEnumerator AddAsync(IEnumerable<object> objects)
{
if (LoadingMask)
LoadingMask.SetActive(true);
foreach (var obj in objects)
{
OnAdd(obj);
}
if (LoadingMask)
LoadingMask.SetActive(false);
yield return 1;
}
private GameObject GetNext()
{
if (RectTransform && RectTransform2)
{
//var next = Instantiate(Prefab, RectTransform.position, RectTransform.rotation) as GameObject;
//var rect = next.GetComponent<RectTransform>();
//rect.parent = RectTransform;
//// idk, scale sometimes goes wierd
//rect.localScale = RectTransform2.localScale;
//next.SetActive(true);
//return next;
var next = Instantiate(Prefab, RectTransform.position, RectTransform.rotation) as GameObject;
next.transform.SetParent(RectTransform);
// idk, scale sometimes goes wierd
next.transform.localScale = RectTransform2.localScale;
next.SetActive(true);
return next;
}
else
{
var next = Instantiate(Prefab, transform.position, transform.rotation) as GameObject;
next.transform.SetParent(RectTransform);
// idk, scale sometimes goes wierd
next.transform.localScale = Prefab.transform.localScale;
next.SetActive(true);
return next;
}
}
private void Recycle(GameObject instance)
{
Destroy(instance);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xunit.Performance;
using Microsoft.Xunit.Performance.Api;
using Xunit;
using Xunit.Abstractions;
namespace LinkBench
{
public class Benchmark
{
public string Name;
public string UnlinkedDir;
public string LinkedDir;
public double UnlinkedMsilSize;
public double LinkedMsilSize;
public double UnlinkedDirSize;
public double LinkedDirSize;
public double MsilSizeReduction;
public double DirSizeReduction;
private DirectoryInfo unlinkedDirInfo;
private DirectoryInfo linkedDirInfo;
private double certDiff;
const double MB = 1024 * 1024;
public Benchmark(string _Name, string _UnlinkedDir, string _LinkedDir)
{
Name = _Name;
UnlinkedDir = _UnlinkedDir;
LinkedDir = _LinkedDir;
unlinkedDirInfo = new DirectoryInfo(UnlinkedDir);
linkedDirInfo = new DirectoryInfo(LinkedDir);
}
public void Compute()
{
ComputeCertDiff();
UnlinkedMsilSize = GetMSILSize(UnlinkedDir);
LinkedMsilSize = GetMSILSize(LinkedDir);
UnlinkedDirSize = GetDirSize(unlinkedDirInfo);
LinkedDirSize = GetDirSize(linkedDirInfo);
MsilSizeReduction = (UnlinkedMsilSize - LinkedMsilSize) / UnlinkedMsilSize * 100;
DirSizeReduction = (UnlinkedDirSize - LinkedDirSize) / UnlinkedDirSize * 100;
}
// Compute total size of a directory, in MegaBytes
// Includes all files and subdirectories recursively
private double GetDirSize(DirectoryInfo dir)
{
double size = 0;
FileInfo[] files = dir.GetFiles();
foreach (FileInfo fileInfo in files)
{
size += fileInfo.Length;
}
DirectoryInfo[] subDirs = dir.GetDirectories();
foreach (DirectoryInfo dirInfo in subDirs)
{
size += GetDirSize(dirInfo);
}
return size / MB;
}
// Compute the size of MSIL files in a directory, in MegaBytes
// Top level only, excludes crossgen files.
private double GetMSILSize(string dir)
{
string[] files = Directory.GetFiles(dir);
long msilSize = 0;
foreach (string file in files)
{
if (file.EndsWith(".ni.dll") || file.EndsWith(".ni.exe"))
{
continue;
}
try
{
AssemblyLoadContext.GetAssemblyName(file);
}
catch (BadImageFormatException)
{
continue;
}
msilSize += new FileInfo(file).Length;
}
return msilSize / MB;
}
// Gets the size of the Certificate header in a MSIL or ReadyToRun binary.
private long GetCertSize(string file)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = LinkBench.ScriptDir + "GetCert.cmd";
p.StartInfo.Arguments = file;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
long size = Int32.Parse(output.Substring(18, 8),
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.HexNumber);
return size;
}
// Get the total size difference for all certificates in all managed binaries
// in the unlinked and linked directories.
private double ComputeCertDiff()
{
string[] files = Directory.GetFiles(LinkedDir);
long totalDiff = 0;
foreach (string file in files)
{
try
{
AssemblyLoadContext.GetAssemblyName(file);
}
catch (BadImageFormatException)
{
continue;
}
FileInfo fileInfo = new FileInfo(file);
long linkedCert = GetCertSize(file);
long unlinkedCert = GetCertSize(UnlinkedDir + "\\" + fileInfo.Name);
totalDiff += (unlinkedCert - linkedCert);
}
return totalDiff / MB;
}
}
public class LinkBench
{
private static ScenarioConfiguration scenarioConfiguration = new ScenarioConfiguration(new TimeSpan(2000000));
private static MetricModel SizeMetric = new MetricModel { Name = "Size", DisplayName = "File Size", Unit = "MB" };
private static MetricModel PercMetric = new MetricModel { Name = "Perc", DisplayName = "% Reduction", Unit = "%" };
public static string Workspace;
public static string ScriptDir;
public static string AssetsDir;
private static Benchmark CurrentBenchmark;
public static int Main(String [] args)
{
// Workspace is the ROOT of the coreclr tree.
// If CORECLR_REPO is not set, the script assumes that the location of sandbox
// is <path>\coreclr\sandbox.
bool doClone = true;
bool doBuild = true;
for(int i=0; i < args.Length; i++)
{
if (String.Compare(args[i], "noclone", true) == 0)
{
doClone = false;
}
else if (String.Compare(args[i], "nobuild", true) == 0)
{
doClone = false;
doBuild = false;
}
else
{
Console.WriteLine("Unknown argument");
return -4;
}
}
Workspace = Environment.GetEnvironmentVariable("CORECLR_REPO");
if (Workspace == null)
{
Workspace = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
}
if (Workspace == null)
{
Console.WriteLine("CORECLR_REPO not found");
return -1;
}
string LinkBenchDir = Workspace + "\\tests\\src\\performance\\linkbench\\";
ScriptDir = LinkBenchDir + "scripts\\";
AssetsDir = LinkBenchDir + "assets\\";
Benchmark[] Benchmarks =
{
new Benchmark("HelloWorld",
"LinkBench\\HelloWorld\\bin\\release\\netcoreapp2.0\\win10-x64\\publish",
"LinkBench\\HelloWorld\\bin\\release\\netcoreapp2.0\\win10-x64\\linked"),
new Benchmark("WebAPI",
"LinkBench\\WebAPI\\bin\\release\\netcoreapp2.0\\win10-x64\\publish",
"LinkBench\\WebAPI\\bin\\release\\netcoreapp2.0\\win10-x64\\linked"),
new Benchmark("MusicStore",
"LinkBench\\JitBench\\src\\MusicStore\\bin\\release\\netcoreapp2.0\\win10-x64\\publish",
"LinkBench\\JitBench\\src\\MusicStore\\bin\\release\\netcoreapp2.0\\win10-x64\\linked"),
new Benchmark("MusicStore_R2R",
"LinkBench\\JitBench\\src\\MusicStore\\bin\\release\\netcoreapp2.0\\win10-x64\\publish_r2r",
"LinkBench\\JitBench\\src\\MusicStore\\bin\\release\\netcoreapp2.0\\win10-x64\\linked_r2r"),
new Benchmark("Corefx",
"LinkBench\\corefx\\bin\\ILLinkTrimAssembly\\netcoreapp-Windows_NT-Release-x64\\pretrimmed",
"LinkBench\\corefx\\bin\\ILLinkTrimAssembly\\netcoreapp-Windows_NT-Release-x64\\trimmed"),
new Benchmark("Roslyn",
"LinkBench\\roslyn\\Binaries\\Release\\Exes\\CscCore",
"LinkBench\\roslyn\\Binaries\\Release\\Exes\\Linked"),
};
// Update the build files to facilitate the link step
if(doClone)
{
if(!Setup())
{
return -2;
}
}
if (doBuild)
{
// Run the setup Script, which clones, builds and links the benchmarks.
using (var setup = new Process())
{
setup.StartInfo.FileName = ScriptDir + "build.cmd";
setup.StartInfo.Arguments = AssetsDir;
setup.Start();
setup.WaitForExit();
if (setup.ExitCode != 0)
{
Console.WriteLine("Setup failed");
return -3;
}
}
}
// Since this is a size measurement scenario, there are no iterations
// to perform. So, create a process that does nothing, to satisfy XUnit.
// All size measurements are performed PostRun()
var emptyCmd = new ProcessStartInfo()
{
FileName = ScriptDir + "empty.cmd"
};
for (int i = 0; i < Benchmarks.Length; i++)
{
CurrentBenchmark = Benchmarks[i];
string[] scriptArgs = { "--perf:runid", CurrentBenchmark.Name };
using (var h = new XunitPerformanceHarness(scriptArgs))
{
h.RunScenario(emptyCmd, null, null, PostRun, scenarioConfiguration);
}
}
return 0;
}
private static ScenarioBenchmark PostRun()
{
// The XUnit output doesn't print the benchmark name, so print it now.
Console.WriteLine("{0}", CurrentBenchmark.Name);
var scenario = new ScenarioBenchmark(CurrentBenchmark.Name)
{
Namespace = "LinkBench"
};
CurrentBenchmark.Compute();
addMeasurement(ref scenario, "MSIL Unlinked", SizeMetric, CurrentBenchmark.UnlinkedMsilSize);
addMeasurement(ref scenario, "MSIL Linked", SizeMetric, CurrentBenchmark.LinkedMsilSize);
addMeasurement(ref scenario, "MSIL %Reduction", PercMetric, CurrentBenchmark.MsilSizeReduction);
addMeasurement(ref scenario, "Total Uninked", SizeMetric, CurrentBenchmark.UnlinkedDirSize);
addMeasurement(ref scenario, "Total Linked", SizeMetric, CurrentBenchmark.LinkedDirSize);
addMeasurement(ref scenario, "Total %Reduction", PercMetric, CurrentBenchmark.DirSizeReduction);
return scenario;
}
private static bool Setup()
{
// Clone the benchmarks
using (var setup = new Process())
{
setup.StartInfo.FileName = ScriptDir + "clone.cmd";
Console.WriteLine("Run {0}", setup.StartInfo.FileName);
setup.Start();
setup.WaitForExit();
if (setup.ExitCode != 0)
{
Console.WriteLine("clone failed");
return false;
}
}
//Update the project files
AddLinkerReference("LinkBench\\HelloWorld\\HelloWorld.csproj");
AddLinkerReference("LinkBench\\WebAPI\\WebAPI.csproj");
AddLinkerReference("LinkBench\\JitBench\\src\\MusicStore\\MusicStore.csproj");
RemoveCrossgenTarget("LinkBench\\JitBench\\src\\MusicStore\\MusicStore.csproj");
return true;
}
private static void AddLinkerReference(string csproj)
{
var xdoc = XDocument.Load(csproj);
var ns = xdoc.Root.GetDefaultNamespace();
bool added = false;
foreach (var el in xdoc.Root.Elements(ns + "ItemGroup"))
{
if (el.Elements(ns + "PackageReference").Any())
{
el.Add(new XElement(ns + "PackageReference",
new XAttribute("Include", "ILLink.Tasks"),
new XAttribute("Version", "0.1.0-preview")));
added = true;
break;
}
}
if (!added)
{
xdoc.Root.Add(new XElement(ns + "ItemGroup",
new XElement(ns + "PackageReference",
new XAttribute("Include", "ILLink.Tasks"),
new XAttribute("Version", "0.1.0-preview"))));
added = true;
}
using (var fs = new FileStream(csproj, FileMode.Create))
{
xdoc.Save(fs);
}
}
private static void RemoveCrossgenTarget(string csproj)
{
var xdoc = XDocument.Load(csproj);
var ns = xdoc.Root.GetDefaultNamespace();
var target = xdoc.Root.Element(ns + "Target");
target.Remove();
using (var fs = new FileStream(csproj, FileMode.Create))
{
xdoc.Save(fs);
}
}
private static void addMeasurement(ref ScenarioBenchmark scenario, string name, MetricModel metric, double value)
{
var iteration = new IterationModel
{
Iteration = new Dictionary<string, double>()
};
iteration.Iteration.Add(metric.Name, value);
var size = new ScenarioTestModel(name);
size.Performance.Metrics.Add(metric);
size.Performance.IterationModels.Add(iteration);
scenario.Tests.Add(size);
}
}
}
| |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass(typeof(global::java.lang.ClassLoader_))]
public abstract partial class ClassLoader : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ClassLoader()
{
InitJNI();
}
protected ClassLoader(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _loadClass12884;
protected virtual global::java.lang.Class loadClass(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._loadClass12884, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._loadClass12884, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _loadClass12885;
public virtual global::java.lang.Class loadClass(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._loadClass12885, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._loadClass12885, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _getSystemClassLoader12886;
public static global::java.lang.ClassLoader getSystemClassLoader()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getSystemClassLoader12886)) as java.lang.ClassLoader;
}
internal static global::MonoJavaBridge.MethodId _getPackage12887;
protected virtual global::java.lang.Package getPackage(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._getPackage12887, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Package;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getPackage12887, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Package;
}
internal static global::MonoJavaBridge.MethodId _setSigners12888;
protected virtual void setSigners(java.lang.Class arg0, java.lang.Object[] arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ClassLoader._setSigners12888, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._setSigners12888, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getResourceAsStream12889;
public virtual global::java.io.InputStream getResourceAsStream(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._getResourceAsStream12889, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.InputStream;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getResourceAsStream12889, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.InputStream;
}
internal static global::MonoJavaBridge.MethodId _getResource12890;
public virtual global::java.net.URL getResource(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._getResource12890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.net.URL;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getResource12890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.net.URL;
}
internal static global::MonoJavaBridge.MethodId _getSystemResourceAsStream12891;
public static global::java.io.InputStream getSystemResourceAsStream(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getSystemResourceAsStream12891, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.InputStream;
}
internal static global::MonoJavaBridge.MethodId _getSystemResource12892;
public static global::java.net.URL getSystemResource(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getSystemResource12892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.net.URL;
}
internal static global::MonoJavaBridge.MethodId _findClass12893;
protected virtual global::java.lang.Class findClass(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._findClass12893, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._findClass12893, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _defineClass12894;
protected virtual global::java.lang.Class defineClass(java.lang.String arg0, byte[] arg1, int arg2, int arg3, java.security.ProtectionDomain arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._defineClass12894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._defineClass12894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _defineClass12895;
protected virtual global::java.lang.Class defineClass(java.lang.String arg0, java.nio.ByteBuffer arg1, java.security.ProtectionDomain arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._defineClass12895, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._defineClass12895, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _defineClass12896;
protected virtual global::java.lang.Class defineClass(java.lang.String arg0, byte[] arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._defineClass12896, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._defineClass12896, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _defineClass12897;
protected virtual global::java.lang.Class defineClass(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._defineClass12897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._defineClass12897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _resolveClass12898;
protected virtual void resolveClass(java.lang.Class arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ClassLoader._resolveClass12898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._resolveClass12898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _findSystemClass12899;
protected virtual global::java.lang.Class findSystemClass(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._findSystemClass12899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._findSystemClass12899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _findLoadedClass12900;
protected virtual global::java.lang.Class findLoadedClass(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._findLoadedClass12900, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._findLoadedClass12900, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
}
internal static global::MonoJavaBridge.MethodId _getResources12901;
public virtual global::java.util.Enumeration getResources(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._getResources12901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.Enumeration;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getResources12901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.Enumeration;
}
internal static global::MonoJavaBridge.MethodId _findResource12902;
protected virtual global::java.net.URL findResource(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._findResource12902, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.net.URL;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._findResource12902, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.net.URL;
}
internal static global::MonoJavaBridge.MethodId _findResources12903;
protected virtual global::java.util.Enumeration findResources(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._findResources12903, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.Enumeration;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._findResources12903, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.Enumeration;
}
internal static global::MonoJavaBridge.MethodId _getSystemResources12904;
public static global::java.util.Enumeration getSystemResources(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallStaticObjectMethod(java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getSystemResources12904, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.Enumeration;
}
internal static global::MonoJavaBridge.MethodId _getParent12905;
public virtual global::java.lang.ClassLoader getParent()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._getParent12905)) as java.lang.ClassLoader;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getParent12905)) as java.lang.ClassLoader;
}
internal static global::MonoJavaBridge.MethodId _definePackage12906;
protected virtual global::java.lang.Package definePackage(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4, java.lang.String arg5, java.lang.String arg6, java.net.URL arg7)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._definePackage12906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7))) as java.lang.Package;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._definePackage12906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7))) as java.lang.Package;
}
internal static global::MonoJavaBridge.MethodId _getPackages12907;
protected virtual global::java.lang.Package[] getPackages()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Package>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._getPackages12907)) as java.lang.Package[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Package>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._getPackages12907)) as java.lang.Package[];
}
internal static global::MonoJavaBridge.MethodId _findLibrary12908;
protected virtual global::java.lang.String findLibrary(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.ClassLoader._findLibrary12908, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._findLibrary12908, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setDefaultAssertionStatus12909;
public virtual void setDefaultAssertionStatus(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ClassLoader._setDefaultAssertionStatus12909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._setDefaultAssertionStatus12909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPackageAssertionStatus12910;
public virtual void setPackageAssertionStatus(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ClassLoader._setPackageAssertionStatus12910, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._setPackageAssertionStatus12910, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setClassAssertionStatus12911;
public virtual void setClassAssertionStatus(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ClassLoader._setClassAssertionStatus12911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._setClassAssertionStatus12911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _clearAssertionStatus12912;
public virtual void clearAssertionStatus()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.lang.ClassLoader._clearAssertionStatus12912);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._clearAssertionStatus12912);
}
internal static global::MonoJavaBridge.MethodId _ClassLoader12913;
protected ClassLoader(java.lang.ClassLoader arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._ClassLoader12913, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ClassLoader12914;
protected ClassLoader() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.ClassLoader.staticClass, global::java.lang.ClassLoader._ClassLoader12914);
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.ClassLoader.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/ClassLoader"));
global::java.lang.ClassLoader._loadClass12884 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "loadClass", "(Ljava/lang/String;Z)Ljava/lang/Class;");
global::java.lang.ClassLoader._loadClass12885 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
global::java.lang.ClassLoader._getSystemClassLoader12886 = @__env.GetStaticMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getSystemClassLoader", "()Ljava/lang/ClassLoader;");
global::java.lang.ClassLoader._getPackage12887 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getPackage", "(Ljava/lang/String;)Ljava/lang/Package;");
global::java.lang.ClassLoader._setSigners12888 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "setSigners", "(Ljava/lang/Class;[Ljava/lang/Object;)V");
global::java.lang.ClassLoader._getResourceAsStream12889 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getResourceAsStream", "(Ljava/lang/String;)Ljava/io/InputStream;");
global::java.lang.ClassLoader._getResource12890 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getResource", "(Ljava/lang/String;)Ljava/net/URL;");
global::java.lang.ClassLoader._getSystemResourceAsStream12891 = @__env.GetStaticMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getSystemResourceAsStream", "(Ljava/lang/String;)Ljava/io/InputStream;");
global::java.lang.ClassLoader._getSystemResource12892 = @__env.GetStaticMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getSystemResource", "(Ljava/lang/String;)Ljava/net/URL;");
global::java.lang.ClassLoader._findClass12893 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
global::java.lang.ClassLoader._defineClass12894 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "defineClass", "(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;");
global::java.lang.ClassLoader._defineClass12895 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "defineClass", "(Ljava/lang/String;Ljava/nio/ByteBuffer;Ljava/security/ProtectionDomain;)Ljava/lang/Class;");
global::java.lang.ClassLoader._defineClass12896 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "defineClass", "(Ljava/lang/String;[BII)Ljava/lang/Class;");
global::java.lang.ClassLoader._defineClass12897 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "defineClass", "([BII)Ljava/lang/Class;");
global::java.lang.ClassLoader._resolveClass12898 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "resolveClass", "(Ljava/lang/Class;)V");
global::java.lang.ClassLoader._findSystemClass12899 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "findSystemClass", "(Ljava/lang/String;)Ljava/lang/Class;");
global::java.lang.ClassLoader._findLoadedClass12900 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "findLoadedClass", "(Ljava/lang/String;)Ljava/lang/Class;");
global::java.lang.ClassLoader._getResources12901 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getResources", "(Ljava/lang/String;)Ljava/util/Enumeration;");
global::java.lang.ClassLoader._findResource12902 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "findResource", "(Ljava/lang/String;)Ljava/net/URL;");
global::java.lang.ClassLoader._findResources12903 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "findResources", "(Ljava/lang/String;)Ljava/util/Enumeration;");
global::java.lang.ClassLoader._getSystemResources12904 = @__env.GetStaticMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getSystemResources", "(Ljava/lang/String;)Ljava/util/Enumeration;");
global::java.lang.ClassLoader._getParent12905 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getParent", "()Ljava/lang/ClassLoader;");
global::java.lang.ClassLoader._definePackage12906 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "definePackage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/net/URL;)Ljava/lang/Package;");
global::java.lang.ClassLoader._getPackages12907 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "getPackages", "()[Ljava/lang/Package;");
global::java.lang.ClassLoader._findLibrary12908 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "findLibrary", "(Ljava/lang/String;)Ljava/lang/String;");
global::java.lang.ClassLoader._setDefaultAssertionStatus12909 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "setDefaultAssertionStatus", "(Z)V");
global::java.lang.ClassLoader._setPackageAssertionStatus12910 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "setPackageAssertionStatus", "(Ljava/lang/String;Z)V");
global::java.lang.ClassLoader._setClassAssertionStatus12911 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "setClassAssertionStatus", "(Ljava/lang/String;Z)V");
global::java.lang.ClassLoader._clearAssertionStatus12912 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "clearAssertionStatus", "()V");
global::java.lang.ClassLoader._ClassLoader12913 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "<init>", "(Ljava/lang/ClassLoader;)V");
global::java.lang.ClassLoader._ClassLoader12914 = @__env.GetMethodIDNoThrow(global::java.lang.ClassLoader.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.lang.ClassLoader))]
public sealed partial class ClassLoader_ : java.lang.ClassLoader
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ClassLoader_()
{
InitJNI();
}
internal ClassLoader_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.ClassLoader_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/ClassLoader"));
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SmokePuff.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace HoneycombRush
{
/// <summary>
/// Represents a puff of smoke fired from the beekeeper's smoke gun.
/// </summary>
/// <remarks>Smoke puffs add and remove themselves from the list of game components as appropriate.</remarks>
public class SmokePuff : TexturedDrawableGameComponent
{
#region Fields/Properties
readonly TimeSpan growthTimeInterval = TimeSpan.FromMilliseconds(50);
const float growthStep = 0.05f;
TimeSpan lifeTime;
TimeSpan growthTimeTrack;
/// <summary>
/// Used to scale the smoke puff
/// </summary>
float spreadFactor;
Vector2 initialVelocity;
Vector2 velocity;
Vector2 acceleration;
Vector2 drawOrigin;
Random random = new Random();
public bool IsGone
{
get
{
return lifeTime <= TimeSpan.Zero;
}
}
bool isInGameComponents;
/// <summary>
/// Represents an area used for collision calculations.
/// </summary>
public override Rectangle CentralCollisionArea
{
get
{
int boundsWidth = (int)(texture.Width * spreadFactor * 1.5f * scaledSpriteBatch.ScaleVector.X);
int boundsHeight = (int)(texture.Height * spreadFactor * 1.5f * scaledSpriteBatch.ScaleVector.Y);
return new Rectangle((int)position.X - boundsWidth / 4, (int)position.Y - boundsHeight / 4,
boundsWidth, boundsHeight);
}
}
#endregion
#region Initialization
/// <summary>
/// Creates a new puff of smoke.
/// </summary>
/// <param name="game">Associated game object.</param>
/// <param name="gameplayScreen">The gameplay screen where the smoke puff will be displayed.</param>
/// <param name="texture">The texture which represents the smoke puff.</param>
public SmokePuff(Game game, GameplayScreen gameplayScreen, Texture2D texture)
: base(game, gameplayScreen)
{
this.texture = texture;
drawOrigin = new Vector2(texture.Width / 2, texture.Height / 2);
DrawOrder = Int32.MaxValue - 15;
}
/// <summary>
/// Fires the smoke puff from a specified position and at a specified velocity. This also adds the smoke puff
/// to the game component collection.
/// </summary>
/// <param name="origin">The position where the smoke puff should first appear.</param>
/// <param name="initialVelocity">A vector indicating the initial velocity for this new smoke puff.</param>
/// <remarks>The smoke puff's acceleration is internaly derived from
/// <paramref name="initialVelocity"/>.
/// This method is not thread safe and calling it from another thread while the smoke puff expires (via
/// its <see cref="Update"/> method) might have undesired effects.</remarks>
public void Fire(Vector2 origin, Vector2 initialVelocity)
{
spreadFactor = 0.05f;
lifeTime = TimeSpan.FromSeconds(5);
growthTimeTrack = TimeSpan.Zero;
position = origin;
velocity = initialVelocity;
this.initialVelocity = initialVelocity;
initialVelocity.Normalize();
acceleration = -(initialVelocity) * 6;
if (!isInGameComponents)
{
Game.Components.Add(this);
isInGameComponents = true;
}
}
#endregion
#region Update
/// <summary>
/// Performs update logic for the smoke puff. The smoke puff slows down while growing and eventually
/// evaporates.
/// </summary>
/// <param name="gameTime">Game time information.</param>
public override void Update(GameTime gameTime)
{
if (!gamePlayScreen.IsActive)
{
base.Update(gameTime);
return;
}
lifeTime -= gameTime.ElapsedGameTime;
// The smoke puff needs to vanish
if (lifeTime <= TimeSpan.Zero)
{
Game.Components.Remove(this);
isInGameComponents = false;
base.Update(gameTime);
return;
}
growthTimeTrack += gameTime.ElapsedGameTime;
// See if it is time for the smoke puff to grow
if ((spreadFactor < 1) && (growthTimeTrack >= growthTimeInterval))
{
growthTimeTrack = TimeSpan.Zero;
spreadFactor += growthStep;
}
// Stop the smoke once it starts moving in the other direction
if (Vector2.Dot(initialVelocity, velocity) > 0)
{
position += velocity;
velocity += acceleration * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
base.Update(gameTime);
}
#endregion
#region Render
/// <summary>
/// Draws the smoke puff.
/// </summary>
/// <param name="gameTime">Game time information.</param>
public override void Draw(GameTime gameTime)
{
if (!gamePlayScreen.IsActive)
{
base.Draw(gameTime);
return;
}
scaledSpriteBatch.Begin();
Vector2 offset = GetRandomOffset();
scaledSpriteBatch.Draw(texture, position + offset, null, Color.White, 0, drawOrigin, spreadFactor,
SpriteEffects.None, 0);
scaledSpriteBatch.End();
base.Draw(gameTime);
}
/// <summary>
/// Used to make the smoke puff shift randomly.
/// </summary>
/// <returns>An offset which should be added to the smoke puff's position.</returns>
private Vector2 GetRandomOffset()
{
return new Vector2(random.Next(2) - 4, random.Next(2) - 4);
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using NUnit.Framework;
using Newtonsoft.Json.Schema;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Text;
using Extensions=Newtonsoft.Json.Schema.Extensions;
namespace Newtonsoft.Json.Tests.Schema
{
public class JsonSchemaGeneratorTests : TestFixtureBase
{
[Test]
public void Generate_GenericDictionary()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof (Dictionary<string, List<string>>));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": [
""array"",
""null""
],
""items"": {
""type"": [
""string"",
""null""
]
}
}
}", json);
Dictionary<string, List<string>> value = new Dictionary<string, List<string>>
{
{"HasValue", new List<string>() { "first", "second", null }},
{"NoValue", null}
};
string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented);
JObject o = JObject.Parse(valueJson);
Assert.IsTrue(o.IsValid(schema));
}
#if !PocketPC
[Test]
public void Generate_DefaultValueAttributeTestClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass));
string json = schema.ToString();
Assert.AreEqual(@"{
""description"": ""DefaultValueAttributeTestClass description!"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
""TestField1"": {
""required"": true,
""type"": ""integer"",
""default"": 21
},
""TestProperty1"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""TestProperty1Value""
}
}
}", json);
}
#endif
[Test]
public void Generate_Person()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Person));
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""Person"",
""title"": ""Title!"",
""description"": ""JsonObjectAttribute description!"",
""type"": ""object"",
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""BirthDate"": {
""required"": true,
""type"": ""string""
},
""LastModified"": {
""required"": true,
""type"": ""string""
}
}
}", json);
}
[Test]
public void Generate_UserNullable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(UserNullable));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Id"": {
""required"": true,
""type"": ""string""
},
""FName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""LName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""RoleId"": {
""required"": true,
""type"": ""integer""
},
""NullableRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""NullRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""Active"": {
""required"": true,
""type"": [
""boolean"",
""null""
]
}
}
}", json);
}
[Test]
public void Generate_RequiredMembersClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(RequiredMembersClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
[Test]
public void Generate_Store()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(11, schema.Properties.Count);
JsonSchema productArraySchema = schema.Properties["product"];
JsonSchema productSchema = productArraySchema.Items[0];
Assert.AreEqual(4, productSchema.Properties.Count);
}
[Test]
public void MissingSchemaIdHandlingTest()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(null, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
schema = generator.Generate(typeof (Store));
Assert.AreEqual(typeof(Store).FullName, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void Generate_NumberFormatInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(NumberFormatInfo));
string json = schema.ToString();
Console.WriteLine(json);
// Assert.AreEqual(@"{
// ""type"": ""object"",
// ""additionalProperties"": {
// ""type"": ""array"",
// ""items"": {
// ""type"": ""string""
// }
// }
//}", json);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.")]
public void CircularReferenceError()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
}
[Test]
public void CircularReferenceWithTypeNameId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void CircularReferenceWithExplicitId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void GenerateSchemaForType()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Type));
Assert.AreEqual(JsonSchemaType.String, schema.Type);
string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented);
JValue v = new JValue(json);
Assert.IsTrue(v.IsValid(schema));
}
#if !SILVERLIGHT && !PocketPC
[Test]
public void GenerateSchemaForISerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Exception));
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(true, schema.AllowAdditionalProperties);
Assert.AreEqual(null, schema.Properties);
}
#endif
[Test]
public void GenerateSchemaForDBNull()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(DBNull));
Assert.AreEqual(JsonSchemaType.Null, schema.Type);
}
public class CustomDirectoryInfoMapper : DefaultContractResolver
{
public CustomDirectoryInfoMapper()
: base(true)
{
}
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(DirectoryInfo))
return base.CreateObjectContract(objectType);
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
JsonPropertyCollection c = new JsonPropertyCollection(type);
CollectionUtils.AddRange(c, (IEnumerable)properties.Where(m => m.PropertyName != "Root"));
return c;
}
}
[Test]
public void GenerateSchemaForDirectoryInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CustomDirectoryInfoMapper();
JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.IO.DirectoryInfo"",
""required"": true,
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Parent"": {
""$ref"": ""System.IO.DirectoryInfo""
},
""Exists"": {
""required"": true,
""type"": ""boolean""
},
""FullName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Extension"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""CreationTime"": {
""required"": true,
""type"": ""string""
},
""CreationTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastAccessTime"": {
""required"": true,
""type"": ""string""
},
""LastAccessTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastWriteTime"": {
""required"": true,
""type"": ""string""
},
""LastWriteTimeUtc"": {
""required"": true,
""type"": ""string""
},
""Attributes"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
DirectoryInfo temp = new DirectoryInfo(@"c:\temp");
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.ContractResolver = new CustomDirectoryInfoMapper();
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
}
[Test]
public void GenerateSchemaCamelCase()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CamelCasePropertyNamesContractResolver();
JsonSchema schema = generator.Generate(typeof (Version), true);
string json = schema.ToString();
Assert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""major"": {
""required"": true,
""type"": ""integer""
},
""minor"": {
""required"": true,
""type"": ""integer""
},
""build"": {
""required"": true,
""type"": ""integer""
},
""revision"": {
""required"": true,
""type"": ""integer""
},
""majorRevision"": {
""required"": true,
""type"": ""integer""
},
""minorRevision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
}
public enum SortTypeFlag
{
No = 0,
Asc = 1,
Desc = -1
}
public class X
{
public SortTypeFlag x;
}
[Test]
public void GenerateSchemaWithNegativeEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X));
string json = schema.ToString();
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""x"": {
""required"": true,
""type"": ""integer"",
""enum"": [
0,
1,
-1
],
""options"": [
{
""value"": 0,
""label"": ""No""
},
{
""value"": 1,
""label"": ""Asc""
},
{
""value"": -1,
""label"": ""Desc""
}
]
}
}
}", json);
}
[Test]
public void CircularCollectionReferences()
{
Type type = typeof (Workspace);
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type);
// should succeed
Assert.IsNotNull(jsonSchema);
}
[Test]
public void CircularReferenceWithMixedRequires()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass));
string json = jsonSchema.ToString();
Assert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"",
""type"": [
""object"",
""null""
],
""properties"": {
""Name"": {
""required"": true,
""type"": ""string""
},
""Child"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass""
}
}
}", json);
}
[Test]
public void JsonPropertyWithHandlingValues()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues));
string json = jsonSchema.ToString();
Assert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"",
""required"": true,
""type"": [
""object"",
""null""
],
""properties"": {
""DefaultValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingPopulateProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIgnoreAndPopulateProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""NullValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
]
},
""NullValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""ReferenceLoopHandlingErrorProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingIgnoreProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingSerializeProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
}
}
}", json);
}
}
public class DMDSLBase
{
public String Comment;
}
public class Workspace : DMDSLBase
{
public ControlFlowItemCollection Jobs = new ControlFlowItemCollection();
}
public class ControlFlowItemBase : DMDSLBase
{
public String Name;
}
public class ControlFlowItem : ControlFlowItemBase//A Job
{
public TaskCollection Tasks = new TaskCollection();
public ContainerCollection Containers = new ContainerCollection();
}
public class ControlFlowItemCollection : List<ControlFlowItem>
{
}
public class Task : ControlFlowItemBase
{
public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection();
public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection();
}
public class TaskCollection : List<Task>
{
}
public class Container : ControlFlowItemBase
{
public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection();
}
public class ContainerCollection : List<Container>
{
}
public class DataFlowTask_DSL : ControlFlowItemBase
{
}
public class DataFlowTaskCollection : List<DataFlowTask_DSL>
{
}
public class SequenceContainer_DSL : Container
{
}
public class BulkInsertTaskCollection : List<BulkInsertTask_DSL>
{
}
public class BulkInsertTask_DSL
{
}
}
| |
// 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.IO;
using System.Text;
using System.Xml.Schema;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Xml
{
// Specifies the state of the XmlWriter.
public enum WriteState
{
// Nothing has been written yet.
Start,
// Writing the prolog.
Prolog,
// Writing a the start tag for an element.
Element,
// Writing an attribute value.
Attribute,
// Writing element content.
Content,
// XmlWriter is closed; Close has been called.
Closed,
// Writer is in error state.
Error,
};
// Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents
// that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification.
public abstract partial class XmlWriter : IDisposable
{
// Helper buffer for WriteNode(XmlReader, bool)
private char[] _writeNodeBuffer;
// Constants
private const int WriteNodeBufferSize = 1024;
// Returns the settings describing the features of the the writer. Returns null for V1 XmlWriters (XmlTextWriter).
public virtual XmlWriterSettings Settings
{
get
{
return null;
}
}
// Write methods
// Writes out the XML declaration with the version "1.0".
public abstract void WriteStartDocument();
//Writes out the XML declaration with the version "1.0" and the speficied standalone attribute.
public abstract void WriteStartDocument(bool standalone);
//Closes any open elements or attributes and puts the writer back in the Start state.
public abstract void WriteEndDocument();
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public abstract void WriteDocType(string name, string pubid, string sysid, string subset);
// Writes out the specified start tag and associates it with the given namespace.
public void WriteStartElement(string localName, string ns)
{
WriteStartElement(null, localName, ns);
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public abstract void WriteStartElement(string prefix, string localName, string ns);
// Writes out a start tag with the specified local name with no namespace.
public void WriteStartElement(string localName)
{
WriteStartElement(null, localName, (string)null);
}
// Closes one element and pops the corresponding namespace scope.
public abstract void WriteEndElement();
// Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>.
public abstract void WriteFullEndElement();
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
public void WriteAttributeString(string localName, string ns, string value)
{
WriteStartAttribute(null, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified LocalName and value.
public void WriteAttributeString(string localName, string value)
{
WriteStartAttribute(null, localName, (string)null);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
public void WriteAttributeString(string prefix, string localName, string ns, string value)
{
WriteStartAttribute(prefix, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes the start of an attribute.
public void WriteStartAttribute(string localName, string ns)
{
WriteStartAttribute(null, localName, ns);
}
// Writes the start of an attribute.
public abstract void WriteStartAttribute(string prefix, string localName, string ns);
// Writes the start of an attribute.
public void WriteStartAttribute(string localName)
{
WriteStartAttribute(null, localName, (string)null);
}
// Closes the attribute opened by WriteStartAttribute call.
public abstract void WriteEndAttribute();
// Writes out a <![CDATA[...]]>; block containing the specified text.
public abstract void WriteCData(string text);
// Writes out a comment <!--...-->; containing the specified text.
public abstract void WriteComment(string text);
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public abstract void WriteProcessingInstruction(string name, string text);
// Writes out an entity reference as follows: "&"+name+";".
public abstract void WriteEntityRef(string name);
// Forces the generation of a character entity for the specified Unicode character value.
public abstract void WriteCharEntity(char ch);
// Writes out the given whitespace.
public abstract void WriteWhitespace(string ws);
// Writes out the specified text content.
public abstract void WriteString(string text);
// Write out the given surrogate pair as an entity reference.
public abstract void WriteSurrogateCharEntity(char lowChar, char highChar);
// Writes out the specified text content.
public abstract void WriteChars(char[] buffer, int index, int count);
// Writes raw markup from the given character buffer.
public abstract void WriteRaw(char[] buffer, int index, int count);
// Writes raw markup from the given string.
public abstract void WriteRaw(string data);
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public abstract void WriteBase64(byte[] buffer, int index, int count);
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public virtual void WriteBinHex(byte[] buffer, int index, int count)
{
BinHexEncoder.Encode(buffer, index, count, this);
}
// Returns the state of the XmlWriter.
public abstract WriteState WriteState { get; }
// Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader.
public abstract void Flush();
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
public abstract string LookupPrefix(string ns);
// Gets an XmlSpace representing the current xml:space scope.
public virtual XmlSpace XmlSpace
{
get
{
return XmlSpace.Default;
}
}
// Gets the current xml:lang scope.
public virtual string XmlLang
{
get
{
return string.Empty;
}
}
// Scalar Value Methods
// Writes out the specified name, ensuring it is a valid NmToken according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteNmToken(string name)
{
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException));
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteName(string name)
{
WriteString(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException));
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public virtual void WriteQualifiedName(string localName, string ns)
{
if (ns != null && ns.Length > 0)
{
string prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
WriteString(prefix);
WriteString(":");
}
WriteString(localName);
}
// Writes out the specified value.
public virtual void WriteValue(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
WriteString(XmlUntypedStringConverter.Instance.ToString(value, null));
}
// Writes out the specified value.
public virtual void WriteValue(string value)
{
if (value == null)
{
return;
}
WriteString(value);
}
// Writes out the specified value.
public virtual void WriteValue(bool value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
internal virtual void WriteValue(DateTime value)
{
WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind));
}
// Writes out the specified value.
public virtual void WriteValue(DateTimeOffset value)
{
// Under Win8P, WriteValue(DateTime) will invoke this overload, but custom writers
// might not have implemented it. This base implementation should call WriteValue(DateTime).
// The following conversion results in the same string as calling ToString with DateTimeOffset.
if (value.Offset != TimeSpan.Zero)
{
WriteValue(value.LocalDateTime);
}
else
{
WriteValue(value.UtcDateTime);
}
}
// Writes out the specified value.
public virtual void WriteValue(double value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(float value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(decimal value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(int value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(long value)
{
WriteString(XmlConvert.ToString(value));
}
// XmlReader Helper Methods
// Writes out all the attributes found at the current position in the specified XmlReader.
public virtual void WriteAttributes(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration)
{
if (reader.MoveToFirstAttribute())
{
WriteAttributes(reader, defattr);
reader.MoveToElement();
}
}
else if (reader.NodeType != XmlNodeType.Attribute)
{
throw new XmlException(SR.Xml_InvalidPosition, string.Empty);
}
else
{
do
{
// we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault.
// If either of these is true and defattr=false, we should not write the attribute out
if (defattr || !reader.IsDefaultInternal)
{
WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
WriteEntityRef(reader.Name);
}
else
{
WriteString(reader.Value);
}
}
WriteEndAttribute();
}
}
while (reader.MoveToNextAttribute());
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
public virtual void WriteNode(XmlReader reader, bool defattr)
{
if (null == reader)
{
throw new ArgumentNullException(nameof(reader));
}
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
WriteAttributes(reader, defattr);
if (reader.IsEmptyElement)
{
WriteEndElement();
break;
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
if (_writeNodeBuffer == null)
{
_writeNodeBuffer = new char[WriteNodeBufferSize];
}
int read;
while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
this.WriteChars(_writeNodeBuffer, 0, read);
}
}
else
{
WriteString(reader.Value);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
WriteWhitespace(reader.Value);
break;
case XmlNodeType.CDATA:
WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
break;
case XmlNodeType.Comment:
WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
WriteFullEndElement();
break;
}
} while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Element Helper Methods
// Writes out an element with the specified name containing the specified string value.
public void WriteElementString(string localName, String value)
{
WriteElementString(localName, null, value);
}
// Writes out an attribute with the specified name, namespace URI and string value.
public void WriteElementString(string localName, String ns, String value)
{
WriteStartElement(localName, ns);
if (null != value && 0 != value.Length)
{
WriteString(value);
}
WriteEndElement();
}
// Writes out an attribute with the specified name, namespace URI, and string value.
public void WriteElementString(string prefix, String localName, String ns, String value)
{
WriteStartElement(prefix, localName, ns);
if (null != value && 0 != value.Length)
{
WriteString(value);
}
WriteEndElement();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
}
//
// Static methods for creating writers
//
// Creates an XmlWriter for writing into the provided stream.
public static XmlWriter Create(Stream output)
{
return Create(output, null);
}
// Creates an XmlWriter for writing into the provided stream with the specified settings.
public static XmlWriter Create(Stream output, XmlWriterSettings settings)
{
if (settings == null)
{
settings = new XmlWriterSettings();
}
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided TextWriter.
public static XmlWriter Create(TextWriter output)
{
return Create(output, null);
}
// Creates an XmlWriter for writing into the provided TextWriter with the specified settings.
public static XmlWriter Create(TextWriter output, XmlWriterSettings settings)
{
if (settings == null)
{
settings = new XmlWriterSettings();
}
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided StringBuilder.
public static XmlWriter Create(StringBuilder output)
{
return Create(output, null);
}
// Creates an XmlWriter for writing into the provided StringBuilder with the specified settings.
public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings)
{
if (settings == null)
{
settings = new XmlWriterSettings();
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture));
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the default settings.
public static XmlWriter Create(XmlWriter output)
{
return Create(output, null);
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings.
public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings)
{
if (settings == null)
{
settings = new XmlWriterSettings();
}
return settings.CreateWriter(output);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Validation;
using BCL = System.Collections.Generic;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable unordered dictionary implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<,>))]
public sealed partial class ImmutableDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IImmutableDictionaryInternal<TKey, TValue>, IHashKeyCollection<TKey>, IDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// An empty immutable dictionary with default equality comparers.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableDictionary<TKey, TValue> Empty = new ImmutableDictionary<TKey, TValue>();
/// <summary>
/// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen.
/// </summary>
private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = (kv) => kv.Value.Freeze();
/// <summary>
/// The number of elements in the collection.
/// </summary>
private readonly int _count;
/// <summary>
/// The root node of the tree that stores this map.
/// </summary>
private readonly SortedInt32KeyNode<HashBucket> _root;
/// <summary>
/// The comparer used when comparing hash buckets.
/// </summary>
private readonly Comparers _comparers;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="root">The root.</param>
/// <param name="comparers">The comparers.</param>
/// <param name="count">The number of elements in the map.</param>
private ImmutableDictionary(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count)
: this(Requires.NotNullPassthrough(comparers, "comparers"))
{
Requires.NotNull(root, "root");
root.Freeze(s_FreezeBucketAction);
_root = root;
_count = count;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="comparers">The comparers.</param>
private ImmutableDictionary(Comparers comparers = null)
{
_comparers = comparers ?? Comparers.Get(EqualityComparer<TKey>.Default, EqualityComparer<TValue>.Default);
_root = SortedInt32KeyNode<HashBucket>.EmptyNode;
}
/// <summary>
/// How to respond when a key collision is discovered.
/// </summary>
internal enum KeyCollisionBehavior
{
/// <summary>
/// Sets the value for the given key, even if that overwrites an existing value.
/// </summary>
SetValue,
/// <summary>
/// Skips the mutating operation if a key conflict is detected.
/// </summary>
Skip,
/// <summary>
/// Throw an exception if the key already exists with a different key.
/// </summary>
ThrowIfValueDifferent,
/// <summary>
/// Throw an exception if the key already exists regardless of its value.
/// </summary>
ThrowAlways,
}
/// <summary>
/// The result of a mutation operation.
/// </summary>
internal enum OperationResult
{
/// <summary>
/// The change was applied and did not require a change to the number of elements in the collection.
/// </summary>
AppliedWithoutSizeChange,
/// <summary>
/// The change required element(s) to be added or removed from the collection.
/// </summary>
SizeChanged,
/// <summary>
/// No change was required (the operation ended in a no-op).
/// </summary>
NoChangeRequired,
}
#region Public Properties
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public ImmutableDictionary<TKey, TValue> Clear()
{
return this.IsEmpty ? this : EmptyWithComparers(_comparers);
}
/// <summary>
/// Gets the number of elements in this collection.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return this.Count == 0; }
}
/// <summary>
/// Gets the key comparer.
/// </summary>
public IEqualityComparer<TKey> KeyComparer
{
get { return _comparers.KeyComparer; }
}
/// <summary>
/// Gets the value comparer used to determine whether values are equal.
/// </summary>
public IEqualityComparer<TValue> ValueComparer
{
get { return _comparers.ValueComparer; }
}
/// <summary>
/// Gets the keys in the map.
/// </summary>
public IEnumerable<TKey> Keys
{
get
{
foreach (var bucket in _root)
{
foreach (var item in bucket.Value)
{
yield return item.Key;
}
}
}
}
/// <summary>
/// Gets the values in the map.
/// </summary>
public IEnumerable<TValue> Values
{
get
{
foreach (var bucket in _root)
{
foreach (var item in bucket.Value)
{
yield return item.Value;
}
}
}
}
#endregion
#region IImmutableDictionary<TKey,TValue> Properties
/// <summary>
/// Gets the empty instance.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
{
return this.Clear();
}
#endregion
#region IDictionary<TKey, TValue> Properties
/// <summary>
/// Gets the keys.
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets the values.
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
/// <summary>
/// Gets a data structure that captures the current state of this map, as an input into a query or mutating function.
/// </summary>
private MutationInput Origin
{
get { return new MutationInput(this); }
}
/// <summary>
/// Gets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
public TValue this[TKey key]
{
get
{
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
}
/// <summary>
/// Gets or sets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get { return this[key]; }
set { throw new NotSupportedException(); }
}
#region ICollection<KeyValuePair<TKey, TValue>> Properties
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
#endregion
#region Public methods
/// <summary>
/// Creates a collection with the same contents as this collection that
/// can be efficiently mutated across multiple operations using standard
/// mutable interfaces.
/// </summary>
/// <remarks>
/// This is an O(1) operation and results in only a single (small) memory allocation.
/// The mutable collection that is returned is *not* thread-safe.
/// </remarks>
[Pure]
public Builder ToBuilder()
{
// We must not cache the instance created here and return it to various callers.
// Those who request a mutable collection must get references to the collection
// that version independently of each other.
return new Builder(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, new MutationInput(this));
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
Requires.NotNull(pairs, "pairs");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return this.AddRange(pairs, false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
Contract.Ensures(!Contract.Result<ImmutableDictionary<TKey, TValue>>().IsEmpty);
var result = Add(key, value, KeyCollisionBehavior.SetValue, new MutationInput(this));
return result.Finalize(this);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
[Pure]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, "items");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = AddRange(items, this.Origin, KeyCollisionBehavior.SetValue);
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> Remove(TKey key)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = Remove(key, new MutationInput(this));
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
int count = _count;
var root = _root;
foreach (var key in keys)
{
int hashCode = this.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (root.TryGetValue(hashCode, out bucket))
{
OperationResult result;
var newBucket = bucket.Remove(key, _comparers.KeyOnlyComparer, out result);
root = UpdateRoot(root, hashCode, newBucket, _comparers.HashBucketEqualityComparer);
if (result == OperationResult.SizeChanged)
{
count--;
}
}
}
return this.Wrap(root, count);
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(TKey key)
{
Requires.NotNullAllowStructs(key, "key");
return ContainsKey(key, new MutationInput(this));
}
/// <summary>
/// Determines whether [contains] [the specified key value pair].
/// </summary>
/// <param name="pair">The key value pair.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified key value pair]; otherwise, <c>false</c>.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> pair)
{
return Contains(pair, this.Origin);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
Requires.NotNullAllowStructs(key, "key");
return TryGetValue(key, this.Origin, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, "equalKey");
return TryGetKey(equalKey, this.Origin, out actualKey);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
if (keyComparer == null)
{
keyComparer = EqualityComparer<TKey>.Default;
}
if (valueComparer == null)
{
valueComparer = EqualityComparer<TValue>.Default;
}
if (this.KeyComparer == keyComparer)
{
if (this.ValueComparer == valueComparer)
{
return this;
}
else
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
var comparers = _comparers.WithValueComparer(valueComparer);
return new ImmutableDictionary<TKey, TValue>(_root, comparers, _count);
}
}
else
{
var comparers = Comparers.Get(keyComparer, valueComparer);
var set = new ImmutableDictionary<TKey, TValue>(comparers);
set = set.AddRange(this, avoidToHashMap: true);
return set;
}
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer)
{
return this.WithComparers(keyComparer, _comparers.ValueComparer);
}
/// <summary>
/// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
if (this.ValueComparer.Equals(value, item.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_root);
}
#endregion
#region IImmutableDictionary<TKey,TValue> Methods
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
return this.Add(key, value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
{
return this.SetItem(key, value);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return this.SetItems(items);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
return this.AddRange(pairs);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
{
return this.RemoveRange(keys);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key)
{
return this.Remove(key);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="IDictionary{TKey, TValue}"/> is read-only.
/// </exception>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="IDictionary{TKey, TValue}"/> is read-only.
/// </exception>
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException();
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Methods
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
/// <summary>
/// Gets the root node (for testing purposes).
/// </summary>
internal SortedInt32KeyNode<HashBucket> Root
{
get { return _root; }
}
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Clears this instance.
/// </summary>
/// <exception cref="System.NotSupportedException"></exception>
void IDictionary.Clear()
{
throw new NotSupportedException();
}
#endregion
#region ICollection Methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (var item in this)
{
array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++);
}
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage]
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Gets an empty collection with the specified comparers.
/// </summary>
/// <param name="comparers">The comparers.</param>
/// <returns>The empty dictionary.</returns>
[Pure]
private static ImmutableDictionary<TKey, TValue> EmptyWithComparers(Comparers comparers)
{
Requires.NotNull(comparers, "comparers");
return Empty._comparers == comparers
? Empty
: new ImmutableDictionary<TKey, TValue>(comparers);
}
/// <summary>
/// Attempts to discover an <see cref="ImmutableDictionary{TKey, TValue}"/> instance beneath some enumerable sequence
/// if one exists.
/// </summary>
/// <param name="sequence">The sequence that may have come from an immutable map.</param>
/// <param name="other">Receives the concrete <see cref="ImmutableDictionary{TKey, TValue}"/> typed value if one can be found.</param>
/// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns>
private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, out ImmutableDictionary<TKey, TValue> other)
{
other = sequence as ImmutableDictionary<TKey, TValue>;
if (other != null)
{
return true;
}
var builder = sequence as Builder;
if (builder != null)
{
other = builder.ToImmutable();
return true;
}
return false;
}
#region Static query and manipulator methods
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool ContainsKey(TKey key, MutationInput origin)
{
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
TValue value;
return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value);
}
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool Contains(KeyValuePair<TKey, TValue> keyValuePair, MutationInput origin)
{
int hashCode = origin.KeyComparer.GetHashCode(keyValuePair.Key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
TValue value;
return bucket.TryGetValue(keyValuePair.Key, origin.KeyOnlyComparer, out value)
&& origin.ValueComparer.Equals(value, keyValuePair.Value);
}
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool TryGetValue(TKey key, MutationInput origin, out TValue value)
{
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value);
}
value = default(TValue);
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static bool TryGetKey(TKey equalKey, MutationInput origin, out TKey actualKey)
{
int hashCode = origin.KeyComparer.GetHashCode(equalKey);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
return bucket.TryGetKey(equalKey, origin.KeyOnlyComparer, out actualKey);
}
actualKey = equalKey;
return false;
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static MutationResult Add(TKey key, TValue value, KeyCollisionBehavior behavior, MutationInput origin)
{
Requires.NotNullAllowStructs(key, "key");
OperationResult result;
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket = origin.Root.GetValueOrDefault(hashCode);
var newBucket = bucket.Add(key, value, origin.KeyOnlyComparer, origin.ValueComparer, behavior, out result);
if (result == OperationResult.NoChangeRequired)
{
return new MutationResult(origin);
}
var newRoot = UpdateRoot(origin.Root, hashCode, newBucket, origin.HashBucketComparer);
return new MutationResult(newRoot, result == OperationResult.SizeChanged ? +1 : 0);
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static MutationResult AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, MutationInput origin, KeyCollisionBehavior collisionBehavior = KeyCollisionBehavior.ThrowIfValueDifferent)
{
Requires.NotNull(items, "items");
int countAdjustment = 0;
var newRoot = origin.Root;
foreach (var pair in items)
{
int hashCode = origin.KeyComparer.GetHashCode(pair.Key);
HashBucket bucket = newRoot.GetValueOrDefault(hashCode);
OperationResult result;
var newBucket = bucket.Add(pair.Key, pair.Value, origin.KeyOnlyComparer, origin.ValueComparer, collisionBehavior, out result);
newRoot = UpdateRoot(newRoot, hashCode, newBucket, origin.HashBucketComparer);
if (result == OperationResult.SizeChanged)
{
countAdjustment++;
}
}
return new MutationResult(newRoot, countAdjustment);
}
/// <summary>
/// Performs the operation on a given data structure.
/// </summary>
private static MutationResult Remove(TKey key, MutationInput origin)
{
int hashCode = origin.KeyComparer.GetHashCode(key);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
OperationResult result;
var newRoot = UpdateRoot(origin.Root, hashCode, bucket.Remove(key, origin.KeyOnlyComparer, out result), origin.HashBucketComparer);
return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0);
}
return new MutationResult(origin);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket, IEqualityComparer<HashBucket> hashBucketComparer)
{
bool mutated;
if (newBucket.IsEmpty)
{
return root.Remove(hashCode, out mutated);
}
else
{
bool replacedExistingValue;
return root.SetItem(hashCode, newBucket, hashBucketComparer, out replacedExistingValue, out mutated);
}
}
#endregion
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="comparers">The comparers.</param>
/// <param name="count">The number of elements in the data structure.</param>
/// <returns>
/// The immutable collection.
/// </returns>
private static ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count)
{
Requires.NotNull(root, "root");
Requires.NotNull(comparers, "comparers");
Requires.Range(count >= 0, "count");
return new ImmutableDictionary<TKey, TValue>(root, comparers, count);
}
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param>
/// <returns>The immutable collection.</returns>
private ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot)
{
if (root == null)
{
return this.Clear();
}
if (_root != root)
{
return root.IsEmpty ? this.Clear() : new ImmutableDictionary<TKey, TValue>(root, _comparers, adjustedCountIfDifferentRoot);
}
return this;
}
/// <summary>
/// Bulk adds entries to the map.
/// </summary>
/// <param name="pairs">The entries to add.</param>
/// <param name="avoidToHashMap"><c>true</c> when being called from <see cref="WithComparers(IEqualityComparer{TKey}, IEqualityComparer{TValue})"/> to avoid <see cref="T:System.StackOverflowException"/>.</param>
[Pure]
private ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool avoidToHashMap)
{
Requires.NotNull(pairs, "pairs");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
// Some optimizations may apply if we're an empty list.
if (this.IsEmpty && !avoidToHashMap)
{
// If the items being added actually come from an ImmutableDictionary<TKey, TValue>
// then there is no value in reconstructing it.
ImmutableDictionary<TKey, TValue> other;
if (TryCastToImmutableMap(pairs, out other))
{
return other.WithComparers(this.KeyComparer, this.ValueComparer);
}
}
var result = AddRange(pairs, this.Origin);
return result.Finalize(this);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
using OpenMetaverse;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
/// <summary>
/// Version 2.02 - Still hacky
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")]
public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule, IVegetationModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commander m_commander = new Commander("tree");
private Scene m_scene;
[XmlRootAttribute(ElementName = "Copse", IsNullable = false)]
public class Copse
{
public string m_name;
public Boolean m_frozen;
public Tree m_tree_type;
public int m_tree_quantity;
public float m_treeline_low;
public float m_treeline_high;
public Vector3 m_seed_point;
public double m_range;
public Vector3 m_initial_scale;
public Vector3 m_maximum_scale;
public Vector3 m_rate;
[XmlIgnore]
public Boolean m_planted;
[XmlIgnore]
public List<UUID> m_trees;
public Copse()
{
}
public Copse(string fileName, Boolean planted)
{
Copse cp = (Copse)DeserializeObject(fileName);
this.m_name = cp.m_name;
this.m_frozen = cp.m_frozen;
this.m_tree_quantity = cp.m_tree_quantity;
this.m_treeline_high = cp.m_treeline_high;
this.m_treeline_low = cp.m_treeline_low;
this.m_range = cp.m_range;
this.m_tree_type = cp.m_tree_type;
this.m_seed_point = cp.m_seed_point;
this.m_initial_scale = cp.m_initial_scale;
this.m_maximum_scale = cp.m_maximum_scale;
this.m_initial_scale = cp.m_initial_scale;
this.m_rate = cp.m_rate;
this.m_planted = planted;
this.m_trees = new List<UUID>();
}
public Copse(string copsedef)
{
char[] delimiterChars = {':', ';'};
string[] field = copsedef.Split(delimiterChars);
this.m_name = field[1].Trim();
this.m_frozen = (copsedef[0] == 'F');
this.m_tree_quantity = int.Parse(field[2]);
this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
this.m_range = double.Parse(field[5], Culture.NumberFormatInfo);
this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
this.m_seed_point = Vector3.Parse(field[7]);
this.m_initial_scale = Vector3.Parse(field[8]);
this.m_maximum_scale = Vector3.Parse(field[9]);
this.m_rate = Vector3.Parse(field[10]);
this.m_planted = true;
this.m_trees = new List<UUID>();
}
public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List<UUID> trees)
{
this.m_name = name;
this.m_frozen = false;
this.m_tree_quantity = quantity;
this.m_treeline_high = high;
this.m_treeline_low = low;
this.m_range = range;
this.m_tree_type = type;
this.m_seed_point = point;
this.m_initial_scale = scale;
this.m_maximum_scale = max_scale;
this.m_rate = rate;
this.m_planted = false;
this.m_trees = trees;
}
public override string ToString()
{
string frozen = (this.m_frozen ? "F" : "A");
return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};",
frozen,
this.m_name,
this.m_tree_quantity,
this.m_treeline_high,
this.m_treeline_low,
this.m_range,
this.m_tree_type,
this.m_seed_point.ToString(),
this.m_initial_scale.ToString(),
this.m_maximum_scale.ToString(),
this.m_rate.ToString());
}
}
private List<Copse> m_copse;
private double m_update_ms = 1000.0; // msec between updates
private bool m_active_trees = false;
Timer CalculateTrees;
#region ICommandableModule Members
public ICommander CommandInterface
{
get { return m_commander; }
}
#endregion
#region Region Module interface
public void Initialise(IConfigSource config)
{
// ini file settings
try
{
m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
}
catch (Exception)
{
m_log.Debug("[TREES]: ini failure for active_trees - using default");
}
try
{
m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms);
}
catch (Exception)
{
m_log.Debug("[TREES]: ini failure for update_rate - using default");
}
InstallCommands();
m_log.Debug("[TREES]: Initialised tree module");
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleCommander(m_commander);
m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
ReloadCopse();
if (m_copse.Count > 0)
m_log.Info("[TREES]: Copse load complete");
if (m_active_trees)
activeizeTreeze(true);
}
public void Close()
{
}
public string Name
{
get { return "TreePopulatorModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
//--------------------------------------------------------------
#region ICommandableModule Members
private void HandleTreeActive(Object[] args)
{
if ((Boolean)args[0] && !m_active_trees)
{
m_log.InfoFormat("[TREES]: Activating Trees");
m_active_trees = true;
activeizeTreeze(m_active_trees);
}
else if (!(Boolean)args[0] && m_active_trees)
{
m_log.InfoFormat("[TREES]: Trees module is no longer active");
m_active_trees = false;
activeizeTreeze(m_active_trees);
}
else
{
m_log.InfoFormat("[TREES]: Trees module is already in the required state");
}
}
private void HandleTreeFreeze(Object[] args)
{
string copsename = ((string)args[0]).Trim();
Boolean freezeState = (Boolean) args[1];
foreach (Copse cp in m_copse)
{
if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState))
{
cp.m_frozen = freezeState;
foreach (UUID tree in cp.m_trees)
{
SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM"));
sop.ParentGroup.HasGroupChanged = true;
}
m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
return;
}
else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState))
{
m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
return;
}
}
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
private void HandleTreeLoad(Object[] args)
{
Copse copse;
m_log.InfoFormat("[TREES]: Loading copse definition....");
copse = new Copse(((string)args[0]), false);
foreach (Copse cp in m_copse)
{
if (cp.m_name == copse.m_name)
{
m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
return;
}
}
m_copse.Add(copse);
m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
}
private void HandleTreePlant(Object[] args)
{
string copsename = ((string)args[0]).Trim();
m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
foreach (Copse copse in m_copse)
{
if (copse.m_name == copsename)
{
if (!copse.m_planted)
{
// The first tree for a copse is created here
CreateTree(uuid, copse, copse.m_seed_point);
copse.m_planted = true;
return;
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
}
}
}
m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename);
}
private void HandleTreeRate(Object[] args)
{
m_update_ms = (double)args[0];
if (m_update_ms >= 1000.0)
{
if (m_active_trees)
{
activeizeTreeze(false);
activeizeTreeze(true);
}
m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms);
}
else
{
m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed");
}
}
private void HandleTreeReload(Object[] args)
{
if (m_active_trees)
{
CalculateTrees.Stop();
}
ReloadCopse();
if (m_active_trees)
{
CalculateTrees.Start();
}
}
private void HandleTreeRemove(Object[] args)
{
string copsename = ((string)args[0]).Trim();
Copse copseIdentity = null;
foreach (Copse cp in m_copse)
{
if (cp.m_name == copsename)
{
copseIdentity = cp;
}
}
if (copseIdentity != null)
{
foreach (UUID tree in copseIdentity.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
// Delete tree and alert clients (not silent)
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
copseIdentity.m_trees = new List<UUID>();
m_copse.Remove(copseIdentity);
m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
}
else
{
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
}
private void HandleTreeStatistics(Object[] args)
{
m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
foreach (Copse cp in m_copse)
{
m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
}
}
private void InstallCommands()
{
Command treeActiveCommand =
new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module");
treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean");
Command treeFreezeCommand =
new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse");
treeFreezeCommand.AddArgument("copse", "The required copse", "String");
treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean");
Command treeLoadCommand =
new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file");
treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String");
Command treePlantCommand =
new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse");
treePlantCommand.AddArgument("copse", "The required copse", "String");
Command treeRateCommand =
new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)");
treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
Command treeReloadCommand =
new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
Command treeRemoveCommand =
new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
treeRemoveCommand.AddArgument("copse", "The required copse", "String");
Command treeStatisticsCommand =
new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees");
m_commander.RegisterCommand("active", treeActiveCommand);
m_commander.RegisterCommand("freeze", treeFreezeCommand);
m_commander.RegisterCommand("load", treeLoadCommand);
m_commander.RegisterCommand("plant", treePlantCommand);
m_commander.RegisterCommand("rate", treeRateCommand);
m_commander.RegisterCommand("reload", treeReloadCommand);
m_commander.RegisterCommand("remove", treeRemoveCommand);
m_commander.RegisterCommand("statistics", treeStatisticsCommand);
}
/// <summary>
/// Processes commandline input. Do not call directly.
/// </summary>
/// <param name="args">Commandline arguments</param>
private void EventManager_OnPluginConsole(string[] args)
{
if (args[0] == "tree")
{
if (args.Length == 1)
{
m_commander.ProcessConsoleCommand("help", new string[0]);
return;
}
string[] tmpArgs = new string[args.Length - 2];
int i;
for (i = 2; i < args.Length; i++)
{
tmpArgs[i - 2] = args[i];
}
m_commander.ProcessConsoleCommand(args[1], tmpArgs);
}
}
#endregion
#region IVegetationModule Members
public SceneObjectGroup AddTree(
UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree)
{
PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
treeShape.PathCurve = 16;
treeShape.PathEnd = 49900;
treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
treeShape.Scale = scale;
treeShape.State = (byte)treeType;
return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
}
#endregion
#region IEntityCreator Members
protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
public PCode[] CreationCapabilities { get { return creationCapabilities; } }
public SceneObjectGroup CreateEntity(
UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
{
if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
{
m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
return null;
}
SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
SceneObjectPart rootPart = sceneObject.GetPart(sceneObject.UUID);
rootPart.AddFlag(PrimFlags.Phantom);
sceneObject.SetGroup(groupID, null);
m_scene.AddNewSceneObject(sceneObject, true);
sceneObject.AggregatePerms();
return sceneObject;
}
#endregion
//--------------------------------------------------------------
#region Tree Utilities
static public void SerializeObject(string fileName, Object obj)
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(Copse));
using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
{
writer.Formatting = Formatting.Indented;
xs.Serialize(writer, obj);
}
}
catch (SystemException ex)
{
throw new ApplicationException("Unexpected failure in Tree serialization", ex);
}
}
static public object DeserializeObject(string fileName)
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(Copse));
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
return xs.Deserialize(fs);
}
catch (SystemException ex)
{
throw new ApplicationException("Unexpected failure in Tree de-serialization", ex);
}
}
private void ReloadCopse()
{
m_copse = new List<Copse>();
EntityBase[] objs = m_scene.GetEntities();
foreach (EntityBase obj in objs)
{
if (obj is SceneObjectGroup)
{
SceneObjectGroup grp = (SceneObjectGroup)obj;
if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
{
// Create a new copse definition or add uuid to an existing definition
try
{
Boolean copsefound = false;
Copse copse = new Copse(grp.Name);
foreach (Copse cp in m_copse)
{
if (cp.m_name == copse.m_name)
{
copsefound = true;
cp.m_trees.Add(grp.UUID);
//m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID);
}
}
if (!copsefound)
{
m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
m_copse.Add(copse);
copse.m_trees.Add(grp.UUID);
}
}
catch
{
m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
}
}
}
}
}
#endregion
private void activeizeTreeze(bool activeYN)
{
if (activeYN)
{
CalculateTrees = new Timer(m_update_ms);
CalculateTrees.Elapsed += CalculateTrees_Elapsed;
CalculateTrees.Start();
}
else
{
CalculateTrees.Stop();
}
}
private void growTrees()
{
foreach (Copse copse in m_copse)
{
if (!copse.m_frozen)
{
foreach (UUID tree in copse.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z)
{
s_tree.Scale += copse.m_rate;
s_tree.ParentGroup.HasGroupChanged = true;
s_tree.ScheduleFullUpdate();
}
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
}
}
}
private void seedTrees()
{
foreach (Copse copse in m_copse)
{
if (!copse.m_frozen)
{
foreach (UUID tree in copse.m_trees)
{
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
if (copse.m_trees.Count < copse.m_tree_quantity)
{
// Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0)
{
if (Util.RandomClass.NextDouble() > 0.75)
{
SpawnChild(copse, s_tree);
}
}
}
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
}
}
}
private void killTrees()
{
foreach (Copse copse in m_copse)
{
if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
{
foreach (UUID tree in copse.m_trees)
{
double killLikelyhood = 0.0;
if (m_scene.Entities.ContainsKey(tree))
{
SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
Math.Pow(selectedTree.Scale.Y, 2) +
Math.Pow(selectedTree.Scale.Z, 2));
foreach (UUID picktree in copse.m_trees)
{
if (picktree != tree)
{
SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
Math.Pow(pickedTree.Scale.Y, 2) +
Math.Pow(pickedTree.Scale.Z, 2));
double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
}
}
if (Util.RandomClass.NextDouble() < killLikelyhood)
{
// Delete tree and alert clients (not silent)
m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
break;
}
}
else
{
m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
}
}
}
}
}
private void SpawnChild(Copse copse, SceneObjectPart s_tree)
{
Vector3 position = new Vector3();
double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
position.X = s_tree.AbsolutePosition.X + (float)randX;
position.Y = s_tree.AbsolutePosition.Y + (float)randY;
if (position.X <= (m_scene.RegionInfo.RegionSizeX - 1) && position.X >= 0 &&
position.Y <= (m_scene.RegionInfo.RegionSizeY - 1) && position.Y >= 0 &&
Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
{
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
CreateTree(uuid, copse, position);
}
}
private void CreateTree(UUID uuid, Copse copse, Vector3 position)
{
position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
{
SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
tree.Name = copse.ToString();
copse.m_trees.Add(tree.UUID);
tree.SendGroupFullUpdate();
}
}
private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
{
growTrees();
seedTrees();
killTrees();
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
namespace BitCoinSharp.Test
{
[TestFixture]
public class WalletTest
{
private static readonly NetworkParameters _params = NetworkParameters.UnitTests();
private Address _myAddress;
private Wallet _wallet;
private IBlockStore _blockStore;
[SetUp]
public void SetUp()
{
var myKey = new EcKey();
_myAddress = myKey.ToAddress(_params);
_wallet = new Wallet(_params);
_wallet.AddKey(myKey);
_blockStore = new MemoryBlockStore(_params);
}
[TearDown]
public void TearDown()
{
_blockStore.Dispose();
}
private static Transaction CreateFakeTx(ulong nanocoins, Address to)
{
var t = new Transaction(_params);
var o1 = new TransactionOutput(_params, t, nanocoins, to);
t.AddOutput(o1);
// Make a previous tx simply to send us sufficient coins. This previous tx is not really valid but it doesn't
// matter for our purposes.
var prevTx = new Transaction(_params);
var prevOut = new TransactionOutput(_params, prevTx, nanocoins, to);
prevTx.AddOutput(prevOut);
// Connect it.
t.AddInput(prevOut);
return t;
}
private class BlockPair
{
public StoredBlock StoredBlock { get; set; }
public Block Block { get; set; }
}
// Emulates receiving a valid block that builds on top of the chain.
private BlockPair CreateFakeBlock(params Transaction[] transactions)
{
var b = _blockStore.GetChainHead().Header.CreateNextBlock(new EcKey().ToAddress(_params));
foreach (var tx in transactions)
b.AddTransaction(tx);
b.Solve();
var pair = new BlockPair();
pair.Block = b;
pair.StoredBlock = _blockStore.GetChainHead().Build(b);
_blockStore.Put(pair.StoredBlock);
_blockStore.SetChainHead(pair.StoredBlock);
return pair;
}
[Test]
public void TestBasicSpending()
{
// We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
var v1 = Utils.ToNanoCoins(1, 0);
var t1 = CreateFakeTx(v1, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(v1, _wallet.GetBalance());
var k2 = new EcKey();
var v2 = Utils.ToNanoCoins(0, 50);
var t2 = _wallet.CreateSend(k2.ToAddress(_params), v2);
// Do some basic sanity checks.
Assert.AreEqual(1, t2.Inputs.Count);
Assert.AreEqual(_myAddress, t2.Inputs[0].ScriptSig.FromAddress);
// We have NOT proven that the signature is correct!
}
[Test]
public void TestSideChain()
{
// The wallet receives a coin on the main chain, then on a side chain. Only main chain counts towards balance.
var v1 = Utils.ToNanoCoins(1, 0);
var t1 = CreateFakeTx(v1, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(v1, _wallet.GetBalance());
var v2 = Utils.ToNanoCoins(0, 50);
var t2 = CreateFakeTx(v2, _myAddress);
_wallet.Receive(t2, null, BlockChain.NewBlockType.SideChain);
Assert.AreEqual(v1, _wallet.GetBalance());
}
[Test]
public void TestListener()
{
var fakeTx = CreateFakeTx(Utils.ToNanoCoins(1, 0), _myAddress);
var didRun = false;
_wallet.CoinsReceived +=
(sender, e) =>
{
Assert.True(e.PrevBalance.Equals(0));
Assert.True(e.NewBalance.Equals(Utils.ToNanoCoins(1, 0)));
Assert.AreEqual(e.Tx, fakeTx);
Assert.AreEqual(sender, _wallet);
didRun = true;
};
_wallet.Receive(fakeTx, null, BlockChain.NewBlockType.BestChain);
Assert.True(didRun);
}
[Test]
public void TestBalance()
{
// Receive 5 coins then half a coin.
var v1 = Utils.ToNanoCoins(5, 0);
var v2 = Utils.ToNanoCoins(0, 50);
var t1 = CreateFakeTx(v1, _myAddress);
var t2 = CreateFakeTx(v2, _myAddress);
var b1 = CreateFakeBlock(t1).StoredBlock;
var b2 = CreateFakeBlock(t2).StoredBlock;
var expected = Utils.ToNanoCoins(5, 50);
_wallet.Receive(t1, b1, BlockChain.NewBlockType.BestChain);
_wallet.Receive(t2, b2, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(expected, _wallet.GetBalance());
// Now spend one coin.
var v3 = Utils.ToNanoCoins(1, 0);
var spend = _wallet.CreateSend(new EcKey().ToAddress(_params), v3);
_wallet.ConfirmSend(spend);
// Available and estimated balances should not be the same. We don't check the exact available balance here
// because it depends on the coin selection algorithm.
Assert.AreEqual(Utils.ToNanoCoins(4, 50), _wallet.GetBalance(Wallet.BalanceType.Estimated));
Assert.False(_wallet.GetBalance(Wallet.BalanceType.Available).Equals(
_wallet.GetBalance(Wallet.BalanceType.Estimated)));
// Now confirm the transaction by including it into a block.
var b3 = CreateFakeBlock(spend).StoredBlock;
_wallet.Receive(spend, b3, BlockChain.NewBlockType.BestChain);
// Change is confirmed. We started with 5.50 so we should have 4.50 left.
var v4 = Utils.ToNanoCoins(4, 50);
Assert.AreEqual(v4, _wallet.GetBalance(Wallet.BalanceType.Available));
}
// Intuitively you'd expect to be able to create a transaction with identical inputs and outputs and get an
// identical result to the official client. However the signatures are not deterministic - signing the same data
// with the same key twice gives two different outputs. So we cannot prove bit-for-bit compatibility in this test
// suite.
[Test]
public void TestBlockChainCatchup()
{
var tx1 = CreateFakeTx(Utils.ToNanoCoins(1, 0), _myAddress);
var b1 = CreateFakeBlock(tx1).StoredBlock;
_wallet.Receive(tx1, b1, BlockChain.NewBlockType.BestChain);
// Send 0.10 to somebody else.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress);
// Pretend it makes it into the block chain, our wallet state is cleared but we still have the keys, and we
// want to get back to our previous state. We can do this by just not confirming the transaction as
// createSend is stateless.
var b2 = CreateFakeBlock(send1).StoredBlock;
_wallet.Receive(send1, b2, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(Utils.BitcoinValueToFriendlyString(_wallet.GetBalance()), "0.90");
// And we do it again after the catch-up.
var send2 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress);
// What we'd really like to do is prove the official client would accept it .... no such luck unfortunately.
_wallet.ConfirmSend(send2);
var b3 = CreateFakeBlock(send2).StoredBlock;
_wallet.Receive(send2, b3, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(Utils.BitcoinValueToFriendlyString(_wallet.GetBalance()), "0.80");
}
[Test]
public void TestBalances()
{
var nanos = Utils.ToNanoCoins(1, 0);
var tx1 = CreateFakeTx(nanos, _myAddress);
_wallet.Receive(tx1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(nanos, tx1.GetValueSentToMe(_wallet, true));
// Send 0.10 to somebody else.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress);
// Re-serialize.
var send2 = new Transaction(_params, send1.BitcoinSerialize());
Assert.AreEqual(nanos, send2.GetValueSentFromMe(_wallet));
}
[Test]
public void TestFinneyAttack()
{
// A Finney attack is where a miner includes a transaction spending coins to themselves but does not
// broadcast it. When they find a solved block, they hold it back temporarily whilst they buy something with
// those same coins. After purchasing, they broadcast the block thus reversing the transaction. It can be
// done by any miner for products that can be bought at a chosen time and very quickly (as every second you
// withhold your block means somebody else might find it first, invalidating your work).
//
// Test that we handle ourselves performing the attack correctly: a double spend on the chain moves
// transactions from pending to dead.
//
// Note that the other way around, where a pending transaction sending us coins becomes dead,
// isn't tested because today BitCoinJ only learns about such transactions when they appear in the chain.
Transaction eventDead = null;
Transaction eventReplacement = null;
_wallet.DeadTransaction +=
(sender, e) =>
{
eventDead = e.DeadTx;
eventReplacement = e.ReplacementTx;
};
// Receive 1 BTC.
var nanos = Utils.ToNanoCoins(1, 0);
var t1 = CreateFakeTx(nanos, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
// Create a send to a merchant.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 50));
// Create a double spend.
var send2 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 50));
// Broadcast send1.
_wallet.ConfirmSend(send1);
// Receive a block that overrides it.
_wallet.Receive(send2, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(send1, eventDead);
Assert.AreEqual(send2, eventReplacement);
}
}
}
| |
/*
* Crt0.cs - Program startup support definitions.
*
* This file is part of the Portable.NET "C language support" library.
* Copyright (C) 2002, 2004 Southern Storm Software, Pty Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace OpenSystem.C
{
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Security;
using System.Reflection;
//
// The "Crt0" class contains methods that support the "crt0" code
// that the compiler outputs into modules with a "main" function.
// The "crt0" code looks something like this:
//
// public static void .start(String[] args)
// {
// try
// {
// int argc;
// IntPtr argv;
// IntPtr envp;
// argv = Crt0.GetArgV(args, out argc);
// envp = Crt0.GetEnvironment();
// Crt0.Startup();
// Crt0.Shutdown(main(argc, argv, envp));
// }
// catch(OutOfMemoryException)
// {
// throw;
// }
// catch(Object e)
// {
// throw Crt0.ShutdownWithException(e);
// }
// }
//
// If the "main" function does not have all three arguments, the
// compiler will only pass those arguments that "main" specifies.
//
// The "crt0" code is kept deliberately simple, with the bulk of the
// hard work done in this class. This makes it easier to change the
// startup behaviour by altering "Crt0", without requiring every
// application to be recompiled.
//
// Note: the "crt0" code catches all exceptions, including those
// that don't inherit from "System.Exception". Out of memory
// exceptions are explicitly excluded because there's nothing that
// can be done in that situation anyway.
//
public unsafe sealed class Crt0
{
// Internal state.
private static IntPtr argV;
private static int argC;
private static IntPtr environ;
private static Module libcModule;
private static MethodInfo finiMethod;
private static bool startupDone = false;
private static bool finiDone = false;
// Get the "argv" and "argc" values for the running task.
// "mainArgs" is the value passed to the program's entry point.
public static IntPtr GetArgV(String[] mainArgs, out int argc)
{
lock(typeof(Crt0))
{
// Bail out if we were already called previously.
if(argV != IntPtr.Zero)
{
argc = argC;
return argV;
}
// Get the actual command-line arguments, including
// the application name. The application name isn't
// normally included in "mainArgs", so we have to
// do the following instead.
String[] args;
try
{
args = Environment.GetCommandLineArgs();
}
catch(NotSupportedException)
{
args = null;
}
if(args == null)
{
// We couldn't get the arguments from the runtime
// engine directly, so use "mainArgs" and simulate
// the application name. This may happen in embedded
// environments that don't have a real command-line.
if(mainArgs != null)
{
args = new String [mainArgs.Length + 1];
Array.Copy(mainArgs, 0, args, 1,
mainArgs.Length);
}
else
{
args = new String [1];
}
args[0] = "cliapp.exe";
}
// Convert "args" into an array of native strings,
// terminated by a NULL pointer.
int ptrSize = (int)(sizeof(void *));
argV = Marshal.AllocHGlobal
(new IntPtr(ptrSize * (args.Length + 1)));
if(argV == IntPtr.Zero)
{
// We probably don't have permission to allocate
// memory using "AllocHGlobal". If that is the
// case, then bail out. C is useless without it.
throw new NotSupportedException
("Fatal error: cannot allocate unmanaged memory");
}
argC = args.Length;
for(int index = 0; index < argC; ++index)
{
Marshal.WriteIntPtr(argV, ptrSize * index,
Marshal.StringToHGlobalAnsi(args[index]));
}
Marshal.WriteIntPtr(argV, ptrSize * argC, IntPtr.Zero);
// Return the final values to the caller.
argc = argC;
return argV;
}
}
// Get the "environ" value for the running task.
public static IntPtr GetEnvironment()
{
lock(typeof(Crt0))
{
// Bail out if we were already called previously.
if(environ != IntPtr.Zero)
{
return environ;
}
// Get the environment variables for the running task.
IDictionary env;
int count;
IDictionaryEnumerator e;
try
{
env = Environment.GetEnvironmentVariables();
}
catch(SecurityException)
{
// The runtime engine has decided that we don't have
// sufficient permissions to get the environment.
// We continue with an empty environment.
env = null;
}
if(env != null)
{
count = env.Count;
e = env.GetEnumerator();
}
else
{
count = 0;
e = null;
}
// Allocate an array to hold the converted values.
int pointerSize = (int)(sizeof(void *));
environ = Marshal.AllocHGlobal
(new IntPtr(pointerSize * (count + 1)));
// Convert the environment variables into native strings.
int index = 0;
String value;
while(index < count && e != null && e.MoveNext())
{
value = String.Concat((String)(e.Key), "=",
(String)(e.Value));
Marshal.WriteIntPtr(environ, pointerSize * index,
Marshal.StringToHGlobalAnsi(value));
++index;
}
Marshal.WriteIntPtr
(environ, pointerSize * count, IntPtr.Zero);
// The environment is ready to go.
return environ;
}
}
// Perform system library startup tasks. This is normally
// called just before invoking the program's "main" function.
public static void Startup()
{
Module mainModule;
Assembly assembly;
Type type;
FieldInfo field;
// Bail out if we've already done the startup code.
lock(typeof(Crt0))
{
if(startupDone)
{
return;
}
startupDone = true;
}
// Find the module that contains the "main" function.
mainModule = null;
try
{
assembly = Assembly.GetCallingAssembly();
type = assembly.GetType("<Module>");
if(type != null)
{
mainModule = type.Module;
}
}
catch(NotImplementedException)
{
// The runtime engine probably does not have support
// for reflection, so there's nothing we can do.
}
// Find standard C library's global module.
libcModule = null;
try
{
assembly = Assembly.Load("libc");
type = assembly.GetType("libc");
if(type != null)
{
libcModule = type.Module;
}
}
catch(OutOfMemoryException)
{
// Send out of memory conditions back up the stack.
throw;
}
catch(Exception)
{
// We weren't able to load "libc" for some reason.
}
// Set the global "__environ" variable within "libc".
if(libcModule != null)
{
field = libcModule.GetField("__environ");
if(field != null)
{
field.SetValue(null, (Object)environ);
}
}
// Initialize the stdin, stdout, and stderr file descriptors.
#if CONFIG_SMALL_CONSOLE
FileTable.SetFileDescriptor(0, Stream.Null);
FileTable.SetFileDescriptor(1, new ConsoleStream());
FileTable.SetFileDescriptor(2, new ConsoleStream());
#else
FileTable.SetFileDescriptor
(0, new FDStream(0, Console.OpenStandardInput()));
FileTable.SetFileDescriptor
(1, new FDStream(1, Console.OpenStandardOutput()));
FileTable.SetFileDescriptor
(2, new FDStream(2, Console.OpenStandardError()));
#endif
// Invoke the application's ".init" function, if present.
if(mainModule != null)
{
MethodInfo initMethod = mainModule.GetMethod(".init");
if(initMethod != null)
{
initMethod.Invoke(null, null);
}
}
// Locate the application's ".fini" function.
if(mainModule != null)
{
finiMethod = mainModule.GetMethod(".fini");
}
else
{
finiMethod = null;
}
}
// Perform system library shutdown tasks and exit the application.
// This is normally called after invoking the program's "main" function.
public static void Shutdown(int status)
{
// Find the global "exit" function and call it.
if(libcModule != null)
{
MethodInfo method = libcModule.GetMethod("exit");
if(method != null)
{
Object[] args = new Object [1];
args[0] = (Object)(status);
method.Invoke(null, args);
}
}
// If we get here, then we weren't able to find "exit",
// or it returned to us by mistake. Bail out through
// "System.Environment".
Environment.Exit(status);
}
// Perform system library shutdown tasks when an exception occurs.
public static Object ShutdownWithException(Object e)
{
// Nothing to do here yet, so return the exception object
// to the caller to be rethrown to the runtime engine.
return e;
}
// Invoke the ".fini" function at system shutdown.
public static void InvokeFini()
{
lock(typeof(Crt0))
{
if(finiDone)
{
return;
}
finiDone = true;
}
if(finiMethod != null)
{
finiMethod.Invoke(null, null);
}
}
// Get the module that contains "libc". Returns "null" if unknown.
public static Module LibC
{
get
{
return libcModule;
}
}
// Set the contents of a wide character string during initialization.
public unsafe static void SetWideString(char *dest, String src)
{
int index = 0;
foreach(char ch in src)
{
dest[index++] = ch;
}
dest[index] = '\0';
}
// Alignment flags. Keep in sync with "c_types.h" in the pnet C compiler.
private const uint C_ALIGN_BYTE = 0x0001;
private const uint C_ALIGN_2 = 0x0002;
private const uint C_ALIGN_4 = 0x0004;
private const uint C_ALIGN_8 = 0x0008;
private const uint C_ALIGN_16 = 0x0010;
private const uint C_ALIGN_SHORT = 0x0020;
private const uint C_ALIGN_INT = 0x0040;
private const uint C_ALIGN_LONG = 0x0080;
private const uint C_ALIGN_FLOAT = 0x0100;
private const uint C_ALIGN_DOUBLE = 0x0200;
private const uint C_ALIGN_POINTER = 0x0400;
private const uint C_ALIGN_UNKNOWN = 0x0800;
// Align a size value according to a set of flags. Used by the
// compiler to help compute the size of complicated types.
public unsafe static uint Align(uint size, uint flags)
{
uint align;
uint temp;
// Get the basic alignment value.
align = 1;
if((flags & C_ALIGN_2) != 0)
{
align = 2;
}
if((flags & C_ALIGN_4) != 0)
{
align = 4;
}
if((flags & C_ALIGN_8) != 0)
{
align = 8;
}
if((flags & C_ALIGN_16) != 0)
{
align = 16;
}
// Adjust for specific types that appear.
if((flags & C_ALIGN_SHORT) != 0)
{
temp = (uint)(int)(IntPtr)(void *)
(&(((align_short *)(void *)(IntPtr.Zero))->value));
if(temp > align)
{
align = temp;
}
}
if((flags & C_ALIGN_INT) != 0)
{
temp = (uint)(int)(IntPtr)(void *)
(&(((align_int *)(void *)(IntPtr.Zero))->value));
if(temp > align)
{
align = temp;
}
}
if((flags & C_ALIGN_LONG) != 0)
{
temp = (uint)(int)(IntPtr)(void *)
(&(((align_long *)(void *)(IntPtr.Zero))->value));
if(temp > align)
{
align = temp;
}
}
if((flags & C_ALIGN_FLOAT) != 0)
{
temp = (uint)(int)(IntPtr)(void *)
(&(((align_float *)(void *)(IntPtr.Zero))->value));
if(temp > align)
{
align = temp;
}
}
if((flags & C_ALIGN_DOUBLE) != 0)
{
temp = (uint)(int)(IntPtr)(void *)
(&(((align_double *)(void *)(IntPtr.Zero))->value));
if(temp > align)
{
align = temp;
}
}
if((flags & C_ALIGN_POINTER) != 0)
{
temp = (uint)(int)(IntPtr)(void *)
(&(((align_pointer *)(void *)(IntPtr.Zero))->value));
if(temp > align)
{
align = temp;
}
}
// Align the final size value and return it.
if((size % align) != 0)
{
size += align - (size % align);
}
return size;
}
// Types that are used to aid with alignment computations.
[StructLayout(LayoutKind.Sequential)]
private struct align_short
{
public byte pad;
public short value;
}; // struct align_short
[StructLayout(LayoutKind.Sequential)]
private struct align_int
{
public byte pad;
public int value;
}; // struct align_int
[StructLayout(LayoutKind.Sequential)]
private struct align_long
{
public byte pad;
public long value;
}; // struct align_long
[StructLayout(LayoutKind.Sequential)]
private struct align_float
{
public byte pad;
public float value;
}; // struct align_float
[StructLayout(LayoutKind.Sequential)]
private struct align_double
{
public byte pad;
public double value;
}; // struct align_double
[StructLayout(LayoutKind.Sequential)]
private unsafe struct align_pointer
{
public byte pad;
public void *value;
}; // struct align_pointer
#if CONFIG_SMALL_CONSOLE
// Helper class for writing to stdout when the System.Console
// class does not have "OpenStandardOutput".
private sealed class ConsoleStream : Stream
{
// Constructor.
public ConsoleStream() {}
// Stub out all stream functionality.
public override void Flush() {}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override int ReadByte()
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
// Validate the buffer argument.
if(buffer == null)
{
throw new ArgumentNullException("buffer");
}
else if(offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException();
}
else if(count < 0)
{
throw new ArgumentOutOfRangeException();
}
else if((buffer.Length - offset) < count)
{
throw new ArgumentException();
}
// Write the contents of the buffer.
while(count > 0)
{
Console.Write((char)(buffer[offset]));
++offset;
--count;
}
}
public override void WriteByte(byte value)
{
Console.Write((char)value);
}
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
}; // class ConsoleStream
#endif // !CONFIG_SMALL_CONSOLE
} // class Crt0
} // namespace OpenSystem.C
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcdv = Google.Cloud.DataLabeling.V1Beta1;
using sys = System;
namespace Google.Cloud.DataLabeling.V1Beta1
{
/// <summary>Resource name for the <c>AnnotationSpecSet</c> resource.</summary>
public sealed partial class AnnotationSpecSetName : gax::IResourceName, sys::IEquatable<AnnotationSpecSetName>
{
/// <summary>The possible contents of <see cref="AnnotationSpecSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
ProjectAnnotationSpecSet = 1,
}
private static gax::PathTemplate s_projectAnnotationSpecSet = new gax::PathTemplate("projects/{project}/annotationSpecSets/{annotation_spec_set}");
/// <summary>Creates a <see cref="AnnotationSpecSetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AnnotationSpecSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AnnotationSpecSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AnnotationSpecSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AnnotationSpecSetName"/> with the pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AnnotationSpecSetName"/> constructed from the provided ids.</returns>
public static AnnotationSpecSetName FromProjectAnnotationSpecSet(string projectId, string annotationSpecSetId) =>
new AnnotationSpecSetName(ResourceNameType.ProjectAnnotationSpecSet, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), annotationSpecSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecSetId, nameof(annotationSpecSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </returns>
public static string Format(string projectId, string annotationSpecSetId) =>
FormatProjectAnnotationSpecSet(projectId, annotationSpecSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </returns>
public static string FormatProjectAnnotationSpecSet(string projectId, string annotationSpecSetId) =>
s_projectAnnotationSpecSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecSetId, nameof(annotationSpecSetId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AnnotationSpecSetName"/> if successful.</returns>
public static AnnotationSpecSetName Parse(string annotationSpecSetName) => Parse(annotationSpecSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AnnotationSpecSetName"/> if successful.</returns>
public static AnnotationSpecSetName Parse(string annotationSpecSetName, bool allowUnparsed) =>
TryParse(annotationSpecSetName, allowUnparsed, out AnnotationSpecSetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecSetName, out AnnotationSpecSetName result) =>
TryParse(annotationSpecSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecSetName, bool allowUnparsed, out AnnotationSpecSetName result)
{
gax::GaxPreconditions.CheckNotNull(annotationSpecSetName, nameof(annotationSpecSetName));
gax::TemplatedResourceName resourceName;
if (s_projectAnnotationSpecSet.TryParseName(annotationSpecSetName, out resourceName))
{
result = FromProjectAnnotationSpecSet(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(annotationSpecSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AnnotationSpecSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string annotationSpecSetId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AnnotationSpecSetId = annotationSpecSetId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AnnotationSpecSetName"/> class from the component parts of pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
public AnnotationSpecSetName(string projectId, string annotationSpecSetId) : this(ResourceNameType.ProjectAnnotationSpecSet, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), annotationSpecSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecSetId, nameof(annotationSpecSetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AnnotationSpecSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string AnnotationSpecSetId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectAnnotationSpecSet: return s_projectAnnotationSpecSet.Expand(ProjectId, AnnotationSpecSetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AnnotationSpecSetName);
/// <inheritdoc/>
public bool Equals(AnnotationSpecSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AnnotationSpecSetName a, AnnotationSpecSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AnnotationSpecSetName a, AnnotationSpecSetName b) => !(a == b);
}
public partial class AnnotationSpecSet
{
/// <summary>
/// <see cref="gcdv::AnnotationSpecSetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::AnnotationSpecSetName AnnotationSpecSetName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::AnnotationSpecSetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*
* This files defines the following types:
* - NativeOverlapped
* - _IOCompletionCallback
* - OverlappedData
* - Overlapped
* - OverlappedDataCache
*/
/*=============================================================================
**
**
**
** Purpose: Class for converting information to and from the native
** overlapped structure used in asynchronous file i/o
**
**
=============================================================================*/
namespace System.Threading
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
using System.Collections.Concurrent;
#region struct NativeOverlapped
// Valuetype that represents the (unmanaged) Win32 OVERLAPPED structure
// the layout of this structure must be identical to OVERLAPPED.
// The first five matches OVERLAPPED structure.
// The remaining are reserved at the end
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct NativeOverlapped
{
public IntPtr InternalLow;
public IntPtr InternalHigh;
public int OffsetLow;
public int OffsetHigh;
public IntPtr EventHandle;
}
#endregion struct NativeOverlapped
#region class _IOCompletionCallback
unsafe internal class _IOCompletionCallback
{
[System.Security.SecurityCritical] // auto-generated
IOCompletionCallback _ioCompletionCallback;
ExecutionContext _executionContext;
uint _errorCode; // Error code
uint _numBytes; // No. of bytes transferred
[SecurityCritical]
NativeOverlapped* _pOVERLAP;
[System.Security.SecuritySafeCritical] // auto-generated
static _IOCompletionCallback()
{
}
[System.Security.SecurityCritical] // auto-generated
internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ref StackCrawlMark stackMark)
{
_ioCompletionCallback = ioCompletionCallback;
// clone the exection context
_executionContext = ExecutionContext.Capture(
ref stackMark,
ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
}
// Context callback: same sig for SendOrPostCallback and ContextCallback
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context);
[System.Security.SecurityCritical]
static internal void IOCompletionCallback_Context(Object state)
{
_IOCompletionCallback helper = (_IOCompletionCallback)state;
Contract.Assert(helper != null,"_IOCompletionCallback cannot be null");
helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP);
}
// call back helper
[System.Security.SecurityCritical] // auto-generated
static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code
uint numBytes, // No. of bytes transferred
NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
)
{
Overlapped overlapped;
_IOCompletionCallback helper;
do
{
overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped;
helper = overlapped.iocbHelper;
if (helper == null || helper._executionContext == null || helper._executionContext.IsDefaultFTContext(true))
{
// We got here because of UnsafePack (or) Pack with EC flow supressed
IOCompletionCallback callback = overlapped.UserCallback;
callback( errorCode, numBytes, pOVERLAP);
}
else
{
// We got here because of Pack
helper._errorCode = errorCode;
helper._numBytes = numBytes;
helper._pOVERLAP = pOVERLAP;
using (ExecutionContext executionContext = helper._executionContext.CreateCopy())
ExecutionContext.Run(executionContext, _ccb, helper, true);
}
//Quickly check the VM again, to see if a packet has arrived.
OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes);
} while (pOVERLAP != null);
}
}
#endregion class _IOCompletionCallback
#region class OverlappedData
sealed internal class OverlappedData
{
// ! If you make any change to the layout here, you need to make matching change
// ! to OverlappedObject in vm\nativeoverlapped.h
internal IAsyncResult m_asyncResult;
[System.Security.SecurityCritical] // auto-generated
internal IOCompletionCallback m_iocb;
internal _IOCompletionCallback m_iocbHelper;
internal Overlapped m_overlapped;
private Object m_userObject;
private IntPtr m_pinSelf;
private IntPtr m_userObjectInternal;
private int m_AppDomainId;
#pragma warning disable 414 // Field is not used from managed.
#pragma warning disable 169
private byte m_isArray;
private byte m_toBeCleaned;
#pragma warning restore 414
#pragma warning restore 169
internal NativeOverlapped m_nativeOverlapped;
#if FEATURE_CORECLR
// Adding an empty default ctor for annotation purposes
[System.Security.SecuritySafeCritical] // auto-generated
internal OverlappedData(){}
#endif // FEATURE_CORECLR
[System.Security.SecurityCritical]
internal void ReInitialize()
{
m_asyncResult = null;
m_iocb = null;
m_iocbHelper = null;
m_overlapped = null;
m_userObject = null;
Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
m_pinSelf = (IntPtr)0;
m_userObjectInternal = (IntPtr)0;
Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
m_AppDomainId = 0;
m_nativeOverlapped.EventHandle = (IntPtr)0;
m_isArray = 0;
m_nativeOverlapped.InternalLow = (IntPtr)0;
m_nativeOverlapped.InternalHigh = (IntPtr)0;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
if (!m_pinSelf.IsNull()) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
}
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
if (iocb != null)
{
m_iocbHelper = new _IOCompletionCallback(iocb, ref stackMark);
m_iocb = iocb;
}
else
{
m_iocbHelper = null;
m_iocb = null;
}
m_userObject = userData;
if (m_userObject != null)
{
if (m_userObject.GetType() == typeof(Object[]))
{
m_isArray = 1;
}
else
{
m_isArray = 0;
}
}
return AllocateNativeOverlapped();
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
if (!m_pinSelf.IsNull()) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
}
m_userObject = userData;
if (m_userObject != null)
{
if (m_userObject.GetType() == typeof(Object[]))
{
m_isArray = 1;
}
else
{
m_isArray = 0;
}
}
m_iocb = iocb;
m_iocbHelper = null;
return AllocateNativeOverlapped();
}
[ComVisible(false)]
internal IntPtr UserHandle
{
get { return m_nativeOverlapped.EventHandle; }
set { m_nativeOverlapped.EventHandle = value; }
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private extern NativeOverlapped* AllocateNativeOverlapped();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes);
}
#endregion class OverlappedData
#region class Overlapped
/// <internalonly/>
[System.Runtime.InteropServices.ComVisible(true)]
public class Overlapped
{
private OverlappedData m_overlappedData;
private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData());
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
public Overlapped()
{
m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
}
public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar)
{
m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo;
m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi;
m_overlappedData.UserHandle = hEvent;
m_overlappedData.m_asyncResult = ar;
}
[Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")]
public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar)
{
}
public IAsyncResult AsyncResult
{
get { return m_overlappedData.m_asyncResult; }
set { m_overlappedData.m_asyncResult = value; }
}
public int OffsetLow
{
get { return m_overlappedData.m_nativeOverlapped.OffsetLow; }
set { m_overlappedData.m_nativeOverlapped.OffsetLow = value; }
}
public int OffsetHigh
{
get { return m_overlappedData.m_nativeOverlapped.OffsetHigh; }
set { m_overlappedData.m_nativeOverlapped.OffsetHigh = value; }
}
[Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int EventHandle
{
get { return m_overlappedData.UserHandle.ToInt32(); }
set { m_overlappedData.UserHandle = new IntPtr(value); }
}
[ComVisible(false)]
public IntPtr EventHandleIntPtr
{
get { return m_overlappedData.UserHandle; }
set { m_overlappedData.UserHandle = value; }
}
internal _IOCompletionCallback iocbHelper
{
get { return m_overlappedData.m_iocbHelper; }
}
internal IOCompletionCallback UserCallback
{
[System.Security.SecurityCritical]
get { return m_overlappedData.m_iocb; }
}
/*====================================================================
* Packs a managed overlapped class into native Overlapped struct.
* Roots the iocb and stores it in the ReservedCOR field of native Overlapped
* Pins the native Overlapped struct and returns the pinned index.
====================================================================*/
[System.Security.SecurityCritical] // auto-generated
[Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb)
{
return Pack (iocb, null);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false),ComVisible(false)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.Pack(iocb, userData);
}
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb)
{
return UnsafePack (iocb, null);
}
[System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false), ComVisible(false)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.UnsafePack(iocb, userData);
}
/*====================================================================
* Unpacks an unmanaged native Overlapped struct.
* Unpins the native Overlapped struct
====================================================================*/
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
unsafe public static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException("nativeOverlappedPtr");
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
return overlapped;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr)
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException("nativeOverlappedPtr");
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr);
OverlappedData overlappedData = overlapped.m_overlappedData;
overlapped.m_overlappedData = null;
overlappedData.ReInitialize();
s_overlappedDataCache.Free(overlappedData);
}
}
#endregion class Overlapped
} // namespace
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Config.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Kanbans.
/// </summary>
[RoutePrefix("api/v1.0/config/kanban")]
public class KanbanController : FrapidApiController
{
/// <summary>
/// The Kanban repository.
/// </summary>
private readonly IKanbanRepository KanbanRepository;
public KanbanController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.KanbanRepository = new Frapid.Config.DataAccess.Kanban
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public KanbanController(IKanbanRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.KanbanRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "kanban" entity.
/// </summary>
/// <returns>Returns the "kanban" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/config/kanban/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "kanban_id",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "kanban_id", PropertyName = "KanbanId", DataType = "long", DbDataType = "int8", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "object_name", PropertyName = "ObjectName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 128 },
new EntityColumn { ColumnName = "user_id", PropertyName = "UserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "kanban_name", PropertyName = "KanbanName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 128 },
new EntityColumn { ColumnName = "description", PropertyName = "Description", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of kanbans.
/// </summary>
/// <returns>Returns the count of the kanbans.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/config/kanban/count")]
[Authorize]
public long Count()
{
try
{
return this.KanbanRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of kanban.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/config/kanban/all")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Kanban> GetAll()
{
try
{
return this.KanbanRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of kanban for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/config/kanban/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.KanbanRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of kanban.
/// </summary>
/// <param name="kanbanId">Enter KanbanId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{kanbanId}")]
[Route("~/api/config/kanban/{kanbanId}")]
[Authorize]
public Frapid.Config.Entities.Kanban Get(long kanbanId)
{
try
{
return this.KanbanRepository.Get(kanbanId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/config/kanban/get")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Kanban> Get([FromUri] long[] kanbanIds)
{
try
{
return this.KanbanRepository.Get(kanbanIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of kanban.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/config/kanban/first")]
[Authorize]
public Frapid.Config.Entities.Kanban GetFirst()
{
try
{
return this.KanbanRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of kanban.
/// </summary>
/// <param name="kanbanId">Enter KanbanId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{kanbanId}")]
[Route("~/api/config/kanban/previous/{kanbanId}")]
[Authorize]
public Frapid.Config.Entities.Kanban GetPrevious(long kanbanId)
{
try
{
return this.KanbanRepository.GetPrevious(kanbanId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of kanban.
/// </summary>
/// <param name="kanbanId">Enter KanbanId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{kanbanId}")]
[Route("~/api/config/kanban/next/{kanbanId}")]
[Authorize]
public Frapid.Config.Entities.Kanban GetNext(long kanbanId)
{
try
{
return this.KanbanRepository.GetNext(kanbanId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of kanban.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/config/kanban/last")]
[Authorize]
public Frapid.Config.Entities.Kanban GetLast()
{
try
{
return this.KanbanRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 kanbans on each page, sorted by the property KanbanId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/config/kanban")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Kanban> GetPaginatedResult()
{
try
{
return this.KanbanRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 kanbans on each page, sorted by the property KanbanId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/config/kanban/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Kanban> GetPaginatedResult(long pageNumber)
{
try
{
return this.KanbanRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of kanbans using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered kanbans.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/config/kanban/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.KanbanRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 kanbans on each page, sorted by the property KanbanId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/config/kanban/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Kanban> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.KanbanRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of kanbans using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered kanbans.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/config/kanban/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.KanbanRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 kanbans on each page, sorted by the property KanbanId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/config/kanban/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Kanban> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.KanbanRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of kanbans.
/// </summary>
/// <returns>Returns an enumerable key/value collection of kanbans.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/config/kanban/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.KanbanRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for kanbans.
/// </summary>
/// <returns>Returns an enumerable custom field collection of kanbans.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/config/kanban/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.KanbanRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for kanbans.
/// </summary>
/// <returns>Returns an enumerable custom field collection of kanbans.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/config/kanban/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.KanbanRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of Kanban class.
/// </summary>
/// <param name="kanban">Your instance of kanbans class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/config/kanban/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic kanban = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (kanban == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.KanbanRepository.AddOrEdit(kanban, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of Kanban class.
/// </summary>
/// <param name="kanban">Your instance of kanbans class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{kanban}")]
[Route("~/api/config/kanban/add/{kanban}")]
[Authorize]
public void Add(Frapid.Config.Entities.Kanban kanban)
{
if (kanban == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.KanbanRepository.Add(kanban);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of Kanban class.
/// </summary>
/// <param name="kanban">Your instance of Kanban class to edit.</param>
/// <param name="kanbanId">Enter the value for KanbanId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{kanbanId}")]
[Route("~/api/config/kanban/edit/{kanbanId}")]
[Authorize]
public void Edit(long kanbanId, [FromBody] Frapid.Config.Entities.Kanban kanban)
{
if (kanban == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.KanbanRepository.Update(kanban, kanbanId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of Kanban class.
/// </summary>
/// <param name="collection">Your collection of Kanban class to bulk import.</param>
/// <returns>Returns list of imported kanbanIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any Kanban class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/config/kanban/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> kanbanCollection = this.ParseCollection(collection);
if (kanbanCollection == null || kanbanCollection.Count.Equals(0))
{
return null;
}
try
{
return this.KanbanRepository.BulkImport(kanbanCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of Kanban class via KanbanId.
/// </summary>
/// <param name="kanbanId">Enter the value for KanbanId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{kanbanId}")]
[Route("~/api/config/kanban/delete/{kanbanId}")]
[Authorize]
public void Delete(long kanbanId)
{
try
{
this.KanbanRepository.Delete(kanbanId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
/*
* Reading & Writing Using Raw Byte Streams
* ========================================
* Stream (abstract)
* IO.FileStream
* IO.BufferedStream
* IO.Compression.DeflateStream
* IO.Compression.GZipStream
* IO.MemoryStream
* + others, see Stream class documentation
* Stream.Null (aka /dev/null)
* IO.BinaryReader
* IO.BinaryWriter
*
* Reading & Writing using Encodings
* =================================
* These classes are the ones you want to use for text files.
*
* TextReader (abstract)
* StringReader - read from a string
* StreamReader - read from an existing stream or filename
* TextWriter (abstract)
* StringWriter - write to a string
* StreamWriter - write to an existing stream or filename
*
*/
namespace Streams {
class Program {
static void Main(string[] args) {
TestStreamReaderWriter();
TestStreamReaderWriter2();
TestStreamWriterRandom();
TestMemoryStream();
TestBinaryFile();
TestBufferedStream();
}
private static void TestBinaryFile() {
const string file = @"C:\Temp\BinaryFile.txt";
if (File.Exists(file))
File.Delete(file);
// Was attempting to make ASCII, Unicode etc, but I don't think it works.
// If you want to create a Unicode file in binary, then you need to write
// the pre-amble.
//using (StreamWriter writer = new StreamWriter(file, false, Encoding.ASCII))
//using (BinaryWriter bw = new BinaryWriter(writer.BaseStream)) {
// Binary writers are constructed as wrappers around existing streams/reader-writers.
// Note: only use the binary reader/writer for IO.
using (FileStream fs = new FileStream(file, FileMode.Create))
using (BinaryWriter bw = new BinaryWriter(fs)) {
// Write the word "hello" in binary.
bw.Write((byte)0x68);
bw.Write((byte)0x65);
bw.Write((byte)0x6C);
bw.Write((byte)0x6C);
bw.Write((byte)0x6F);
bw.Write((byte)0xA3);
// CRLF.
bw.Write((byte)0x0D);
bw.Write((byte)0x0A);
bw.Write("Second string");
bw.Write(42);
}
// Read it back as text.
StreamReader rdr = new StreamReader(file);
string s = rdr.ReadToEnd();
Console.Write("Read from file: " + s);
Console.WriteLine("Next line");
}
private static void TestStreamWriterRandom() {
const string file = @"C:\Temp\file.txt";
if (File.Exists(file))
File.Delete(file);
using (StreamWriter sw = new StreamWriter(file)) {
sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
sw.WriteLine("Line 3");
FileStream fs = sw.BaseStream as FileStream;
Debug.Assert(fs != null);
// Without this flush() the pointer will not be reset to the beginning
// of the file. Flushing fs does not work either.
sw.Flush();
fs.Seek(0, SeekOrigin.Begin);
sw.WriteLine("Line A");
}
}
private static void TestMemoryStream() {
byte[] byteArray;
ASCIIEncoding enc = new ASCIIEncoding();
using (MemoryStream ms = new MemoryStream(1000)) {
byteArray = enc.GetBytes("Line 1");
ms.Write(byteArray, 0, byteArray.Length);
byteArray = enc.GetBytes("Line 2");
ms.Write(byteArray, 0, byteArray.Length);
byteArray = enc.GetBytes("Line 3");
ms.Write(byteArray, 0, byteArray.Length);
// Now this works! Can seek OK in memory streams.
// No flushing is required.
ms.Seek(0, SeekOrigin.Begin);
byteArray = enc.GetBytes("Line A");
ms.Write(byteArray, 0, byteArray.Length);
}
}
private static void TestStreamReaderWriter2() {
const string file = @"C:\Temp\Afileio.txt";
if (File.Exists(file))
File.Delete(file);
using (StreamWriter sw = new StreamWriter(file, false, Encoding.Unicode)) {
sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
sw.WriteLine("Line 3");
sw.WriteLine(12);
Stream bs = sw.BaseStream;
if (bs.GetType() == typeof(FileStream))
Console.WriteLine("The stream writer 'sw' is backed by a FileStream, as you would expect.");
if (bs.CanSeek)
Console.WriteLine("This FileStream can seek.");
// If you don't flush flush then strange things happen in Notepad
// because the encoding gets screwed up!
sw.Flush();
// This will write zero-bytes into the file. They look like
// spaces in notepad, but check them in Emacs hexl-mode.
bs.Seek(1000, SeekOrigin.Current);
sw.WriteLine("The end");
// This actually truncates the file!
bs.Position = 0;
sw.WriteLine("Actually the penultimate line written");
// This lets us overwrite the beginning.
bs.Seek(0, SeekOrigin.Begin);
sw.WriteLine("aaa");
}
}
private static void TestStreamReaderWriter() {
const string file = @"C:\Temp\fileio.txt";
const string file2 = @"C:\Temp\fileio2.txt";
if (File.Exists(file))
File.Delete(file);
if (File.Exists(file2))
File.Delete(file2);
using (StreamWriter sw = new StreamWriter(file, false, Encoding.Unicode)) {
sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
sw.WriteLine("Line 3");
sw.WriteLine(12);
}
if (File.Exists(file)) {
using (StreamReader sr = new StreamReader(file, true)) {
string s = sr.ReadToEnd();
// This should be identical - check with ExamDiff. This proves that
// the encoding was detected correctly.
using (StreamWriter sw = new StreamWriter(file2, false, Encoding.Unicode)) {
sw.Write(s);
}
}
} else {
throw new ApplicationException("The file should exist.");
}
}
private static void TestBufferedStream() {
// A BufferedStream is a type of stream that is wrapped around another stream
// and provides buffering facilities, no matter the capabilities of the wrapped stream.
const string file = @"C:\Temp\fileio.txt";
if (File.Exists(file))
File.Delete(file);
using (FileStream fs = File.Create(file)) {
using (BufferedStream buff = new BufferedStream(fs, 10000)) {
buff.WriteByte((byte)0x68);
buff.WriteByte((byte)0x65);
buff.WriteByte((byte)0x6C);
buff.WriteByte((byte)0x6C);
buff.WriteByte((byte)0x6F);
buff.WriteByte((byte)0xA3);
// CRLF.
buff.WriteByte((byte)0x0D);
buff.WriteByte((byte)0x0A);
buff.Flush();
}
}
}
}
}
| |
//
// Paned.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
namespace Xwt
{
[BackendType (typeof(IPanedBackend))]
public class Paned: Widget
{
Orientation direction;
Panel panel1;
Panel panel2;
EventHandler positionChanged;
protected new class WidgetBackendHost: Widget.WidgetBackendHost<Paned,IPanedBackend>, IContainerEventSink<Panel>, IPanedEventSink
{
protected override IBackend OnCreateBackend ()
{
IPanedBackend b = (IPanedBackend) base.OnCreateBackend ();
// We always want to listen this event because we use it
// to reallocate the children
if (!EngineBackend.HandlesSizeNegotiation)
b.EnableEvent (PanedEvent.PositionChanged);
return b;
}
protected override void OnBackendCreated ()
{
Backend.Initialize (Parent.direction);
base.OnBackendCreated ();
}
public void ChildChanged (Panel child, string hint)
{
((Paned)Parent).OnChildChanged (child, hint);
}
public void ChildReplaced (Panel child, Widget oldWidget, Widget newWidget)
{
((Paned)Parent).OnReplaceChild (child, oldWidget, newWidget);
}
public void OnPositionChanged ()
{
((Paned)Parent).NotifyPositionChanged ();
}
}
internal Paned (Orientation direction)
{
this.direction = direction;
panel1 = new Panel ((WidgetBackendHost)BackendHost, 1);
panel2 = new Panel ((WidgetBackendHost)BackendHost, 2);
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IPanedBackend Backend {
get { return (IPanedBackend) BackendHost.Backend; }
}
/// <summary>
/// Left or top panel
/// </summary>
public Panel Panel1 {
get { return panel1; }
}
/// <summary>
/// Right or bottom panel
/// </summary>
public Panel Panel2 {
get { return panel2; }
}
/// <summary>
/// Gets or sets the position of the panel separator
/// </summary>
/// <value>
/// The position.
/// </value>
public double Position {
get { return Backend.Position; }
set { Backend.Position = value; }
}
/// <summary>
/// Gets or sets the position of the panel separator as a fraction available size
/// </summary>
/// <value>
/// The position.
/// </value>
public double PositionFraction {
get {
return Backend.Position / ((direction == Orientation.Horizontal) ? ScreenBounds.Width : ScreenBounds.Height);
}
set { Backend.Position = ((direction == Orientation.Horizontal) ? ScreenBounds.Width : ScreenBounds.Height) * value; }
}
void OnReplaceChild (Panel panel, Widget oldChild, Widget newChild)
{
if (oldChild != null) {
Backend.RemovePanel (panel.NumPanel);
UnregisterChild (oldChild);
}
if (newChild != null) {
RegisterChild (newChild);
Backend.SetPanel (panel.NumPanel, (IWidgetBackend)GetBackend (newChild), panel.Resize, panel.Shrink);
UpdatePanel (panel);
}
}
/// <summary>
/// Removes a child widget
/// </summary>
/// <param name='child'>
/// A widget bound to one of the panels
/// </param>
public void Remove (Widget child)
{
if (panel1.Content == child)
panel1.Content = null;
else if (panel2.Content == child)
panel2.Content = null;
}
void OnChildChanged (Panel panel, object hint)
{
UpdatePanel (panel);
}
void UpdatePanel (Panel panel)
{
Backend.UpdatePanel (panel.NumPanel, panel.Resize, panel.Shrink);
}
void NotifyPositionChanged ()
{
if (!BackendHost.EngineBackend.HandlesSizeNegotiation) {
if (panel1.Content != null)
panel1.Content.Surface.Reallocate ();
if (panel2.Content != null)
panel2.Content.Surface.Reallocate ();
}
OnPositionChanged ();
}
[MappedEvent(PanedEvent.PositionChanged)]
protected virtual void OnPositionChanged ()
{
if (positionChanged != null)
positionChanged (this, EventArgs.Empty);
}
public event EventHandler PositionChanged {
add {
BackendHost.OnBeforeEventAdd (PanedEvent.PositionChanged, positionChanged);
positionChanged += value;
}
remove {
positionChanged -= value;
BackendHost.OnAfterEventRemove (PanedEvent.PositionChanged, positionChanged);
}
}
}
public class Panel
{
IContainerEventSink<Panel> parent;
bool resize;
bool shrink;
int numPanel;
Widget child;
internal Panel (IContainerEventSink<Panel> parent, int numPanel)
{
this.parent = parent;
this.numPanel = numPanel;
}
/// <summary>
/// Gets or sets a value indicating whether this panel should be resized when the Paned container is resized.
/// </summary>
/// <value>
/// <c>true</c> if the panel has to be resized; otherwise, <c>false</c>.
/// </value>
public bool Resize {
get {
return this.resize;
}
set {
resize = value;
parent.ChildChanged (this, "Resize");
}
}
/// <summary>
/// Gets or sets a value indicating whether this panel can be made smaller than its min size
/// </summary>
/// <value>
/// <c>true</c> if the panel has to be shrinked; otherwise, <c>false</c>.
/// </value>
public bool Shrink {
get {
return this.shrink;
}
set {
shrink = value;
parent.ChildChanged (this, "Shrink");
}
}
/// <summary>
/// Gets or sets the content of the panel
/// </summary>
/// <value>
/// The content.
/// </value>
public Widget Content {
get {
return child;
}
set {
var old = child;
child = value;
parent.ChildReplaced (this, old, value);
}
}
internal int NumPanel {
get {
return this.numPanel;
}
set {
numPanel = value;
}
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="ResolveNamesRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the ResolveNamesRequest class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System.Collections.Generic;
/// <summary>
/// Represents a ResolveNames request.
/// </summary>
internal sealed class ResolveNamesRequest : MultiResponseServiceRequest<ResolveNamesResponse>, IJsonSerializable
{
private static LazyMember<Dictionary<ResolveNameSearchLocation, string>> searchScopeMap = new LazyMember<Dictionary<ResolveNameSearchLocation, string>>(
delegate
{
Dictionary<ResolveNameSearchLocation, string> map = new Dictionary<ResolveNameSearchLocation, string>();
map.Add(ResolveNameSearchLocation.DirectoryOnly, "ActiveDirectory");
map.Add(ResolveNameSearchLocation.DirectoryThenContacts, "ActiveDirectoryContacts");
map.Add(ResolveNameSearchLocation.ContactsOnly, "Contacts");
map.Add(ResolveNameSearchLocation.ContactsThenDirectory, "ContactsActiveDirectory");
return map;
});
private string nameToResolve;
private bool returnFullContactData;
private ResolveNameSearchLocation searchLocation;
private PropertySet contactDataPropertySet;
private FolderIdWrapperList parentFolderIds = new FolderIdWrapperList();
/// <summary>
/// Asserts the valid.
/// </summary>
internal override void Validate()
{
base.Validate();
EwsUtilities.ValidateNonBlankStringParam(this.NameToResolve, "NameToResolve");
}
/// <summary>
/// Creates the service response.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="responseIndex">Index of the response.</param>
/// <returns>Service response.</returns>
internal override ResolveNamesResponse CreateServiceResponse(ExchangeService service, int responseIndex)
{
return new ResolveNamesResponse(service);
}
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal override string GetXmlElementName()
{
return XmlElementNames.ResolveNames;
}
/// <summary>
/// Gets the name of the response XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal override string GetResponseXmlElementName()
{
return XmlElementNames.ResolveNamesResponse;
}
/// <summary>
/// Gets the name of the response message XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal override string GetResponseMessageXmlElementName()
{
return XmlElementNames.ResolveNamesResponseMessage;
}
/// <summary>
/// Initializes a new instance of the <see cref="ResolveNamesRequest"/> class.
/// </summary>
/// <param name="service">The service.</param>
internal ResolveNamesRequest(ExchangeService service)
: base(service, ServiceErrorHandling.ThrowOnError)
{
}
/// <summary>
/// Gets the expected response message count.
/// </summary>
/// <returns>Number of expected response messages.</returns>
internal override int GetExpectedResponseMessageCount()
{
return 1;
}
/// <summary>
/// Writes the attributes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteAttributesToXml(EwsServiceXmlWriter writer)
{
writer.WriteAttributeValue(
XmlAttributeNames.ReturnFullContactData,
this.ReturnFullContactData);
string searchScope = null;
searchScopeMap.Member.TryGetValue(this.SearchLocation, out searchScope);
EwsUtilities.Assert(
!string.IsNullOrEmpty(searchScope),
"ResolveNameRequest.WriteAttributesToXml",
"The specified search location cannot be mapped to an EWS search scope.");
string propertySet = null;
if (this.contactDataPropertySet != null)
{
PropertySet.DefaultPropertySetMap.Member.TryGetValue(this.contactDataPropertySet.BasePropertySet, out propertySet);
}
if (!this.Service.Exchange2007CompatibilityMode)
{
writer.WriteAttributeValue(XmlAttributeNames.SearchScope, searchScope);
}
if (!string.IsNullOrEmpty(propertySet))
{
writer.WriteAttributeValue(XmlAttributeNames.ContactDataShape, propertySet);
}
}
/// <summary>
/// Writes the elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
this.ParentFolderIds.WriteToXml(
writer,
XmlNamespace.Messages,
XmlElementNames.ParentFolderIds);
writer.WriteElementValue(
XmlNamespace.Messages,
XmlElementNames.UnresolvedEntry,
this.NameToResolve);
}
/// <summary>
/// Creates a JSON representation of this object.
/// </summary>
/// <param name="service">The service.</param>
/// <returns>
/// A Json value (either a JsonObject, an array of Json values, or a Json primitive)
/// </returns>
object IJsonSerializable.ToJson(ExchangeService service)
{
JsonObject jsonRequest = new JsonObject();
if (this.ParentFolderIds.Count > 0)
{
jsonRequest.Add(XmlElementNames.ParentFolderIds, this.ParentFolderIds.InternalToJson(service));
}
jsonRequest.Add(XmlElementNames.UnresolvedEntry, this.NameToResolve);
jsonRequest.Add(XmlAttributeNames.ReturnFullContactData, this.ReturnFullContactData);
string searchScope = null;
searchScopeMap.Member.TryGetValue(this.SearchLocation, out searchScope);
EwsUtilities.Assert(
!string.IsNullOrEmpty(searchScope),
"ResolveNameRequest.ToJson",
"The specified search location cannot be mapped to an EWS search scope.");
string propertySet = null;
if (this.contactDataPropertySet != null)
{
PropertySet.DefaultPropertySetMap.Member.TryGetValue(this.contactDataPropertySet.BasePropertySet, out propertySet);
}
if (!this.Service.Exchange2007CompatibilityMode)
{
jsonRequest.Add(XmlAttributeNames.SearchScope, searchScope);
}
if (!string.IsNullOrEmpty(propertySet))
{
jsonRequest.Add(XmlAttributeNames.ContactDataShape, propertySet);
}
return jsonRequest;
}
/// <summary>
/// Gets the request version.
/// </summary>
/// <returns>Earliest Exchange version in which this request is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2007_SP1;
}
/// <summary>
/// Gets or sets the name to resolve.
/// </summary>
/// <value>The name to resolve.</value>
public string NameToResolve
{
get { return this.nameToResolve; }
set { this.nameToResolve = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to return full contact data or not.
/// </summary>
/// <value>
/// <c>true</c> if should return full contact data; otherwise, <c>false</c>.
/// </value>
public bool ReturnFullContactData
{
get { return this.returnFullContactData; }
set { this.returnFullContactData = value; }
}
/// <summary>
/// Gets or sets the search location.
/// </summary>
/// <value>The search scope.</value>
public ResolveNameSearchLocation SearchLocation
{
get { return this.searchLocation; }
set { this.searchLocation = value; }
}
/// <summary>
/// Gets or sets the PropertySet for Contact Data
/// </summary>
/// <value>The PropertySet</value>
public PropertySet ContactDataPropertySet
{
get { return this.contactDataPropertySet; }
set { this.contactDataPropertySet = value; }
}
/// <summary>
/// Gets the parent folder ids.
/// </summary>
/// <value>The parent folder ids.</value>
public FolderIdWrapperList ParentFolderIds
{
get { return this.parentFolderIds; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace CS2JSWeb.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public abstract partial class SafeNCryptHandle : System.Runtime.InteropServices.SafeHandle
{
protected SafeNCryptHandle() : base(default(System.IntPtr), default(bool)) { }
protected override bool ReleaseHandle() { return default(bool); }
protected abstract bool ReleaseNativeHandle();
public override bool IsInvalid { get { return default(bool); } }
}
public sealed partial class SafeNCryptKeyHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptKeyHandle() { }
protected override bool ReleaseNativeHandle() { return default(bool); }
}
public sealed partial class SafeNCryptProviderHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptProviderHandle() { }
protected override bool ReleaseNativeHandle() { return default(bool); }
}
public sealed partial class SafeNCryptSecretHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptSecretHandle() { }
protected override bool ReleaseNativeHandle() { return default(bool); }
}
}
namespace System.Security.Cryptography
{
public sealed partial class CngAlgorithm : System.IEquatable<System.Security.Cryptography.CngAlgorithm>
{
public CngAlgorithm(string algorithm) { }
public string Algorithm { get { return default(string); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP521 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP521 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm MD5 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Rsa { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha1 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha512 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngAlgorithm other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { return default(bool); }
public override string ToString() { return default(string); }
}
public sealed partial class CngAlgorithmGroup : System.IEquatable<System.Security.Cryptography.CngAlgorithmGroup>
{
public CngAlgorithmGroup(string algorithmGroup) { }
public string AlgorithmGroup { get { return default(string); } }
public static System.Security.Cryptography.CngAlgorithmGroup DiffieHellman { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup Dsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDiffieHellman { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup Rsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngAlgorithmGroup other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { return default(bool); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum CngExportPolicies
{
AllowArchiving = 4,
AllowExport = 1,
AllowPlaintextArchiving = 8,
AllowPlaintextExport = 2,
None = 0,
}
public sealed partial class CngKey : System.IDisposable
{
internal CngKey() { }
public System.Security.Cryptography.CngAlgorithm Algorithm { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public System.Security.Cryptography.CngAlgorithmGroup AlgorithmGroup { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public System.Security.Cryptography.CngExportPolicies ExportPolicy { get { return default(System.Security.Cryptography.CngExportPolicies); } }
public Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle Handle { get { return default(Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle); } }
public bool IsEphemeral { get { return default(bool); } }
public bool IsMachineKey { get { return default(bool); } }
public string KeyName { get { return default(string); } }
public int KeySize { get { return default(int); } }
public System.Security.Cryptography.CngKeyUsages KeyUsage { get { return default(System.Security.Cryptography.CngKeyUsages); } }
public System.IntPtr ParentWindowHandle { get { return default(System.IntPtr); } set { } }
public System.Security.Cryptography.CngProvider Provider { get { return default(System.Security.Cryptography.CngProvider); } }
public Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle ProviderHandle { get { return default(Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle); } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { return default(System.Security.Cryptography.CngUIPolicy); } }
public string UniqueName { get { return default(string); } }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName, System.Security.Cryptography.CngKeyCreationParameters creationParameters) { return default(System.Security.Cryptography.CngKey); }
public void Delete() { }
public void Dispose() { }
public static bool Exists(string keyName) { return default(bool); }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider) { return default(bool); }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions options) { return default(bool); }
public byte[] Export(System.Security.Cryptography.CngKeyBlobFormat format) { return default(byte[]); }
public System.Security.Cryptography.CngProperty GetProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { return default(System.Security.Cryptography.CngProperty); }
public bool HasProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { return default(bool); }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format, System.Security.Cryptography.CngProvider provider) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle keyHandle, System.Security.Cryptography.CngKeyHandleOpenOptions keyHandleOpenOptions) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions openOptions) { return default(System.Security.Cryptography.CngKey); }
public void SetProperty(System.Security.Cryptography.CngProperty property) { }
}
public sealed partial class CngKeyBlobFormat : System.IEquatable<System.Security.Cryptography.CngKeyBlobFormat>
{
public CngKeyBlobFormat(string format) { }
public static System.Security.Cryptography.CngKeyBlobFormat EccPrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat EccPublicBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public string Format { get { return default(string); } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPublicBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat OpaqueTransportBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat Pkcs8PrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngKeyBlobFormat other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { return default(bool); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum CngKeyCreationOptions
{
MachineKey = 32,
None = 0,
OverwriteExistingKey = 128,
}
public sealed partial class CngKeyCreationParameters
{
public CngKeyCreationParameters() { }
public System.Nullable<System.Security.Cryptography.CngExportPolicies> ExportPolicy { get { return default(System.Nullable<System.Security.Cryptography.CngExportPolicies>); } set { } }
public System.Security.Cryptography.CngKeyCreationOptions KeyCreationOptions { get { return default(System.Security.Cryptography.CngKeyCreationOptions); } set { } }
public System.Nullable<System.Security.Cryptography.CngKeyUsages> KeyUsage { get { return default(System.Nullable<System.Security.Cryptography.CngKeyUsages>); } set { } }
public System.Security.Cryptography.CngPropertyCollection Parameters { get { return default(System.Security.Cryptography.CngPropertyCollection); } }
public System.IntPtr ParentWindowHandle { get { return default(System.IntPtr); } set { } }
public System.Security.Cryptography.CngProvider Provider { get { return default(System.Security.Cryptography.CngProvider); } set { } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { return default(System.Security.Cryptography.CngUIPolicy); } set { } }
}
[System.FlagsAttribute]
public enum CngKeyHandleOpenOptions
{
EphemeralKey = 1,
None = 0,
}
[System.FlagsAttribute]
public enum CngKeyOpenOptions
{
MachineKey = 32,
None = 0,
Silent = 64,
UserKey = 0,
}
[System.FlagsAttribute]
public enum CngKeyUsages
{
AllUsages = 16777215,
Decryption = 1,
KeyAgreement = 4,
None = 0,
Signing = 2,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct CngProperty : System.IEquatable<System.Security.Cryptography.CngProperty>
{
public CngProperty(string name, byte[] value, System.Security.Cryptography.CngPropertyOptions options) { throw new System.NotImplementedException(); }
public string Name { get { return default(string); } }
public System.Security.Cryptography.CngPropertyOptions Options { get { return default(System.Security.Cryptography.CngPropertyOptions); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngProperty other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public byte[] GetValue() { return default(byte[]); }
public static bool operator ==(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { return default(bool); }
}
public sealed partial class CngPropertyCollection : System.Collections.ObjectModel.Collection<System.Security.Cryptography.CngProperty>
{
public CngPropertyCollection() { }
}
[System.FlagsAttribute]
public enum CngPropertyOptions
{
CustomProperty = 1073741824,
None = 0,
Persist = -2147483648,
}
public sealed partial class CngProvider : System.IEquatable<System.Security.Cryptography.CngProvider>
{
public CngProvider(string provider) { }
public static System.Security.Cryptography.CngProvider MicrosoftSmartCardKeyStorageProvider { get { return default(System.Security.Cryptography.CngProvider); } }
public static System.Security.Cryptography.CngProvider MicrosoftSoftwareKeyStorageProvider { get { return default(System.Security.Cryptography.CngProvider); } }
public string Provider { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngProvider other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { return default(bool); }
public override string ToString() { return default(string); }
}
public sealed partial class CngUIPolicy
{
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext, string creationTitle) { }
public string CreationTitle { get { return default(string); } }
public string Description { get { return default(string); } }
public string FriendlyName { get { return default(string); } }
public System.Security.Cryptography.CngUIProtectionLevels ProtectionLevel { get { return default(System.Security.Cryptography.CngUIProtectionLevels); } }
public string UseContext { get { return default(string); } }
}
[System.FlagsAttribute]
public enum CngUIProtectionLevels
{
ForceHighProtection = 2,
None = 0,
ProtectKey = 1,
}
public sealed partial class RSACng : System.Security.Cryptography.RSA
{
public RSACng() { }
public RSACng(int keySize) { }
public RSACng(System.Security.Cryptography.CngKey key) { }
public System.Security.Cryptography.CngKey Key { get { return default(System.Security.Cryptography.CngKey); } }
public override byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { return default(byte[]); }
protected override void Dispose(bool disposing) { }
public override byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { return default(byte[]); }
public override System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters) { return default(System.Security.Cryptography.RSAParameters); }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters) { }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } }
public override byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); }
public override bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); }
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
#if !UNITY_5 || UNITY_5_0
#error Oculus Utilities require Unity 5.1 or higher.
#endif
using System;
using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using VR = UnityEngine.VR;
/// <summary>
/// Configuration data for Oculus virtual reality.
/// </summary>
public class OVRManager : MonoBehaviour
{
/// <summary>
/// Gets the singleton instance.
/// </summary>
public static OVRManager instance { get; private set; }
/// <summary>
/// Gets a reference to the active OVRDisplay
/// </summary>
public static OVRDisplay display { get; private set; }
/// <summary>
/// Gets a reference to the active OVRTracker
/// </summary>
public static OVRTracker tracker { get; private set; }
/// <summary>
/// Gets a reference to the active OVRInput
/// </summary>
public static OVRInput input { get; private set; }
private static bool _profileIsCached = false;
private static OVRProfile _profile;
/// <summary>
/// Gets the current profile, which contains information about the user's settings and body dimensions.
/// </summary>
public static OVRProfile profile
{
get {
if (!_profileIsCached)
{
_profile = new OVRProfile();
_profile.TriggerLoad();
while (_profile.state == OVRProfile.State.LOADING)
System.Threading.Thread.Sleep(1);
if (_profile.state != OVRProfile.State.READY)
Debug.LogWarning("Failed to load profile.");
_profileIsCached = true;
}
return _profile;
}
}
/// <summary>
/// Occurs when an HMD attached.
/// </summary>
public static event Action HMDAcquired;
/// <summary>
/// Occurs when an HMD detached.
/// </summary>
public static event Action HMDLost;
/// <summary>
/// Occurs when the tracker gained tracking.
/// </summary>
public static event Action TrackingAcquired;
/// <summary>
/// Occurs when the tracker lost tracking.
/// </summary>
public static event Action TrackingLost;
/// <summary>
/// Occurs when HSW dismissed.
/// </summary>
public static event Action HSWDismissed;
private static bool _isHmdPresentCached = false;
private static bool _isHmdPresent = false;
/// <summary>
/// If true, a head-mounted display is connected and present.
/// </summary>
public static bool isHmdPresent
{
get {
if (!_isHmdPresentCached)
{
_isHmdPresentCached = true;
_isHmdPresent = OVRPlugin.hmdPresent;
}
return _isHmdPresent;
}
private set {
_isHmdPresentCached = true;
_isHmdPresent = value;
}
}
private static bool _isHSWDisplayedCached = false;
private static bool _isHSWDisplayed = false;
private static bool _wasHSWDisplayed;
/// <summary>
/// If true, then the Oculus health and safety warning (HSW) is currently visible.
/// </summary>
public static bool isHSWDisplayed
{
get {
if (!isHmdPresent)
return false;
if (!_isHSWDisplayedCached)
{
_isHSWDisplayedCached = true;
_isHSWDisplayed = OVRPlugin.hswVisible;
}
return _isHSWDisplayed;
}
private set {
_isHSWDisplayedCached = true;
_isHSWDisplayed = value;
}
}
/// <summary>
/// If the HSW has been visible for the necessary amount of time, this will make it disappear.
/// </summary>
public static void DismissHSWDisplay()
{
if (!isHmdPresent)
return;
OVRPlugin.DismissHSW();
}
/// <summary>
/// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth.
/// </summary>
public bool chromatic
{
get {
if (!isHmdPresent)
return false;
return OVRPlugin.chromatic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.chromatic = value;
}
}
/// <summary>
/// If true, both eyes will see the same image, rendered from the center eye pose, saving performance.
/// </summary>
public bool monoscopic
{
get {
if (!isHmdPresent)
return true;
return OVRPlugin.monoscopic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.monoscopic = value;
}
}
/// <summary>
/// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.
/// </summary>
public bool queueAhead = true;
/// <summary>
/// Gets the current battery level.
/// </summary>
/// <returns><c>battery level in the range [0.0,1.0]</c>
/// <param name="batteryLevel">Battery level.</param>
public static float batteryLevel
{
get {
if (!isHmdPresent)
return 1f;
return OVRPlugin.batteryLevel;
}
}
/// <summary>
/// Gets the current battery temperature.
/// </summary>
/// <returns><c>battery temperature in Celsius</c>
/// <param name="batteryTemperature">Battery temperature.</param>
public static float batteryTemperature
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.batteryTemperature;
}
}
/// <summary>
/// Gets the current battery status.
/// </summary>
/// <returns><c>battery status</c>
/// <param name="batteryStatus">Battery status.</param>
public static int batteryStatus
{
get {
if (!isHmdPresent)
return -1;
return (int)OVRPlugin.batteryStatus;
}
}
/// <summary>
/// Gets the current volume level.
/// </summary>
/// <returns><c>volume level in the range [0,1].</c>
public static float volumeLevel
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.systemVolume;
}
}
/// <summary>
/// If true, head tracking will affect the orientation of each OVRCameraRig's cameras.
/// </summary>
public bool usePositionTracking = true;
/// <summary>
/// If true, each scene load will cause the head pose to reset.
/// </summary>
public bool resetTrackerOnLoad = true;
/// <summary>
/// True if the current platform supports virtual reality.
/// </summary>
public bool isSupportedPlatform { get; private set; }
private static bool wasHmdPresent = false;
private static bool wasPositionTracked = false;
[NonSerialized]
private static OVRVolumeControl volumeController = null;
[NonSerialized]
private Transform volumeControllerTransform = null;
#region Unity Messages
private void Awake()
{
// Only allow one instance at runtime.
if (instance != null)
{
enabled = false;
DestroyImmediate(this);
return;
}
instance = this;
System.Version netVersion = OVRPlugin.wrapperVersion;
System.Version ovrVersion = OVRPlugin.version;
Debug.Log("Unity v" + Application.unityVersion + ", " +
"Oculus Utilities v" + netVersion + ", " +
"OVRPlugin v" + ovrVersion + ".");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if (SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
Debug.LogWarning("VR rendering requires Direct3D11. Your graphics device: " + SystemInfo.graphicsDeviceType);
#endif
// Detect whether this platform is a supported platform
RuntimePlatform currPlatform = Application.platform;
isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
//isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
if (!isSupportedPlatform)
{
Debug.LogWarning("This platform is unsupported");
return;
}
#if UNITY_ANDROID && !UNITY_EDITOR
// We want to set up our touchpad messaging system
OVRTouchpad.Create();
// Turn off chromatic aberration by default to save texture bandwidth.
chromatic = false;
#endif
InitVolumeController();
if (display == null)
display = new OVRDisplay();
if (tracker == null)
tracker = new OVRTracker();
if (input == null)
input = new OVRInput();
if (resetTrackerOnLoad)
display.RecenterPose();
}
private void OnEnable()
{
if (volumeController != null)
{
volumeController.UpdatePosition(volumeControllerTransform);
}
}
private void Update()
{
tracker.isEnabled = usePositionTracking;
// Dispatch any events.
isHmdPresent = OVRPlugin.hmdPresent;
if (isHmdPresent)
{
OVRPlugin.queueAheadFraction = (queueAhead) ? 0.25f : 0f;
}
if (HMDLost != null && wasHmdPresent && !isHmdPresent)
HMDLost();
if (HMDAcquired != null && !wasHmdPresent && isHmdPresent)
HMDAcquired();
wasHmdPresent = isHmdPresent;
if (TrackingLost != null && wasPositionTracked && !tracker.isPositionTracked)
TrackingLost();
if (TrackingAcquired != null && !wasPositionTracked && tracker.isPositionTracked)
TrackingAcquired();
wasPositionTracked = tracker.isPositionTracked;
isHSWDisplayed = OVRPlugin.hswVisible;
if (isHSWDisplayed && Input.anyKeyDown)
DismissHSWDisplay();
if (!isHSWDisplayed && _wasHSWDisplayed)
{
if (HSWDismissed != null)
HSWDismissed();
}
_wasHSWDisplayed = isHSWDisplayed;
display.Update();
input.Update();
if (volumeController != null)
{
if (volumeControllerTransform == null)
{
if (gameObject.GetComponent<OVRCameraRig>() != null)
{
volumeControllerTransform = gameObject.GetComponent<OVRCameraRig>().centerEyeAnchor;
}
}
volumeController.UpdatePosition(volumeControllerTransform);
}
}
/// <summary>
/// Creates a popup dialog that shows when volume changes.
/// </summary>
private static void InitVolumeController()
{
if (volumeController == null)
{
Debug.Log("Creating volume controller...");
// Create the volume control popup
GameObject go = GameObject.Instantiate(Resources.Load("OVRVolumeController")) as GameObject;
if (go != null)
{
volumeController = go.GetComponent<OVRVolumeControl>();
}
else
{
Debug.LogError("Unable to instantiate volume controller");
}
}
}
/// <summary>
/// Leaves the application/game and returns to the launcher/dashboard
/// </summary>
public void ReturnToLauncher()
{
// show the platform UI quit prompt
OVRManager.PlatformUIConfirmQuit();
}
#endregion
public static void PlatformUIConfirmQuit()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit);
}
public static void PlatformUIGlobalMenu()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.GlobalMenu);
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="UnsafeNativeMethods.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web {
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Util;
[
System.Runtime.InteropServices.ComVisible(false),
System.Security.SuppressUnmanagedCodeSecurityAttribute()
]
internal static class UnsafeNativeMethods {
static internal readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
/*
* ADVAPI32.dll
*/
[DllImport(ModName.ADVAPI32_FULL_NAME)]
internal static extern int SetThreadToken(IntPtr threadref, IntPtr token);
[DllImport(ModName.ADVAPI32_FULL_NAME)]
internal static extern int RevertToSelf();
public const int TOKEN_ALL_ACCESS = 0x000f01ff;
public const int TOKEN_EXECUTE = 0x00020000;
public const int TOKEN_READ = 0x00020008;
public const int TOKEN_IMPERSONATE = 0x00000004;
public const int ERROR_NO_TOKEN = 1008;
[DllImport(ModName.ADVAPI32_FULL_NAME, SetLastError=true)]
internal static extern int OpenThreadToken(IntPtr thread, int access, bool openAsSelf, ref IntPtr hToken);
public const int OWNER_SECURITY_INFORMATION = 0x00000001;
public const int GROUP_SECURITY_INFORMATION = 0x00000002;
public const int DACL_SECURITY_INFORMATION = 0x00000004;
public const int SACL_SECURITY_INFORMATION = 0x00000008;
[DllImport(ModName.ADVAPI32_FULL_NAME, SetLastError=true, CharSet=CharSet.Unicode)]
internal static extern int GetFileSecurity(string filename, int requestedInformation, byte[] securityDescriptor, int length, ref int lengthNeeded);
[DllImport(ModName.ADVAPI32_FULL_NAME, SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int LogonUser(String username, String domain, String password, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport(ModName.ADVAPI32_FULL_NAME, SetLastError = true, CharSet = CharSet.Unicode)]
public extern static int ConvertStringSidToSid(string stringSid, out IntPtr pSid);
[DllImport(ModName.ADVAPI32_FULL_NAME, SetLastError = true, CharSet = CharSet.Unicode)]
public extern static int LookupAccountSid(string systemName, IntPtr pSid, StringBuilder szName, ref int nameSize, StringBuilder szDomain, ref int domainSize, ref int eUse);
/*
* ASPNET_STATE.EXE
*/
[DllImport(ModName.STATE_FULL_NAME)]
internal static extern void STWNDCloseConnection(IntPtr tracker);
[DllImport(ModName.STATE_FULL_NAME)]
internal static extern void STWNDDeleteStateItem(IntPtr stateItem);
[DllImport(ModName.STATE_FULL_NAME)]
internal static extern void STWNDEndOfRequest(IntPtr tracker);
[DllImport(ModName.STATE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern void STWNDGetLocalAddress(IntPtr tracker, StringBuilder buf);
[DllImport(ModName.STATE_FULL_NAME)]
internal static extern int STWNDGetLocalPort(IntPtr tracker);
[DllImport(ModName.STATE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern void STWNDGetRemoteAddress(IntPtr tracker, StringBuilder buf);
[DllImport(ModName.STATE_FULL_NAME)]
internal static extern int STWNDGetRemotePort(IntPtr tracker);
[DllImport(ModName.STATE_FULL_NAME)]
internal static extern bool STWNDIsClientConnected(IntPtr tracker);
[DllImport(ModName.STATE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void STWNDSendResponse(IntPtr tracker, StringBuilder status, int statusLength,
StringBuilder headers, int headersLength, IntPtr unmanagedState);
/*
* KERNEL32.DLL
*/
internal const int FILE_ATTRIBUTE_READONLY = 0x00000001;
internal const int FILE_ATTRIBUTE_HIDDEN = 0x00000002;
internal const int FILE_ATTRIBUTE_SYSTEM = 0x00000004;
internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
internal const int FILE_ATTRIBUTE_ARCHIVE = 0x00000020;
internal const int FILE_ATTRIBUTE_DEVICE = 0x00000040;
internal const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
internal const int FILE_ATTRIBUTE_TEMPORARY = 0x00000100;
internal const int FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200;
internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;
internal const int FILE_ATTRIBUTE_COMPRESSED = 0x00000800;
internal const int FILE_ATTRIBUTE_OFFLINE = 0x00001000;
internal const int FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000;
internal const int FILE_ATTRIBUTE_ENCRYPTED = 0x00004000;
internal const int DELETE = 0x00010000;
internal const int READ_CONTROL = 0x00020000;
internal const int WRITE_DAC = 0x00040000;
internal const int WRITE_OWNER = 0x00080000;
internal const int SYNCHRONIZE = 0x00100000;
internal const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
internal const int STANDARD_RIGHTS_EXECUTE = READ_CONTROL;
internal const int GENERIC_READ = unchecked(((int)0x80000000));
internal const int STANDARD_RIGHTS_ALL = 0x001F0000;
internal const int SPECIFIC_RIGHTS_ALL = 0x0000FFFF;
internal const int FILE_SHARE_READ = 0x00000001;
internal const int FILE_SHARE_WRITE = 0x00000002;
internal const int FILE_SHARE_DELETE = 0x00000004;
internal const int OPEN_EXISTING = 3;
internal const int OPEN_ALWAYS = 4;
internal const int FILE_FLAG_WRITE_THROUGH = unchecked((int)0x80000000);
internal const int FILE_FLAG_OVERLAPPED = 0x40000000;
internal const int FILE_FLAG_NO_BUFFERING = 0x20000000;
internal const int FILE_FLAG_RANDOM_ACCESS = 0x10000000;
internal const int FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000;
internal const int FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
internal const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
internal const int FILE_FLAG_POSIX_SEMANTICS = 0x01000000;
// Win32 Structs in N/Direct style
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct WIN32_FIND_DATA {
internal uint dwFileAttributes;
// ftCreationTime was a by-value FILETIME structure
internal uint ftCreationTime_dwLowDateTime ;
internal uint ftCreationTime_dwHighDateTime;
// ftLastAccessTime was a by-value FILETIME structure
internal uint ftLastAccessTime_dwLowDateTime;
internal uint ftLastAccessTime_dwHighDateTime;
// ftLastWriteTime was a by-value FILETIME structure
internal uint ftLastWriteTime_dwLowDateTime;
internal uint ftLastWriteTime_dwHighDateTime;
internal uint nFileSizeHigh;
internal uint nFileSizeLow;
internal uint dwReserved0;
internal uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
internal string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)]
internal string cAlternateFileName;
}
[StructLayout(LayoutKind.Sequential)]
internal struct WIN32_FILE_ATTRIBUTE_DATA {
internal int fileAttributes;
internal uint ftCreationTimeLow;
internal uint ftCreationTimeHigh;
internal uint ftLastAccessTimeLow;
internal uint ftLastAccessTimeHigh;
internal uint ftLastWriteTimeLow;
internal uint ftLastWriteTimeHigh;
internal uint fileSizeHigh;
internal uint fileSizeLow;
}
[StructLayout(LayoutKind.Sequential)]
internal struct WIN32_BY_HANDLE_FILE_INFORMATION {
internal int fileAttributes;
internal uint ftCreationTimeLow;
internal uint ftCreationTimeHigh;
internal uint ftLastAccessTimeLow;
internal uint ftLastAccessTimeHigh;
internal uint ftLastWriteTimeLow;
internal uint ftLastWriteTimeHigh;
internal uint volumeSerialNumber;
internal uint fileSizeHigh;
internal uint fileSizeLow;
internal uint numberOfLinks;
internal uint fileIndexHigh;
internal uint fileIndexLow;
}
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int lstrlenW(IntPtr ptr);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Ansi)]
internal static extern int lstrlenA(IntPtr ptr);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool MoveFileEx(string oldFilename, string newFilename, UInt32 flags);
[DllImport(ModName.KERNEL32_FULL_NAME, SetLastError=true)]
internal static extern bool CloseHandle(IntPtr handle);
[DllImport(ModName.KERNEL32_FULL_NAME, SetLastError=true)]
internal static extern bool FindClose(IntPtr hndFindFile);
[DllImport(ModName.KERNEL32_FULL_NAME, SetLastError=true, CharSet=CharSet.Unicode)]
internal static extern IntPtr FindFirstFile(
string pFileName, out WIN32_FIND_DATA pFindFileData);
[DllImport(ModName.KERNEL32_FULL_NAME, SetLastError=true, CharSet=CharSet.Unicode)]
internal static extern bool FindNextFile(
IntPtr hndFindFile, out WIN32_FIND_DATA pFindFileData);
internal const int GetFileExInfoStandard = 0;
[DllImport(ModName.KERNEL32_FULL_NAME, SetLastError=true, CharSet=CharSet.Unicode)]
internal static extern bool GetFileAttributesEx(string name, int fileInfoLevel, out WIN32_FILE_ATTRIBUTE_DATA data);
#if !FEATURE_PAL // FEATURE_PAL native imports
[DllImport(ModName.KERNEL32_FULL_NAME)]
internal extern static int GetProcessAffinityMask(
IntPtr handle,
out IntPtr processAffinityMask,
out IntPtr systemAffinityMask);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode)]
internal extern static int GetComputerName(StringBuilder nameBuffer, ref int bufferSize);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode)]
internal /*public*/ extern static int GetModuleFileName(IntPtr module, StringBuilder filename, int size);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode)]
internal /*public*/ extern static IntPtr GetModuleHandle(string moduleName);
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct SYSTEM_INFO {
public ushort wProcessorArchitecture;
public ushort wReserved;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public IntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort wProcessorLevel;
public ushort wProcessorRevision;
};
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void GetSystemInfo(out SYSTEM_INFO si);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern IntPtr LoadLibrary(string libFilename);
[DllImport(ModName.KERNEL32_FULL_NAME, SetLastError=true)]
internal static extern bool FreeLibrary(IntPtr hModule);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern IntPtr FindResource(IntPtr hModule, IntPtr lpName, IntPtr lpType);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern int SizeofResource(IntPtr hModule, IntPtr hResInfo);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern IntPtr LockResource(IntPtr hResData);
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode)]
public extern static IntPtr LocalFree(IntPtr pMem);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct MEMORYSTATUSEX {
internal int dwLength;
internal int dwMemoryLoad;
internal long ullTotalPhys;
internal long ullAvailPhys;
internal long ullTotalPageFile;
internal long ullAvailPageFile;
internal long ullTotalVirtual;
internal long ullAvailVirtual;
internal long ullAvailExtendedVirtual;
internal void Init() {
dwLength = Marshal.SizeOf(typeof(UnsafeNativeMethods.MEMORYSTATUSEX));
}
}
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode)]
internal extern static int GlobalMemoryStatusEx(ref MEMORYSTATUSEX memoryStatusEx);
#else // !FEATURE_PAL
internal static int GetProcessAffinityMask(
IntPtr handle,
out IntPtr processAffinityMask,
out IntPtr systemAffinityMask)
{
// ROTORTODO - PAL should supply GetProcessAffinityMask
// The only code that calls here is in SystemInfo::GetNumProcessCPUs and
// it fails graciously if we return 0
processAffinityMask = IntPtr.Zero;
systemAffinityMask = IntPtr.Zero;
return 0; // fail
}
internal static IntPtr GetModuleHandle(string moduleName)
{
// ROTORTODO
// So we never find any modules, so what? :-)
return IntPtr.Zero;
}
internal static int GlobalMemoryStatusEx(ref MEMORYSTATUSEX memoryStatusEx)
{
// ROTORTODO
// This API is called from two places in CacheMemoryTotalMemoryPressure
// Does it fail gracefully if the API fails?
return 0;
}
internal static void AppDomainRestart(string appId)
{
// ROTORTODO
// Do Nothing
}
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="PAL_GetUserTempDirectoryW")]
internal extern static bool GetUserTempDirectory(DeploymentDirectoryType ddt, StringBuilder sb, ref UInt32 length);
// The order should be the same as in rotor_pal.h
internal enum DeploymentDirectoryType
{
ddtInstallationDependentDirectory = 0,
ddtInstallationIndependentDirectory
}
[DllImport(ModName.KERNEL32_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="PAL_GetMachineConfigurationDirectoryW")]
internal extern static bool GetMachineConfigurationDirectory(StringBuilder sb, ref UInt32 length);
#endif // !FEATURE_PAL
[DllImport(ModName.KERNEL32_FULL_NAME)]
internal static extern IntPtr GetCurrentThread();
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa366569(v=vs.85).aspx
[DllImport(ModName.KERNEL32_FULL_NAME, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern IntPtr GetProcessHeap();
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa366701(v=vs.85).aspx
[DllImport(ModName.KERNEL32_FULL_NAME, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
internal static extern bool HeapFree(
[In] IntPtr hHeap,
[In] uint dwFlags,
[In] IntPtr lpMem);
/*
* webengine.dll
*/
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern void AppDomainRestart(string appId);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int AspCompatProcessRequest(AspCompatCallback callback, [MarshalAs(UnmanagedType.Interface)] Object context, bool sharedActivity, int activityHash);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int AspCompatOnPageStart([MarshalAs(UnmanagedType.Interface)] Object obj);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int AspCompatOnPageEnd();
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int AspCompatIsApartmentComponent([MarshalAs(UnmanagedType.Interface)] Object obj);
#endif // !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int AttachDebugger(string clsId, string sessId, IntPtr userToken);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int ChangeAccessToKeyContainer(string containerName, string accountName, string csp, int options);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int CookieAuthParseTicket (byte [] pData,
int iDataLen,
StringBuilder szName,
int iNameLen,
StringBuilder szData,
int iUserDataLen,
StringBuilder szPath,
int iPathLen,
byte [] pBytes,
long [] pDates);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int CookieAuthConstructTicket (byte [] pData,
int iDataLen,
string szName,
string szData,
string szPath,
byte [] pBytes,
long [] pDates);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern IntPtr CreateUserToken(string name, string password, int fImpersonationToken, StringBuilder strError, int iErrorSize);
internal const uint FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001;
internal const uint FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002;
internal const uint FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004;
internal const uint FILE_NOTIFY_CHANGE_SIZE = 0x00000008;
internal const uint FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010;
internal const uint FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020;
internal const uint FILE_NOTIFY_CHANGE_CREATION = 0x00000040;
internal const uint FILE_NOTIFY_CHANGE_SECURITY = 0x00000100;
internal const uint RDCW_FILTER_FILE_AND_DIR_CHANGES =
FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_CREATION |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_SECURITY;
internal const uint RDCW_FILTER_FILE_CHANGES =
FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_CREATION |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_SECURITY;
internal const uint RDCW_FILTER_DIR_RENAMES = FILE_NOTIFY_CHANGE_DIR_NAME;
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void GetDirMonConfiguration(out int FCNMode);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void DirMonClose(HandleRef dirMon, bool fNeedToDispose);
#if !FEATURE_PAL // FEATURE_PAL does not enable file change notification
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int DirMonOpen(string dir, string appId, bool watchSubtree, uint notifyFilter, int fcnMode, NativeFileChangeNotification callback, out IntPtr pCompletion);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int GrowFileNotificationBuffer( string appId, bool fWatchSubtree );
#endif // !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void EcbFreeExecUrlEntityInfo(IntPtr pEntity);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetBasics(IntPtr pECB, byte[] buffer, int size, int[] contentInfo);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetBasicsContentInfo(IntPtr pECB, int[] contentInfo);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetTraceFlags(IntPtr pECB, int[] contentInfo);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet = CharSet.Unicode)]
internal static extern int EcbEmitSimpleTrace(IntPtr pECB, int type, string eventData);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet = CharSet.Unicode)]
internal static extern int EcbEmitWebEventTrace(
IntPtr pECB,
int webEventType,
int fieldCount,
string[] fieldNames,
int[] fieldTypes,
string[] fieldData);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetClientCertificate(IntPtr pECB, byte[] buffer, int size, int [] pInts, long [] pDates);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetExecUrlEntityInfo(int entityLength, byte[] entity, out IntPtr ppEntity);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetTraceContextId(IntPtr pECB, out Guid traceContextId);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int EcbGetServerVariable(IntPtr pECB, string name, byte[] buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetServerVariableByIndex(IntPtr pECB, int nameIndex, byte[] buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int EcbGetQueryString(IntPtr pECB, int encode, StringBuilder buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int EcbGetUnicodeServerVariable(IntPtr pECB, string name, IntPtr buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetUnicodeServerVariableByIndex(IntPtr pECB, int nameIndex, IntPtr buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetUnicodeServerVariables(IntPtr pECB, IntPtr buffer, int bufferSizeInChars, int[] serverVarLengths, int serverVarCount, int startIndex, ref int requiredSize);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetVersion(IntPtr pECB);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetQueryStringRawBytes(IntPtr pECB, byte[] buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetPreloadedPostedContent(IntPtr pECB, byte[] bytes, int offset, int bufferSize);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbGetAdditionalPostedContent(IntPtr pECB, byte[] bytes, int offset, int bufferSize);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbReadClientAsync(IntPtr pECB, int dwBytesToRead, AsyncCompletionCallback pfnCallback);
#if !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbFlushCore(IntPtr pECB,
byte[] status,
byte[] header,
int keepConnected,
int totalBodySize,
int numBodyFragments,
IntPtr[] bodyFragments,
int[] bodyFragmentLengths,
int doneWithSession,
int finalStatus,
int kernelCache,
int async,
ISAPIAsyncCompletionCallback asyncCompletionCallback);
#endif // !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbIsClientConnected(IntPtr pECB);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbCloseConnection(IntPtr pECB);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int EcbMapUrlToPath(IntPtr pECB, string url, byte[] buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern IntPtr EcbGetImpersonationToken(IntPtr pECB, IntPtr processHandle);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern IntPtr EcbGetVirtualPathToken(IntPtr pECB, IntPtr processHandle);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int EcbAppendLogParameter(IntPtr pECB, string logParam);
#if !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int EcbExecuteUrlUnicode(IntPtr pECB,
string url,
string method,
string childHeaders,
bool sendHeaders,
bool addUserIndo,
IntPtr token,
string name,
string authType,
IntPtr pEntity,
ISAPIAsyncCompletionCallback asyncCompletionCallback);
#endif // !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void InvalidateKernelCache(string key);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void FreeFileSecurityDescriptor(IntPtr securityDesciptor);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern IntPtr GetFileHandleForTransmitFile(string strFile);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern IntPtr GetFileSecurityDescriptor(string strFile);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int GetGroupsForUser(IntPtr token, StringBuilder allGroups, int allGrpSize, StringBuilder error, int errorSize);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int GetHMACSHA1Hash(byte[] data1, int dataOffset1, int dataSize1, byte[] data2, int dataSize2,
byte[] innerKey, int innerKeySize, byte[] outerKey, int outerKeySize,
byte[] hash, int hashSize);
#if !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int GetPrivateBytesIIS6(out long privatePageCount, bool nocache);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int GetProcessMemoryInformation(uint pid, out uint privatePageCount, out uint peakPagefileUsage, bool nocache);
#else // !FEATURE_PAL
internal static int GetProcessMemoryInformation(uint pid, out uint privatePageCount, out uint peakPagefileUsage, bool nocache)
{
// ROTORTODO
// called from CacheMemoryPrivateBytesPressure.GetCurrentPressure;
// returning 0 causes it to ignore memory pressure
privatePageCount = 0;
peakPagefileUsage = 0;
return 0;
}
#endif // !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int GetSHA1Hash(byte[] data, int dataSize,
byte[] hash, int hashSize);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int GetW3WPMemoryLimitInKB();
[DllImport(ModName.ENGINE_FULL_NAME)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "This isn't a dangerous method.")]
internal static extern void SetClrThreadPoolLimits(int maxWorkerThreads, int maxIoThreads, bool autoConfig);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void SetMinRequestsExecutingToDetectDeadlock(int minRequestsExecutingToDetectDeadlock);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void InitializeLibrary(bool reduceMaxThreads);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void PerfCounterInitialize();
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void InitializeHealthMonitor(int deadlockIntervalSeconds, int requestQueueLimit);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int IsAccessToFileAllowed(IntPtr securityDesciptor, IntPtr iThreadToken, int iAccess);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int IsUserInRole(IntPtr token, string rolename, StringBuilder error, int errorSize);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void UpdateLastActivityTimeForHealthMonitor();
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern int GetCredentialFromRegistry(String strRegKey, StringBuilder buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME, BestFitMapping=false)]
internal static extern int EcbGetChannelBindingToken(IntPtr pECB, out IntPtr token, out int tokenSize);
/////////////////////////////////////////////////////////////////////////////
// List of functions supported by PMCallISAPI
//
// ATTENTION!!
// If you change this list, make sure it is in [....] with the
// CallISAPIFunc enum in ecbdirect.h
//
internal enum CallISAPIFunc : int {
GetSiteServerComment = 1,
RestrictIISFolders = 2,
CreateTempDir = 3,
GetAutogenKeys = 4,
GenerateToken = 5
};
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EcbCallISAPI(IntPtr pECB, UnsafeNativeMethods.CallISAPIFunc iFunction, byte[] bufferIn, int sizeIn, byte[] bufferOut, int sizeOut);
// Constants as defined in ndll.h
public const int RESTRICT_BIN =0x00000001;
/////////////////////////////////////////////////////////////////////////////
// Passport Auth
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int PassportVersion();
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportCreateHttpRaw(
string szRequestLine,
string szHeaders,
int fSecure,
StringBuilder szBufOut,
int dwRetBufSize,
ref IntPtr passportManager);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportTicket(
IntPtr pManager,
string szAttr,
out object pReturn);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetCurrentConfig(
IntPtr pManager,
string szAttr,
out object pReturn);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportLogoutURL(
IntPtr pManager,
string szReturnURL,
string szCOBrandArgs,
int iLangID,
string strDomain,
int iUseSecureAuth,
StringBuilder szAuthVal,
int iAuthValSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetOption(
IntPtr pManager,
string szOption,
out Object vOut);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportSetOption(
IntPtr pManager,
string szOption,
Object vOut);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetLoginChallenge(
IntPtr pManager,
string szRetURL,
int iTimeWindow,
int fForceLogin,
string szCOBrandArgs,
int iLangID,
string strNameSpace,
int iKPP,
int iUseSecureAuth,
object vExtraParams,
StringBuilder szOut,
int iOutSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportHexPUID(
IntPtr pManager,
StringBuilder szOut,
int iOutSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportCreate (string szQueryStrT,
string szQueryStrP,
string szAuthCookie,
string szProfCookie,
string szProfCCookie,
StringBuilder szAuthCookieRet,
StringBuilder szProfCookieRet,
int iRetBufSize,
ref IntPtr passportManager);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportAuthURL (
IntPtr iPassport,
string szReturnURL,
int iTimeWindow,
int fForceLogin,
string szCOBrandArgs,
int iLangID,
string strNameSpace,
int iKPP,
int iUseSecureAuth,
StringBuilder szAuthVal,
int iAuthValSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportAuthURL2 (
IntPtr iPassport,
string szReturnURL,
int iTimeWindow,
int fForceLogin,
string szCOBrandArgs,
int iLangID,
string strNameSpace,
int iKPP,
int iUseSecureAuth,
StringBuilder szAuthVal,
int iAuthValSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetError(IntPtr iPassport);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportDomainFromMemberName (
IntPtr iPassport,
string szDomain,
StringBuilder szMember,
int iMemberSize);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int PassportGetFromNetworkServer (IntPtr iPassport);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetDomainAttribute (
IntPtr iPassport,
string szAttributeName,
int iLCID,
string szDomain,
StringBuilder szValue,
int iValueSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportHasProfile (
IntPtr iPassport,
string szProfile);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportHasFlag (
IntPtr iPassport,
int iFlagMask);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportHasConsent (
IntPtr iPassport,
int iFullConsent,
int iNeedBirthdate);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetHasSavedPassword (IntPtr iPassport);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportHasTicket (IntPtr iPassport);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportIsAuthenticated (
IntPtr iPassport,
int iTimeWindow,
int fForceLogin,
int iUseSecureAuth);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportLogoTag (
IntPtr iPassport,
string szRetURL,
int iTimeWindow,
int fForceLogin,
string szCOBrandArgs,
int iLangID,
int fSecure,
string strNameSpace,
int iKPP,
int iUseSecureAuth,
StringBuilder szValue,
int iValueSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportLogoTag2 (
IntPtr iPassport,
string szRetURL,
int iTimeWindow,
int fForceLogin,
string szCOBrandArgs,
int iLangID,
int fSecure,
string strNameSpace,
int iKPP,
int iUseSecureAuth,
StringBuilder szValue,
int iValueSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetProfile (
IntPtr iPassport,
string szProfile,
out Object rOut);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetTicketAge(IntPtr iPassport);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportGetTimeSinceSignIn(IntPtr iPassport);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void PassportDestroy(IntPtr iPassport);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportCrypt(
int iFunctionID,
string szSrc,
StringBuilder szDest,
int iDestLength);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int PassportCryptPut(
int iFunctionID,
string szSrc);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int PassportCryptIsValid();
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int PostThreadPoolWorkItem(WorkItemCallback callback);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern IntPtr InstrumentedMutexCreate(string name);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void InstrumentedMutexDelete(HandleRef mutex);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int InstrumentedMutexGetLock(HandleRef mutex, int timeout);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int InstrumentedMutexReleaseLock(HandleRef mutex);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void InstrumentedMutexSetState(HandleRef mutex, int state);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern int IsapiAppHostMapPath(String appId, String virtualPath, StringBuilder buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern int IsapiAppHostGetAppPath(String aboPath, StringBuilder buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern int IsapiAppHostGetUncUser(String appId, StringBuilder usernameBuffer, int usernameSize, StringBuilder passwordBuffer, int passwordSize);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern int IsapiAppHostGetSiteName(String appId, StringBuilder buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern int IsapiAppHostGetSiteId(String site, StringBuilder buffer, int size);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode, BestFitMapping=false)]
internal static extern int IsapiAppHostGetNextVirtualSubdir(String aboPath, bool inApp, ref int index, StringBuilder sb, int size);
[DllImport(ModName.ENGINE_FULL_NAME, BestFitMapping=false)]
internal static extern IntPtr BufferPoolGetPool(int bufferSize, int maxFreeListCount);
[DllImport(ModName.ENGINE_FULL_NAME, BestFitMapping=false)]
internal static extern IntPtr BufferPoolGetBuffer(IntPtr pool);
[DllImport(ModName.ENGINE_FULL_NAME, BestFitMapping=false)]
internal static extern void BufferPoolReleaseBuffer(IntPtr buffer);
/*
* ASPNET_WP.EXE
*/
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetTraceContextId")]
internal static extern int PMGetTraceContextId(IntPtr pMsg, out Guid traceContextId);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetHistoryTable")]
internal static extern int PMGetHistoryTable (int iRows,
int [] dwPIDArr,
int [] dwReqExecuted,
int [] dwReqPending,
int [] dwReqExecuting,
int [] dwReasonForDeath,
int [] dwPeakMemoryUsed,
long [] tmCreateTime,
long [] tmDeathTime);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetCurrentProcessInfo")]
internal static extern int PMGetCurrentProcessInfo (ref int dwReqExecuted,
ref int dwReqExecuting,
ref int dwPeakMemoryUsed,
ref long tmCreateTime,
ref int pid);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetMemoryLimitInMB")]
internal static extern int PMGetMemoryLimitInMB ();
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetBasics")]
internal static extern int PMGetBasics(IntPtr pMsg, byte[] buffer, int size, int[] contentInfo);
[DllImport(ModName.WP_FULL_NAME)]
internal static extern int PMGetClientCertificate(IntPtr pMsg, byte[] buffer, int size, int [] pInts, long [] pDates);
[DllImport(ModName.WP_FULL_NAME)]
internal static extern long PMGetStartTimeStamp(IntPtr pMsg);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetAllServerVariables")]
internal static extern int PMGetAllServerVariables(IntPtr pMsg, byte[] buffer, int size);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetQueryString", CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int PMGetQueryString(IntPtr pMsg, int encode, StringBuilder buffer, int size);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetQueryStringRawBytes")]
internal static extern int PMGetQueryStringRawBytes(IntPtr pMsg, byte[] buffer, int size);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetPreloadedPostedContent")]
internal static extern int PMGetPreloadedPostedContent(IntPtr pMsg, byte[] bytes, int offset, int bufferSize);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetAdditionalPostedContent")]
internal static extern int PMGetAdditionalPostedContent(IntPtr pMsg, byte[] bytes, int offset, int bufferSize);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMEmptyResponse")]
internal static extern int PMEmptyResponse(IntPtr pMsg);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMIsClientConnected")]
internal static extern int PMIsClientConnected(IntPtr pMsg);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMCloseConnection")]
internal static extern int PMCloseConnection(IntPtr pMsg);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMMapUrlToPath", CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int PMMapUrlToPath(IntPtr pMsg, string url, byte[] buffer, int size);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetImpersonationToken")]
internal static extern IntPtr PMGetImpersonationToken(IntPtr pMsg);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMGetVirtualPathToken")]
internal static extern IntPtr PMGetVirtualPathToken(IntPtr pMsg);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMAppendLogParameter", CharSet=CharSet.Ansi, BestFitMapping=false)]
internal static extern int PMAppendLogParameter(IntPtr pMsg, string logParam);
[DllImport(ModName.WP_FULL_NAME, EntryPoint="PMFlushCore")]
internal static extern int PMFlushCore(IntPtr pMsg,
byte[] status,
byte[] header,
int keepConnected,
int totalBodySize,
int bodyFragmentsOffset,
int numBodyFragments,
IntPtr[] bodyFragments,
int[] bodyFragmentLengths,
int doneWithSession,
int finalStatus);
[DllImport(ModName.WP_FULL_NAME)]
internal static extern int PMCallISAPI(IntPtr pECB, UnsafeNativeMethods.CallISAPIFunc iFunction, byte[] bufferIn, int sizeIn, byte[] bufferOut, int sizeOut);
// perf counters support
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern IntPtr PerfOpenGlobalCounters();
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern IntPtr PerfOpenStateCounters();
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern PerfInstanceDataHandle PerfOpenAppCounters(string AppName);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void PerfCloseAppCounters(IntPtr pCounters);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void PerfIncrementCounter(IntPtr pCounters, int number);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void PerfDecrementCounter(IntPtr pCounters, int number);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void PerfIncrementCounterEx(IntPtr pCounters, int number, int increment);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void PerfSetCounter(IntPtr pCounters, int number, int increment);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int PerfGetCounter(IntPtr pCounters, int number);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void GetEtwValues(out int level, out int flags);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void TraceRaiseEventMgdHandler(int eventType, IntPtr pRequestContext, string data1, string data2, string data3, string data4);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void TraceRaiseEventWithEcb(int eventType, IntPtr ecb, string data1, string data2, string data3, string data4);
[DllImport(ModName.WP_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void PMTraceRaiseEvent(int eventType, IntPtr pMsg, string data1, string data2, string data3, string data4);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int SessionNDConnectToService(string server);
[StructLayout(LayoutKind.Sequential)]
internal struct SessionNDMakeRequestResults {
internal IntPtr socket;
internal int httpStatus;
internal int timeout;
internal int contentLength;
internal IntPtr content;
internal int lockCookie;
internal long lockDate;
internal int lockAge;
internal int stateServerMajVer;
internal int actionFlags;
internal int lastPhase;
};
internal enum SessionNDMakeRequestPhase {
Initialization = 0,
Connecting,
SendingRequest,
ReadingResponse
};
internal enum StateProtocolVerb {
GET = 1,
PUT = 2,
DELETE = 3,
HEAD = 4,
};
internal enum StateProtocolExclusive {
NONE = 0,
ACQUIRE = 1,
RELEASE = 2,
};
internal const int StateProtocolFlagUninitialized = 0x00000001;
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Ansi, BestFitMapping=false, ThrowOnUnmappableChar=true)]
internal static extern int SessionNDMakeRequest(
HandleRef socket,
string server,
int port,
bool forceIPv6,
int networkTimeout,
StateProtocolVerb verb,
string uri,
StateProtocolExclusive exclusive,
int extraFlags,
int timeout,
int lockCookie,
byte[] body,
int cb,
bool checkVersion,
out SessionNDMakeRequestResults results);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void SessionNDFreeBody(HandleRef body);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void SessionNDCloseConnection(HandleRef socket);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int TransactManagedCallback(TransactedExecCallback callback, int mode);
[DllImport(ModName.ENGINE_FULL_NAME, SetLastError=true)]
internal static extern bool IsValidResource(IntPtr hModule, IntPtr ip, int size);
/*
* Fusion API's (now coming from mscorwks.dll)
*/
[DllImport(ModName.MSCORWKS_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int GetCachePath(int dwCacheFlags, StringBuilder pwzCachePath, ref int pcchPath);
#if !FEATURE_PAL
[DllImport(ModName.MSCORWKS_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int DeleteShadowCache(string pwzCachePath, string pwzAppName);
#else // !FEATURE_PAL
internal static int DeleteShadowCache(string pwzCachePath, string pwzAppName)
{
// ROTORTODO
return 0;
}
#endif // !FEATURE_PAL
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int InitializeWmiManager();
[DllImport(ModName.ENGINE_FULL_NAME, CharSet = CharSet.Unicode)]
internal static extern int DoesKeyContainerExist(string containerName, string provider, int useMachineContainer);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct WmiData {
internal int eventType;
// WebBaseEvent + WebProcessInformation + WebApplicationInformation
internal int eventCode;
internal int eventDetailCode;
internal string eventTime;
internal string eventMessage;
internal string eventId;
internal string sequenceNumber;
internal string occurrence;
internal int processId;
internal string processName;
internal string accountName;
internal string machineName;
internal string appDomain;
internal string trustLevel;
internal string appVirtualPath;
internal string appPath;
internal string details;
// WebRequestInformation
internal string requestUrl;
internal string requestPath;
internal string userHostAddress;
internal string userName;
internal bool userAuthenticated;
internal string userAuthenticationType;
internal string requestThreadAccountName;
// WebProcessStatistics
internal string processStartTime;
internal int threadCount;
internal string workingSet;
internal string peakWorkingSet;
internal string managedHeapSize;
internal int appdomainCount;
internal int requestsExecuting;
internal int requestsQueued;
internal int requestsRejected;
// WebThreadInformation
internal int threadId;
internal string threadAccountName;
internal string stackTrace;
internal bool isImpersonating;
// Exception
internal string exceptionType;
internal string exceptionMessage;
internal string nameToAuthenticate;
// ViewStateException
internal string remoteAddress;
internal string remotePort;
internal string userAgent;
internal string persistedState;
internal string referer;
internal string path;
};
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int RaiseWmiEvent(
ref WmiData pWmiData,
bool IsInAspCompatMode
);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern int RaiseEventlogEvent(
int eventType, string[] dataFields, int size);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void LogWebeventProviderFailure(
string appUrl,
string providerName,
string exception);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern IntPtr GetEcb(
IntPtr pHttpCompletion);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern void SetDoneWithSessionCalled(
IntPtr pHttpCompletion);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void ReportUnhandledException(
string eventInfo);
[DllImport(ModName.ENGINE_FULL_NAME, CharSet=CharSet.Unicode)]
internal static extern void RaiseFileMonitoringEventlogEvent(
string eventInfo,
string path,
string appVirtualPath,
int hr);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int StartPrefetchActivity(
uint ulActivityId);
[DllImport(ModName.ENGINE_FULL_NAME)]
internal static extern int EndPrefetchActivity(
uint ulActivityId);
[DllImport(ModName.FILTER_FULL_NAME)]
internal static extern IntPtr GetExtensionlessUrlAppendage();
[DllImport(ModName.OLE32_FULL_NAME, CharSet = CharSet.Unicode)]
internal static extern int CoCreateInstanceEx(ref Guid clsid, IntPtr pUnkOuter,
int dwClsContext, [In, Out] COSERVERINFO srv,
int num, [In, Out] MULTI_QI[] amqi);
[DllImport(ModName.OLE32_FULL_NAME, CharSet = CharSet.Unicode)]
internal static extern int CoCreateInstanceEx(ref Guid clsid, IntPtr pUnkOuter,
int dwClsContext, [In, Out] COSERVERINFO_X64 srv,
int num, [In, Out] MULTI_QI_X64[] amqi);
[DllImport(ModName.OLE32_FULL_NAME, CharSet = CharSet.Unicode)]
internal static extern int CoSetProxyBlanket(IntPtr pProxy, RpcAuthent authent, RpcAuthor author,
string serverprinc, RpcLevel level, RpcImpers
impers,
IntPtr ciptr, int dwCapabilities);
#if FEATURE_PAL // FEATURE_PAL-specific perf counter constants
// PerfCounters support
internal static int FILE_MAP_READ = 0x00000004;
internal static int FILE_MAP_WRITE = 0x00000002; // same as FILE_MAP_ALL_ACCESS
internal static uint PAGE_READONLY = 0x00000002;
internal static uint PAGE_READWRITE = 0x00000004;
internal static int ERROR_FILE_NOT_FOUND = 0x00000002;
#endif // FEATURE_pAL
}
}
| |
// 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.Composition;
using System.Globalization;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression
{
[ExportSuppressionFixProvider(PredefinedCodeFixProviderNames.Suppression, LanguageNames.CSharp), Shared]
internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider
{
protected override SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, bool needsTrailingEndOfLine)
{
var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword);
return CreatePragmaDirectiveTrivia(restoreKeyword, diagnostic, true, needsTrailingEndOfLine);
}
protected override SyntaxTriviaList CreatePragmaDisableDirectiveTrivia(Diagnostic diagnostic, bool needsLeadingEndOfLine)
{
var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword);
return CreatePragmaDirectiveTrivia(disableKeyword, diagnostic, needsLeadingEndOfLine, true);
}
private SyntaxTriviaList CreatePragmaDirectiveTrivia(SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine)
{
var id = SyntaxFactory.IdentifierName(diagnostic.Id);
var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id);
var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true);
var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective.WithAdditionalAnnotations(Formatter.Annotation));
var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia);
var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
if (!string.IsNullOrWhiteSpace(title))
{
var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation);
triviaList = triviaList.Add(titleComment);
}
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Insert(0, endOfLineTrivia);
}
if (needsTrailingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return triviaList;
}
protected override string DefaultFileExtension
{
get
{
return ".cs";
}
}
protected override string SingleLineCommentStart
{
get
{
return "//";
}
}
protected override string TitleForPragmaWarningSuppressionFix
{
get
{
return CSharpFeaturesResources.SuppressWithPragma;
}
}
protected override bool IsAttributeListWithAssemblyAttributes(SyntaxNode node)
{
var attributeList = node as AttributeListSyntax;
return attributeList != null &&
attributeList.Target != null &&
attributeList.Target.Identifier.Kind() == SyntaxKind.AssemblyKeyword;
}
protected override bool IsEndOfLine(SyntaxTrivia trivia)
{
return trivia.Kind() == SyntaxKind.EndOfLineTrivia;
}
protected override bool IsEndOfFileToken(SyntaxToken token)
{
return token.Kind() == SyntaxKind.EndOfFileToken;
}
protected override SyntaxNode AddGlobalSuppressMessageAttribute(SyntaxNode newRoot, ISymbol targetSymbol, Diagnostic diagnostic)
{
var compilationRoot = (CompilationUnitSyntax)newRoot;
var leadingTriviaForAttributeList = !compilationRoot.AttributeLists.Any() ?
SyntaxFactory.TriviaList(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment)) :
default(SyntaxTriviaList);
var attributeList = CreateAttributeList(targetSymbol, diagnostic, isAssemblyAttribute: true, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: false);
return compilationRoot.AddAttributeLists(attributeList);
}
protected override SyntaxNode AddLocalSuppressMessageAttribute(SyntaxNode targetNode, ISymbol targetSymbol, Diagnostic diagnostic)
{
var memberNode = (MemberDeclarationSyntax)targetNode;
SyntaxTriviaList leadingTriviaForAttributeList;
bool needsLeadingEndOfLine;
if (!memberNode.GetAttributes().Any())
{
leadingTriviaForAttributeList = memberNode.GetLeadingTrivia();
memberNode = memberNode.WithoutLeadingTrivia();
needsLeadingEndOfLine = !leadingTriviaForAttributeList.Any() || !IsEndOfLine(leadingTriviaForAttributeList.Last());
}
else
{
leadingTriviaForAttributeList = default(SyntaxTriviaList);
needsLeadingEndOfLine = true;
}
var attributeList = CreateAttributeList(targetSymbol, diagnostic, isAssemblyAttribute: false, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: needsLeadingEndOfLine);
return memberNode.AddAttributeLists(attributeList);
}
private AttributeListSyntax CreateAttributeList(
ISymbol targetSymbol,
Diagnostic diagnostic,
bool isAssemblyAttribute,
SyntaxTriviaList leadingTrivia,
bool needsLeadingEndOfLine)
{
var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute);
var attribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName(SuppressMessageAttributeName), attributeArguments)
.WithAdditionalAnnotations(Simplifier.Annotation);
var attributes = new SeparatedSyntaxList<AttributeSyntax>().Add(attribute);
AttributeListSyntax attributeList;
if (isAssemblyAttribute)
{
var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword));
attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes);
}
else
{
attributeList = SyntaxFactory.AttributeList(attributes);
}
var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed;
var triviaList = SyntaxFactory.TriviaList();
if (needsLeadingEndOfLine)
{
triviaList = triviaList.Add(endOfLineTrivia);
}
return attributeList
.WithLeadingTrivia(leadingTrivia.AddRange(triviaList))
.WithAdditionalAnnotations(Formatter.Annotation);
}
private AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic, bool isAssemblyAttribute)
{
// SuppressMessage("Rule Category", "Rule Id", Justification = "Justification", MessageId = "MessageId", Scope = "Scope", Target = "Target")
var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category));
var categoryArgument = SyntaxFactory.AttributeArgument(category);
var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture);
var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title);
var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText));
var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId);
var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.SuppressionPendingJustification));
var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr);
var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument);
if (isAssemblyAttribute)
{
var scopeString = GetScopeString(targetSymbol.Kind);
if (scopeString != null)
{
var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString));
var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr);
var targetString = GetTargetString(targetSymbol);
var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString));
var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr);
attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument);
}
}
return attributeArgumentList;
}
}
}
| |
using System;
using System.Collections.Generic;
using EmergeTk.Model;
using EmergeTk.Model.Security;
using SimpleJson;
namespace EmergeTk.WebServices
{
public interface IRestServiceManager
{
string GetHelpText();
void Authorize(RestOperation operation, JsonObject recordNode, AbstractRecord record);
bool AuthorizeField( RestOperation op, AbstractRecord record, string property );
AbstractRecord GenerateExampleRecord();
string GenerateExampleFields(string method);
List<RestTypeDescription> GetTypeDescriptions();
}
public class DefaultServiceManager : IRestServiceManager
{
#region IRestServiceManager implementation
public string GetHelpText ()
{
return "Default service manager. Useful for developer purposes. No security.";
}
public void Authorize (RestOperation operation, JsonObject recordNode, AbstractRecord record)
{
return;
}
public bool AuthorizeField (RestOperation op, AbstractRecord record, string property)
{
return true;
}
public AbstractRecord GenerateExampleRecord ()
{
throw new System.NotImplementedException();
}
public string GenerateExampleFields (string method)
{
throw new System.NotImplementedException();
}
public List<RestTypeDescription> GetTypeDescriptions ()
{
return null;
}
#endregion
}
public class RootOnlyServiceManager : IRestServiceManager
{
#region IRestServiceManager implementation
public string GetHelpText()
{
return "Root Access Only service manager.";
}
public void Authorize(RestOperation operation, JsonObject recordNode, AbstractRecord record)
{
// root bypasses the Authorize call because of DoAuth so always throw exception
throw new UnauthorizedAccessException("Not Authorized.");
}
public bool AuthorizeField(RestOperation op, AbstractRecord record, string property)
{
return true;
}
public AbstractRecord GenerateExampleRecord()
{
throw new System.NotImplementedException();
}
public string GenerateExampleFields(string method)
{
throw new System.NotImplementedException();
}
public List<RestTypeDescription> GetTypeDescriptions()
{
return null;
}
#endregion
}
public class AuthenticatedReadOnlyServiceManager : IRestServiceManager
{
#region IRestServiceManager implementation
public string GetHelpText()
{
return "Authenticated Read-Only service manager.";
}
public void Authorize(RestOperation operation, JsonObject recordNode, AbstractRecord record)
{
User.AuthenticateUser();
if (operation != RestOperation.Get)
{
throw new UnauthorizedAccessException("Authenticated users can only GET this service.");
}
}
public bool AuthorizeField(RestOperation op, AbstractRecord record, string property)
{
return true;
}
public AbstractRecord GenerateExampleRecord()
{
throw new System.NotImplementedException();
}
public string GenerateExampleFields(string method)
{
throw new System.NotImplementedException();
}
public List<RestTypeDescription> GetTypeDescriptions()
{
return null;
}
#endregion
}
public class AuthenticatedPostOnlyServiceManager : IRestServiceManager
{
#region IRestServiceManager implementation
public string GetHelpText()
{
return "Authenticated POST-Only service manager.";
}
public void Authorize(RestOperation operation, JsonObject recordNode, AbstractRecord record)
{
User.AuthenticateUser();
if (operation != RestOperation.Post)
{
throw new UnauthorizedAccessException("Authenticated users can only POST to this service.");
}
}
public bool AuthorizeField(RestOperation op, AbstractRecord record, string property)
{
return true;
}
public AbstractRecord GenerateExampleRecord()
{
throw new System.NotImplementedException();
}
public string GenerateExampleFields(string method)
{
throw new System.NotImplementedException();
}
public List<RestTypeDescription> GetTypeDescriptions()
{
return null;
}
#endregion
}
public struct RestTypeDescription
{
public Type RestType;
public string ModelName;
public string ModelPluralName;
public RestOperation Verb;
public override string ToString ()
{
return string.Format ("[RestTypeDescription: RestType={0}, ModelName={1}]", RestType, ModelName);
}
}
}
| |
// 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 BlendVariableInt16()
{
var test = new SimpleTernaryOpTest__BlendVariableInt16();
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();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 SimpleTernaryOpTest__BlendVariableInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public Vector256<Int16> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt16("0xFFFF", 16) : (short)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableInt16 testClass)
{
var result = Avx2.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableInt16 testClass)
{
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
fixed (Vector256<Int16>* pFld3 = &_fld3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2)),
Avx.LoadVector256((Int16*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Int16[] _data3 = new Int16[Op3ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private static Vector256<Int16> _clsVar3;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private Vector256<Int16> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__BlendVariableInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt16("0xFFFF", 16) : (short)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public SimpleTernaryOpTest__BlendVariableInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt16("0xFFFF", 16) : (short)0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (((i % 2) == 0) ? Convert.ToInt16("0xFFFF", 16) : (short)0); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int16[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.BlendVariable(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.BlendVariable(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int16>* pClsVar2 = &_clsVar2)
fixed (Vector256<Int16>* pClsVar3 = &_clsVar3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int16*)(pClsVar1)),
Avx.LoadVector256((Int16*)(pClsVar2)),
Avx.LoadVector256((Int16*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray3Ptr);
var result = Avx2.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Int16*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__BlendVariableInt16();
var result = Avx2.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__BlendVariableInt16();
fixed (Vector256<Int16>* pFld1 = &test._fld1)
fixed (Vector256<Int16>* pFld2 = &test._fld2)
fixed (Vector256<Int16>* pFld3 = &test._fld3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2)),
Avx.LoadVector256((Int16*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
fixed (Vector256<Int16>* pFld3 = &_fld3)
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2)),
Avx.LoadVector256((Int16*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.BlendVariable(
Avx.LoadVector256((Int16*)(&test._fld1)),
Avx.LoadVector256((Int16*)(&test._fld2)),
Avx.LoadVector256((Int16*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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<Int16> op1, Vector256<Int16> op2, Vector256<Int16> op3, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] inArray3 = new Int16[Op3ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] inArray3 = new Int16[Op3ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((thirdOp[0] != 0) ? secondOp[0] != result[0] : firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((thirdOp[i] != 0) ? secondOp[i] != result[i] : firstOp[i] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.BlendVariable)}<Int16>(Vector256<Int16>, Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcov = Google.Cloud.OsConfig.V1Alpha;
using sys = System;
namespace Google.Cloud.OsConfig.V1Alpha
{
/// <summary>Resource name for the <c>VulnerabilityReport</c> resource.</summary>
public sealed partial class VulnerabilityReportName : gax::IResourceName, sys::IEquatable<VulnerabilityReportName>
{
/// <summary>The possible contents of <see cref="VulnerabilityReportName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </summary>
ProjectLocationInstance = 1,
}
private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport");
/// <summary>Creates a <see cref="VulnerabilityReportName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="VulnerabilityReportName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static VulnerabilityReportName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new VulnerabilityReportName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="VulnerabilityReportName"/> with the pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="VulnerabilityReportName"/> constructed from the provided ids.
/// </returns>
public static VulnerabilityReportName FromProjectLocationInstance(string projectId, string locationId, string instanceId) =>
new VulnerabilityReportName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </returns>
public static string Format(string projectId, string locationId, string instanceId) =>
FormatProjectLocationInstance(projectId, locationId, instanceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VulnerabilityReportName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>.
/// </returns>
public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) =>
s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="VulnerabilityReportName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="vulnerabilityReportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="VulnerabilityReportName"/> if successful.</returns>
public static VulnerabilityReportName Parse(string vulnerabilityReportName) => Parse(vulnerabilityReportName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="VulnerabilityReportName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="vulnerabilityReportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="VulnerabilityReportName"/> if successful.</returns>
public static VulnerabilityReportName Parse(string vulnerabilityReportName, bool allowUnparsed) =>
TryParse(vulnerabilityReportName, allowUnparsed, out VulnerabilityReportName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="VulnerabilityReportName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="vulnerabilityReportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="VulnerabilityReportName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string vulnerabilityReportName, out VulnerabilityReportName result) =>
TryParse(vulnerabilityReportName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="VulnerabilityReportName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="vulnerabilityReportName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="VulnerabilityReportName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string vulnerabilityReportName, bool allowUnparsed, out VulnerabilityReportName result)
{
gax::GaxPreconditions.CheckNotNull(vulnerabilityReportName, nameof(vulnerabilityReportName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationInstance.TryParseName(vulnerabilityReportName, out resourceName))
{
result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(vulnerabilityReportName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private VulnerabilityReportName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
InstanceId = instanceId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="VulnerabilityReportName"/> class from the component parts of
/// pattern <c>projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
public VulnerabilityReportName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as VulnerabilityReportName);
/// <inheritdoc/>
public bool Equals(VulnerabilityReportName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(VulnerabilityReportName a, VulnerabilityReportName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(VulnerabilityReportName a, VulnerabilityReportName b) => !(a == b);
}
public partial class VulnerabilityReport
{
/// <summary>
/// <see cref="gcov::VulnerabilityReportName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::VulnerabilityReportName VulnerabilityReportName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::VulnerabilityReportName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetVulnerabilityReportRequest
{
/// <summary>
/// <see cref="gcov::VulnerabilityReportName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcov::VulnerabilityReportName VulnerabilityReportName
{
get => string.IsNullOrEmpty(Name) ? null : gcov::VulnerabilityReportName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListVulnerabilityReportsRequest
{
/// <summary>
/// <see cref="InstanceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public InstanceName ParentAsInstanceName
{
get => string.IsNullOrEmpty(Parent) ? null : InstanceName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;
namespace WebApplication2
{
/// <summary>
/// Called by ProcRes. Used for planning.
/// </summary>
public partial class frmProcRReq : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Label Label2;
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
if (Session["MgrName"] == null)
{
lblOrg.Text = Session["OrgName"].ToString();
}
else
{
lblOrg.Text = Session["MgrName"].ToString();
}
lblService.Text = "Service: " + Session["ServiceName"].ToString();
lblLoc.Text = "Location: " + Session["LocName"].ToString();
btnAddNew.Text = "Identify Procurement Need";
btnAddExisting.Text = "Add from Existing Service Contracts";
DataGrid1.Columns[0].Visible = false;//Id
DataGrid1.Columns[1].Visible = true;//ItemName
if (Session["ResTypesType"].ToString() == "0")//goods
{
lblGS.Text = "Type of Good: " + Session["ResourceName"].ToString();
btnAddExisting.Text = "Add from Existing Goods";
DataGrid1.Columns[2].Visible = true;//txtQty
DataGrid1.Columns[2].HeaderText = "Qty (" + Session["QtyMeasure"].ToString() + ")";
}
else
{
lblGS.Text = "Type of Service: " + Session["ResourceName"].ToString();
btnAddExisting.Text = "Add from Existing Services";
DataGrid1.Columns[2].Visible = false;
}
DataGrid1.Columns[3].Visible = false;//textbox Price
DataGrid1.Columns[4].Visible = false;//Cost (Computed)
DataGrid1.Columns[5].Visible = false;//Qty
DataGrid1.Columns[6].Visible = false;//Price
DataGrid1.Columns[7].Visible = false;//Inventory - Owner Organization
DataGrid1.Columns[8].Visible = true;//Inventory - Location
DataGrid1.Columns[9].Visible = true;//Inventory - SubLocation
if (Session["CallerOpt"] == "EM")
{
DataGrid1.Columns[10].Visible = true;//cbxBackup
}
else
{
DataGrid1.Columns[10].Visible = false;//cbxBackup
}
DataGrid1.Columns[11].Visible = true;//BudgetsId List
if (Session["PAY"] == null)
{
DataGrid1.Columns[12].Visible = false;
}
else if (Session["PAY"].ToString() == "0")
{
DataGrid1.Columns[0].Visible = false;
}
DataGrid1.Columns[13].Visible = true;//btnDelete
DataGrid1.Columns[14].Visible = false;//BackupFlag
DataGrid1.Columns[15].Visible = false;//BudgetsId
if (Session["InventoryId"] != null)
{
AddProcRReq();
Session["InventoryId"] = null;
}
if (Session["ContractIdSel"] != null)
{
AddProcRReq();
Session["ContractIdSel"] = null;
}
if (Session["PRS"].ToString() == "1")
{
lblDel.Text = "Deliverable: " + Session["EventName"].ToString();
lblTask.Text = Session["PJNameS"].ToString() + ": "
+ Session["ProjName"].ToString()
+ " (Procedure: " + Session["ProcName"].ToString() + ")";
}
else
{
lblDel.Text = "Procedure: " + Session["ProcName"].ToString();
}
loadData();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand);
}
#endregion
private void loadData ()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "wms_RetrievePSEPRInv";
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Int32.Parse(Session["OrgId"].ToString());
cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
cmd.Parameters["@LocationsId"].Value = Int32.Parse(Session["LocationsId"].ToString());
cmd.Parameters.Add("@PSEPResID", SqlDbType.Int);
cmd.Parameters["@PSEPResID"].Value = Int32.Parse(Session["PSEPResID"].ToString());
if (Session["PRS"].ToString() == "1")
{
cmd.Parameters.Add("@ProjectId", SqlDbType.Int);
cmd.Parameters["@ProjectId"].Value = Int32.Parse(Session["ProjectId"].ToString());
}
cmd.Connection = this.epsDbConn;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "ProcS");
if (ds.Tables["ProcS"].Rows.Count == 0)
{
DataGrid1.Visible = false;
lblContents1.Text = "Note: There is no resource assigned."
+ ". Click on 'Add' to assign resources.";
//lblOrg.Text = "PP" + Session["MgrId"].ToString() + "LL" + Session["LocationsId"].ToString()
// + "PSepResID:" + Session["PSEPResID"].ToString()
// + "PRS:" + Session["PRS"].ToString() + "Project:" + Session["ProjectId"].ToString();
}
Session["ds"] = ds;
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
refreshGrid();
}
private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[10].FindControl("cbxBackup"));
DropDownList dl = (DropDownList) (i.Cells[11].FindControl("lstBudgets"));
TextBox tQ = (TextBox)(i.Cells[2].FindControl("txtQty"));
//TextBox tP = (TextBox)(i.Cells[3].FindControl("txtPrice"));
if (i.Cells[14].Text == "1")
{
cb.Checked = true;
}
if (i.Cells[5].Text.StartsWith("&") == false)
{
tQ.Text = i.Cells[5].Text;
}
/*if (i.Cells[6].Text.StartsWith("&") == false)
{
tP.Text = i.Cells[6].Text;
}*/
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "fms_RetrieveFunds";
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
/*cmd.Parameters.Add("@OrgIdP", SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value = Session["OrgIdP"].ToString();
cmd.Parameters.Add("@LicenseId", SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value = Session["LicenseId"].ToString();
cmd.Parameters.Add("@DomainId", SqlDbType.Int);
cmd.Parameters["@DomainId"].Value = Session["DomainId"].ToString();*/
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "Funds");
dl.DataSource = ds;
dl.DataMember = "Funds";
dl.DataTextField = "Name";
dl.DataValueField = "Id";
dl.DataBind();
if (i.Cells[15].Text != "")
{
dl.SelectedIndex = dl.Items.IndexOf(dl.Items.FindByValue(i.Cells[15].Text));
}
}
}
private void updateGrid()
{
float r = 1;
foreach (DataGridItem i in DataGrid1.Items)
{
if (r == 0)
{
break;
}
CheckBox cb = (CheckBox)(i.Cells[10].FindControl("cbxBackup"));
DropDownList dl = (DropDownList)(i.Cells[11].FindControl("lstBudgets"));
TextBox tQ = (TextBox)(i.Cells[2].FindControl("txtQty"));
//TextBox tP = (TextBox)(i.Cells[3].FindControl("txtPrice"));
if (Session["ResTypesType"].ToString() == "0" && tQ.Text.Trim() != "")
{
string s = tQ.Text.Trim();
bool result = float.TryParse(s, out r);
if (r == 0)
{
lblContents1.Text = "Please enter valid number in the Column titled 'Quantity'.";
break;
}
else
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "fms_UpdatePSEPResInv";
cmd.Connection = this.epsDbConn;
cmd.Parameters.Add("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value = Int32.Parse(i.Cells[0].Text);
cmd.Parameters.Add("@BackupFlag", SqlDbType.Int);
if (cb.Checked)
{
cmd.Parameters["@BackupFlag"].Value = 1;
}
else
{
cmd.Parameters["@BackupFlag"].Value = 0;
}
cmd.Parameters.Add("@Budgets", SqlDbType.Int);
cmd.Parameters["@Budgets"].Value = Int32.Parse(dl.SelectedItem.Value);
cmd.Parameters.Add("@Qty", SqlDbType.Decimal);
if (tQ.Text != "")
{
if (Session["ResTypesType"].ToString() == "0")
{
cmd.Parameters["@Qty"].Value = decimal.Parse(tQ.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
}
}
/*cmd.Parameters.Add("@Price", SqlDbType.Decimal);
if (tP.Text != "")
{
cmd.Parameters["@Price"].Value = decimal.Parse(tP.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
}*/
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
r = 1;
}
}
else
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "fms_UpdatePSEPResInv";
cmd.Connection = this.epsDbConn;
cmd.Parameters.Add("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value = Int32.Parse(i.Cells[0].Text);
cmd.Parameters.Add("@BackupFlag", SqlDbType.Int);
if (cb.Checked)
{
cmd.Parameters["@BackupFlag"].Value = 1;
}
else
{
cmd.Parameters["@BackupFlag"].Value = 0;
}
cmd.Parameters.Add("@BudgetsId", SqlDbType.Int);
cmd.Parameters["@BudgetsId"].Value = Int32.Parse(dl.SelectedItem.Value);
cmd.Parameters.Add("@Qty", SqlDbType.Decimal);
if (tQ.Text != "")
{
if (Session["ResTypesType"].ToString() == "0")
{
cmd.Parameters["@Qty"].Value = decimal.Parse(tQ.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
}
}
/*cmd.Parameters.Add("@Price", SqlDbType.Decimal);
if (tP.Text != "")
{
cmd.Parameters["@Price"].Value = decimal.Parse(tP.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
}*/
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
if (r == 1)
{
Exit();
}
}
/*if (tP.Text.Trim() != "")
{
float r = 0;
string s = tP.Text.Trim();
bool result = float.TryParse(s, out r);
if (r == 0)
{
lblContents1.Text = "Please enter valid number in the Column titled 'Price'.";
break;
}
}*/
private void AddProcRReq()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "wms_AddPSEPResInv";
cmd.Connection = this.epsDbConn;
cmd.Parameters.Add("@PSEPResId", SqlDbType.Int);
cmd.Parameters["@PSEPResId"].Value = Session["PSEPResId"].ToString();
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
cmd.Parameters["@LocationsId"].Value = Session["LocationsId"].ToString();
if (Session["InventoryId"] != null)
{
cmd.Parameters.Add("@InventoryId", SqlDbType.Int);
cmd.Parameters["@InventoryId"].Value = Session["InventoryId"].ToString();
}
if (Session["ContractIdSel"] != null)
{
cmd.Parameters.Add("@ContractsId", SqlDbType.Int);
cmd.Parameters["@ContractsId"].Value = Session["ContractIdSel"].ToString();
}
if (Session["PRS"].ToString() == "1")
{
cmd.Parameters.Add("@ProjectId", SqlDbType.Int);
cmd.Parameters["@ProjectId"].Value = Session["ProjectId"].ToString();
}
cmd.Parameters.Add("@BudgetsId", SqlDbType.Int);
cmd.Parameters["@BudgetsId"].Value = 5;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Update")
{
Session["CPPR"]="frmProcRReq";
Session["btnAction"]="Update";
Session["ProcProcureId"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmUpdProcPReq.aspx?");
}
else if (e.CommandName == "Pay")
{
Session["CPay"]="frmProcRReq";
Session["ProcProcuresId"] = e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmPayments.aspx?");
}
else if (e.CommandName == "Delete")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText = "wms_DeletePSEPResInv";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
/*private void btnAdd_Click(object sender, System.EventArgs e)
{
Session["CallerUpdProcure"]="frmProcRReq";
Session["Contractor"] = "Table";
Session["btnAction"]="Add";
Session["Id"]="0";
Response.Redirect (strURL + "frmUpdProcProcure.aspx?");
}*/
private void Exit()
{
Response.Redirect (strURL + Session["cps"].ToString() + ".aspx?");
}
protected void btnOK_Click(object sender, System.EventArgs e)
{
updateGrid();
}
private void getInv()
{
Session["InventoryId"] = null;
Session["Update"] = "No";
Session["CInv"] = "frmProcRReq";
Response.Redirect(strURL + "frmInventory.aspx?");
}
protected void btnAddNew_Click(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Session["InventoryId"] = null;
AddProcRReq();
loadData();
}
protected void btnAddExisting_Click1(object sender, EventArgs e)
{
if (Session["ResTypesType"].ToString() == "0")
{
getInv();
}
else
{
Session["CContracts"] = "frmProcRReq";
Response.Redirect(strURL + "frmContractsS.aspx?");
}
}
}
}
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using System.Xml;
using System.Xml.Serialization;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
using System.Reflection;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.OSM.OSMClassExtension;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("4613b4ca-22d1-4bfc-9ee1-03ad63d20b2f")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.OSMGPAddExtension")]
public class OSMGPAddExtension : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = "Add OSM Editor Extension";
int in_osmFeaturesNumber, out_osmFeaturesNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
public OSMGPAddExtension()
{
osmGPFactory = new OSMGPFactory();
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return default(ESRI.ArcGIS.esriSystem.UID);
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_AddExtensionName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPParameter inputFeatureClassParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
IGPValue inputFeatureGPValue = gpUtilities3.UnpackGPValue(inputFeatureClassParameter) as IGPValue;
IFeatureClass osmFeatureClass = null;
IQueryFilter queryFilter = null;
gpUtilities3.DecodeFeatureLayer((IGPValue)inputFeatureGPValue, out osmFeatureClass, out queryFilter);
((ITable)osmFeatureClass).ApplyOSMClassExtension();
}
catch (Exception ex)
{
message.AddError(120050, ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_AddExtensionName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return default(object);
}
public int HelpContext
{
get
{
return default(int);
}
}
public string HelpFile
{
get
{
return default(string);
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "osmgpaddextension.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpaddextension_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpaddextension_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_AddExtensionName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
IArray parameters = new ArrayClass();
IGPParameterEdit3 inputOSMFeatureLayer = new GPParameterClass() as IGPParameterEdit3;
inputOSMFeatureLayer.Name = "in_osmfeatures";
inputOSMFeatureLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPAddExtension_inputlayer_displayname");
inputOSMFeatureLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
inputOSMFeatureLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputOSMFeatureLayer.DataType = new GPFeatureLayerTypeClass();
in_osmFeaturesNumber = 0;
parameters.Add((IGPParameter) inputOSMFeatureLayer);
IGPParameterEdit3 outputOSMFeatureLayer = new GPParameterClass() as IGPParameterEdit3;
outputOSMFeatureLayer.Name = "out_osmfeatures";
outputOSMFeatureLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPAddExtension_outputlayer_displayname");
outputOSMFeatureLayer.ParameterType = esriGPParameterType.esriGPParameterTypeDerived;
outputOSMFeatureLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
outputOSMFeatureLayer.DataType = new GPFeatureLayerTypeClass();
outputOSMFeatureLayer.AddDependency("in_osmfeatures");
out_osmFeaturesNumber = 1;
parameters.Add((IGPParameter) outputOSMFeatureLayer);
return parameters;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
IGPParameter inputFCParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
IGPValue osmFCGPValue = gpUtilities3.UnpackGPValue(inputFCParameter);
if (osmFCGPValue.IsEmpty())
{
return;
}
IFeatureClass osmFeatureClass = null;
IQueryFilter queryFilter = null;
if (osmFCGPValue is IGPFeatureLayer)
{
gpUtilities3.DecodeFeatureLayer(osmFCGPValue, out osmFeatureClass, out queryFilter);
int osmTagFieldIndex = osmFeatureClass.Fields.FindField("osmTags");
if (osmTagFieldIndex == -1)
{
Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPAddExtension_noosmtagfield"));
}
}
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Net;
using System.Management.Automation;
using System.ComponentModel;
using System.Reflection;
using System.Globalization;
using System.Management.Automation.Runspaces;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
using System.Resources;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Powershell.Commands.GetCounter.PdhNative;
using Microsoft.PowerShell.Commands.GetCounter;
using Microsoft.PowerShell.Commands.Diagnostics.Common;
namespace Microsoft.PowerShell.Commands
{
///
/// Class that implements the Get-Counter cmdlet.
///
[Cmdlet(VerbsData.Import, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138338")]
public sealed class ImportCounterCommand : PSCmdlet
{
//
// Path parameter
//
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessageBaseName = "GetEventResources")]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Scope = "member",
Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
Justification = "A string[] is required here because that is the type Powershell supports")]
public string[] Path
{
get { return _path; }
set { _path = value; }
}
private string[] _path;
private StringCollection _resolvedPaths = new StringCollection();
private List<string> _accumulatedFileNames = new List<string>();
//
// ListSet parameter
//
[Parameter(
Mandatory = true,
ParameterSetName = "ListSetSet",
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
HelpMessageBaseName = "GetEventResources")]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Scope = "member",
Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
Justification = "A string[] is required here because that is the type Powershell supports")]
public string[] ListSet
{
get { return _listSet; }
set { _listSet = value; }
}
private string[] _listSet = new string[0];
//
// StartTime parameter
//
[Parameter(
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
ParameterSetName = "GetCounterSet",
HelpMessageBaseName = "GetEventResources")]
public DateTime StartTime
{
get { return _startTime; }
set { _startTime = value; }
}
private DateTime _startTime = DateTime.MinValue;
//
// EndTime parameter
//
[Parameter(
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
ParameterSetName = "GetCounterSet",
HelpMessageBaseName = "GetEventResources")]
public DateTime EndTime
{
get { return _endTime; }
set { _endTime = value; }
}
private DateTime _endTime = DateTime.MaxValue;
//
// Counter parameter
//
[Parameter(
Mandatory = false,
ParameterSetName = "GetCounterSet",
ValueFromPipeline = false,
HelpMessageBaseName = "GetEventResources")]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Scope = "member",
Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
Justification = "A string[] is required here because that is the type Powershell supports")]
public string[] Counter
{
get { return _counter; }
set { _counter = value; }
}
private string[] _counter = new string[0];
//
// Summary switch
//
[Parameter(ParameterSetName = "SummarySet")]
public SwitchParameter Summary
{
get { return _summary; }
set { _summary = value; }
}
private SwitchParameter _summary;
//
// MaxSamples parameter
//
private const Int64 KEEP_ON_SAMPLING = -1;
[Parameter(
ParameterSetName = "GetCounterSet",
ValueFromPipeline = false,
ValueFromPipelineByPropertyName = false,
HelpMessageBaseName = "GetEventResources")]
[ValidateRange((Int64)1, Int64.MaxValue)]
public Int64 MaxSamples
{
get { return _maxSamples; }
set { _maxSamples = value; }
}
private Int64 _maxSamples = KEEP_ON_SAMPLING;
private ResourceManager _resourceMgr = null;
private PdhHelper _pdhHelper = null;
private bool _stopping = false;
//
// AccumulatePipelineFileNames() accumulates counter file paths in the pipeline scenario:
// we do not want to construct a Pdh query until all the file names are supplied.
//
private void AccumulatePipelineFileNames()
{
_accumulatedFileNames.AddRange(_path);
}
//
// BeginProcessing() is invoked once per pipeline
//
protected override void BeginProcessing()
{
#if CORECLR
if (Platform.IsIoT)
{
// IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet.
throw new PlatformNotSupportedException();
}
// PowerShell Core requires at least Windows 7,
// so no version test is needed
_pdhHelper = new PdhHelper(false);
#else
_pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6);
#endif
_resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager();
}
//
// EndProcessing() is invoked once per pipeline
//
protected override void EndProcessing()
{
//
// Resolve and validate the Path argument: present for all parametersets.
//
if (!ResolveFilePaths())
{
return;
}
ValidateFilePaths();
switch (ParameterSetName)
{
case "ListSetSet":
ProcessListSet();
break;
case "GetCounterSet":
ProcessGetCounter();
break;
case "SummarySet":
ProcessSummary();
break;
default:
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
break;
}
_pdhHelper.Dispose();
}
//
// Handle Control-C
//
protected override void StopProcessing()
{
_stopping = true;
_pdhHelper.Dispose();
}
//
// ProcessRecord() override.
// This is the main entry point for the cmdlet.
//
protected override void ProcessRecord()
{
AccumulatePipelineFileNames();
}
//
// ProcessSummary().
// Does the work to process Summary parameter set.
//
private void ProcessSummary()
{
uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
CounterFileInfo summaryObj;
res = _pdhHelper.GetFilesSummary(out summaryObj);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
WriteObject(summaryObj);
}
//
// ProcessListSet().
// Does the work to process ListSet parameter set.
//
private void ProcessListSet()
{
uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
StringCollection machineNames = new StringCollection();
res = _pdhHelper.EnumBlgFilesMachines(ref machineNames);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
foreach (string machine in machineNames)
{
StringCollection counterSets = new StringCollection();
res = _pdhHelper.EnumObjects(machine, ref counterSets);
if (res != 0)
{
return;
}
StringCollection validPaths = new StringCollection();
foreach (string pattern in _listSet)
{
bool bMatched = false;
WildcardPattern wildLogPattern = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
foreach (string counterSet in counterSets)
{
if (!wildLogPattern.IsMatch(counterSet))
{
continue;
}
StringCollection counterSetCounters = new StringCollection();
StringCollection counterSetInstances = new StringCollection();
res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances);
if (res != 0)
{
ReportPdhError(res, false);
continue;
}
string[] instanceArray = new string[counterSetInstances.Count];
int i = 0;
foreach (string instance in counterSetInstances)
{
instanceArray[i++] = instance;
}
Dictionary<string, string[]> counterInstanceMapping = new Dictionary<string, string[]>();
foreach (string counter in counterSetCounters)
{
counterInstanceMapping.Add(counter, instanceArray);
}
PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
if (counterSetInstances.Count > 1)
{
categoryType = PerformanceCounterCategoryType.MultiInstance;
}
else // if (counterSetInstances.Count == 1) //???
{
categoryType = PerformanceCounterCategoryType.SingleInstance;
}
string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet);
CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping);
WriteObject(setObj);
bMatched = true;
}
if (!bMatched)
{
string msg = _resourceMgr.GetString("NoMatchingCounterSetsInFile");
Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg,
CommonUtilities.StringArrayToString(_resolvedPaths),
pattern));
WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsInFile", ErrorCategory.ObjectNotFound, null));
}
}
}
}
//
// ProcessGetCounter()
// Does the work to process GetCounterSet parameter set.
//
private void ProcessGetCounter()
{
// Validate StartTime-EndTime, if present
if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue)
{
if (_startTime >= _endTime)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidDateRange"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidDateRange", ErrorCategory.InvalidArgument, null));
return;
}
}
uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths);
if (res != 0)
{
ReportPdhError(res, true);
return;
}
StringCollection validPaths = new StringCollection();
if (_counter.Length > 0)
{
foreach (string path in _counter)
{
StringCollection expandedPaths;
res = _pdhHelper.ExpandWildCardPath(path, out expandedPaths);
if (res != 0)
{
WriteDebug(path);
ReportPdhError(res, false);
continue;
}
foreach (string expandedPath in expandedPaths)
{
if (!_pdhHelper.IsPathValid(expandedPath))
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathIsInvalid"), path);
Exception exc = new Exception(msg);
WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null));
continue;
}
validPaths.Add(expandedPath);
}
}
if (validPaths.Count == 0)
{
return;
}
}
else
{
res = _pdhHelper.GetValidPathsFromFiles(ref validPaths);
if (res != 0)
{
ReportPdhError(res, false);
}
}
if (validPaths.Count == 0)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathsInFilesInvalid"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterPathsInFilesInvalid", ErrorCategory.InvalidResult, null));
}
res = _pdhHelper.OpenQuery();
if (res != 0)
{
ReportPdhError(res, false);
}
if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue)
{
res = _pdhHelper.SetQueryTimeRange(_startTime, _endTime);
if (res != 0)
{
ReportPdhError(res, true);
}
}
res = _pdhHelper.AddCounters(ref validPaths, true);
if (res != 0)
{
ReportPdhError(res, true);
}
PerformanceCounterSampleSet nextSet;
uint samplesRead = 0;
while (!_stopping)
{
res = _pdhHelper.ReadNextSet(out nextSet, false);
if (res == PdhResults.PDH_NO_MORE_DATA)
{
break;
}
if (res != 0 && res != PdhResults.PDH_INVALID_DATA)
{
ReportPdhError(res, false);
continue;
}
//
// Display data
//
WriteSampleSetObject(nextSet, (samplesRead == 0));
samplesRead++;
if (_maxSamples != KEEP_ON_SAMPLING && samplesRead >= _maxSamples)
{
break;
}
}
}
//
// ValidateFilePaths() helper.
// Validates the _resolvedPaths: present for all parametersets.
// We cannot have more than 32 blg files, or more than one CSV or TSC file.
// Files have to all be of the same type (.blg, .csv, .tsv).
//
private void ValidateFilePaths()
{
Debug.Assert(_resolvedPaths.Count > 0);
string firstExt = System.IO.Path.GetExtension(_resolvedPaths[0]);
foreach (string fileName in _resolvedPaths)
{
WriteVerbose(fileName);
string curExtension = System.IO.Path.GetExtension(fileName);
if (!curExtension.Equals(".blg", StringComparison.OrdinalIgnoreCase)
&& !curExtension.Equals(".csv", StringComparison.OrdinalIgnoreCase)
&& !curExtension.Equals(".tsv", StringComparison.OrdinalIgnoreCase))
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNotALogFile"), fileName);
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterNotALogFile", ErrorCategory.InvalidResult, null));
return;
}
if (!curExtension.Equals(firstExt, StringComparison.OrdinalIgnoreCase))
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterNoMixedLogTypes"), fileName);
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "CounterNoMixedLogTypes", ErrorCategory.InvalidResult, null));
return;
}
}
if (firstExt.Equals(".blg", StringComparison.OrdinalIgnoreCase))
{
if (_resolvedPaths.Count > 32)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter32FileLimit"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "Counter32FileLimit", ErrorCategory.InvalidResult, null));
return;
}
}
else if (_resolvedPaths.Count > 1)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("Counter1FileLimit"));
Exception exc = new Exception(msg);
ThrowTerminatingError(new ErrorRecord(exc, "Counter1FileLimit", ErrorCategory.InvalidResult, null));
return;
}
}
//
// ResolveFilePath helper.
// Returns a string collection of resolved file paths.
// Writes non-terminating errors for invalid paths
// and returns an empty collection.
//
private bool ResolveFilePaths()
{
StringCollection retColl = new StringCollection();
foreach (string origPath in _accumulatedFileNames)
{
Collection<PathInfo> resolvedPathSubset = null;
try
{
resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(origPath);
}
catch (PSNotSupportedException notSupported)
{
WriteError(new ErrorRecord(notSupported, string.Empty, ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
WriteError(new ErrorRecord(driveNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(new ErrorRecord(providerNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (ItemNotFoundException pathNotFound)
{
WriteError(new ErrorRecord(pathNotFound, string.Empty, ErrorCategory.ObjectNotFound, origPath));
continue;
}
catch (Exception exc)
{
WriteError(new ErrorRecord(exc, string.Empty, ErrorCategory.ObjectNotFound, origPath));
continue;
}
foreach (PathInfo pi in resolvedPathSubset)
{
//
// Check the provider: only FileSystem provider paths are acceptable.
//
if (pi.Provider.Name != "FileSystem")
{
string msg = _resourceMgr.GetString("NotAFileSystemPath");
Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, origPath));
WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, origPath));
continue;
}
_resolvedPaths.Add(pi.ProviderPath.ToLowerInvariant());
}
}
return (_resolvedPaths.Count > 0);
}
private void ReportPdhError(uint res, bool bTerminate)
{
string msg;
uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg);
if (formatRes != 0)
{
msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res);
}
Exception exc = new Exception(msg);
if (bTerminate)
{
ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
}
else
{
WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
}
}
//
// WriteSampleSetObject() helper.
// In addition to writing the PerformanceCounterSampleSet object,
// it writes a single error if one of the samples has an invalid (non-zero) status.
// The only exception is the first set, where we allow for the formatted value to be 0 -
// this is expected for CSV and TSV files.
private void WriteSampleSetObject(PerformanceCounterSampleSet set, bool firstSet)
{
if (!firstSet)
{
foreach (PerformanceCounterSample sample in set.CounterSamples)
{
if (sample.Status != 0)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid"));
Exception exc = new Exception(msg);
WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
break;
}
}
}
WriteObject(set);
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
#endregion Namespaces
/// <summary>
/// This class represents the internal buffer of the <see cref="ODataBatchReaderStream"/>.
/// </summary>
internal sealed class ODataBatchReaderStreamBuffer
{
/// <summary>The size of the look-ahead buffer.</summary>
internal const int BufferLength = 8000;
/// <summary>Length of the longest supported line terminator character sequence; makes the code easier to read.</summary>
private const int MaxLineFeedLength = 2;
/// <summary>The length of two '-' characters to make the code easier to read.</summary>
private const int TwoDashesLength = 2;
/// <summary>The byte array storing the actual bytes of the buffer.</summary>
private readonly byte[] bytes = new byte[BufferLength];
/// <summary>The current position inside the buffer.</summary>
/// <remarks>This is the position of the byte that is the next to be read.</remarks>
private int currentReadPosition = 0;
/// <summary>The number of (not yet consumed) bytes currently in the buffer.</summary>
private int numberOfBytesInBuffer;
/// <summary>
/// The byte array that acts as the actual storage of the buffered data.
/// </summary>
internal byte[] Bytes
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.bytes;
}
}
/// <summary>
/// The current position inside the buffer.
/// </summary>
/// <remarks>This is the position of the byte that is the next to be read.</remarks>
internal int CurrentReadPosition
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.currentReadPosition;
}
}
/// <summary>
/// The number of (not yet consumed) bytes currently in the buffer.
/// </summary>
internal int NumberOfBytesInBuffer
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.numberOfBytesInBuffer;
}
}
/// <summary>
/// Indexer into the byte buffer.
/// </summary>
/// <param name="index">The position in the buffer to get.</param>
/// <returns>The byte at position <paramref name="index"/> in the buffer.</returns>
internal byte this[int index]
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.bytes[index];
}
}
/// <summary>
/// Skip to the specified position in the buffer.
/// Adjust the current position and the number of bytes in the buffer.
/// </summary>
/// <param name="newPosition">The position to skip to.</param>
internal void SkipTo(int newPosition)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(newPosition >= this.currentReadPosition, "Can only skip forward.");
Debug.Assert(newPosition <= this.currentReadPosition + this.numberOfBytesInBuffer, "Cannot skip beyond end of buffer.");
int diff = newPosition - this.currentReadPosition;
this.currentReadPosition = newPosition;
this.numberOfBytesInBuffer -= diff;
}
/// <summary>
/// Refills the buffer from the specified stream.
/// </summary>
/// <param name="stream">The stream to refill the buffer from.</param>
/// <param name="preserveFrom">The index in the current buffer starting from which the
/// currently buffered data should be preserved.</param>
/// <returns>true if the underlying stream got exhausted while refilling.</returns>
/// <remarks>This method will first shift any data that is to be preserved to the beginning
/// of the buffer and then refill the rest of the buffer from the <paramref name="stream"/>.</remarks>
internal bool RefillFrom(Stream stream, int preserveFrom)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(stream != null, "stream != null");
Debug.Assert(preserveFrom >= this.currentReadPosition, "preserveFrom must be at least as big as the current position in the buffer.");
this.ShiftToBeginning(preserveFrom);
int numberOfBytesToRead = ODataBatchReaderStreamBuffer.BufferLength - this.numberOfBytesInBuffer;
int numberOfBytesRead = stream.Read(this.bytes, this.numberOfBytesInBuffer, numberOfBytesToRead);
this.numberOfBytesInBuffer += numberOfBytesRead;
// return true if the underlying stream is exhausted
return numberOfBytesRead == 0;
}
/// <summary>
/// Scans the current buffer for a line end.
/// </summary>
/// <param name="lineEndStartPosition">The start position of the line terminator or -1 if not found.</param>
/// <param name="lineEndEndPosition">The end position of the line terminator or -1 if not found.</param>
/// <returns>An enumeration value indicating whether the line termintor was found completely, partially or not at all.</returns>
internal ODataBatchReaderStreamScanResult ScanForLineEnd(out int lineEndStartPosition, out int lineEndEndPosition)
{
DebugUtils.CheckNoExternalCallers();
bool endOfBufferReached;
return this.ScanForLineEnd(
this.currentReadPosition,
BufferLength,
/*allowLeadingWhitespaceOnly*/ false,
out lineEndStartPosition,
out lineEndEndPosition,
out endOfBufferReached);
}
/// <summary>
/// Scans the current buffer for the specified boundary.
/// </summary>
/// <param name="boundaries">The boundary strings to search for; this enumerable is sorted from the inner-most boundary
/// to the top-most boundary. The boundary strings don't include the leading line terminator or the leading dashes.</param>
/// <param name="maxDataBytesToScan">Stop if no boundary (or boundary start) is found after this number of bytes.</param>
/// <param name="boundaryStartPosition">The start position of the boundary or -1 if not found.
/// Note that the start position is the first byte of the leading line terminator.</param>
/// <param name="boundaryEndPosition">The end position of the boundary or -1 if not found.
/// Note that the end position is the last byte of the trailing line terminator.</param>
/// <param name="isEndBoundary">true if the boundary is an end boundary (followed by two dashes); otherwise false.</param>
/// <param name="isParentBoundary">true if the detected boundary is the parent boundary; otherwise false.</param>
/// <returns>An enumeration value indicating whether the boundary was completely, partially or not found in the buffer.</returns>
internal ODataBatchReaderStreamScanResult ScanForBoundary(
IEnumerable<string> boundaries,
int maxDataBytesToScan,
out int boundaryStartPosition,
out int boundaryEndPosition,
out bool isEndBoundary,
out bool isParentBoundary)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(boundaries != null, "boundaries != null");
boundaryStartPosition = -1;
boundaryEndPosition = -1;
isEndBoundary = false;
isParentBoundary = false;
int lineScanStartIndex = this.currentReadPosition;
while (true)
{
// NOTE: a boundary has to start with a line terminator followed by two dashes ('-'),
// the actual boundary string, another two dashes (for an end boundary),
// optional whitespace characters and another line terminator.
// NOTE: for WCF DS compatibility we do not require the leading line terminator.
int lineEndStartPosition, boundaryDelimiterStartPosition;
ODataBatchReaderStreamScanResult lineEndScanResult = this.ScanForBoundaryStart(
lineScanStartIndex,
maxDataBytesToScan,
out lineEndStartPosition,
out boundaryDelimiterStartPosition);
switch (lineEndScanResult)
{
case ODataBatchReaderStreamScanResult.NoMatch:
// Did not find a line end or boundary delimiter in the buffer or after reading maxDataBytesToScan bytes.
// Report no boundary match.
return ODataBatchReaderStreamScanResult.NoMatch;
case ODataBatchReaderStreamScanResult.PartialMatch:
// Found a partial line end or boundary delimiter at the end of the buffer but before reading maxDataBytesToScan.
// Report a partial boundary match.
boundaryStartPosition = lineEndStartPosition < 0 ? boundaryDelimiterStartPosition : lineEndStartPosition;
return ODataBatchReaderStreamScanResult.PartialMatch;
case ODataBatchReaderStreamScanResult.Match:
// Found a full line end or boundary delimiter start ('--') before reading maxDataBytesToScan or
// hitting the end of the buffer. Start matching the boundary delimiters.
//
// Start with the expected boundary (the first one in the enumerable):
// * if we find a full match - return match because we are done
// * if we find a partial match - return partial match because we have to continue checking the expected boundary.
// * if we find no match - we know that it is not the expected boundary; check the parent boundary (if it exists).
isParentBoundary = false;
foreach (string boundary in boundaries)
{
ODataBatchReaderStreamScanResult boundaryMatch = this.MatchBoundary(
lineEndStartPosition,
boundaryDelimiterStartPosition,
boundary,
out boundaryStartPosition,
out boundaryEndPosition,
out isEndBoundary);
switch (boundaryMatch)
{
case ODataBatchReaderStreamScanResult.Match:
return ODataBatchReaderStreamScanResult.Match;
case ODataBatchReaderStreamScanResult.PartialMatch:
boundaryEndPosition = -1;
isEndBoundary = false;
return ODataBatchReaderStreamScanResult.PartialMatch;
case ODataBatchReaderStreamScanResult.NoMatch:
// try the parent boundary (if any) or continue scanning
boundaryStartPosition = -1;
boundaryEndPosition = -1;
isEndBoundary = false;
isParentBoundary = true;
break;
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReaderStreamBuffer_ScanForBoundary));
}
}
// If we could not match the boundary, try again starting at the current boundary start index. Or if we already did that
// move one character ahead.
lineScanStartIndex = lineScanStartIndex == boundaryDelimiterStartPosition
? boundaryDelimiterStartPosition + 1
: boundaryDelimiterStartPosition;
break;
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReaderStreamBuffer_ScanForBoundary));
}
}
}
/// <summary>
/// Scans the current buffer for a boundary start, which is either a line feed or two dashes (since we don't require the leading line feed).
/// </summary>
/// <param name="scanStartIx">The index at which to start scanning for the boundary start.</param>
/// <param name="maxDataBytesToScan">Stop if no boundary start was found after this number of non end-of-line bytes.</param>
/// <param name="lineEndStartPosition">The start position of the line end or -1 if not found.</param>
/// <param name="boundaryDelimiterStartPosition">The start position of the boundary delimiter or -1 if not found.</param>
/// <returns>An enumeration value indicating whether the boundary start was completely, partially or not found in the buffer.</returns>
private ODataBatchReaderStreamScanResult ScanForBoundaryStart(
int scanStartIx,
int maxDataBytesToScan,
out int lineEndStartPosition,
out int boundaryDelimiterStartPosition)
{
int lastByteToCheck = this.currentReadPosition + Math.Min(maxDataBytesToScan, this.numberOfBytesInBuffer) - 1;
for (int i = scanStartIx; i <= lastByteToCheck; ++i)
{
char ch = (char)this.bytes[i];
// Note the following common line feed chars:
// \n - UNIX \r\n - DOS \r - Mac
if (ch == '\r' || ch == '\n')
{
// We found a line end; now we have to check whether it
// consists of a second character or not.
lineEndStartPosition = i;
// We only want to report PartialMatch if we ran out of bytes in the buffer;
// so even if we found the start of a line end in the last byte to check (and
// have more bytes in the buffer) we still look ahead by one.
if (ch == '\r' && i == lastByteToCheck && maxDataBytesToScan >= this.numberOfBytesInBuffer)
{
boundaryDelimiterStartPosition = i;
return ODataBatchReaderStreamScanResult.PartialMatch;
}
// If the next char is '\n' we found a line end consisting of two characters; adjust the end position.
boundaryDelimiterStartPosition = (ch == '\r' && (char)this.bytes[i + 1] == '\n') ? i + 2 : i + 1;
return ODataBatchReaderStreamScanResult.Match;
}
else if (ch == '-')
{
lineEndStartPosition = -1;
// We found a potential start of a boundary; we only want to report PartialMatch
// if we ran out of bytes in the buffer.
// So even if we found the start of a potential boundary start in the last byte to check (and
// have more bytes in the buffer) we still look ahead by one.
if (i == lastByteToCheck && maxDataBytesToScan >= this.numberOfBytesInBuffer)
{
boundaryDelimiterStartPosition = i;
return ODataBatchReaderStreamScanResult.PartialMatch;
}
if ((char)this.bytes[i + 1] == '-')
{
boundaryDelimiterStartPosition = i;
return ODataBatchReaderStreamScanResult.Match;
}
}
}
lineEndStartPosition = -1;
boundaryDelimiterStartPosition = -1;
return ODataBatchReaderStreamScanResult.NoMatch;
}
/// <summary>
/// Scans the current buffer for a line end.
/// </summary>
/// <param name="scanStartIx">The index at which to start scanning for the line terminator.</param>
/// <param name="maxDataBytesToScan">Stop if no line end (or beginning of line end) was found after this number of non end-of-line bytes.</param>
/// <param name="allowLeadingWhitespaceOnly">true if only whitespace data bytes are expected before the end-of-line characters; otherwise false.</param>
/// <param name="lineEndStartPosition">The start position of the line terminator or -1 if not found.</param>
/// <param name="lineEndEndPosition">The end position of the line terminator or -1 if not found.</param>
/// <param name="endOfBufferReached">true if the end of the buffer was reached while scanning for the line end; otherwise false.</param>
/// <returns>An enumeration value indicating whether the line termintor was found completely, partially or not at all.</returns>
/// <remarks>This method only returns <see cref="ODataBatchReaderStreamScanResult.PartialMatch"/> if we found the start
/// of a line terminator at the last character in the buffer.</remarks>
private ODataBatchReaderStreamScanResult ScanForLineEnd(
int scanStartIx,
int maxDataBytesToScan,
bool allowLeadingWhitespaceOnly,
out int lineEndStartPosition,
out int lineEndEndPosition,
out bool endOfBufferReached)
{
endOfBufferReached = false;
int lastByteToCheck = this.currentReadPosition + Math.Min(maxDataBytesToScan, this.numberOfBytesInBuffer) - 1;
for (int i = scanStartIx; i <= lastByteToCheck; ++i)
{
char ch = (char)this.bytes[i];
// Note the following common line feed chars:
// \n - UNIX \r\n - DOS \r - Mac
if (ch == '\r' || ch == '\n')
{
// We found a line end; now we have to check whether it
// consists of a second character or not.
lineEndStartPosition = i;
// We only want to report PartialMatch if we ran out of bytes in the buffer;
// so if we found the start of a line end in the last byte to check we still
// look ahead by one.
if (ch == '\r' && i == lastByteToCheck && maxDataBytesToScan >= this.numberOfBytesInBuffer)
{
lineEndEndPosition = -1;
return ODataBatchReaderStreamScanResult.PartialMatch;
}
lineEndEndPosition = lineEndStartPosition;
// If the next char is '\n' we found a line end consisting of two characters; adjust the end position.
if (ch == '\r' && (char)this.bytes[i + 1] == '\n')
{
lineEndEndPosition++;
}
return ODataBatchReaderStreamScanResult.Match;
}
else if (allowLeadingWhitespaceOnly && !char.IsWhiteSpace(ch))
{
// We found a non-whitespace character but only whitespace characters are allowed
lineEndStartPosition = -1;
lineEndEndPosition = -1;
return ODataBatchReaderStreamScanResult.NoMatch;
}
}
endOfBufferReached = true;
lineEndStartPosition = -1;
lineEndEndPosition = -1;
return ODataBatchReaderStreamScanResult.NoMatch;
}
/// <summary>
/// Check whether the bytes in the buffer at the specified start index match the expected boundary string.
/// </summary>
/// <param name="lineEndStartPosition">The start of the line feed preceding the boundary (if present).</param>
/// <param name="boundaryDelimiterStartPosition">The start position of the boundary delimiter.</param>
/// <param name="boundary">The boundary string to check for.</param>
/// <param name="boundaryStartPosition">If a match is detected, the start of the boundary delimiter,
/// i.e., either the start of the leading line feed or of the leading dashes.</param>
/// <param name="boundaryEndPosition">If a match is detected, the position of the boundary end; otherwise -1.</param>
/// <param name="isEndBoundary">true if the detected boundary is an end boundary; otherwise false.</param>
/// <returns>An <see cref="ODataBatchReaderStreamScanResult"/> indicating whether a match, a partial match or no match was found.</returns>
private ODataBatchReaderStreamScanResult MatchBoundary(
int lineEndStartPosition,
int boundaryDelimiterStartPosition,
string boundary,
out int boundaryStartPosition,
out int boundaryEndPosition,
out bool isEndBoundary)
{
boundaryStartPosition = -1;
boundaryEndPosition = -1;
int bufferLastByte = this.currentReadPosition + this.numberOfBytesInBuffer - 1;
int boundaryEndPositionAfterLineFeed =
boundaryDelimiterStartPosition + TwoDashesLength + boundary.Length + TwoDashesLength - 1;
// NOTE: for simplicity reasons we require that the full end (!) boundary plus the maximum size
// of the line terminator fits into the buffer to get a non-partial match.
// By doing so we can reliably detect whether we are dealing with an end boundary or not.
// Otherwise the logic to figure out whether we found a boundary or not is riddled with
// corner cases that only complicate the code.
bool isPartialMatch;
int matchLength;
if (bufferLastByte < boundaryEndPositionAfterLineFeed + MaxLineFeedLength)
{
isPartialMatch = true;
matchLength = Math.Min(bufferLastByte, boundaryEndPositionAfterLineFeed) - boundaryDelimiterStartPosition + 1;
}
else
{
isPartialMatch = false;
matchLength = boundaryEndPositionAfterLineFeed - boundaryDelimiterStartPosition + 1;
}
if (this.MatchBoundary(boundary, boundaryDelimiterStartPosition, matchLength, out isEndBoundary))
{
boundaryStartPosition = lineEndStartPosition < 0 ? boundaryDelimiterStartPosition : lineEndStartPosition;
if (isPartialMatch)
{
isEndBoundary = false;
return ODataBatchReaderStreamScanResult.PartialMatch;
}
else
{
// If we fully matched the boundary compute the boundary end position
boundaryEndPosition = boundaryDelimiterStartPosition + TwoDashesLength + boundary.Length - 1;
if (isEndBoundary)
{
boundaryEndPosition += TwoDashesLength;
}
// Once we could match all the characters and delimiters of the boundary string
// (and the optional trailing '--') we now have to continue reading until the next
// line feed that terminates the boundary. Only whitespace characters may exist
// after the boundary and before the line feed.
int terminatingLineFeedStartPosition, terminatingLineFeedEndPosition;
bool endOfBufferReached;
ODataBatchReaderStreamScanResult terminatingLineFeedScanResult =
this.ScanForLineEnd(
boundaryEndPosition + 1,
int.MaxValue,
/*allowLeadingWhitespaceOnly*/true,
out terminatingLineFeedStartPosition,
out terminatingLineFeedEndPosition,
out endOfBufferReached);
switch (terminatingLineFeedScanResult)
{
case ODataBatchReaderStreamScanResult.NoMatch:
if (endOfBufferReached)
{
// Reached the end of the buffer and only found whitespaces.
if (boundaryStartPosition == 0)
{
// If the boundary starts at the first position in the buffer
// and we still could not find the end of it because there are
// so many whitespaces before the terminating line feed - fail
// (security limit on the whitespaces)
throw new ODataException(Strings.ODataBatchReaderStreamBuffer_BoundaryLineSecurityLimitReached(BufferLength));
}
// Report a partial match.
isEndBoundary = false;
return ODataBatchReaderStreamScanResult.PartialMatch;
}
else
{
// Found a different character than whitespace or end-of-line
// so we did not match the boundary.
break;
}
case ODataBatchReaderStreamScanResult.PartialMatch:
// Found only a partial line end at the end of the buffer.
if (boundaryStartPosition == 0)
{
// If the boundary starts at the first position in the buffer
// and we still could not find the end of it because there are
// so many whitespaces before the terminating line feed - fail
// (security limit on the whitespaces)
throw new ODataException(Strings.ODataBatchReaderStreamBuffer_BoundaryLineSecurityLimitReached(BufferLength));
}
// Report a partial match.
isEndBoundary = false;
return ODataBatchReaderStreamScanResult.PartialMatch;
case ODataBatchReaderStreamScanResult.Match:
// At this point we only found whitespace characters and then the terminating line feed;
// adjust the boundary end position
boundaryEndPosition = terminatingLineFeedEndPosition;
return ODataBatchReaderStreamScanResult.Match;
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReaderStreamBuffer_ScanForBoundary));
}
}
}
return ODataBatchReaderStreamScanResult.NoMatch;
}
/// <summary>
/// Try to match the specified boundary string starting at the specified position.
/// </summary>
/// <param name="boundary">The boundary string to search for; this does not include
/// the leading line terminator or the leading dashes.</param>
/// <param name="startIx">The index at which to start matching the boundary.</param>
/// <param name="matchLength">The number of characters to match.</param>
/// <param name="isEndBoundary">true if the boundary string is used in an end boundary; otherwise false.</param>
/// <returns>true if it was established that the buffer starting at <paramref name="startIx"/>
/// matches the <paramref name="boundary"/>; otherwise false.</returns>
/// <remarks>This method also returns false if the boundary string was completly matched against the
/// buffer but it could not be determined whether it is used in an end boundary or not.</remarks>
private bool MatchBoundary(string boundary, int startIx, int matchLength, out bool isEndBoundary)
{
Debug.Assert(!string.IsNullOrEmpty(boundary), "!string.IsNullOrEmpty(boundary)");
Debug.Assert(matchLength >= 0, "Match length must not be negative.");
Debug.Assert(matchLength <= boundary.Length + 4, "Must never try to match more than the boundary string and the delimiting '--' on each side.");
Debug.Assert(startIx + matchLength <= this.currentReadPosition + this.numberOfBytesInBuffer, "Match length must not exceed buffer.");
isEndBoundary = false;
if (matchLength == 0)
{
return true;
}
int trailingDashes = 0;
int currentIx = startIx;
// Shift the range by 2 so that 'i' will line up with the index of the character in the boundary
// string. 'i < 0' means check for a leading '-', 'i >= boundary.Length' means check for a trailing '-'.
for (int i = -TwoDashesLength; i < matchLength - TwoDashesLength; ++i)
{
if (i < 0)
{
// Check for a leading '-'
if (this.bytes[currentIx] != '-')
{
return false;
}
}
else if (i < boundary.Length)
{
// Compare against the character in the boundary string
if (this.bytes[currentIx] != boundary[i])
{
return false;
}
}
else
{
// Check for a trailing '-'
if (this.bytes[currentIx] != '-')
{
// We matched the full boundary; return true but it is not an end boundary.
return true;
}
trailingDashes++;
}
currentIx++;
}
Debug.Assert(trailingDashes <= TwoDashesLength, "Should never look for more than " + TwoDashesLength + " trailing dashes.");
isEndBoundary = trailingDashes == TwoDashesLength;
return true;
}
/// <summary>
/// Shifts all bytes in the buffer after a specified start index to the beginning of the buffer.
/// </summary>
/// <param name="startIndex">The start index where to start shifting.</param>
private void ShiftToBeginning(int startIndex)
{
Debug.Assert(startIndex >= this.currentReadPosition, "Start of shift must be greater or equal than current position.");
int bytesToShift = this.currentReadPosition + this.numberOfBytesInBuffer - startIndex;
this.currentReadPosition = 0;
if (bytesToShift <= 0)
{
// Nothing to shift; start index is too large
this.numberOfBytesInBuffer = 0;
}
else
{
this.numberOfBytesInBuffer = bytesToShift;
Buffer.BlockCopy(this.bytes, startIndex, this.bytes, 0, bytesToShift);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Portable;
/// <summary>
/// Native utility methods.
/// </summary>
internal static class IgniteUtils
{
/** Environment variable: JAVA_HOME. */
private const string EnvJavaHome = "JAVA_HOME";
/** Directory: jre. */
private const string DirJre = "jre";
/** Directory: bin. */
private const string DirBin = "bin";
/** Directory: server. */
private const string DirServer = "server";
/** File: jvm.dll. */
private const string FileJvmDll = "jvm.dll";
/** File: Ignite.Common.dll. */
internal const string FileIgniteJniDll = "ignite.common.dll";
/** Prefix for temp directory names. */
private const string DirIgniteTmp = "Ignite_";
/** Loaded. */
private static bool _loaded;
/** Thread-local random. */
[ThreadStatic]
private static Random _rnd;
/// <summary>
/// Initializes the <see cref="IgniteUtils"/> class.
/// </summary>
static IgniteUtils()
{
TryCleanTempDirectories();
}
/// <summary>
/// Gets thread local random.
/// </summary>
/// <returns>Thread local random.</returns>
public static Random ThreadLocalRandom()
{
if (_rnd == null)
_rnd = new Random();
return _rnd;
}
/// <summary>
/// Returns shuffled list copy.
/// </summary>
/// <returns>Shuffled list copy.</returns>
public static IList<T> Shuffle<T>(IList<T> list)
{
int cnt = list.Count;
if (cnt > 1) {
List<T> res = new List<T>(list);
Random rnd = ThreadLocalRandom();
while (cnt > 1)
{
cnt--;
int idx = rnd.Next(cnt + 1);
T val = res[idx];
res[idx] = res[cnt];
res[cnt] = val;
}
return res;
}
return list;
}
/// <summary>
/// Load JVM DLL if needed.
/// </summary>
/// <param name="configJvmDllPath">JVM DLL path from config.</param>
public static void LoadDlls(string configJvmDllPath)
{
if (_loaded) return;
// 1. Load JNI dll.
LoadJvmDll(configJvmDllPath);
// 2. Load GG JNI dll.
UnmanagedUtils.Initialize();
_loaded = true;
}
/// <summary>
/// Create new instance of specified class.
/// </summary>
/// <param name="assemblyName">Assembly name.</param>
/// <param name="clsName">Class name</param>
/// <returns>New Instance.</returns>
public static object CreateInstance(string assemblyName, string clsName)
{
IgniteArgumentCheck.NotNullOrEmpty(clsName, "clsName");
var type = new TypeResolver().ResolveType(clsName, assemblyName);
if (type == null)
throw new IgniteException("Failed to create class instance [assemblyName=" + assemblyName +
", className=" + clsName + ']');
return Activator.CreateInstance(type);
}
/// <summary>
/// Set properties on the object.
/// </summary>
/// <param name="target">Target object.</param>
/// <param name="props">Properties.</param>
public static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props)
{
if (props == null)
return;
IgniteArgumentCheck.NotNull(target, "target");
Type typ = target.GetType();
foreach (KeyValuePair<string, object> prop in props)
{
PropertyInfo prop0 = typ.GetProperty(prop.Key,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (prop0 == null)
throw new IgniteException("Property is not found [type=" + typ.Name +
", property=" + prop.Key + ']');
prop0.SetValue(target, prop.Value, null);
}
}
/// <summary>
/// Loads the JVM DLL.
/// </summary>
private static void LoadJvmDll(string configJvmDllPath)
{
var messages = new List<string>();
foreach (var dllPath in GetJvmDllPaths(configJvmDllPath))
{
var errCode = LoadDll(dllPath.Value, FileJvmDll);
if (errCode == 0)
return;
messages.Add(string.Format("[option={0}, path={1}, errorCode={2}]",
dllPath.Key, dllPath.Value, errCode));
if (dllPath.Value == configJvmDllPath)
break; // if configJvmDllPath is specified and is invalid - do not try other options
}
if (!messages.Any()) // not loaded and no messages - everything was null
messages.Add(string.Format("Please specify IgniteConfiguration.JvmDllPath or {0}.", EnvJavaHome));
if (messages.Count == 1)
throw new IgniteException(string.Format("Failed to load {0} ({1})", FileJvmDll, messages[0]));
var combinedMessage = messages.Aggregate((x, y) => string.Format("{0}\n{1}", x, y));
throw new IgniteException(string.Format("Failed to load {0}:\n{1}", FileJvmDll, combinedMessage));
}
/// <summary>
/// Try loading DLLs first using file path, then using it's simple name.
/// </summary>
/// <param name="filePath"></param>
/// <param name="simpleName"></param>
/// <returns>Zero in case of success, error code in case of failure.</returns>
private static int LoadDll(string filePath, string simpleName)
{
int res = 0;
IntPtr ptr;
if (filePath != null)
{
ptr = NativeMethods.LoadLibrary(filePath);
if (ptr == IntPtr.Zero)
res = Marshal.GetLastWin32Error();
else
return res;
}
// Failed to load using file path, fallback to simple name.
ptr = NativeMethods.LoadLibrary(simpleName);
if (ptr == IntPtr.Zero)
{
// Preserve the first error code, if any.
if (res == 0)
res = Marshal.GetLastWin32Error();
}
else
res = 0;
return res;
}
/// <summary>
/// Gets the JVM DLL paths in order of lookup priority.
/// </summary>
private static IEnumerable<KeyValuePair<string, string>> GetJvmDllPaths(string configJvmDllPath)
{
if (!string.IsNullOrEmpty(configJvmDllPath))
yield return new KeyValuePair<string, string>("IgniteConfiguration.JvmDllPath", configJvmDllPath);
var javaHomeDir = Environment.GetEnvironmentVariable(EnvJavaHome);
if (!string.IsNullOrEmpty(javaHomeDir))
yield return
new KeyValuePair<string, string>(EnvJavaHome, GetJvmDllPath(Path.Combine(javaHomeDir, DirJre)));
}
/// <summary>
/// Gets the JVM DLL path from JRE dir.
/// </summary>
private static string GetJvmDllPath(string jreDir)
{
return Path.Combine(jreDir, DirBin, DirServer, FileJvmDll);
}
/// <summary>
/// Unpacks an embedded resource into a temporary folder and returns the full path of resulting file.
/// </summary>
/// <param name="resourceName">Resource name.</param>
/// <returns>Path to a temp file with an unpacked resource.</returns>
public static string UnpackEmbeddedResource(string resourceName)
{
var dllRes = Assembly.GetExecutingAssembly().GetManifestResourceNames()
.Single(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase));
return WriteResourceToTempFile(dllRes, resourceName);
}
/// <summary>
/// Writes the resource to temporary file.
/// </summary>
/// <param name="resource">The resource.</param>
/// <param name="name">File name prefix</param>
/// <returns>Path to the resulting temp file.</returns>
private static string WriteResourceToTempFile(string resource, string name)
{
// Dll file name should not be changed, so we create a temp folder with random name instead.
var file = Path.Combine(GetTempDirectoryName(), name);
using (var src = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource))
using (var dest = File.OpenWrite(file))
{
// ReSharper disable once PossibleNullReferenceException
src.CopyTo(dest);
return file;
}
}
/// <summary>
/// Tries to clean temporary directories created with <see cref="GetTempDirectoryName"/>.
/// </summary>
private static void TryCleanTempDirectories()
{
foreach (var dir in Directory.GetDirectories(Path.GetTempPath(), DirIgniteTmp + "*"))
{
try
{
Directory.Delete(dir, true);
}
catch (IOException)
{
// Expected
}
catch (UnauthorizedAccessException)
{
// Expected
}
}
}
/// <summary>
/// Creates a uniquely named, empty temporary directory on disk and returns the full path of that directory.
/// </summary>
/// <returns>The full path of the temporary directory.</returns>
private static string GetTempDirectoryName()
{
while (true)
{
var dir = Path.Combine(Path.GetTempPath(), DirIgniteTmp + Path.GetRandomFileName());
try
{
return Directory.CreateDirectory(dir).FullName;
}
catch (IOException)
{
// Expected
}
catch (UnauthorizedAccessException)
{
// Expected
}
}
}
/// <summary>
/// Convert unmanaged char array to string.
/// </summary>
/// <param name="chars">Char array.</param>
/// <param name="charsLen">Char array length.</param>
/// <returns></returns>
public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen)
{
IntPtr ptr = new IntPtr(chars);
if (ptr == IntPtr.Zero)
return null;
byte[] arr = new byte[charsLen];
Marshal.Copy(ptr, arr, 0, arr.Length);
return Encoding.UTF8.GetString(arr);
}
/// <summary>
/// Convert string to unmanaged byte array.
/// </summary>
/// <param name="str">String.</param>
/// <returns>Unmanaged byte array.</returns>
public static unsafe sbyte* StringToUtf8Unmanaged(string str)
{
var ptr = IntPtr.Zero;
if (str != null)
{
byte[] strBytes = Encoding.UTF8.GetBytes(str);
ptr = Marshal.AllocHGlobal(strBytes.Length + 1);
Marshal.Copy(strBytes, 0, ptr, strBytes.Length);
*((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator.
}
return (sbyte*)ptr.ToPointer();
}
/// <summary>
/// Reads node collection from stream.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="pred">The predicate.</param>
/// <returns> Nodes list or null. </returns>
public static List<IClusterNode> ReadNodes(IPortableRawReader reader, Func<ClusterNodeImpl, bool> pred = null)
{
var cnt = reader.ReadInt();
if (cnt < 0)
return null;
var res = new List<IClusterNode>(cnt);
var ignite = ((PortableReaderImpl)reader).Marshaller.Ignite;
if (pred == null)
{
for (var i = 0; i < cnt; i++)
res.Add(ignite.GetNode(reader.ReadGuid()));
}
else
{
for (var i = 0; i < cnt; i++)
{
var node = ignite.GetNode(reader.ReadGuid());
if (pred(node))
res.Add(node);
}
}
return res;
}
/// <summary>
/// Gets the asynchronous mode disabled exception.
/// </summary>
/// <returns>Asynchronous mode disabled exception.</returns>
public static InvalidOperationException GetAsyncModeDisabledException()
{
return new InvalidOperationException("Asynchronous mode is disabled");
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework.Api;
using NUnit.Framework.Internal;
#if true
#endif
namespace NUnit.Framework.Builders
{
/// <summary>
/// PairwiseStrategy creates test cases by combining the parameter
/// data so that all possible pairs of data items are used.
/// </summary>
public class PairwiseStrategy : CombiningStrategy
{
internal class FleaRand
{
private const int FleaRandSize = 256;
private uint b;
private uint c;
private uint d;
private uint z;
private uint[] m = new uint[FleaRandSize];
private uint[] r = new uint[FleaRandSize];
private uint q;
/// <summary>
/// Initializes a new instance of the <see cref="FleaRand"/> class.
/// </summary>
/// <param name="seed">The seed.</param>
public FleaRand(uint seed)
{
this.b = seed;
this.c = seed;
this.d = seed;
this.z = seed;
for (int i = 0; i < this.m.Length; i++)
{
this.m[i] = seed;
}
for (int i = 0; i < 10; i++)
{
this.Batch();
}
this.q = 0;
}
public uint Next()
{
if (this.q == 0)
{
this.Batch();
this.q = (uint)this.r.Length - 1;
}
else
{
this.q--;
}
return this.r[this.q];
}
private void Batch()
{
uint a;
uint b = this.b;
uint c = this.c + (++this.z);
uint d = this.d;
for (int i = 0; i < this.r.Length; i++)
{
a = this.m[b % this.m.Length];
this.m[b % this.m.Length] = d;
d = (c << 19) + (c >> 13) + b;
c = b ^ this.m[i];
b = a + d;
this.r[i] = c;
}
this.b = b;
this.c = c;
this.d = d;
}
}
internal class FeatureInfo
{
public const string Names = "abcdefghijklmnopqrstuvwxyz";
public readonly int Dimension;
public readonly int Feature;
public FeatureInfo(int dimension, int feature)
{
this.Dimension = dimension;
this.Feature = feature;
}
#if DEBUG
public override string ToString()
{
return (this.Dimension + 1).ToString() + FeatureInfo.Names[this.Feature];
}
#endif
}
internal class Tuple
{
#if true
private readonly List<FeatureInfo> features = new List<FeatureInfo>();
#else
private readonly ArrayList features = new ArrayList();
#endif
public int Count
{
get
{
return this.features.Count;
}
}
public FeatureInfo this[int index]
{
get
{
return (FeatureInfo)this.features[index];
}
}
public void Add(FeatureInfo feature)
{
this.features.Add(feature);
}
#if DEBUG
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('(');
for (int i = 0; i < this.features.Count; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(this.features[i].ToString());
}
sb.Append(')');
return sb.ToString();
}
#endif
}
internal class TupleCollection
{
#if true
private readonly List<Tuple> tuples = new List<Tuple>();
#else
private readonly ArrayList tuples = new ArrayList();
#endif
public int Count
{
get
{
return this.tuples.Count;
}
}
public Tuple this[int index]
{
get
{
return (Tuple)this.tuples[index];
}
}
public void Add(Tuple tuple)
{
this.tuples.Add(tuple);
}
public void RemoveAt(int index)
{
this.tuples.RemoveAt(index);
}
}
internal class TestCase
{
public readonly int[] Features;
public TestCase(int numberOfDimensions)
{
this.Features = new int[numberOfDimensions];
}
public bool IsTupleCovered(Tuple tuple)
{
for (int i = 0; i < tuple.Count; i++)
{
if (this.Features[tuple[i].Dimension] != tuple[i].Feature)
{
return false;
}
}
return true;
}
#if DEBUG
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.Features.Length; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(i + 1);
sb.Append(FeatureInfo.Names[this.Features[i]]);
}
return sb.ToString();
}
#endif
}
internal class TestCaseCollection : IEnumerable
{
#if true
private readonly List<TestCase> testCases = new List<TestCase>();
#else
private readonly ArrayList testCases = new ArrayList();
#endif
public void Add(TestCase testCase)
{
this.testCases.Add(testCase);
}
public IEnumerator GetEnumerator()
{
return this.testCases.GetEnumerator();
}
public bool IsTupleCovered(Tuple tuple)
{
foreach (TestCase testCase in this.testCases)
{
if (testCase.IsTupleCovered(tuple))
{
return true;
}
}
return false;
}
}
internal class PairwiseTestCaseGenerator
{
private const int MaxTupleLength = 2;
private readonly FleaRand random = new FleaRand(0);
private readonly int[] dimensions;
private readonly TupleCollection[][] uncoveredTuples;
private readonly int[][] currentTupleLength;
private readonly TestCaseCollection testCases = new TestCaseCollection();
public PairwiseTestCaseGenerator(int[] dimensions)
{
this.dimensions = dimensions;
this.uncoveredTuples = new TupleCollection[this.dimensions.Length][];
for (int d = 0; d < this.uncoveredTuples.Length; d++)
{
this.uncoveredTuples[d] = new TupleCollection[this.dimensions[d]];
for (int f = 0; f < this.dimensions[d]; f++)
{
this.uncoveredTuples[d][f] = new TupleCollection();
}
}
this.currentTupleLength = new int[this.dimensions.Length][];
for (int d = 0; d < this.dimensions.Length; d++)
{
this.currentTupleLength[d] = new int[this.dimensions[d]];
}
}
public IEnumerable GetTestCases()
{
this.CreateTestCases();
this.SelfTest();
return this.testCases;
}
private void CreateTestCases()
{
while (true)
{
this.ExtendTupleSet();
Tuple tuple = this.FindTupleToCover();
if (tuple == null)
{
return;
}
TestCase testCase = this.FindGoodTestCase(tuple);
this.RemoveTuplesCoveredBy(testCase);
this.testCases.Add(testCase);
}
}
private void ExtendTupleSet()
{
for (int d = 0; d < this.dimensions.Length; d++)
{
for (int f = 0; f < this.dimensions[d]; f++)
{
this.ExtendTupleSet(d, f);
}
}
}
private void ExtendTupleSet(int dimension, int feature)
{
// If tuples for [dimension][feature] already exists, it's no needs to add more tuples.
if (this.uncoveredTuples[dimension][feature].Count > 0)
{
return;
}
// If maximum tuple length for [dimension][feature] is reached, it's no needs to add more tuples.
if (this.currentTupleLength[dimension][feature] == MaxTupleLength)
{
return;
}
this.currentTupleLength[dimension][feature]++;
int tupleLength = this.currentTupleLength[dimension][feature];
if (tupleLength == 1)
{
Tuple tuple = new Tuple();
tuple.Add(new FeatureInfo(dimension, feature));
if (this.testCases.IsTupleCovered(tuple))
{
return;
}
this.uncoveredTuples[dimension][feature].Add(tuple);
}
else
{
for (int d = 0; d < this.dimensions.Length; d++)
{
for (int f = 0; f < this.dimensions[d]; f++)
{
Tuple tuple = new Tuple();
tuple.Add(new FeatureInfo(d, f));
if (tuple[0].Dimension == dimension)
{
continue;
}
tuple.Add(new FeatureInfo(dimension, feature));
if (this.testCases.IsTupleCovered(tuple))
{
continue;
}
this.uncoveredTuples[dimension][feature].Add(tuple);
}
}
}
}
private Tuple FindTupleToCover()
{
int tupleLength = MaxTupleLength;
int tupleCount = 0;
Tuple tuple = null;
for (int d = 0; d < this.dimensions.Length; d++)
{
for (int f = 0; f < this.dimensions[d]; f++)
{
if (this.currentTupleLength[d][f] < tupleLength)
{
tupleLength = this.currentTupleLength[d][f];
tupleCount = this.uncoveredTuples[d][f].Count;
tuple = this.uncoveredTuples[d][f][0];
}
else
{
if (this.currentTupleLength[d][f] == tupleLength && this.uncoveredTuples[d][f].Count > tupleCount)
{
tupleCount = this.uncoveredTuples[d][f].Count;
tuple = this.uncoveredTuples[d][f][0];
}
}
}
}
return tuple;
}
private TestCase FindGoodTestCase(Tuple tuple)
{
TestCase bestTest = null;
int bestCoverage = -1;
for (int i = 0; i < 5; i++)
{
TestCase test = new TestCase(this.dimensions.Length);
int coverage = this.CreateTestCase(tuple, test);
if (coverage > bestCoverage)
{
bestTest = test;
bestCoverage = coverage;
}
}
return bestTest;
}
private int CreateTestCase(Tuple tuple, TestCase test)
{
// Create a random test case...
for (int i = 0; i < test.Features.Length; i++)
{
test.Features[i] = (int)(this.random.Next() % this.dimensions[i]);
}
// ...and inject the tuple into it!
for (int i = 0; i < tuple.Count; i++)
{
test.Features[tuple[i].Dimension] = tuple[i].Feature;
}
return this.MaximizeCoverage(test, tuple);
}
private int MaximizeCoverage(TestCase test, Tuple tuple)
{
int[] dimensionOrder = this.GetMutableDimensions(tuple);
while (true)
{
bool progress = false;
int totalCoverage = 1;
// Scramble dimensions.
for (int i = dimensionOrder.Length; i > 1; i--)
{
int j = (int)(this.random.Next() % i);
int t = dimensionOrder[i - 1];
dimensionOrder[i - 1] = dimensionOrder[j];
dimensionOrder[j] = t;
}
// For each dimension that can be modified...
for (int i = 0; i < dimensionOrder.Length; i++)
{
int d = dimensionOrder[i];
#if true
List<int> bestFeatures = new List<int>();
#else
ArrayList bestFeatures = new ArrayList();
#endif
int bestCoverage = this.CountTuplesCovered(test, d, test.Features[d]);
int bestTupleLength = this.currentTupleLength[d][test.Features[d]];
// For each feature that can be modified, check if it can extend coverage.
for (int f = 0; f < this.dimensions[d]; f++)
{
test.Features[d] = f;
int coverage = this.CountTuplesCovered(test, d, f);
if (this.currentTupleLength[d][f] < bestTupleLength)
{
progress = true;
bestTupleLength = this.currentTupleLength[d][f];
bestCoverage = coverage;
bestFeatures.Clear();
bestFeatures.Add(f);
}
else
{
if (this.currentTupleLength[d][f] == bestTupleLength && coverage >= bestCoverage)
{
if (coverage > bestCoverage)
{
progress = true;
bestCoverage = coverage;
bestFeatures.Clear();
}
bestFeatures.Add(f);
}
}
}
if (bestFeatures.Count == 1)
{
test.Features[d] = (int)bestFeatures[0];
}
else
{
test.Features[d] = (int)bestFeatures[(int)(this.random.Next() % bestFeatures.Count)];
}
totalCoverage += bestCoverage;
}
if (!progress)
{
return totalCoverage;
}
}
}
private int[] GetMutableDimensions(Tuple tuple)
{
bool[] immutableDimensions = new bool[this.dimensions.Length];
for (int i = 0; i < tuple.Count; i++)
{
immutableDimensions[tuple[i].Dimension] = true;
}
#if true
List<int> mutableDimensions = new List<int>();
#else
ArrayList mutableDimensions = new ArrayList();
#endif
for (int i = 0; i < this.dimensions.Length; i++)
{
if (!immutableDimensions[i])
{
mutableDimensions.Add(i);
}
}
#if true
return mutableDimensions.ToArray();
#else
return (int[])mutableDimensions.ToArray(typeof(int));
#endif
}
private int CountTuplesCovered(TestCase test, int dimension, int feature)
{
int tuplesCovered = 0;
TupleCollection tuples = this.uncoveredTuples[dimension][feature];
for (int i = 0; i < tuples.Count; i++)
{
if (test.IsTupleCovered(tuples[i]))
{
tuplesCovered++;
}
}
return tuplesCovered;
}
private void RemoveTuplesCoveredBy(TestCase testCase)
{
for (int d = 0; d < this.uncoveredTuples.Length; d++)
{
for (int f = 0; f < this.uncoveredTuples[d].Length; f++)
{
TupleCollection tuples = this.uncoveredTuples[d][f];
for (int i = tuples.Count - 1; i >= 0; i--)
{
if (testCase.IsTupleCovered(tuples[i]))
{
tuples.RemoveAt(i);
}
}
}
}
}
private void SelfTest()
{
for (int d1 = 0; d1 < this.dimensions.Length - 1; d1++)
{
for (int d2 = d1 + 1; d2 < this.dimensions.Length; d2++)
{
for (int f1 = 0; f1 < this.dimensions[d1]; f1++)
{
for (int f2 = 0; f2 < this.dimensions[d2]; f2++)
{
Tuple tuple = new Tuple();
tuple.Add(new FeatureInfo(d1, f1));
tuple.Add(new FeatureInfo(d2, f2));
if (!this.testCases.IsTupleCovered(tuple))
{
throw new ApplicationException("PairwiseStrategy self-test failed : Not all pairs are covered!");
}
}
}
}
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PairwiseStrategy"/> class.
/// </summary>
/// <param name="sources">The sources.</param>
public PairwiseStrategy(IEnumerable[] sources) : base(sources) { }
/// <summary>
/// Gets the test cases generated by this strategy instance.
/// </summary>
/// <returns>The test cases.</returns>
#if true
public override IEnumerable<ITestCaseData> GetTestCases()
{
List<ITestCaseData> testCases = new List<ITestCaseData>();
#else
public override IEnumerable GetTestCases()
{
ArrayList testCases = new ArrayList();
#endif
ObjectList[] valueSet = CreateValueSet();
int[] dimensions = CreateDimensions(valueSet);
IEnumerable pairwiseTestCases = new PairwiseTestCaseGenerator(dimensions).GetTestCases();
foreach (TestCase pairwiseTestCase in pairwiseTestCases)
{
object[] testData = new object[pairwiseTestCase.Features.Length];
for (int i = 0; i < pairwiseTestCase.Features.Length; i++)
{
testData[i] = valueSet[i][pairwiseTestCase.Features[i]];
}
ParameterSet parms = new ParameterSet();
parms.Arguments = testData;
testCases.Add(parms);
}
return testCases;
}
private ObjectList[] CreateValueSet()
{
ObjectList[] valueSet = new ObjectList[Sources.Length];
for (int i = 0; i < valueSet.Length; i++)
{
ObjectList values = new ObjectList();
foreach (object value in Sources[i])
{
values.Add(value);
}
valueSet[i] = values;
}
return valueSet;
}
private int[] CreateDimensions(ObjectList[] valueSet)
{
int[] dimensions = new int[valueSet.Length];
for (int i = 0; i < valueSet.Length; i++)
{
dimensions[i] = valueSet[i].Count;
}
return dimensions;
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek and Jan Benda.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
/*
TODO:
- implement all functions
- Added (PHP 5.1.0):
stream_socket_enable_crypto()
*/
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Threading;
using PHP.Core;
namespace PHP.Library
{
/// <summary>
/// Gives access to various network-based stream properties.
/// </summary>
/// <threadsafety static="true"/>
public static class StreamSocket
{
#region Enums
/// <summary>
/// Options used for <see cref="StreamSocket.Connect"/>.
/// </summary>
public enum SocketOptions
{
/// <summary>
/// Default option.
/// </summary>
[ImplementsConstant("STREAM_CLIENT_CONNECT")]
None = 0,
/// <summary>
/// Client socket opened with <c>stream_socket_client</c> should remain persistent
/// between page loads.
/// </summary>
[ImplementsConstant("STREAM_CLIENT_PERSISTENT")]
Persistent = 1,
/// <summary>
/// Open client socket asynchronously.
/// </summary>
[ImplementsConstant("STREAM_CLIENT_ASYNC_CONNECT")]
Asynchronous = 2
}
public enum _AddressFamily
{
[ImplementsConstant("STREAM_PF_INET")]
InterNetwork = AddressFamily.InterNetwork,
[ImplementsConstant("STREAM_PF_INET6")]
InterNetworkV6 = AddressFamily.InterNetworkV6,
[ImplementsConstant("STREAM_PF_UNIX")]
Unix = AddressFamily.Unix
}
public enum _SocketType
{
Unknown = SocketType.Unknown,
[ImplementsConstant("STREAM_SOCK_STREAM")]
Stream = SocketType.Stream,
[ImplementsConstant("STREAM_SOCK_DGRAM")]
Dgram = SocketType.Dgram,
[ImplementsConstant("STREAM_SOCK_RAW")]
Raw = SocketType.Raw,
[ImplementsConstant("STREAM_SOCK_RDM")]
Rdm = SocketType.Rdm,
[ImplementsConstant("STREAM_SOCK_SEQPACKET")]
Seqpacket = SocketType.Seqpacket,
}
public enum _ProtocolType
{
[ImplementsConstant("STREAM_IPPROTO_IP")]
IP = ProtocolType.IP,
[ImplementsConstant("STREAM_IPPROTO_ICMP")]
Icmp = ProtocolType.Icmp,
[ImplementsConstant("STREAM_IPPROTO_TCP")]
Tcp = ProtocolType.Tcp,
[ImplementsConstant("STREAM_IPPROTO_UDP")]
Udp = ProtocolType.Udp,
[ImplementsConstant("STREAM_IPPROTO_RAW")]
Raw = ProtocolType.Raw
}
public enum SendReceiveOptions
{
None = 0,
[ImplementsConstant("STREAM_OOB")]
OutOfBand = 1,
[ImplementsConstant("STREAM_PEEK")]
Peek = 2
}
#endregion
#region TODO: stream_get_transports, stream_socket_get_name
/// <summary>Retrieve list of registered socket transports</summary>
[ImplementsFunction("stream_get_transports", FunctionImplOptions.NotSupported)]
public static PhpArray GetTransports()
{
PhpException.FunctionNotSupported();
return null;
}
/// <summary>
/// Retrieve the name of the local or remote sockets.
/// </summary>
[ImplementsFunction("stream_socket_get_name", FunctionImplOptions.NotSupported)]
public static string SocketGetName(PhpResource handle, bool wantPeer)
{
PhpException.FunctionNotSupported();
return null;
}
#endregion
#region TODO: stream_socket_client
//private static void SplitSocketAddressPort(ref string socket, out int port)
//{
// port = 0;
// String[] arr = socket.Split(new[] {':'}, 2, StringSplitOptions.RemoveEmptyEntries);
// if (arr.Length == 2)
// {
// socket = arr[0];
// port = int.Parse(arr[1]);
// }
//}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_client")]
public static PhpResource ConnectClient(string remoteSocket)
{
int errno;
string errstr;
int port = 0;
//SplitSocketAddressPort(ref remoteSocket, out port);
return Connect(remoteSocket, port, out errno, out errstr, Double.NaN, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_client")]
public static PhpResource ConnectClient(string remoteSocket, out int errno)
{
string errstr;
int port = 0;
//SplitSocketAddressPort(ref remoteSocket, out port);
return Connect(remoteSocket, port, out errno, out errstr, Double.NaN, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_client")]
public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr)
{
int port = 0;
//SplitSocketAddressPort(ref remoteSocket, out port);
return Connect(remoteSocket, port, out errno, out errstr, Double.NaN, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_client")]
public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr,
double timeout)
{
int port = 0;
//SplitSocketAddressPort(ref remoteSocket, out port);
return Connect(remoteSocket, port, out errno, out errstr, timeout, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_client")]
public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr,
double timeout, SocketOptions flags)
{
int port = 0;
//SplitSocketAddressPort(ref remoteSocket, out port);
return Connect(remoteSocket, port, out errno, out errstr, timeout, flags, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_client")]
public static PhpResource ConnectClient(string remoteSocket, out int errno, out string errstr,
double timeout, SocketOptions flags, PhpResource context)
{
StreamContext sc = StreamContext.GetValid(context);
if (sc == null)
{
errno = -1;
errstr = null;
return null;
}
int port = 0;
//SplitSocketAddressPort(ref remoteSocket, out port);
return Connect(remoteSocket, port, out errno, out errstr, timeout, flags, sc);
}
#endregion
#region TODO: stream_socket_server
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_server")]
public static PhpResource ConnectServer(string localSocket)
{
int errno;
string errstr;
int port = 0;
//SplitSocketAddressPort(ref localSocket, out port);
return Connect(localSocket, port, out errno, out errstr, Double.NaN, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_server")]
public static PhpResource ConnectServer(string localSocket, out int errno)
{
string errstr;
int port = 0;
//SplitSocketAddressPort(ref localSocket, out port);
return Connect(localSocket, port, out errno, out errstr, Double.NaN, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_server")]
public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr)
{
int port = 0;
//SplitSocketAddressPort(ref localSocket, out port);
return Connect(localSocket, port, out errno, out errstr, Double.NaN, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_server")]
public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr,
double timeout)
{
int port = 0;
//SplitSocketAddressPort(ref localSocket, out port);
return Connect(localSocket, port, out errno, out errstr, timeout, SocketOptions.None, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_server")]
public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr,
double timeout, SocketOptions flags)
{
int port = 0;
//SplitSocketAddressPort(ref localSocket, out port);
return Connect(localSocket, port, out errno, out errstr, timeout, flags, StreamContext.Default);
}
/// <summary>
/// Open client socket.
/// </summary>
[ImplementsFunction("stream_socket_server")]
public static PhpResource ConnectServer(string localSocket, out int errno, out string errstr,
double timeout, SocketOptions flags, PhpResource context)
{
StreamContext sc = StreamContext.GetValid(context);
if (sc == null)
{
errno = -1;
errstr = null;
return null;
}
int port = 0;
//SplitSocketAddressPort(ref localSocket, out port);
return Connect(localSocket, port, out errno, out errstr, timeout, flags, sc);
}
#endregion
#region TODO: stream_socket_accept
/// <summary>
/// Accepts a connection on a server socket.
/// </summary>
[ImplementsFunction("stream_socket_accept", FunctionImplOptions.NotSupported)]
public static bool Accept(PhpResource serverSocket)
{
string peerName;
return Accept(serverSocket, Configuration.Local.FileSystem.DefaultSocketTimeout, out peerName);
}
/// <summary>
/// Accepts a connection on a server socket.
/// </summary>
[ImplementsFunction("stream_socket_accept", FunctionImplOptions.NotSupported)]
public static bool Accept(PhpResource serverSocket, int timeout)
{
string peerName;
return Accept(serverSocket, timeout, out peerName);
}
/// <summary>
/// Accepts a connection on a server socket.
/// </summary>
[ImplementsFunction("stream_socket_accept", FunctionImplOptions.NotSupported)]
public static bool Accept(PhpResource serverSocket, int timeout, out string peerName)
{
peerName = "";
SocketStream stream = SocketStream.GetValid(serverSocket);
if (stream == null) return false;
PhpException.FunctionNotSupported();
return false;
}
#endregion
#region TODO: stream_socket_recvfrom
[ImplementsFunction("stream_socket_recvfrom", FunctionImplOptions.NotSupported)]
public static string ReceiveFrom(PhpResource socket, int length)
{
string address;
return ReceiveFrom(socket, length, SendReceiveOptions.None, out address);
}
[ImplementsFunction("stream_socket_recvfrom", FunctionImplOptions.NotSupported)]
public static string ReceiveFrom(PhpResource socket, int length, SendReceiveOptions flags)
{
string address;
return ReceiveFrom(socket, length, flags, out address);
}
[ImplementsFunction("stream_socket_recvfrom", FunctionImplOptions.NotSupported)]
public static string ReceiveFrom(PhpResource socket, int length, SendReceiveOptions flags,
out string address)
{
address = null;
SocketStream stream = SocketStream.GetValid(socket);
if (stream == null) return null;
PhpException.FunctionNotSupported();
return null;
}
#endregion
#region TODO: stream_socket_sendto
[ImplementsFunction("stream_socket_sendto", FunctionImplOptions.NotSupported)]
public static int SendTo(PhpResource socket, string data)
{
return SendTo(socket, data, SendReceiveOptions.None, null);
}
[ImplementsFunction("stream_socket_sendto", FunctionImplOptions.NotSupported)]
public static int SendTo(PhpResource socket, string data, SendReceiveOptions flags)
{
return SendTo(socket, data, flags, null);
}
[ImplementsFunction("stream_socket_sendto", FunctionImplOptions.NotSupported)]
public static int SendTo(PhpResource socket, string data, SendReceiveOptions flags,
string address)
{
SocketStream stream = SocketStream.GetValid(socket);
if (stream == null) return -1;
PhpException.FunctionNotSupported();
return -1;
}
#endregion
#region TODO: stream_socket_pair
//[ImplementsFunction("stream_socket_pair", FunctionImplOptions.NotSupported)]
public static PhpArray CreatePair(ProtocolFamily protocolFamily, SocketType type, ProtocolType protocol)
{
PhpException.FunctionNotSupported();
return null;
}
#endregion
#region Connect
/// <summary>
/// Opens a new SocketStream
/// </summary>
internal static SocketStream Connect(string remoteSocket, int port, out int errno, out string errstr,
double timeout, SocketOptions flags, StreamContext/*!*/ context)
{
errno = 0;
errstr = null;
if (remoteSocket == null)
{
PhpException.ArgumentNull("remoteSocket");
return null;
}
// TODO: extract schema (tcp://, udp://) and port from remoteSocket
// Uri uri = Uri.TryCreate(remoteSocket);
ProtocolType protocol = ProtocolType.Tcp;
if (remoteSocket.Contains("://"))
{
String[] separator = { "://" };
String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None);
switch (socketParts[0])
{
case "udp":
protocol = ProtocolType.Udp;
break;
case "tcp":
default:
protocol = ProtocolType.Tcp;
break;
}
remoteSocket = socketParts[1];
}
if (remoteSocket.Contains(":"))
{
Char[] separator = { ':' };
String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None);
remoteSocket = socketParts[0];
int result = 0;
if (socketParts[1] != "" && int.TryParse(socketParts[1], out result) &&
(0 < result && result < 65536))
{
port = result;
}
}
if (Double.IsNaN(timeout))
timeout = Configuration.Local.FileSystem.DefaultSocketTimeout;
// TODO:
if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous)
PhpException.ArgumentValueNotSupported("flags", (int)flags);
try
{
// workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address
//IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];
IPAddress address;
if (!IPAddress.TryParse(remoteSocket, out address)) // if remoteSocket is not a valid IP address then lookup the DNS
address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];
Socket socket = new Socket(address.AddressFamily, SocketType.Stream, protocol);
IAsyncResult res = socket.BeginConnect(
new IPEndPoint(address, port),
new AsyncCallback(StreamSocket.ConnectResultCallback),
socket);
int msec = 0;
while (!res.IsCompleted)
{
Thread.Sleep(100);
msec += 100;
if (msec / 1000.0 > timeout)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_timeout",
FileSystemUtils.StripPassword(remoteSocket)));
return null;
}
}
socket.EndConnect(res);
// socket.Connect(new IPEndPoint(address, port));
return new SocketStream(socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) == SocketOptions.Asynchronous);
}
catch (SocketException e)
{
errno = e.ErrorCode;
errstr = e.Message;
}
catch (System.Exception e)
{
errno = -1;
errstr = e.Message;
}
PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_error",
FileSystemUtils.StripPassword(remoteSocket), errstr));
return null;
}
private static void ConnectResultCallback(IAsyncResult res)
{
}
#endregion
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Data;
using System.Threading;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Stats;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Logger;
namespace Alachisoft.NCache.Storage
{
/// <summary>
/// This is the base class of all Cache stores. Provides additional optional
/// functions that can be overridden as well as default implementation of the
/// some of the methods in the ICacheStorage interface, wherever possible.
/// Implements ICacheStorage.
/// </summary>
internal class StorageProviderBase : ICacheStorage
{
#region / --- Store Status --- /
/// <summary>
/// Staus of the Store.
/// </summary>
protected enum StoreStatus
{
/// <summary> Store has space.</summary>
HasSpace,
/// <summary> Store is almost full,but can accomadate some data. </summary>
NearEviction,
/// <summary> Store has no space to accomodate new data.</summary>
HasNotEnoughSpace
}
#endregion
public const uint KB = 1024;
public const uint MB = KB * KB;
public const uint GB = MB * KB;
private string _cacheContext;
private Boolean _virtualUnlimitedSpace = false;
/// <summary>
/// The default starting capacity of stores.
/// </summary>
protected readonly int DEFAULT_CAPACITY = 25000;
/// <summary>
/// The default percentage of the extra data which can be accomdated.
/// </summary>
protected readonly double DEFAULT_EXTRA_ACCOMDATION_PERCENTAGE = 0.20f;
/// <summary>
/// Maximam data size, in bytes, that store can hold
/// </summary>
private long _maxSize;
/// <summary>
///Size of data which can be accomdated even after we reach max size.
/// </summary>
private long _extraDataSize = 0;
/// <summary>
/// Maximam number of object in cache
/// </summary>
private long _maxCount;
/// <summary>
/// Size of data, in bytes, stored in cache
/// </summary>
protected long _dataSize;
/// <summary>
/// Reader, writer lock to be used for synchronization.
/// </summary>
protected ReaderWriterLock _syncObj;
protected bool _reportCacheNearEviction = false;
protected int _evictionReportSize = 0;
protected int _reportInterval = 5;
protected DateTime _lastReportedTime = DateTime.MinValue;
ILogger _ncacheLog;
private ISizableIndex _iSizableQueryIndexManager = null;
private ISizableIndex _iSizableExpirationIndexManager = null;
private ISizableIndex _iSizableEvictionIndexManager = null;
protected long TotalDataSize
{
get
{
long temp = _dataSize;
if (ISizableQueryIndexManager != null)
temp += ISizableQueryIndexManager.IndexInMemorySize;
if (ISizableExpirationIndexManager != null)
temp += ISizableExpirationIndexManager.IndexInMemorySize;
if (ISizableEvictionIndexManager != null)
temp += ISizableEvictionIndexManager.IndexInMemorySize;
return temp;
}
set
{
_dataSize = value;
}
}
public ILogger NCacheLog
{
get { return _ncacheLog; }
}
/// <summary>
/// Default contructor.
/// </summary>
public StorageProviderBase()
: this(0)
{
}
/// <summary>
/// Overloaded constructor. Takes the max objects limit, and the listener as parameters.
/// </summary>
/// <param name="maxLimit">maximum number of objects to contain.</param>
public StorageProviderBase(long maxSize)
{
_syncObj = new ReaderWriterLock();
_maxSize = maxSize;
}
public StorageProviderBase(IDictionary properties, bool evictionEnabled)
: this(properties, evictionEnabled, null)
{
}
/// <summary>
/// Overloaded constructor. Takes the properties as a map.
/// </summary>
/// <param name="properties">property collection</param>
public StorageProviderBase(IDictionary properties, bool evictionEnabled, ILogger NCacheLog)
{
Initialize(properties, evictionEnabled);
_ncacheLog = NCacheLog;
string tmp = System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.CacheSizeThreshold"];
if (tmp != null && tmp != "")
{
int size = Convert.ToInt32(tmp);
if (size > 0)
{
_evictionReportSize = size;
_reportCacheNearEviction = true;
}
}
tmp = System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.CacheSizeReportInterval"];
if (tmp != null && tmp != "")
{
int interval = Convert.ToInt32(tmp);
if (interval > 5)
{
_reportInterval = interval;
}
}
}
protected void CheckForStoreNearEviction()
{
if (_reportCacheNearEviction && !VirtualUnlimitedSpace)
{
if (_lastReportedTime.AddMinutes(_reportInterval) < DateTime.Now)
{
if (_maxSize > 0 && _evictionReportSize > 0)
{
double currentSizeInPerc = ((double)TotalDataSize / (double)_maxSize) * (double)100;
if (currentSizeInPerc >= _evictionReportSize)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(InformCacheNearEviction));
_lastReportedTime = DateTime.Now;
}
}
}
}
}
private void InformCacheNearEviction(object state)
{
try
{
string cacheserver = "NCache";
long currentSizeInPerc = (TotalDataSize / _maxSize) * 100;
if (currentSizeInPerc > 100) currentSizeInPerc = 100;
AppUtil.LogEvent(cacheserver, "Cache '" + _cacheContext + "' has exceeded " + _evictionReportSize + "% of allocated cache size", System.Diagnostics.EventLogEntryType.Warning, EventCategories.Warning, EventID.CacheSizeWarning);
NCacheLog.CriticalInfo("CacheStore", "cache has exceeded " + _evictionReportSize + "% of allocated cache size");
}
catch (Exception e)
{
}
}
/// <summary>
/// Initialize settings
/// </summary>
/// <param name="properties"></param>
public void Initialize(IDictionary properties, bool evictionEnabled)
{
_syncObj = new ReaderWriterLock();
if (properties == null) return;
if (properties.Contains("max-size"))
{
try
{
_maxSize = ToBytes(Convert.ToInt64(properties["max-size"]));
if (evictionEnabled)
{
//we give user extra cution to add/insert data into the store even
//when you have reached the max limit. But if this limit is also reached
//then we reject the request.
_extraDataSize = (long)(_maxSize * DEFAULT_EXTRA_ACCOMDATION_PERCENTAGE);
}
}
catch (Exception)
{
}
}
}
private long ToBytes(long mbytes)
{
return mbytes * 1024 * 1024;
}
#region / --- IDisposable --- /
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
_syncObj = null;
this.Cleared();
}
#endregion
/// <summary>
/// get or set the maximam size of store, in bytes
/// </summary>
public virtual long MaxSize
{
get { return _maxSize; }
set { _maxSize = value; }
}
/// <summary>
/// get or set the maximam number of objects
/// </summary>
public virtual long MaxCount
{
get { return _maxCount; }
set { _maxCount = value; }
}
/// <summary>
///Gets/Sets the cache context used for the Compact serialization framework.
/// </summary>
public string CacheContext
{
get { return _cacheContext; }
set { _cacheContext = value; }
}
/// <summary>
/// get the synchronization object for this store.
/// </summary>
public ReaderWriterLock Sync
{
get { return _syncObj; }
}
#region / --- ICacheStorage --- /
/// <summary>
/// returns the number of objects contained in the cache.
/// </summary>
public virtual long Count
{
get { return 0; }
}
/// <summary>
/// returns the size of data, in bytes, stored in cache
/// </summary>
public virtual long Size
{
get { return TotalDataSize; }
}
public virtual Array Keys
{
get
{
return null;
}
}
/// <summary>
/// Removes all entries from the store.
/// </summary>
public virtual void Clear()
{
}
/// <summary>
/// Determines whether the store contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the store.</param>
/// <returns>true if the store contains an element
/// with the specified key; otherwise, false.</returns>
public virtual bool Contains(object key)
{
return false;
}
/// <summary>
/// Get an object from the store, specified by the passed in key. Must be implemented
/// by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <returns>cache entry.</returns>
public virtual object Get(object key)
{
return null;
}
/// <summary>
/// Get the size of item stored in store
/// </summary>
/// <param name="key">The key whose items size to get</param>
/// <returns>Items size</returns>
public virtual int GetItemSize(object key)
{
return 0;
}
/// <summary>
/// Add the key value pair to the store. Must be implemented by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public virtual StoreAddResult Add(object key, object item, Boolean allowExtendedSize)
{
return StoreAddResult.Failure;
}
/// <summary>
/// Insert the key value pair to the store. Must be implemented by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public virtual StoreInsResult Insert(object key, object item, Boolean allowExtendedSize)
{
return StoreInsResult.Failure;
}
/// <summary>
/// Removes an object from the store, specified by the passed in key. Must be implemented by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <returns>cache entry.</returns>
public virtual object Remove(object key)
{
return null;
}
/// <summary>
/// Returns a .NET IEnumerator interface so that a client should be able
/// to iterate over the elements of the cache store.
/// </summary>
/// <returns>IDictionaryEnumerator enumerator.</returns>
public virtual IDictionaryEnumerator GetEnumerator()
{
return null;
}
#endregion
/// <summary>
/// Check if store has enough space to add new item
/// </summary>
/// <param name="item">item to be added</param>
/// <returns>true is store has space, else false</returns>
protected StoreStatus HasSpace(ISizable item, long keySize, Boolean allowExtendedSize)
{
if (VirtualUnlimitedSpace)
return StoreStatus.HasSpace;
long maxSize = _maxSize;
if (!allowExtendedSize)
{
maxSize = (long)(_maxSize * .95);
}
//Keysize will be included in actual cachesize
long nextSize = TotalDataSize + item.InMemorySize + keySize;
StoreStatus status = StoreStatus.HasSpace;
if (SystemMemoryTask.PercentMemoryUsed > 90)
{
if (_extraDataSize > 0)
status = StoreStatus.NearEviction;
else
status = StoreStatus.HasNotEnoughSpace;
}
if (nextSize > maxSize)
{
if (nextSize > (maxSize + _extraDataSize))
status = StoreStatus.HasNotEnoughSpace;
else
status = StoreStatus.NearEviction;
}
return status;
}
/// <summary>
/// Check if store has enough space to add new item
/// </summary>
/// <param name="oldItem">old item</param>
/// <param name="newItem">new item to be inserted</param>
/// <returns>true is store has space, else false</returns>
protected StoreStatus HasSpace(ISizable oldItem, ISizable newItem, long keySize, Boolean allowExtendedSize)
{
if (VirtualUnlimitedSpace)
return StoreStatus.HasSpace;
long maxSize = _maxSize;
if (!allowExtendedSize)
{
maxSize = (long)(_maxSize * .95);
}
long nextSize = TotalDataSize + newItem.InMemorySize - (oldItem == null ? -keySize : oldItem.InMemorySize);
StoreStatus status = StoreStatus.HasSpace;
try
{
if (SystemMemoryTask.PercentMemoryUsed > 90)
{
if (_extraDataSize > 0)
return StoreStatus.NearEviction;
return StoreStatus.HasNotEnoughSpace;
}
}
catch (Exception) { }
if (nextSize > maxSize)
{
if (nextSize > (maxSize + _extraDataSize))
return StoreStatus.HasNotEnoughSpace;
return StoreStatus.NearEviction;
}
return status;
}
/// <summary>
/// Increments the data size in cache, after item is Added
/// </summary>
/// <param name="itemSize">item added</param>
protected void Added(ISizable item,long keySize)
{
_dataSize += (item.InMemorySize + keySize);
}
/// <summary>
/// Increments the data size in cache, after item is inserted
/// </summary>
/// <param name="oldItem">old item</param>
/// <param name="newItem">new item to be inserted</param>
protected void Inserted(ISizable oldItem, ISizable newItem, long keySize)
{
_dataSize += newItem.InMemorySize - (oldItem == null ? -keySize : oldItem.InMemorySize);
}
/// <summary>
/// Decrement the data size in cache, after item is removed
/// </summary>
/// <param name="itemSize">item removed</param>
protected void Removed(ISizable item, long keySize)
{
_dataSize -= (item.InMemorySize + keySize);
}
/// <summary>
/// Reset data size when cache is cleared
/// </summary>
protected void Cleared()
{
TotalDataSize = 0;
}
/// <summary>
/// Returns the thread safe synchronized wrapper over cache store.
/// </summary>
/// <param name="storageProvider"></param>
/// <returns></returns>
public static StorageProviderBase Synchronized(StorageProviderBase cacheStorage)
{
return new StorageProviderSyncWrapper(cacheStorage);
}
public bool VirtualUnlimitedSpace
{
get
{
return _virtualUnlimitedSpace;
}
set
{
_virtualUnlimitedSpace = value;
}
}
public ISizableIndex ISizableQueryIndexManager
{
get
{
return _iSizableQueryIndexManager;
}
set
{
_iSizableQueryIndexManager = value;
}
}
public ISizableIndex ISizableExpirationIndexManager
{
get
{
return _iSizableExpirationIndexManager;
}
set
{
_iSizableExpirationIndexManager = value;
}
}
public ISizableIndex ISizableEvictionIndexManager
{
get
{
return _iSizableEvictionIndexManager;
}
set
{
_iSizableEvictionIndexManager = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
///This file contains all the typed enums that the client rest api spec exposes.
///This file is automatically generated from https://github.com/elastic/elasticsearch/tree/v5.0.0-alpha3/rest-api-spec
///Generated of commit v5.0.0-alpha3
namespace Elasticsearch.Net
{
public enum Consistency
{
[EnumMember(Value = "one")]
One,
[EnumMember(Value = "quorum")]
Quorum,
[EnumMember(Value = "all")]
All
}
public enum Bytes
{
[EnumMember(Value = "b")]
B,
[EnumMember(Value = "k")]
K,
[EnumMember(Value = "kb")]
Kb,
[EnumMember(Value = "m")]
M,
[EnumMember(Value = "mb")]
Mb,
[EnumMember(Value = "g")]
G,
[EnumMember(Value = "gb")]
Gb,
[EnumMember(Value = "t")]
T,
[EnumMember(Value = "tb")]
Tb,
[EnumMember(Value = "p")]
P,
[EnumMember(Value = "pb")]
Pb
}
public enum Size
{
[EnumMember(Value = "")]
Raw,
[EnumMember(Value = "k")]
K,
[EnumMember(Value = "m")]
M,
[EnumMember(Value = "g")]
G,
[EnumMember(Value = "t")]
T,
[EnumMember(Value = "p")]
P
}
public enum Level
{
[EnumMember(Value = "cluster")]
Cluster,
[EnumMember(Value = "indices")]
Indices,
[EnumMember(Value = "shards")]
Shards
}
public enum WaitForStatus
{
[EnumMember(Value = "green")]
Green,
[EnumMember(Value = "yellow")]
Yellow,
[EnumMember(Value = "red")]
Red
}
public enum ExpandWildcards
{
[EnumMember(Value = "open")]
Open,
[EnumMember(Value = "closed")]
Closed,
[EnumMember(Value = "none")]
None,
[EnumMember(Value = "all")]
All
}
public enum DefaultOperator
{
[EnumMember(Value = "AND")]
And,
[EnumMember(Value = "OR")]
Or
}
public enum VersionType
{
[EnumMember(Value = "internal")]
Internal,
[EnumMember(Value = "external")]
External,
[EnumMember(Value = "external_gte")]
ExternalGte,
[EnumMember(Value = "force")]
Force
}
public enum Conflicts
{
[EnumMember(Value = "abort")]
Abort,
[EnumMember(Value = "proceed")]
Proceed
}
public enum SearchType
{
[EnumMember(Value = "query_then_fetch")]
QueryThenFetch,
[EnumMember(Value = "dfs_query_then_fetch")]
DfsQueryThenFetch
}
public enum SuggestMode
{
[EnumMember(Value = "missing")]
Missing,
[EnumMember(Value = "popular")]
Popular,
[EnumMember(Value = "always")]
Always
}
public enum OpType
{
[EnumMember(Value = "index")]
Index,
[EnumMember(Value = "create")]
Create
}
public enum Format
{
[EnumMember(Value = "detailed")]
Detailed,
[EnumMember(Value = "text")]
Text
}
public enum ThreadType
{
[EnumMember(Value = "cpu")]
Cpu,
[EnumMember(Value = "wait")]
Wait,
[EnumMember(Value = "block")]
Block
}
public enum PercolateFormat
{
[EnumMember(Value = "ids")]
Ids
}
public enum GroupBy
{
[EnumMember(Value = "nodes")]
Nodes,
[EnumMember(Value = "parents")]
Parents
}
[Flags]public enum ClusterStateMetric
{
[EnumMember(Value = "blocks")]
Blocks = 1 << 0,
[EnumMember(Value = "metadata")]
Metadata = 1 << 1,
[EnumMember(Value = "nodes")]
Nodes = 1 << 2,
[EnumMember(Value = "routing_table")]
RoutingTable = 1 << 3,
[EnumMember(Value = "routing_nodes")]
RoutingNodes = 1 << 4,
[EnumMember(Value = "master_node")]
MasterNode = 1 << 5,
[EnumMember(Value = "version")]
Version = 1 << 6,
[EnumMember(Value = "_all")]
All = 1 << 7
}
[Flags]public enum Feature
{
[EnumMember(Value = "_settings")]
Settings = 1 << 0,
[EnumMember(Value = "_mappings")]
Mappings = 1 << 1,
[EnumMember(Value = "_aliases")]
Aliases = 1 << 2
}
[Flags]public enum IndicesStatsMetric
{
[EnumMember(Value = "completion")]
Completion = 1 << 0,
[EnumMember(Value = "docs")]
Docs = 1 << 1,
[EnumMember(Value = "fielddata")]
Fielddata = 1 << 2,
[EnumMember(Value = "query_cache")]
QueryCache = 1 << 3,
[EnumMember(Value = "flush")]
Flush = 1 << 4,
[EnumMember(Value = "get")]
Get = 1 << 5,
[EnumMember(Value = "indexing")]
Indexing = 1 << 6,
[EnumMember(Value = "merge")]
Merge = 1 << 7,
[EnumMember(Value = "percolate")]
Percolate = 1 << 8,
[EnumMember(Value = "request_cache")]
RequestCache = 1 << 9,
[EnumMember(Value = "refresh")]
Refresh = 1 << 10,
[EnumMember(Value = "search")]
Search = 1 << 11,
[EnumMember(Value = "segments")]
Segments = 1 << 12,
[EnumMember(Value = "store")]
Store = 1 << 13,
[EnumMember(Value = "warmer")]
Warmer = 1 << 14,
[EnumMember(Value = "suggest")]
Suggest = 1 << 15,
[EnumMember(Value = "_all")]
All = 1 << 16
}
[Flags]public enum NodesInfoMetric
{
[EnumMember(Value = "settings")]
Settings = 1 << 0,
[EnumMember(Value = "os")]
Os = 1 << 1,
[EnumMember(Value = "process")]
Process = 1 << 2,
[EnumMember(Value = "jvm")]
Jvm = 1 << 3,
[EnumMember(Value = "thread_pool")]
ThreadPool = 1 << 4,
[EnumMember(Value = "transport")]
Transport = 1 << 5,
[EnumMember(Value = "http")]
Http = 1 << 6,
[EnumMember(Value = "plugins")]
Plugins = 1 << 7,
[EnumMember(Value = "ingest")]
Ingest = 1 << 8
}
[Flags]public enum NodesStatsMetric
{
[EnumMember(Value = "breaker")]
Breaker = 1 << 0,
[EnumMember(Value = "fs")]
Fs = 1 << 1,
[EnumMember(Value = "http")]
Http = 1 << 2,
[EnumMember(Value = "indices")]
Indices = 1 << 3,
[EnumMember(Value = "jvm")]
Jvm = 1 << 4,
[EnumMember(Value = "os")]
Os = 1 << 5,
[EnumMember(Value = "process")]
Process = 1 << 6,
[EnumMember(Value = "thread_pool")]
ThreadPool = 1 << 7,
[EnumMember(Value = "transport")]
Transport = 1 << 8,
[EnumMember(Value = "discovery")]
Discovery = 1 << 9,
[EnumMember(Value = "_all")]
All = 1 << 10
}
[Flags]public enum NodesStatsIndexMetric
{
[EnumMember(Value = "completion")]
Completion = 1 << 0,
[EnumMember(Value = "docs")]
Docs = 1 << 1,
[EnumMember(Value = "fielddata")]
Fielddata = 1 << 2,
[EnumMember(Value = "query_cache")]
QueryCache = 1 << 3,
[EnumMember(Value = "flush")]
Flush = 1 << 4,
[EnumMember(Value = "get")]
Get = 1 << 5,
[EnumMember(Value = "indexing")]
Indexing = 1 << 6,
[EnumMember(Value = "merge")]
Merge = 1 << 7,
[EnumMember(Value = "percolate")]
Percolate = 1 << 8,
[EnumMember(Value = "request_cache")]
RequestCache = 1 << 9,
[EnumMember(Value = "refresh")]
Refresh = 1 << 10,
[EnumMember(Value = "search")]
Search = 1 << 11,
[EnumMember(Value = "segments")]
Segments = 1 << 12,
[EnumMember(Value = "store")]
Store = 1 << 13,
[EnumMember(Value = "warmer")]
Warmer = 1 << 14,
[EnumMember(Value = "suggest")]
Suggest = 1 << 15,
[EnumMember(Value = "_all")]
All = 1 << 16
}
public static class KnownEnums
{
public static string UnknownEnum { get; } = "_UNKNOWN_ENUM_";
public static string Resolve(Enum e)
{
if (e is Consistency)
{
switch((Consistency)e)
{
case Consistency.One: return "one";
case Consistency.Quorum: return "quorum";
case Consistency.All: return "all";
}
}
if (e is Bytes)
{
switch((Bytes)e)
{
case Bytes.B: return "b";
case Bytes.K: return "k";
case Bytes.Kb: return "kb";
case Bytes.M: return "m";
case Bytes.Mb: return "mb";
case Bytes.G: return "g";
case Bytes.Gb: return "gb";
case Bytes.T: return "t";
case Bytes.Tb: return "tb";
case Bytes.P: return "p";
case Bytes.Pb: return "pb";
}
}
if (e is Size)
{
switch((Size)e)
{
case Size.Raw: return "";
case Size.K: return "k";
case Size.M: return "m";
case Size.G: return "g";
case Size.T: return "t";
case Size.P: return "p";
}
}
if (e is Level)
{
switch((Level)e)
{
case Level.Cluster: return "cluster";
case Level.Indices: return "indices";
case Level.Shards: return "shards";
}
}
if (e is WaitForStatus)
{
switch((WaitForStatus)e)
{
case WaitForStatus.Green: return "green";
case WaitForStatus.Yellow: return "yellow";
case WaitForStatus.Red: return "red";
}
}
if (e is ExpandWildcards)
{
switch((ExpandWildcards)e)
{
case ExpandWildcards.Open: return "open";
case ExpandWildcards.Closed: return "closed";
case ExpandWildcards.None: return "none";
case ExpandWildcards.All: return "all";
}
}
if (e is DefaultOperator)
{
switch((DefaultOperator)e)
{
case DefaultOperator.And: return "AND";
case DefaultOperator.Or: return "OR";
}
}
if (e is VersionType)
{
switch((VersionType)e)
{
case VersionType.Internal: return "internal";
case VersionType.External: return "external";
case VersionType.ExternalGte: return "external_gte";
case VersionType.Force: return "force";
}
}
if (e is Conflicts)
{
switch((Conflicts)e)
{
case Conflicts.Abort: return "abort";
case Conflicts.Proceed: return "proceed";
}
}
if (e is SearchType)
{
switch((SearchType)e)
{
case SearchType.QueryThenFetch: return "query_then_fetch";
case SearchType.DfsQueryThenFetch: return "dfs_query_then_fetch";
}
}
if (e is SuggestMode)
{
switch((SuggestMode)e)
{
case SuggestMode.Missing: return "missing";
case SuggestMode.Popular: return "popular";
case SuggestMode.Always: return "always";
}
}
if (e is OpType)
{
switch((OpType)e)
{
case OpType.Index: return "index";
case OpType.Create: return "create";
}
}
if (e is Format)
{
switch((Format)e)
{
case Format.Detailed: return "detailed";
case Format.Text: return "text";
}
}
if (e is ThreadType)
{
switch((ThreadType)e)
{
case ThreadType.Cpu: return "cpu";
case ThreadType.Wait: return "wait";
case ThreadType.Block: return "block";
}
}
if (e is PercolateFormat)
{
switch((PercolateFormat)e)
{
case PercolateFormat.Ids: return "ids";
}
}
if (e is GroupBy)
{
switch((GroupBy)e)
{
case GroupBy.Nodes: return "nodes";
case GroupBy.Parents: return "parents";
}
}
if (e is ClusterStateMetric)
{
var list = new List<string>();
if (e.HasFlag(ClusterStateMetric.Blocks)) list.Add("blocks");
if (e.HasFlag(ClusterStateMetric.Metadata)) list.Add("metadata");
if (e.HasFlag(ClusterStateMetric.Nodes)) list.Add("nodes");
if (e.HasFlag(ClusterStateMetric.RoutingTable)) list.Add("routing_table");
if (e.HasFlag(ClusterStateMetric.RoutingNodes)) list.Add("routing_nodes");
if (e.HasFlag(ClusterStateMetric.MasterNode)) list.Add("master_node");
if (e.HasFlag(ClusterStateMetric.Version)) list.Add("version");
if (e.HasFlag(ClusterStateMetric.All)) return "_all";
return string.Join(",", list);
}
if (e is Feature)
{
var list = new List<string>();
if (e.HasFlag(Feature.Settings)) list.Add("_settings");
if (e.HasFlag(Feature.Mappings)) list.Add("_mappings");
if (e.HasFlag(Feature.Aliases)) list.Add("_aliases");
return string.Join(",", list);
}
if (e is IndicesStatsMetric)
{
var list = new List<string>();
if (e.HasFlag(IndicesStatsMetric.Completion)) list.Add("completion");
if (e.HasFlag(IndicesStatsMetric.Docs)) list.Add("docs");
if (e.HasFlag(IndicesStatsMetric.Fielddata)) list.Add("fielddata");
if (e.HasFlag(IndicesStatsMetric.QueryCache)) list.Add("query_cache");
if (e.HasFlag(IndicesStatsMetric.Flush)) list.Add("flush");
if (e.HasFlag(IndicesStatsMetric.Get)) list.Add("get");
if (e.HasFlag(IndicesStatsMetric.Indexing)) list.Add("indexing");
if (e.HasFlag(IndicesStatsMetric.Merge)) list.Add("merge");
if (e.HasFlag(IndicesStatsMetric.Percolate)) list.Add("percolate");
if (e.HasFlag(IndicesStatsMetric.RequestCache)) list.Add("request_cache");
if (e.HasFlag(IndicesStatsMetric.Refresh)) list.Add("refresh");
if (e.HasFlag(IndicesStatsMetric.Search)) list.Add("search");
if (e.HasFlag(IndicesStatsMetric.Segments)) list.Add("segments");
if (e.HasFlag(IndicesStatsMetric.Store)) list.Add("store");
if (e.HasFlag(IndicesStatsMetric.Warmer)) list.Add("warmer");
if (e.HasFlag(IndicesStatsMetric.Suggest)) list.Add("suggest");
if (e.HasFlag(IndicesStatsMetric.All)) return "_all";
return string.Join(",", list);
}
if (e is NodesInfoMetric)
{
var list = new List<string>();
if (e.HasFlag(NodesInfoMetric.Settings)) list.Add("settings");
if (e.HasFlag(NodesInfoMetric.Os)) list.Add("os");
if (e.HasFlag(NodesInfoMetric.Process)) list.Add("process");
if (e.HasFlag(NodesInfoMetric.Jvm)) list.Add("jvm");
if (e.HasFlag(NodesInfoMetric.ThreadPool)) list.Add("thread_pool");
if (e.HasFlag(NodesInfoMetric.Transport)) list.Add("transport");
if (e.HasFlag(NodesInfoMetric.Http)) list.Add("http");
if (e.HasFlag(NodesInfoMetric.Plugins)) list.Add("plugins");
if (e.HasFlag(NodesInfoMetric.Ingest)) list.Add("ingest");
return string.Join(",", list);
}
if (e is NodesStatsMetric)
{
var list = new List<string>();
if (e.HasFlag(NodesStatsMetric.Breaker)) list.Add("breaker");
if (e.HasFlag(NodesStatsMetric.Fs)) list.Add("fs");
if (e.HasFlag(NodesStatsMetric.Http)) list.Add("http");
if (e.HasFlag(NodesStatsMetric.Indices)) list.Add("indices");
if (e.HasFlag(NodesStatsMetric.Jvm)) list.Add("jvm");
if (e.HasFlag(NodesStatsMetric.Os)) list.Add("os");
if (e.HasFlag(NodesStatsMetric.Process)) list.Add("process");
if (e.HasFlag(NodesStatsMetric.ThreadPool)) list.Add("thread_pool");
if (e.HasFlag(NodesStatsMetric.Transport)) list.Add("transport");
if (e.HasFlag(NodesStatsMetric.Discovery)) list.Add("discovery");
if (e.HasFlag(NodesStatsMetric.All)) return "_all";
return string.Join(",", list);
}
if (e is NodesStatsIndexMetric)
{
var list = new List<string>();
if (e.HasFlag(NodesStatsIndexMetric.Completion)) list.Add("completion");
if (e.HasFlag(NodesStatsIndexMetric.Docs)) list.Add("docs");
if (e.HasFlag(NodesStatsIndexMetric.Fielddata)) list.Add("fielddata");
if (e.HasFlag(NodesStatsIndexMetric.QueryCache)) list.Add("query_cache");
if (e.HasFlag(NodesStatsIndexMetric.Flush)) list.Add("flush");
if (e.HasFlag(NodesStatsIndexMetric.Get)) list.Add("get");
if (e.HasFlag(NodesStatsIndexMetric.Indexing)) list.Add("indexing");
if (e.HasFlag(NodesStatsIndexMetric.Merge)) list.Add("merge");
if (e.HasFlag(NodesStatsIndexMetric.Percolate)) list.Add("percolate");
if (e.HasFlag(NodesStatsIndexMetric.RequestCache)) list.Add("request_cache");
if (e.HasFlag(NodesStatsIndexMetric.Refresh)) list.Add("refresh");
if (e.HasFlag(NodesStatsIndexMetric.Search)) list.Add("search");
if (e.HasFlag(NodesStatsIndexMetric.Segments)) list.Add("segments");
if (e.HasFlag(NodesStatsIndexMetric.Store)) list.Add("store");
if (e.HasFlag(NodesStatsIndexMetric.Warmer)) list.Add("warmer");
if (e.HasFlag(NodesStatsIndexMetric.Suggest)) list.Add("suggest");
if (e.HasFlag(NodesStatsIndexMetric.All)) return "_all";
return string.Join(",", list);
}
return UnknownEnum;
}
}
}
| |
// 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 ConvertToVector128Int32WithTruncationVector128Double()
{
var test = new SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationVector128Double();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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 (Sse2.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 SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationVector128Double
{
private struct TestStruct
{
public Vector128<Double> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationVector128Double testClass)
{
var result = Sse2.ConvertToVector128Int32WithTruncation(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar;
private Vector128<Double> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Double> _dataTable;
static SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationVector128Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationVector128Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Double>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ConvertToVector128Int32WithTruncation(
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ConvertToVector128Int32WithTruncation(
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ConvertToVector128Int32WithTruncation(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32WithTruncation), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32WithTruncation), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32WithTruncation), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ConvertToVector128Int32WithTruncation(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr);
var result = Sse2.ConvertToVector128Int32WithTruncation(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Int32WithTruncation(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Int32WithTruncation(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationVector128Double();
var result = Sse2.ConvertToVector128Int32WithTruncation(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ConvertToVector128Int32WithTruncation(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ConvertToVector128Int32WithTruncation(test._fld);
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(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)firstOp[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < 2) ? (int)firstOp[i] : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertToVector128Int32WithTruncation)}<Int32>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using GLTF.JsonExtensions;
using Newtonsoft.Json;
using UnityEngine;
namespace GLTF
{
public class Accessor : GLTFChildOfRootProperty
{
/// <summary>
/// The index of the bufferView.
/// If this is undefined, look in the sparse object for the index and value buffer views.
/// </summary>
public BufferViewId BufferView;
/// <summary>
/// The offset relative to the start of the bufferView in bytes.
/// This must be a multiple of the size of the component datatype.
/// <minimum>0</minimum>
/// </summary>
public int ByteOffset;
/// <summary>
/// The datatype of components in the attribute.
/// All valid values correspond to WebGL enums.
/// The corresponding typed arrays are: `Int8Array`, `Uint8Array`, `Int16Array`,
/// `Uint16Array`, `Uint32Array`, and `Float32Array`, respectively.
/// 5125 (UNSIGNED_INT) is only allowed when the accessor contains indices
/// i.e., the accessor is only referenced by `primitive.indices`.
/// </summary>
public GLTFComponentType ComponentType;
/// <summary>
/// Specifies whether integer data values should be normalized
/// (`true`) to [0, 1] (for unsigned types) or [-1, 1] (for signed types),
/// or converted directly (`false`) when they are accessed.
/// Must be `false` when accessor is used for animation data.
/// </summary>
public bool Normalized;
/// <summary>
/// The number of attributes referenced by this accessor, not to be confused
/// with the number of bytes or number of components.
/// <minimum>1</minimum>
/// </summary>
public int Count;
/// <summary>
/// Specifies if the attribute is a scalar, vector, or matrix,
/// and the number of elements in the vector or matrix.
/// </summary>
public GLTFAccessorAttributeType Type;
/// <summary>
/// Maximum value of each component in this attribute.
/// Both min and max arrays have the same length.
/// The length is determined by the value of the type property;
/// it can be 1, 2, 3, 4, 9, or 16.
///
/// When `componentType` is `5126` (FLOAT) each array value must be stored as
/// double-precision JSON number with numerical value which is equal to
/// buffer-stored single-precision value to avoid extra runtime conversions.
///
/// `normalized` property has no effect on array values: they always correspond
/// to the actual values stored in the buffer. When accessor is sparse, this
/// property must contain max values of accessor data with sparse substitution
/// applied.
/// <minItems>1</minItems>
/// <maxItems>16</maxItems>
/// </summary>
public List<double> Max;
/// <summary>
/// Minimum value of each component in this attribute.
/// Both min and max arrays have the same length. The length is determined by
/// the value of the type property; it can be 1, 2, 3, 4, 9, or 16.
///
/// When `componentType` is `5126` (FLOAT) each array value must be stored as
/// double-precision JSON number with numerical value which is equal to
/// buffer-stored single-precision value to avoid extra runtime conversions.
///
/// `normalized` property has no effect on array values: they always correspond
/// to the actual values stored in the buffer. When accessor is sparse, this
/// property must contain min values of accessor data with sparse substitution
/// applied.
/// <minItems>1</minItems>
/// <maxItems>16</maxItems>
/// </summary>
public List<double> Min;
/// <summary>
/// Sparse storage of attributes that deviate from their initialization value.
/// </summary>
public AccessorSparse Sparse;
public static Accessor Deserialize(GLTFRoot root, JsonReader reader)
{
var accessor = new Accessor();
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "bufferView":
accessor.BufferView = BufferViewId.Deserialize(root, reader);
break;
case "byteOffset":
accessor.ByteOffset = reader.ReadAsInt32().Value;
break;
case "componentType":
accessor.ComponentType = (GLTFComponentType)reader.ReadAsInt32().Value;
break;
case "normalized":
accessor.Normalized = reader.ReadAsBoolean().Value;
break;
case "count":
accessor.Count = reader.ReadAsInt32().Value;
break;
case "type":
accessor.Type = reader.ReadStringEnum<GLTFAccessorAttributeType>();
break;
case "max":
accessor.Max = reader.ReadDoubleList();
break;
case "min":
accessor.Min = reader.ReadDoubleList();
break;
case "sparse":
accessor.Sparse = AccessorSparse.Deserialize(root, reader);
break;
default:
accessor.DefaultPropertyDeserializer(root, reader);
break;
}
}
return accessor;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
if (BufferView != null)
{
writer.WritePropertyName("bufferView");
writer.WriteValue(BufferView.Id);
}
if (ByteOffset != 0)
{
writer.WritePropertyName("byteOffset");
writer.WriteValue(ByteOffset);
}
writer.WritePropertyName("componentType");
writer.WriteValue(ComponentType);
if (Normalized != false)
{
writer.WritePropertyName("normalized");
writer.WriteValue(true);
}
writer.WritePropertyName("count");
writer.WriteValue(Count);
writer.WritePropertyName("type");
writer.WriteValue(Type.ToString());
writer.WritePropertyName("max");
writer.WriteStartArray();
foreach (var item in Max)
{
writer.WriteValue(item);
}
writer.WriteEndArray();
writer.WritePropertyName("min");
writer.WriteStartArray();
foreach (var item in Min)
{
writer.WriteValue(item);
}
writer.WriteEndArray();
if (Sparse != null)
{
writer.WritePropertyName("sparse");
Sparse.Serialize(writer);
}
base.Serialize(writer);
writer.WriteEndObject();
}
public int[] AsIntArray(byte[] bufferData)
{
var arr = new int[Count];
var totalByteOffset = BufferView.Value.ByteOffset + ByteOffset;
var stride = 0;
switch (ComponentType)
{
case GLTFComponentType.Byte:
stride = BufferView.Value.ByteStride + sizeof(sbyte);
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = (sbyte)bufferData[totalByteOffset + (idx * stride)];
}
break;
case GLTFComponentType.UnsignedByte:
stride = BufferView.Value.ByteStride + sizeof(byte);
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = bufferData[totalByteOffset + (idx * stride)];
}
break;
case GLTFComponentType.Short:
stride = BufferView.Value.ByteStride + sizeof(short);
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride));
}
break;
case GLTFComponentType.UnsignedShort:
if (BufferView.Value.ByteStride == 0)
{
var intermediateArr = new ushort[Count];
System.Buffer.BlockCopy(bufferData, totalByteOffset, intermediateArr, 0, Count * sizeof(ushort));
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = (int)intermediateArr[idx];
}
}
else
{
stride = BufferView.Value.ByteStride + sizeof(ushort);
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride));
}
}
break;
case GLTFComponentType.UnsignedInt:
if (BufferView.Value.ByteStride == 0)
{
var intermediateArr = new uint[Count];
System.Buffer.BlockCopy(bufferData, totalByteOffset, intermediateArr, 0, Count * sizeof(uint));
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = (int)intermediateArr[idx];
}
}
else
{
stride = BufferView.Value.ByteStride + sizeof(uint);
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = (int)BitConverter.ToUInt32(bufferData, totalByteOffset + (idx * stride));
}
}
break;
case GLTFComponentType.Float:
if (BufferView.Value.ByteStride == 0)
{
var intermediateArr = new int[Count];
System.Buffer.BlockCopy(bufferData, totalByteOffset, intermediateArr, 0, Count * sizeof(float));
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = intermediateArr[idx];
}
}
else
{
stride = BufferView.Value.ByteStride + sizeof(float);
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = (int)BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride));
}
}
break;
default:
throw new Exception("Unsupported component type.");
}
return arr;
}
public Vector2[] AsVector2Array(byte[] bufferData)
{
var arr = new Vector2[Count];
var totalByteOffset = BufferView.Value.ByteOffset + ByteOffset;
var stride = 0;
const int numComponents = 2;
switch (ComponentType)
{
case GLTFComponentType.Byte:
stride = numComponents * sizeof(sbyte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = (sbyte)bufferData[totalByteOffset + (idx * stride)];
var y = (sbyte)bufferData[totalByteOffset + (idx * stride) + sizeof(sbyte)];
arr[idx] = new Vector2(x, -y);
}
break;
case GLTFComponentType.UnsignedByte:
stride = numComponents * sizeof(byte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = bufferData[totalByteOffset + (idx * stride)];
var y = bufferData[totalByteOffset + (idx * stride) + sizeof(byte)];
arr[idx] = new Vector2(x, -y);
}
break;
case GLTFComponentType.Short:
stride = numComponents * sizeof(short) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride));
float y = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(short));
arr[idx] = new Vector2(x, -y);
}
break;
case GLTFComponentType.UnsignedShort:
stride = numComponents * sizeof(ushort) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride));
var y = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(ushort));
arr[idx] = new Vector2(x, -y);
}
break;
case GLTFComponentType.UnsignedInt:
stride = numComponents * sizeof(uint) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToUInt32(bufferData, totalByteOffset + (idx * stride));
var y = BitConverter.ToUInt32(bufferData, totalByteOffset + (idx * stride) + sizeof(uint));
arr[idx] = new Vector2(x, -y);
}
break;
case GLTFComponentType.Float:
if (BufferView.Value.ByteStride == 0)
{
var totalComponents = Count * 2;
var intermediateArr = new float[totalComponents];
System.Buffer.BlockCopy(bufferData, totalByteOffset, intermediateArr, 0, totalComponents * sizeof(float));
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = new Vector2(
intermediateArr[idx * 2],
-intermediateArr[idx * 2 + 1]
);
}
}
else
{
stride = numComponents * sizeof(float) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride));
var y = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + sizeof(float));
arr[idx] = new Vector2(x, -y);
}
}
break;
default:
throw new Exception("Unsupported component type.");
}
return arr;
}
public Vector3[] AsVector3Array(byte[] bufferData)
{
var arr = new Vector3[Count];
var totalByteOffset = BufferView.Value.ByteOffset + ByteOffset;
int stride;
const int numComponents = 3;
switch (ComponentType)
{
case GLTFComponentType.Byte:
stride = numComponents * sizeof(sbyte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
float x = (sbyte)bufferData[totalByteOffset + (idx * stride)];
float y = (sbyte)bufferData[totalByteOffset + (idx * stride) + sizeof(sbyte)];
float z = (sbyte)bufferData[totalByteOffset + (idx * stride) + (2 * sizeof(sbyte))];
arr[idx] = new Vector3(x, y, -z);
}
break;
case GLTFComponentType.UnsignedByte:
stride = numComponents * sizeof(byte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
float x = bufferData[totalByteOffset + (idx * stride)];
float y = bufferData[totalByteOffset + (idx * stride) + sizeof(byte)];
float z = bufferData[totalByteOffset + (idx * stride) + (2 * sizeof(byte))];
arr[idx] = new Vector3(x, y, -z);
}
break;
case GLTFComponentType.Short:
stride = numComponents * sizeof(short) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
float x = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride));
float y = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(short));
float z = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(short)));
arr[idx] = new Vector3(x, y, -z);
}
break;
case GLTFComponentType.UnsignedShort:
stride = numComponents * sizeof(ushort) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
float x = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride));
float y = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(ushort));
float z = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(ushort)));
arr[idx] = new Vector3(x, y, -z);
}
break;
case GLTFComponentType.UnsignedInt:
stride = numComponents * sizeof(uint) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
float x = BitConverter.ToUInt32(bufferData, totalByteOffset + (idx * stride));
float y = BitConverter.ToUInt32(bufferData, totalByteOffset + (idx * stride) + sizeof(uint));
float z = BitConverter.ToUInt32(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(uint)));
arr[idx] = new Vector3(x, y, -z);
}
break;
case GLTFComponentType.Float:
if (BufferView.Value.ByteStride == 0)
{
var totalComponents = Count * 3;
var intermediateArr = new float[totalComponents];
System.Buffer.BlockCopy(bufferData, totalByteOffset, intermediateArr, 0, totalComponents * sizeof(float));
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = new Vector3(
intermediateArr[idx * 3],
intermediateArr[idx * 3 + 1],
-intermediateArr[idx * 3 + 2]
);
}
}
else
{
stride = numComponents * sizeof(float) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride));
var y = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + sizeof(float));
var z = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(float)));
arr[idx] = new Vector3(x, y, -z);
}
}
break;
default:
throw new Exception("Unsupported component type.");
}
return arr;
}
public Vector4[] AsVector4Array(byte[] bufferData)
{
var arr = new Vector4[Count];
var totalByteOffset = BufferView.Value.ByteOffset + ByteOffset;
int stride;
const int numComponents = 4;
switch (ComponentType)
{
case GLTFComponentType.Byte:
stride = numComponents * sizeof(sbyte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = (sbyte)bufferData[totalByteOffset + (idx * stride)];
var y = (sbyte)bufferData[totalByteOffset + (idx * stride) + sizeof(sbyte)];
var z = (sbyte)bufferData[totalByteOffset + (idx * stride) + (2 * sizeof(sbyte))];
var w = (sbyte)bufferData[totalByteOffset + (idx * stride) + (3 * sizeof(sbyte))];
arr[idx] = new Vector4(x, y, z, -w);
}
break;
case GLTFComponentType.UnsignedByte:
stride = numComponents * sizeof(byte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = bufferData[totalByteOffset + (idx * stride)];
var y = bufferData[totalByteOffset + (idx * stride) + sizeof(byte)];
var z = bufferData[totalByteOffset + (idx * stride) + (2 * sizeof(byte))];
var w = bufferData[totalByteOffset + (idx * stride) + (3 * sizeof(byte))];
arr[idx] = new Vector4(x, y, z, -w);
}
break;
case GLTFComponentType.Short:
stride = numComponents * sizeof(short) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride));
var y = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(short));
var z = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(short)));
var w = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + (3 * sizeof(short)));
arr[idx] = new Vector4(x, y, z, -w);
}
break;
case GLTFComponentType.UnsignedShort:
stride = numComponents * sizeof(ushort) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride));
var y = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(ushort));
var z = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(ushort)));
var w = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + (3 * sizeof(ushort)));
arr[idx] = new Vector4(x, y, z, -w);
}
break;
case GLTFComponentType.Float:
if (BufferView.Value.ByteStride == 0)
{
var totalComponents = Count * 4;
var intermediateArr = new float[totalComponents];
System.Buffer.BlockCopy(bufferData, totalByteOffset, intermediateArr, 0, totalComponents * sizeof(float));
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = new Vector4(
intermediateArr[idx * 4],
intermediateArr[idx * 4 + 1],
intermediateArr[idx * 4 + 2],
-intermediateArr[idx * 4 + 3]
);
}
}
else
{
stride = numComponents * sizeof(float) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var x = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride));
var y = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + sizeof(float));
var z = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(float)));
var w = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + (3 * sizeof(float)));
arr[idx] = new Vector4(x, y, z, -w);
}
}
break;
default:
throw new Exception("Unsupported component type.");
}
return arr;
}
public Color[] AsColorArray(byte[] bufferData)
{
var arr = new Color[Count];
var totalByteOffset = BufferView.Value.ByteOffset + ByteOffset;
int stride;
const int numComponents = 4;
switch (ComponentType)
{
case GLTFComponentType.Byte:
stride = numComponents * sizeof(sbyte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var r = (sbyte)bufferData[totalByteOffset + (idx * stride)];
var g = (sbyte)bufferData[totalByteOffset + (idx * stride) + sizeof(sbyte)];
var b = (sbyte)bufferData[totalByteOffset + (idx * stride) + (2 * sizeof(sbyte))];
var a = (sbyte)bufferData[totalByteOffset + (idx * stride) + (3 * sizeof(sbyte))];
arr[idx] = new Color(r, g, b, a);
}
break;
case GLTFComponentType.UnsignedByte:
stride = numComponents * sizeof(byte) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var r = bufferData[totalByteOffset + (idx * stride)];
var g = bufferData[totalByteOffset + (idx * stride) + sizeof(byte)];
var b = bufferData[totalByteOffset + (idx * stride) + (2 * sizeof(byte))];
var a = bufferData[totalByteOffset + (idx * stride) + (3 * sizeof(byte))];
arr[idx] = new Color(r, g, b, a);
}
break;
case GLTFComponentType.Short:
stride = numComponents * sizeof(short) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var r = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride));
var g = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(short));
var b = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(short)));
var a = BitConverter.ToInt16(bufferData, totalByteOffset + (idx * stride) + (3 * sizeof(short)));
arr[idx] = new Color(r, g, b, a);
}
break;
case GLTFComponentType.UnsignedShort:
stride = numComponents * sizeof(ushort) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var r = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride));
var g = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + sizeof(ushort));
var b = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(ushort)));
var a = BitConverter.ToUInt16(bufferData, totalByteOffset + (idx * stride) + (3 * sizeof(ushort)));
arr[idx] = new Color(r, g, b, a);
}
break;
case GLTFComponentType.Float:
if (BufferView.Value.ByteStride == 0)
{
var totalComponents = Count * 4;
var intermediateArr = new float[totalComponents];
System.Buffer.BlockCopy(bufferData, totalByteOffset, intermediateArr, 0, totalComponents * sizeof(float));
for (var idx = 0; idx < Count; idx++)
{
arr[idx] = new Color(
intermediateArr[idx * 4],
intermediateArr[idx * 4 + 1],
intermediateArr[idx * 4 + 2],
intermediateArr[idx * 4 + 3]
);
}
}
else
{
stride = numComponents * sizeof(float) + BufferView.Value.ByteStride;
for (var idx = 0; idx < Count; idx++)
{
var r = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride));
var g = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + sizeof(float));
var b = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + (2 * sizeof(float)));
var a = BitConverter.ToSingle(bufferData, totalByteOffset + (idx * stride) + (3 * sizeof(float)));
arr[idx] = new Color(r, g, b, a);
}
}
break;
default:
throw new Exception("Unsupported component type.");
}
return arr;
}
}
public enum GLTFComponentType
{
Byte = 5120,
UnsignedByte = 5121,
Short = 5122,
UnsignedShort = 5123,
UnsignedInt = 5125,
Float = 5126
}
public enum GLTFAccessorAttributeType
{
SCALAR,
VEC2,
VEC3,
VEC4,
MAT2,
MAT3,
MAT4
}
}
| |
using System;
using System.Management.Automation;
using System.Management;
using System.Linq;
using System.Reflection;
using System.Management.Pash.Implementation;
using System.Collections.ObjectModel;
using System.Collections;
using System.Security.Cryptography;
using Extensions.Dictionary;
namespace Pash.Implementation
{
internal class ModuleLoader
{
private readonly string[] _manifestExtensions = new string[] { ".psd1" };
private readonly string[] _scriptExtensions = new string[] { ".psm1", ".ps1" };
private readonly string[] _binaryExtensions = new string[] { ".dll", ".exe" };
private ExecutionContext _executionContext;
internal ModuleLoader(ExecutionContext context)
{
_executionContext = context;
}
internal PSModuleInfo LoadModuleByName(string name, bool loadToGlobalScope, bool importMembers = true)
{
// TODO: where do we handle FileNotFoundExceptions etc?
var path = new Path(name).NormalizeSlashes();
if (name.Contains(path.CorrectSlash) || path.HasExtension())
{
// check if it's already loaded
var moduleInfo = _executionContext.SessionState.LoadedModules.Get(path);
if (moduleInfo != null)
{
return moduleInfo;
}
// load it otherwise
moduleInfo = LoadModuleByPath(path);
// modules are loaded either to global or module scope, never to local scope
var targetScope = loadToGlobalScope ? ModuleIntrinsics.ModuleImportScopes.Global
: ModuleIntrinsics.ModuleImportScopes.Module;
_executionContext.SessionState.LoadedModules.Add(moduleInfo, targetScope);
if (importMembers)
{
_executionContext.SessionState.LoadedModules.ImportMembers(moduleInfo, targetScope);
}
return moduleInfo;
}
// otherwise we'd need to look in our module paths for a module
throw new NotImplementedException("Currently you can only a specific module file, not installed modules");
}
private PSModuleInfo LoadModuleByPath(Path path)
{
// ALWAYS derive from global scope: the Scope parameter only defines where stuff is imported to
var sessionState = new SessionState(_executionContext.SessionStateGlobal.RootSessionState);
sessionState.IsScriptScope = true;
sessionState.PSVariable.Set("PSScriptRoot", path.GetDirectory());
var moduleInfo = new PSModuleInfo(path, path.GetFileNameWithoutExtension(), sessionState);
sessionState.SetModule(moduleInfo);
LoadFileIntoModule(moduleInfo, path);
return moduleInfo;
}
private void LoadFileIntoModule(PSModuleInfo moduleInfo, Path path)
{
// prevents accidental loops while loading a module
moduleInfo.NestingDepth++;
if (moduleInfo.NestingDepth > 10)
{
var msg = "The module is too deeply nested. A module can be only nested 10 times. Make sure to check" +
" the loading order of your module";
throw new PSInvalidOperationException(msg, "Modules_ModuleTooDeeplyNested",
ErrorCategory.InvalidOperation);
}
moduleInfo.Path = path; // update path for nested modules
var stringComparer = StringComparer.InvariantCultureIgnoreCase;
var ext = path.GetExtension();
if (_scriptExtensions.Contains(ext, stringComparer))
{
moduleInfo.ModuleType = ModuleType.Script;
LoadScriptModule(moduleInfo, path); // actually load the script
}
else if (_binaryExtensions.Contains(ext, stringComparer))
{
moduleInfo.ModuleType = ModuleType.Binary;
LoadBinaryModule(moduleInfo, path);
}
else if (_manifestExtensions.Contains(ext, stringComparer))
{
moduleInfo.ModuleType = ModuleType.Manifest;
LoadManifestModule(moduleInfo, path);
}
else
{
var msg = "The extension '" + ext + "' is currently not supported";
throw new PSInvalidOperationException(msg, "Modules_InvalidFileExtension",
ErrorCategory.InvalidOperation, null, false);
}
moduleInfo.ValidateExportedMembers();
}
private void LoadBinaryModule(PSModuleInfo moduleInfo, Path path)
{
Assembly assembly = Assembly.LoadFrom(path);
// load into the local session state of the module
moduleInfo.SessionState.Cmdlet.LoadCmdletsFromAssembly(assembly, moduleInfo);
// load providers. they aren't scoped, so the SessionState object used doesn't matter
_executionContext.SessionState.Provider.Load(assembly, _executionContext, moduleInfo);
moduleInfo.ValidateExportedMembers(); // make sure cmdlets get exported
}
private void LoadScriptModule(PSModuleInfo moduleInfo, Path path)
{
// execute the script in the module scope
// TODO: simply discard the module output?
ExecuteScriptInSessionState(path.ToString(), moduleInfo.SessionState);
}
private void LoadManifestModule(PSModuleInfo moduleInfo, Path path)
{
// Load the manifest (hashtable). We use a isolated SessionState to not affect the existing one
var isolatedSessionState = new SessionState(_executionContext.SessionStateGlobal);
var res = ExecuteScriptInSessionState(path.ToString(), isolatedSessionState);
if (res.Count != 1 || !(res[0].BaseObject is Hashtable))
{
var msg = "The module manifest is invalid as it doesn't simply define a hashtable. ";
throw new PSArgumentException(msg, "Modules_InvalidManifest", ErrorCategory.InvalidOperation);
}
var manifest = (Hashtable)res[0].BaseObject;
// Load the metadata into the PSModuleInfo (simply overwrite if existing due to nesting)
try
{
moduleInfo.SetMetadata(manifest);
}
catch (PSInvalidCastException e)
{
var msg = "The module manifest contains invalid data." + Environment.NewLine + e.Message;
throw new PSInvalidOperationException(msg, "Modules_InvalidManifestData", ErrorCategory.InvalidData, e,
false);
}
// TODO: check and load required assemblies and modules
// Load RootModule / ModuleToProcess
LoadManifestRootModule(moduleInfo, manifest);
// restrict the module exports
RestrictModuleExportsByManifest(moduleInfo, manifest);
}
private void LoadManifestRootModule(PSModuleInfo moduleInfo, Hashtable manifest)
{
var rootModule = manifest["RootModule"];
var moduleToProcess = manifest["ModuleToProcess"];
if (rootModule != null && moduleToProcess != null)
{
var msg = "The module manifest cannot contain both a definition of ModuleToProcess and RootModule.";
// lol, this is the actual error id from PS:
var id = "Modules_ModuleManifestCannotContainBothModuleToProcessAndRootModule";
throw new PSInvalidOperationException(msg, id, ErrorCategory.InvalidOperation, null, false);
}
if (rootModule == null && moduleToProcess == null)
{
return;
}
rootModule = rootModule == null ? moduleToProcess : rootModule; // decide which one to use
string rootModuleName;
if (!LanguagePrimitives.TryConvertTo<string>(rootModule, out rootModuleName))
{
var msg = "The RootModule / ModuleToProcess value must be a string.";
throw new PSInvalidOperationException(msg, "Modules_InvalidManifestRootModule",
ErrorCategory.InvalidData, null, false);
}
try
{
LoadFileIntoModule(moduleInfo, rootModuleName);
}
catch (PSInvalidOperationException e)
{
var errId = "Modules_FailedToLoadNestingModule";
if (e.ErrorRecord.ErrorId.Equals(errId))
{
throw; // this avoids that nested modules result in nested exceptions
}
var msg = "Failed to load the nesting module '" + rootModuleName + "'." +
Environment.NewLine + e.Message;
var terminating = e is PSInvalidOperationException ?
((PSInvalidOperationException)e).Terminating : false;
throw new PSInvalidOperationException(msg, errId, ErrorCategory.InvalidOperation, e, terminating);
}
}
void RestrictModuleExportsByManifest(PSModuleInfo moduleInfo, Hashtable manifest)
{
string[] funs, vars, aliases, cmdlets;
// validate first
try
{
funs = LanguagePrimitives.ConvertTo<string[]>(manifest["FunctionsToExport"]);
vars = LanguagePrimitives.ConvertTo<string[]>(manifest["VariablesToExport"]);
cmdlets = LanguagePrimitives.ConvertTo<string[]>(manifest["CmdletsToExport"]);
aliases = LanguagePrimitives.ConvertTo<string[]>(manifest["AliasesToExport"]);
}
catch (PSInvalidCastException e)
{
var msg = "The module manifest contains invalid definitions for FunctionsToExport, VariablesToExport, "
+ "CmdletsToExport, or AliasesToExport. Make sure they are either strings or string arrays";
throw new PSInvalidOperationException(msg, "Modules_ManifestMembersToExportAreInvalid",
ErrorCategory.InvalidData, e);
}
// only one manifest can restrict the exported members, so check if we did it already
if (moduleInfo.ExportsAreRestrictedByManifest)
{
return;
}
if (funs != null)
{
moduleInfo.ExportedFunctions.ReplaceContents(
WildcardPattern.FilterDictionary(funs, moduleInfo.ExportedFunctions));
}
if (vars != null)
{
moduleInfo.ExportedVariables.ReplaceContents(
WildcardPattern.FilterDictionary(vars, moduleInfo.ExportedVariables));
}
if (aliases != null)
{
moduleInfo.ExportedAliases.ReplaceContents(
WildcardPattern.FilterDictionary(aliases, moduleInfo.ExportedAliases));
}
if (cmdlets != null)
{
moduleInfo.ExportedCmdlets.ReplaceContents(
WildcardPattern.FilterDictionary(cmdlets, moduleInfo.ExportedCmdlets));
}
moduleInfo.ExportsAreRestrictedByManifest = true;
}
private Collection<PSObject> ExecuteScriptInSessionState(string path, SessionState sessionState)
{
var scriptBlock = new ExternalScriptInfo(path, ScopeUsages.CurrentScope).ScriptBlock;
var originalContext = _executionContext;
var scopedContext = _executionContext.Clone(sessionState, ScopeUsages.CurrentScope);
try
{
// actually change the scope by changing the execution context
// there should definitely be a nicer way for this #ExecutionContextChange
_executionContext = scopedContext;
_executionContext.CurrentRunspace.ExecutionContext = scopedContext;
return scriptBlock.Invoke(); // TODO: pass parameters if set
}
catch (ExitException e)
{
var exitCode = LanguagePrimitives.ConvertTo<int>(e.Argument);
_executionContext.SetLastExitCodeVariable(exitCode);
_executionContext.SetSuccessVariable(exitCode == 0);
return new Collection<PSObject>() { PSObject.AsPSObject(e.Argument) };
}
finally
{
// restore original context / scope
_executionContext.CurrentRunspace.ExecutionContext = originalContext;
_executionContext = originalContext;
}
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if !BEHAVIAC_RELEASE
using System;
using System.Runtime.InteropServices;
namespace behaviac
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct InitialSettingsPacket
{
public void Init()
{
messageSize = 0;
command = (byte)CommandId.CMDID_INITIAL_SETTINGS;
platform = (byte)Platform.WINDOWS;
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
this.processId = process.Id;
}
public int PrepareToSend()
{
messageSize = (byte)(Marshal.SizeOf(typeof(InitialSettingsPacket)) - 1);
return messageSize + 1;
}
public byte[] GetData()
{
int len = this.PrepareToSend();
byte[] data = new byte[len];
data[0] = messageSize;
data[1] = command;
data[2] = platform;
byte[] iarray = BitConverter.GetBytes(this.processId);
Array.Copy(iarray, 0, data, 3, sizeof(int));
return data;
}
public byte messageSize;
public byte command;
public byte platform;
public int processId;
};
internal class ConnectorImpl : ConnectorInterface
{
public ConnectorImpl()
{
m_workspaceSent = false;
//don't handle message automatically
m_bHandleMessage = false;
}
//~ConnectorImpl()
//{
//}
private void SendInitialSettings()
{
InitialSettingsPacket initialPacket = new InitialSettingsPacket();
initialPacket.Init();
int bytesWritten = 0;
if (!SocketBase.Write(m_writeSocket, initialPacket.GetData(), ref bytesWritten))
{
Log("behaviac: Couldn't send initial settings.\n");
}
gs_packetsStats.init++;
}
protected override void OnConnection()
{
Log("behaviac: sending initial settings.\n");
this.SendInitialSettings();
SocketUtils.SendWorkspaceSettings();
this.SendInitialProperties();
{
Log("behaviac: sending packets before connecting.\n");
this.SendExistingPackets();
}
SocketUtils.SendText("[connected]precached message done\n");
//when '[connected]' is handled in the designer, it will send back all the breakpoints if any and '[breakcpp]' and '[start]'
//here we block until all those messages have been received, otherwise, if we don't block here to wait for all those messages
//the breakpoints checking might be wrong.
bool bLoop = true;
while (bLoop && m_isDisconnected.Get() == 0 &&
this.m_writeSocket != null && this.m_writeSocket.Connected)
{
//sending packets if any
if (m_packetsCount > 0)
{
SendAllPackets();
}
string kStartMsg = "[start]";
bool bFound = this.ReceivePackets(kStartMsg);
if (bFound)
{
bLoop = false;
}
else
{
System.Threading.Thread.Sleep(1);
}
}
//this.m_bHandleMessage = false;
}
private void SendInitialProperties()
{
Workspace.Instance.LogCurrentStates();
}
public bool IsWorkspaceSent()
{
return m_workspaceSent;
}
public void SetWorkspaceSent(bool bSent)
{
m_workspaceSent = bSent;
}
private bool m_workspaceSent;
protected override void Clear()
{
base.Clear();
m_workspaceSent = false;
}
};
}
#endif
namespace behaviac
{
public static class SocketUtils
{
#if !BEHAVIAC_RELEASE
private static ConnectorImpl s_tracer = new ConnectorImpl();
#endif
internal static bool SetupConnection(bool bBlocking, ushort port)
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
if (!s_tracer.IsInited())
{
const int kMaxThreads = 16;
if (!s_tracer.Init(kMaxThreads, port, bBlocking))
{
return false;
}
}
behaviac.Debug.Log("behaviac: SetupConnection successful\n");
return true;
}
#endif
return false;
}
internal static void ShutdownConnection()
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
s_tracer.Close();
behaviac.Debug.Log("behaviac: ShutdownConnection\n");
}
#endif
}
public static void SendText(string text)
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
s_tracer.SendText(text, (byte)CommandId.CMDID_TEXT);
}
#endif
}
public static bool ReadText(ref string text)
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
return s_tracer.ReadText(ref text);
}
#endif
return false;
}
public static bool IsConnected()
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
return s_tracer.IsConnected();
}
#endif
return false;
}
public static void Flush()
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
while (s_tracer.GetPacketsCount() > 0)
{
System.Threading.Thread.Sleep(1);
}
}
#endif
}
public static void SendWorkspaceSettings()
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
if (!s_tracer.IsWorkspaceSent() && s_tracer.IsConnected())
{
Workspace.Instance.LogWorkspaceInfo();
s_tracer.SetWorkspaceSent(true);
}
}
#endif
}
public static int GetMemoryOverhead()
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
return s_tracer.GetMemoryOverhead();
}
#endif
return 0;
}
public static int GetNumTrackedThreads()
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
return s_tracer.GetNumTrackedThreads();
}
#endif
return 0;
}
public static void UpdatePacketsStats()
{
#if !BEHAVIAC_RELEASE
if (Config.IsSocketing)
{
//uint overhead = (behaviac.GetMemoryOverhead());
//BEHAVIAC_SETTRACEDVAR("Stats.Vars", gs_packetsStats.vars);
}
#endif
}
}
} // behaviac
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using System.Reflection;
using System.Globalization;
using System.Runtime.Versioning;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System
{
// Holds classes (Empty, Null, Missing) for which we guarantee that there is only ever one instance of.
#if CORECLR
internal
#else
public // On CoreRT, this must be public because of the Reflection.Core/CoreLib divide and the need to whitelist past the ReflectionBlock.
#endif
class UnitySerializationHolder : ISerializable, IObjectReference
{
#region Internal Constants
internal const int EmptyUnity = 0x0001;
internal const int NullUnity = 0x0002;
internal const int MissingUnity = 0x0003;
internal const int RuntimeTypeUnity = 0x0004;
public const int ModuleUnity = 0x0005;
public const int AssemblyUnity = 0x0006;
internal const int GenericParameterTypeUnity = 0x0007;
internal const int PartialInstantiationTypeUnity = 0x0008;
internal const int Pointer = 0x0001;
internal const int Array = 0x0002;
internal const int SzArray = 0x0003;
internal const int ByRef = 0x0004;
#endregion
#region Internal Static Members
internal static void GetUnitySerializationInfo(SerializationInfo info, Missing missing)
{
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", MissingUnity);
}
internal static Type AddElementTypes(SerializationInfo info, Type type)
{
List<int> elementTypes = new List<int>();
while (type.HasElementType)
{
if (type.IsSZArray)
{
elementTypes.Add(SzArray);
}
else if (type.IsArray)
{
elementTypes.Add(type.GetArrayRank());
elementTypes.Add(Array);
}
else if (type.IsPointer)
{
elementTypes.Add(Pointer);
}
else if (type.IsByRef)
{
elementTypes.Add(ByRef);
}
type = type.GetElementType();
}
info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[]));
return type;
}
internal Type MakeElementTypes(Type type)
{
for (int i = _elementTypes.Length - 1; i >= 0; i--)
{
if (_elementTypes[i] == SzArray)
{
type = type.MakeArrayType();
}
else if (_elementTypes[i] == Array)
{
type = type.MakeArrayType(_elementTypes[--i]);
}
else if ((_elementTypes[i] == Pointer))
{
type = type.MakePointerType();
}
else if ((_elementTypes[i] == ByRef))
{
type = type.MakeByRefType();
}
}
return type;
}
public static void GetUnitySerializationInfo(SerializationInfo info, Type type)
{
Type rootElementType = type;
while (rootElementType.HasElementType)
{
rootElementType = rootElementType.GetElementType();
}
if (rootElementType.IsGenericParameter)
{
type = AddElementTypes(info, type);
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", GenericParameterTypeUnity);
info.AddValue("GenericParameterPosition", type.GenericParameterPosition);
info.AddValue("DeclaringMethod", type.DeclaringMethod, typeof(MethodBase));
info.AddValue("DeclaringType", type.DeclaringType, typeof(Type));
return;
}
int unityType = RuntimeTypeUnity;
if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
{
// Partial instantiation
unityType = PartialInstantiationTypeUnity;
type = AddElementTypes(info, type);
info.AddValue("GenericArguments", type.GetGenericArguments(), typeof(Type[]));
type = type.GetGenericTypeDefinition();
}
GetUnitySerializationInfo(info, unityType, type.FullName, type.Assembly);
}
public static void GetUnitySerializationInfo(
SerializationInfo info, int unityType, string data, Assembly assembly)
{
// A helper method that returns the SerializationInfo that a class utilizing
// UnitySerializationHelper should return from a call to GetObjectData. It contains
// the unityType (defined above) and any optional data (used only for the reflection
// types.)
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("Data", data, typeof(string));
info.AddValue("UnityType", unityType);
string assemName;
if (assembly == null)
{
assemName = string.Empty;
}
else
{
assemName = assembly.FullName;
}
info.AddValue("AssemblyName", assemName);
}
#endregion
#region Private Data Members
private readonly Type[] _instantiation;
private readonly int[] _elementTypes;
private readonly int _genericParameterPosition;
private readonly Type _declaringType;
private readonly MethodBase _declaringMethod;
private readonly string _data;
private readonly string _assemblyName;
private int _unityType;
#endregion
#region Constructor
public UnitySerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
_unityType = info.GetInt32("UnityType");
if (_unityType == MissingUnity)
return;
if (_unityType == GenericParameterTypeUnity)
{
_declaringMethod = info.GetValue("DeclaringMethod", typeof(MethodBase)) as MethodBase;
_declaringType = info.GetValue("DeclaringType", typeof(Type)) as Type;
_genericParameterPosition = info.GetInt32("GenericParameterPosition");
_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
return;
}
if (_unityType == PartialInstantiationTypeUnity)
{
_instantiation = info.GetValue("GenericArguments", typeof(Type[])) as Type[];
_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
}
_data = info.GetString("Data");
_assemblyName = info.GetString("AssemblyName");
}
#endregion
#region Private Methods
private void ThrowInsufficientInformation(string field)
{
throw new SerializationException(
SR.Format(SR.Serialization_InsufficientDeserializationState, field));
}
#endregion
#region ISerializable
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(SR.NotSupported_UnitySerHolder);
}
#endregion
#region IObjectReference
public virtual object GetRealObject(StreamingContext context)
{
// GetRealObject uses the data we have in _data and _unityType to do a lookup on the correct
// object to return. We have specific code here to handle the different types which we support.
// The reflection types (Assembly, Module, and Type) have to be looked up through their static
// accessors by name.
Assembly assembly;
switch (_unityType)
{
case EmptyUnity:
{
return Empty.Value;
}
case NullUnity:
{
return DBNull.Value;
}
case MissingUnity:
{
return Missing.Value;
}
case PartialInstantiationTypeUnity:
{
_unityType = RuntimeTypeUnity;
Type definition = GetRealObject(context) as Type;
_unityType = PartialInstantiationTypeUnity;
if (_instantiation[0] == null)
return null;
return MakeElementTypes(definition.MakeGenericType(_instantiation));
}
case GenericParameterTypeUnity:
{
if (_declaringMethod == null && _declaringType == null)
ThrowInsufficientInformation("DeclaringMember");
if (_declaringMethod != null)
return _declaringMethod.GetGenericArguments()[_genericParameterPosition];
return MakeElementTypes(_declaringType.GetGenericArguments()[_genericParameterPosition]);
}
case RuntimeTypeUnity:
{
if (_data == null || _data.Length == 0)
ThrowInsufficientInformation("Data");
if (_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
if (_assemblyName.Length == 0)
return Type.GetType(_data, true, false);
assembly = Assembly.Load(_assemblyName);
Type t = assembly.GetType(_data, true, false);
return t;
}
case ModuleUnity:
{
if (_data == null || _data.Length == 0)
ThrowInsufficientInformation("Data");
if (_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(_assemblyName);
Module namedModule = assembly.GetModule(_data);
if (namedModule == null)
throw new SerializationException(
SR.Format(SR.Serialization_UnableToFindModule, _data, _assemblyName));
return namedModule;
}
case AssemblyUnity:
{
if (_data == null || _data.Length == 0)
ThrowInsufficientInformation("Data");
if (_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(_assemblyName);
return assembly;
}
default:
throw new ArgumentException(SR.Argument_InvalidUnity);
}
}
#endregion
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using SearchOption = System.IO.SearchOption;
namespace Alphaleonis.Win32.Filesystem
{
partial class Directory
{
#region .NET
/// <summary>Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path)
{
return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.Folders, PathFormat.RelativePath);
}
/// <summary>Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern)
{
return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, DirectoryEnumerationOptions.Folders, PathFormat.RelativePath);
}
/// <summary>Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="searchOption">
/// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/>
/// should include only the current directory or should include all subdirectories.
/// </param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption)
{
var options = DirectoryEnumerationOptions.Folders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0);
return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, PathFormat.RelativePath);
}
#endregion // .NET
/// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.Folders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, DirectoryEnumerationOptions.Folders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="searchOption">
/// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/>
/// should include only the current directory or should include all subdirectories.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat)
{
var options = DirectoryEnumerationOptions.Folders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0);
return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationOptions options)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files; // Remove enumeration of files.
options |= DirectoryEnumerationOptions.Folders; // Add enumeration of directories.
return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files;
options |= DirectoryEnumerationOptions.Folders;
return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, options, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files;
options |= DirectoryEnumerationOptions.Folders;
return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files;
options |= DirectoryEnumerationOptions.Folders;
return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, pathFormat);
}
#region Transactional
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path)
{
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.Folders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern)
{
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, DirectoryEnumerationOptions.Folders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="searchOption">
/// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/>
/// should include only the current directory or should include all subdirectories.
/// </param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption)
{
var options = DirectoryEnumerationOptions.Folders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0);
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.Folders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, DirectoryEnumerationOptions.Folders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="searchOption">
/// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/>
/// should include only the current directory or should include all subdirectories.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat)
{
var options = DirectoryEnumerationOptions.Folders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0);
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files;
options |= DirectoryEnumerationOptions.Folders;
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files;
options |= DirectoryEnumerationOptions.Folders;
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, options, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files;
options |= DirectoryEnumerationOptions.Folders;
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of directory instances that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary>
/// <returns>An enumerable collection of the full names (including paths) for the directories in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static IEnumerable<string> EnumerateDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
// Adhere to the method name.
options &= ~DirectoryEnumerationOptions.Files;
options |= DirectoryEnumerationOptions.Folders;
return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, pathFormat);
}
#endregion // Transactional
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Test
{
public class SkipSkipWhileTests
{
//
// Skip
//
public static IEnumerable<object[]> SkipUnorderedData(object[] counts)
{
Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct();
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), skip)) yield return results;
}
public static IEnumerable<object[]> SkipData(object[] counts)
{
Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct();
foreach (object[] results in Sources.Ranges(counts.Cast<int>(), skip)) yield return results;
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
foreach (int i in query.Skip(skip))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip_Unordered(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
foreach (int i in query.Skip(skip))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
Assert.All(query.Skip(skip).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip_Unordered_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
Assert.All(query.Skip(skip).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip_NotPipelined(labeled, count, skip);
}
[Fact]
public static void Skip_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Skip(0));
}
//
// SkipWhile
//
public static IEnumerable<object[]> SkipWhileData(object[] counts)
{
foreach (object[] results in Sources.Ranges(counts.Cast<int>()))
{
yield return new[] { results[0], results[1], new[] { 0 } };
yield return new[] { results[0], results[1], Enumerable.Range((int)results[1] / 2, ((int)results[1] - 1) / 2 + 1) };
yield return new[] { results[0], results[1], new[] { (int)results[1] - 1 } };
}
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
foreach (int i in query.SkipWhile(x => x < skip))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Unordered(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
foreach (int i in query.SkipWhile(x => x < skip))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
Assert.All(query.SkipWhile(x => x < skip).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Unordered_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
Assert.All(query.SkipWhile(x => x < skip).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
foreach (int i in query.SkipWhile((x, index) => index < skip))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed_Unordered(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
foreach (int i in query.SkipWhile((x, index) => index < skip))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
Assert.All(query.SkipWhile((x, index) => index < skip), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed_Unordered_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
Assert.All(query.SkipWhile((x, index) => index < skip), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_AllFalse(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.SkipWhile(x => false), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_AllFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_AllFalse(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_AllTrue(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Empty(query.SkipWhile(x => seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_AllTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_AllTrue(labeled, count, skip);
}
[Theory]
[MemberData("SkipWhileData", (object)(new int[] { 2, 16 }))]
public static void SkipWhile_SomeTrue(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = skip.Min() == 0 ? 1 : 0;
Assert.All(query.SkipWhile(x => skip.Contains(x)), x => Assert.Equal(seen++, x));
Assert.Equal(skip.Min() >= count ? 0 : count, seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipWhileData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_SomeTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
SkipWhile_SomeTrue(labeled, count, skip);
}
[Theory]
[MemberData("SkipWhileData", (object)(new int[] { 2, 16 }))]
public static void SkipWhile_SomeFalse(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = skip.Min();
Assert.All(query.SkipWhile(x => !skip.Contains(x)), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipWhileData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_SomeFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
SkipWhile_SomeFalse(labeled, count, skip);
}
[Fact]
public static void SkipWhile_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SkipWhile(x => true));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, bool>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, int, bool>)null));
}
}
}
| |
/*
* 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.Linq;
using Newtonsoft.Json;
using NodaTime;
using NUnit.Framework;
using Python.Runtime;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.CSharp;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Data;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Indicators;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.HistoricalData;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Packets;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Common.Util
{
[TestFixture]
public class ExtensionsTests
{
[TestCase("20220101", false, true, Resolution.Daily)]
[TestCase("20220101", false, false, Resolution.Daily)]
[TestCase("20220103 09:31", true, false, Resolution.Minute)]
[TestCase("20220103 07:31", false, false, Resolution.Minute)]
[TestCase("20220103 07:31", false, false, Resolution.Daily)]
[TestCase("20220103 07:31", true, true, Resolution.Daily)]
[TestCase("20220103 08:31", true, true, Resolution.Daily)]
public void IsMarketOpenSecurity(string exchangeTime, bool expectedResult, bool extendedMarketHours, Resolution resolution)
{
var security = CreateSecurity(Symbols.SPY);
var utcTime = Time.ParseDate(exchangeTime).ConvertToUtc(security.Exchange.TimeZone);
security.SetLocalTimeKeeper(new LocalTimeKeeper(utcTime, security.Exchange.TimeZone));
Assert.AreEqual(expectedResult, security.IsMarketOpen(extendedMarketHours));
}
[TestCase("20220101", false, true)]
[TestCase("20220101", false, false)]
[TestCase("20220103 09:31", true, false)]
[TestCase("20220103 07:31", false, false)]
[TestCase("20220103 08:31", true, true)]
public void IsMarketOpenSymbol(string nyTime, bool expectedResult, bool extendedMarketHours)
{
var utcTime = Time.ParseDate(nyTime).ConvertToUtc(TimeZones.NewYork);
Assert.AreEqual(expectedResult, Symbols.SPY.IsMarketOpen(utcTime, extendedMarketHours));
}
[TestCase("CL XTN6UA1G9QKH")]
[TestCase("ES VU1EHIDJYLMP")]
[TestCase("ES VRJST036ZY0X")]
[TestCase("GE YYBCLAZG1NGH")]
[TestCase("GE YTC58AEQ4C8X")]
[TestCase("BTC XTU2YXLMT1XD")]
[TestCase("UB XUIP59QUPVS5")]
[TestCase("NQ XUERCWA6EWAP")]
[TestCase("PL XVJ4OQA3JSN5")]
public void AdjustSymbolByOffsetTest(string future)
{
var sid = SecurityIdentifier.Parse(future);
var symbol = new Symbol(sid, sid.Symbol);
Assert.AreEqual(symbol.ID.Date, symbol.AdjustSymbolByOffset(0).ID.Date);
var nextExpiration = symbol.AdjustSymbolByOffset(1);
Assert.Greater(nextExpiration.ID.Date, symbol.ID.Date);
var nextNextExpiration = symbol.AdjustSymbolByOffset(2);
Assert.Greater(nextNextExpiration.ID.Date, nextExpiration.ID.Date);
}
[TestCase("A", "a")]
[TestCase("", "")]
[TestCase(null, null)]
[TestCase("Buy", "buy")]
[TestCase("BuyTheDip", "buyTheDip")]
public void ToCamelCase(string toConvert, string expected)
{
Assert.AreEqual(expected, toConvert.ToCamelCase());
}
[Test]
public void BatchAlphaResultPacket()
{
var btcusd = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX);
var insights = new List<Insight>
{
new Insight(DateTime.UtcNow, btcusd, Time.OneMillisecond, InsightType.Price, InsightDirection.Up, 1, 2, "sourceModel1"),
new Insight(DateTime.UtcNow, btcusd, Time.OneSecond, InsightType.Price, InsightDirection.Down, 1, 2, "sourceModel1")
};
var orderEvents = new List<OrderEvent>
{
new OrderEvent(1, btcusd, DateTime.UtcNow, OrderStatus.Submitted, OrderDirection.Buy, 0, 0, OrderFee.Zero, message: "OrderEvent1"),
new OrderEvent(1, btcusd, DateTime.UtcNow, OrderStatus.Filled, OrderDirection.Buy, 1, 1000, OrderFee.Zero, message: "OrderEvent2")
};
var orders = new List<Order> { new MarketOrder(btcusd, 1000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 } };
var packet1 = new AlphaResultPacket("1", 1, insights: insights, portfolio: new AlphaStreamsPortfolioState { TotalPortfolioValue = 11 });
var packet2 = new AlphaResultPacket("1", 1, orders: orders);
var packet3 = new AlphaResultPacket("1", 1, orderEvents: orderEvents, portfolio: new AlphaStreamsPortfolioState { TotalPortfolioValue = 12 });
var result = new List<AlphaResultPacket> { packet1, packet2, packet3 }.Batch();
Assert.AreEqual(2, result.Insights.Count);
Assert.AreEqual(2, result.OrderEvents.Count);
Assert.AreEqual(1, result.Orders.Count);
Assert.AreEqual(12, result.Portfolio.TotalPortfolioValue);
Assert.IsTrue(result.Insights.SequenceEqual(insights));
Assert.IsTrue(result.OrderEvents.SequenceEqual(orderEvents));
Assert.IsTrue(result.Orders.SequenceEqual(orders));
Assert.IsNull(new List<AlphaResultPacket>().Batch());
}
[Test]
public void BatchAlphaResultPacketDuplicateOrder()
{
var btcusd = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX);
var orders = new List<Order>
{
new MarketOrder(btcusd, 1000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 },
new MarketOrder(btcusd, 100, DateTime.UtcNow, "ExpensiveOrder") { Id = 2 },
new MarketOrder(btcusd, 2000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 },
new MarketOrder(btcusd, 10, DateTime.UtcNow, "ExpensiveOrder") { Id = 3 },
new MarketOrder(btcusd, 3000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 }
};
var orders2 = new List<Order>
{
new MarketOrder(btcusd, 200, DateTime.UtcNow, "ExpensiveOrder") { Id = 2 },
new MarketOrder(btcusd, 20, DateTime.UtcNow, "ExpensiveOrder") { Id = 3 }
};
var packet1 = new AlphaResultPacket("1", 1, orders: orders);
var packet2 = new AlphaResultPacket("1", 1, orders: orders2);
var result = new List<AlphaResultPacket> { packet1, packet2 }.Batch();
// we expect just 1 order instance per order id
Assert.AreEqual(3, result.Orders.Count);
Assert.IsTrue(result.Orders.Any(order => order.Id == 1 && order.Quantity == 3000));
Assert.IsTrue(result.Orders.Any(order => order.Id == 2 && order.Quantity == 200));
Assert.IsTrue(result.Orders.Any(order => order.Id == 3 && order.Quantity == 20));
var expected = new List<Order> { orders[4], orders2[0], orders2[1] };
Assert.IsTrue(result.Orders.SequenceEqual(expected));
}
[Test]
public void SeriesIsNotEmpty()
{
var series = new Series("SadSeries")
{ Values = new List<ChartPoint> { new ChartPoint(1, 1) } };
Assert.IsFalse(series.IsEmpty());
}
[Test]
public void SeriesIsEmpty()
{
Assert.IsTrue((new Series("Cat")).IsEmpty());
}
[Test]
public void ChartIsEmpty()
{
Assert.IsTrue((new Chart("HappyChart")).IsEmpty());
}
[Test]
public void ChartIsEmptyWithEmptySeries()
{
Assert.IsTrue((new Chart("HappyChart")
{ Series = new Dictionary<string, Series> { { "SadSeries", new Series("SadSeries") } }}).IsEmpty());
}
[Test]
public void ChartIsNotEmptyWithNonEmptySeries()
{
var series = new Series("SadSeries")
{ Values = new List<ChartPoint> { new ChartPoint(1, 1) } };
Assert.IsFalse((new Chart("HappyChart")
{ Series = new Dictionary<string, Series> { { "SadSeries", series } } }).IsEmpty());
}
[Test]
public void IsSubclassOfGenericWorksWorksForNonGenericType()
{
Assert.IsTrue(typeof(Derived2).IsSubclassOfGeneric(typeof(Derived1)));
}
[Test]
public void IsSubclassOfGenericWorksForGenericTypeWithParameter()
{
Assert.IsTrue(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<int>)));
Assert.IsFalse(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<bool>)));
}
[Test]
public void IsSubclassOfGenericWorksForGenericTypeDefinitions()
{
Assert.IsTrue(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<>)));
Assert.IsTrue(typeof(Derived2).IsSubclassOfGeneric(typeof(Super<>)));
}
[Test]
public void DateTimeRoundDownFullDayDoesntRoundDownByDay()
{
var date = new DateTime(2000, 01, 01);
var rounded = date.RoundDown(TimeSpan.FromDays(1));
Assert.AreEqual(date, rounded);
}
[Test]
public void GetBetterTypeNameHandlesRecursiveGenericTypes()
{
var type = typeof (Dictionary<List<int>, Dictionary<int, string>>);
const string expected = "Dictionary<List<Int32>, Dictionary<Int32, String>>";
var actual = type.GetBetterTypeName();
Assert.AreEqual(expected, actual);
}
[Test]
public void ExchangeRoundDownSkipsWeekends()
{
var time = new DateTime(2015, 05, 02, 18, 01, 00);
var expected = new DateTime(2015, 05, 01);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.FXCM, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDown(Time.OneDay, hours, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownHandlesMarketOpenTime()
{
var time = new DateTime(2016, 1, 25, 9, 31, 0);
var expected = time.Date;
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity);
var exchangeRounded = time.ExchangeRoundDown(Time.OneDay, hours, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ConvertToSkipsDiscontinuitiesBecauseOfDaylightSavingsStart_AddingOneHour()
{
var expected = new DateTime(2014, 3, 9, 3, 0, 0);
var time = new DateTime(2014, 3, 9, 2, 0, 0).ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
var time2 = new DateTime(2014, 3, 9, 2, 0, 1).ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
Assert.AreEqual(expected, time);
Assert.AreEqual(expected, time2);
}
[Test]
public void ConvertToIgnoreDaylightSavingsEnd_SubtractingOneHour()
{
var time1Expected = new DateTime(2014, 11, 2, 1, 59, 59);
var time2Expected = new DateTime(2014, 11, 2, 2, 0, 0);
var time3Expected = new DateTime(2014, 11, 2, 2, 0, 1);
var time1 = time1Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
var time2 = time2Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
var time3 = time3Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork);
Assert.AreEqual(time1Expected, time1);
Assert.AreEqual(time2Expected, time2);
Assert.AreEqual(time3Expected, time3);
}
[Test]
public void ExchangeRoundDownInTimeZoneSkipsWeekends()
{
// moment before EST market open in UTC (time + one day)
var time = new DateTime(2017, 10, 01, 9, 29, 59).ConvertToUtc(TimeZones.NewYork);
var expected = new DateTime(2017, 09, 29).ConvertFromUtc(TimeZones.NewYork);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneDay, hours, TimeZones.Utc, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
// This unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, in ExchangeRoundDownInTimeZone, GH issue 2368.
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_UTC()
{
var time = new DateTime(2014, 3, 9, 16, 0, 1);
var expected = new DateTime(2014, 3, 7, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
// This unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, in ExchangeRoundDownInTimeZone, GH issue 2368.
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_UTC()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 10, 31, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_ExtendedHours_UTC()
{
var time = new DateTime(2014, 3, 9, 2, 0, 1);
var expected = new DateTime(2014, 3, 9, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_ExtendedHours_UTC()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 11, 2, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
// this unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, GH issue 3707.
public void RoundDownInTimeZoneAroundDaylightTimeChanges()
{
// sydney time advanced Sunday, 6 October 2019, 02:00:00 clocks were turned forward 1 hour to
// Sunday, 6 October 2019, 03:00:00 local daylight time instead.
var timeAt = new DateTime(2019, 10, 6, 10, 0, 0);
var expected = new DateTime(2019, 10, 5, 10, 0, 0);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneDay, TimeZones.Sydney, TimeZones.Utc);
// even though there is an entire 'roundingInterval' unit (1 day) between 'timeAt' and 'expected' round down
// is affected by daylight savings and rounds down the timeAt
Assert.AreEqual(expected, exchangeRoundedAt);
timeAt = new DateTime(2019, 10, 7, 10, 0, 0);
expected = new DateTime(2019, 10, 6, 11, 0, 0);
exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneDay, TimeZones.Sydney, TimeZones.Utc);
Assert.AreEqual(expected, exchangeRoundedAt);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_AddingOneHour_UTC()
{
var timeAt = new DateTime(2014, 3, 9, 2, 0, 0);
var timeAfter = new DateTime(2014, 3, 9, 2, 0, 1);
var timeBefore = new DateTime(2014, 3, 9, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 3, 9, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var expected = new DateTime(2014, 3, 9, 3, 0, 0);
Assert.AreEqual(expected, exchangeRoundedAt);
Assert.AreEqual(expected, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(expected, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_UTC()
{
var timeAt = new DateTime(2014, 11, 2, 2, 0, 0);
var timeAfter = new DateTime(2014, 11, 2, 2, 0, 1);
var timeBefore = new DateTime(2014, 11, 2, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 11, 2, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc);
Assert.AreEqual(timeAt, exchangeRoundedAt);
Assert.AreEqual(timeAfter, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(timeAfterDaylightTimeChanges, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_NewYork()
{
var time = new DateTime(2014, 3, 9, 16, 0, 1);
var expected = new DateTime(2014, 3, 7, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_NewYork()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 10, 31, 16, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, false);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_ExtendedHours_NewYork()
{
var time = new DateTime(2014, 3, 9, 2, 0, 1);
var expected = new DateTime(2014, 3, 9, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_ExtendedHours_NewYork()
{
var time = new DateTime(2014, 11, 2, 2, 0, 1);
var expected = new DateTime(2014, 11, 2, 2, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto);
var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, true);
Assert.AreEqual(expected, exchangeRounded);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_AddingOneHour_NewYork()
{
var timeAt = new DateTime(2014, 3, 9, 2, 0, 0);
var timeAfter = new DateTime(2014, 3, 9, 2, 0, 1);
var timeBefore = new DateTime(2014, 3, 9, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 3, 9, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var expected = new DateTime(2014, 3, 9, 3, 0, 0);
Assert.AreEqual(expected, exchangeRoundedAt);
Assert.AreEqual(expected, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(expected, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_NewYork()
{
var timeAt = new DateTime(2014, 11, 2, 2, 0, 0);
var timeAfter = new DateTime(2014, 11, 2, 2, 0, 1);
var timeBefore = new DateTime(2014, 11, 2, 1, 59, 59);
var timeAfterDaylightTimeChanges = new DateTime(2014, 11, 2, 3, 0, 0);
var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex);
var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork);
Assert.AreEqual(timeAt, exchangeRoundedAt);
Assert.AreEqual(timeAfter, exchangeRoundedAfter);
Assert.AreEqual(timeBefore, exchangeRoundedBefore);
Assert.AreEqual(timeAfterDaylightTimeChanges, exchangeRoundedAfterDaylightTimeChanges);
}
[Test]
public void ConvertsInt32FromString()
{
const string input = "12345678";
var value = input.ToInt32();
Assert.AreEqual(12345678, value);
}
[Test]
public void ConvertsInt32FromStringWithDecimalTruncation()
{
const string input = "12345678.9";
var value = input.ToInt32();
Assert.AreEqual(12345678, value);
}
[Test]
public void ConvertsInt64FromString()
{
const string input = "12345678900";
var value = input.ToInt64();
Assert.AreEqual(12345678900, value);
}
[Test]
public void ConvertsInt64FromStringWithDecimalTruncation()
{
const string input = "12345678900.12";
var value = input.ToInt64();
Assert.AreEqual(12345678900, value);
}
[Test]
public void ToCsvDataParsesCorrectly()
{
var csv = "\"hello\",\"world\"".ToCsvData();
Assert.AreEqual(2, csv.Count);
Assert.AreEqual("\"hello\"", csv[0]);
Assert.AreEqual("\"world\"", csv[1]);
var csv2 = "1,2,3,4".ToCsvData();
Assert.AreEqual(4, csv2.Count);
Assert.AreEqual("1", csv2[0]);
Assert.AreEqual("2", csv2[1]);
Assert.AreEqual("3", csv2[2]);
Assert.AreEqual("4", csv2[3]);
}
[Test]
public void ToCsvDataParsesEmptyFinalValue()
{
var line = "\"hello\",world,";
var csv = line.ToCsvData();
Assert.AreEqual(3, csv.Count);
Assert.AreEqual("\"hello\"", csv[0]);
Assert.AreEqual("hello", csv[0].Trim('"'));
Assert.AreEqual("world", csv[1]);
Assert.AreEqual(string.Empty, csv[2]);
}
[Test]
public void ToCsvDataParsesEmptyValue()
{
Assert.AreEqual(string.Empty, string.Empty.ToCsvData()[0]);
}
[Test]
public void ConvertsDecimalFromString()
{
const string input = "123.45678";
var value = input.ToDecimal();
Assert.AreEqual(123.45678m, value);
}
[Test]
public void ConvertsDecimalFromStringWithExtraWhiteSpace()
{
const string input = " 123.45678 ";
var value = input.ToDecimal();
Assert.AreEqual(123.45678m, value);
}
[Test]
public void ConvertsDecimalFromIntStringWithExtraWhiteSpace()
{
const string input = " 12345678 ";
var value = input.ToDecimal();
Assert.AreEqual(12345678m, value);
}
[Test]
public void ConvertsZeroDecimalFromString()
{
const string input = "0.45678";
var value = input.ToDecimal();
Assert.AreEqual(0.45678m, value);
}
[Test]
public void ConvertsOneNumberDecimalFromString()
{
const string input = "1.45678";
var value = input.ToDecimal();
Assert.AreEqual(1.45678m, value);
}
[Test]
public void ConvertsZeroDecimalValueFromString()
{
const string input = "0";
var value = input.ToDecimal();
Assert.AreEqual(0m, value);
}
[Test]
public void ConvertsEmptyDecimalValueFromString()
{
const string input = "";
var value = input.ToDecimal();
Assert.AreEqual(0m, value);
}
[Test]
public void ConvertsNegativeDecimalFromString()
{
const string input = "-123.45678";
var value = input.ToDecimal();
Assert.AreEqual(-123.45678m, value);
}
[Test]
public void ConvertsNegativeDecimalFromStringWithExtraWhiteSpace()
{
const string input = " -123.45678 ";
var value = input.ToDecimal();
Assert.AreEqual(-123.45678m, value);
}
[Test]
public void ConvertsNegativeDecimalFromIntStringWithExtraWhiteSpace()
{
const string input = " -12345678 ";
var value = input.ToDecimal();
Assert.AreEqual(-12345678m, value);
}
[Test]
public void ConvertsNegativeZeroDecimalFromString()
{
const string input = "-0.45678";
var value = input.ToDecimal();
Assert.AreEqual(-0.45678m, value);
}
[Test]
public void ConvertsNegavtiveOneNumberDecimalFromString()
{
const string input = "-1.45678";
var value = input.ToDecimal();
Assert.AreEqual(-1.45678m, value);
}
[Test]
public void ConvertsNegativeZeroDecimalValueFromString()
{
const string input = "-0";
var value = input.ToDecimal();
Assert.AreEqual(-0m, value);
}
[TestCase("1.23%", 0.0123d)]
[TestCase("-1.23%", -0.0123d)]
[TestCase("31.2300%", 0.3123d)]
[TestCase("20%", 0.2d)]
[TestCase("-20%", -0.2d)]
[TestCase("220%", 2.2d)]
public void ConvertsPercent(string input, double expected)
{
Assert.AreEqual(new decimal(expected), input.ToNormalizedDecimal());
}
[Test]
public void ConvertsTimeSpanFromString()
{
const string input = "16:00";
var timespan = input.ConvertTo<TimeSpan>();
Assert.AreEqual(TimeSpan.FromHours(16), timespan);
}
[Test]
public void ConvertsDictionaryFromString()
{
var expected = new Dictionary<string, int> {{"a", 1}, {"b", 2}};
var input = JsonConvert.SerializeObject(expected);
var actual = input.ConvertTo<Dictionary<string, int>>();
CollectionAssert.AreEqual(expected, actual);
}
[Test]
public void DictionaryAddsItemToExistsList()
{
const int key = 0;
var list = new List<int> {1, 2};
var dictionary = new Dictionary<int, List<int>> {{key, list}};
Extensions.Add(dictionary, key, 3);
Assert.AreEqual(3, list.Count);
Assert.AreEqual(3, list[2]);
}
[Test]
public void DictionaryAddCreatesNewList()
{
const int key = 0;
var dictionary = new Dictionary<int, List<int>>();
Extensions.Add(dictionary, key, 1);
Assert.IsTrue(dictionary.ContainsKey(key));
var list = dictionary[key];
Assert.AreEqual(1, list.Count);
Assert.AreEqual(1, list[0]);
}
[Test]
public void SafeDecimalCasts()
{
var input = 2d;
var output = input.SafeDecimalCast();
Assert.AreEqual(2m, output);
}
[Test]
public void SafeDecimalCastRespectsUpperBound()
{
var input = (double) decimal.MaxValue;
var output = input.SafeDecimalCast();
Assert.AreEqual(decimal.MaxValue, output);
}
[Test]
public void SafeDecimalCastRespectsLowerBound()
{
var input = (double) decimal.MinValue;
var output = input.SafeDecimalCast();
Assert.AreEqual(decimal.MinValue, output);
}
[TestCase(Language.CSharp, double.NaN)]
[TestCase(Language.Python, double.NaN)]
[TestCase(Language.CSharp, double.NegativeInfinity)]
[TestCase(Language.Python, double.NegativeInfinity)]
[TestCase(Language.CSharp, double.PositiveInfinity)]
[TestCase(Language.Python, double.PositiveInfinity)]
public void SafeDecimalCastThrowsArgumentException(Language language, double number)
{
if (language == Language.CSharp)
{
Assert.Throws<ArgumentException>(() => number.SafeDecimalCast());
return;
}
using (Py.GIL())
{
var pyNumber = number.ToPython();
var csNumber = pyNumber.As<double>();
Assert.Throws<ArgumentException>(() => csNumber.SafeDecimalCast());
}
}
[Test]
[TestCase(1.200, "1.2")]
[TestCase(1200, "1200")]
[TestCase(123.456, "123.456")]
public void NormalizeDecimalReturnsNoTrailingZeros(decimal input, string expectedOutput)
{
var output = input.Normalize();
Assert.AreEqual(expectedOutput, output.ToStringInvariant());
}
[Test]
[TestCase(0.072842, 3, "0.0728")]
[TestCase(0.0019999, 2, "0.0020")]
[TestCase(0.01234568423, 6, "0.0123457")]
public void RoundToSignificantDigits(decimal input, int digits, string expectedOutput)
{
var output = input.RoundToSignificantDigits(digits).ToStringInvariant();
Assert.AreEqual(expectedOutput, output);
}
[Test]
public void RoundsDownInTimeZone()
{
var dataTimeZone = TimeZones.Utc;
var exchangeTimeZone = TimeZones.EasternStandard;
var time = new DateTime(2000, 01, 01).ConvertTo(dataTimeZone, exchangeTimeZone);
var roundedTime = time.RoundDownInTimeZone(Time.OneDay, exchangeTimeZone, dataTimeZone);
Assert.AreEqual(time, roundedTime);
}
[Test]
public void GetStringBetweenCharsTests()
{
const string expected = "python3.6";
// Different characters cases
var input = "[ python3.6 ]";
var actual = input.GetStringBetweenChars('[', ']');
Assert.AreEqual(expected, actual);
input = "[ python3.6 ] [ python2.7 ]";
actual = input.GetStringBetweenChars('[', ']');
Assert.AreEqual(expected, actual);
input = "[ python2.7 [ python3.6 ] ]";
actual = input.GetStringBetweenChars('[', ']');
Assert.AreEqual(expected, actual);
// Same character cases
input = "\'python3.6\'";
actual = input.GetStringBetweenChars('\'', '\'');
Assert.AreEqual(expected, actual);
input = "\' python3.6 \' \' python2.7 \'";
actual = input.GetStringBetweenChars('\'', '\'');
Assert.AreEqual(expected, actual);
// In this case, it is not equal
input = "\' python2.7 \' python3.6 \' \'";
actual = input.GetStringBetweenChars('\'', '\'');
Assert.AreNotEqual(expected, actual);
}
[Test]
public void PyObjectTryConvertQuoteBar()
{
// Wrap a QuoteBar around a PyObject and convert it back
var value = ConvertToPyObject(new QuoteBar());
QuoteBar quoteBar;
var canConvert = value.TryConvert(out quoteBar);
Assert.IsTrue(canConvert);
Assert.IsNotNull(quoteBar);
Assert.IsAssignableFrom<QuoteBar>(quoteBar);
}
[Test]
public void PyObjectTryConvertSMA()
{
// Wrap a SimpleMovingAverage around a PyObject and convert it back
var value = ConvertToPyObject(new SimpleMovingAverage(14));
IndicatorBase<IndicatorDataPoint> indicatorBaseDataPoint;
var canConvert = value.TryConvert(out indicatorBaseDataPoint);
Assert.IsTrue(canConvert);
Assert.IsNotNull(indicatorBaseDataPoint);
Assert.IsAssignableFrom<SimpleMovingAverage>(indicatorBaseDataPoint);
}
[Test]
public void PyObjectTryConvertATR()
{
// Wrap a AverageTrueRange around a PyObject and convert it back
var value = ConvertToPyObject(new AverageTrueRange(14, MovingAverageType.Simple));
IndicatorBase<IBaseDataBar> indicatorBaseDataBar;
var canConvert = value.TryConvert(out indicatorBaseDataBar);
Assert.IsTrue(canConvert);
Assert.IsNotNull(indicatorBaseDataBar);
Assert.IsAssignableFrom<AverageTrueRange>(indicatorBaseDataBar);
}
[Test]
public void PyObjectTryConvertAD()
{
// Wrap a AccumulationDistribution around a PyObject and convert it back
var value = ConvertToPyObject(new AccumulationDistribution("AD"));
IndicatorBase<TradeBar> indicatorBaseTradeBar;
var canConvert = value.TryConvert(out indicatorBaseTradeBar);
Assert.IsTrue(canConvert);
Assert.IsNotNull(indicatorBaseTradeBar);
Assert.IsAssignableFrom<AccumulationDistribution>(indicatorBaseTradeBar);
}
[Test]
public void PyObjectTryConvertCustomCSharpData()
{
// Wrap a custom C# data around a PyObject and convert it back
var value = ConvertToPyObject(new CustomData());
BaseData baseData;
var canConvert = value.TryConvert(out baseData);
Assert.IsTrue(canConvert);
Assert.IsNotNull(baseData);
Assert.IsAssignableFrom<CustomData>(baseData);
}
[Test]
public void PyObjectTryConvertPythonClass()
{
PyObject value;
using (Py.GIL())
{
// Try to convert a python class which inherits from a C# object
value = PythonEngine.ModuleFromString("testModule",
@"
from AlgorithmImports import *
class Test(PythonData):
def __init__(self):
return 0;").GetAttr("Test");
}
Type type;
bool canConvert = value.TryConvert(out type, true);
Assert.IsTrue(canConvert);
}
[Test]
public void PyObjectTryConvertSymbolArray()
{
PyObject value;
using (Py.GIL())
{
// Wrap a Symbol Array around a PyObject and convert it back
value = new PyList(new[] { Symbols.SPY.ToPython(), Symbols.AAPL.ToPython() });
}
Symbol[] symbols;
var canConvert = value.TryConvert(out symbols);
Assert.IsTrue(canConvert);
Assert.IsNotNull(symbols);
Assert.IsAssignableFrom<Symbol[]>(symbols);
}
[Test]
public void PyObjectTryConvertFailCSharp()
{
// Try to convert a AccumulationDistribution as a QuoteBar
var value = ConvertToPyObject(new AccumulationDistribution("AD"));
QuoteBar quoteBar;
bool canConvert = value.TryConvert(out quoteBar);
Assert.IsFalse(canConvert);
Assert.IsNull(quoteBar);
}
[Test]
public void PyObjectTryConvertFailPython()
{
using (Py.GIL())
{
// Try to convert a python object as a IndicatorBase<TradeBar>
var locals = new PyDict();
PythonEngine.Exec("class A:\n pass", null, locals.Handle);
var value = locals.GetItem("A").Invoke();
IndicatorBase<TradeBar> indicatorBaseTradeBar;
bool canConvert = value.TryConvert(out indicatorBaseTradeBar);
Assert.IsFalse(canConvert);
Assert.IsNull(indicatorBaseTradeBar);
}
}
[Test]
public void PyObjectTryConvertFailPythonClass()
{
PyObject value;
using (Py.GIL())
{
// Try to convert a python class which inherits from a C# object
value = PythonEngine.ModuleFromString("testModule",
@"
from AlgorithmImports import *
class Test(PythonData):
def __init__(self):
return 0;").GetAttr("Test");
}
Type type;
bool canConvert = value.TryConvert(out type);
Assert.IsFalse(canConvert);
}
[Test]
[TestCase("coarseSelector = lambda coarse: [ x.Symbol for x in coarse if x.Price % 2 == 0 ]")]
[TestCase("def coarseSelector(coarse): return [ x.Symbol for x in coarse if x.Price % 2 == 0 ]")]
public void PyObjectTryConvertToFunc(string code)
{
Func<IEnumerable<CoarseFundamental>, Symbol[]> coarseSelector;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec(code, null, locals.Handle);
var pyObject = locals.GetItem("coarseSelector");
pyObject.TryConvertToDelegate(out coarseSelector);
}
var coarse = Enumerable
.Range(0, 9)
.Select(x => new CoarseFundamental { Symbol = Symbol.Create(x.ToStringInvariant(), SecurityType.Equity, Market.USA), Value = x });
var symbols = coarseSelector(coarse);
Assert.AreEqual(5, symbols.Length);
foreach (var symbol in symbols)
{
var price = symbol.Value.ConvertInvariant<int>();
Assert.AreEqual(0, price % 2);
}
}
[Test]
public void PyObjectTryConvertToAction1()
{
Action<int> action;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec("def raise_number(a): raise ValueError(a)", null, locals.Handle);
var pyObject = locals.GetItem("raise_number");
pyObject.TryConvertToDelegate(out action);
}
try
{
action(2);
Assert.Fail();
}
catch (PythonException e)
{
Assert.AreEqual($"ValueError : {2}", e.Message);
}
}
[Test]
public void PyObjectTryConvertToAction2()
{
Action<int, decimal> action;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec("def raise_number(a, b): raise ValueError(a * b)", null, locals.Handle);
var pyObject = locals.GetItem("raise_number");
pyObject.TryConvertToDelegate(out action);
}
try
{
action(2, 3m);
Assert.Fail();
}
catch (PythonException e)
{
Assert.AreEqual("ValueError : 6.0", e.Message);
}
}
[Test]
public void PyObjectTryConvertToNonDelegateFail()
{
int action;
using (Py.GIL())
{
var locals = new PyDict();
PythonEngine.Exec("def raise_number(a, b): raise ValueError(a * b)", null, locals.Handle);
var pyObject = locals.GetItem("raise_number");
Assert.Throws<ArgumentException>(() => pyObject.TryConvertToDelegate(out action));
}
}
[Test]
public void PyObjectStringConvertToSymbolEnumerable()
{
SymbolCache.Clear();
SymbolCache.Set("SPY", Symbols.SPY);
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = new PyString("SPY").ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectStringListConvertToSymbolEnumerable()
{
SymbolCache.Clear();
SymbolCache.Set("SPY", Symbols.SPY);
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = new PyList(new[] { "SPY".ToPython() }).ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectSymbolConvertToSymbolEnumerable()
{
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = Symbols.SPY.ToPython().ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectSymbolListConvertToSymbolEnumerable()
{
IEnumerable<Symbol> symbols;
using (Py.GIL())
{
symbols = new PyList(new[] {Symbols.SPY.ToPython()}).ConvertToSymbolEnumerable();
}
Assert.AreEqual(Symbols.SPY, symbols.Single());
}
[Test]
public void PyObjectNonSymbolObjectConvertToSymbolEnumerable()
{
using (Py.GIL())
{
Assert.Throws<ArgumentException>(() => new PyInt(1).ConvertToSymbolEnumerable().ToList());
}
}
[Test]
public void PyObjectDictionaryConvertToDictionary_Success()
{
using (Py.GIL())
{
var actualDictionary = PythonEngine.ModuleFromString(
"PyObjectDictionaryConvertToDictionary_Success",
@"
from datetime import datetime as dt
actualDictionary = dict()
actualDictionary.update({'SPY': dt(2019,10,3)})
actualDictionary.update({'QQQ': dt(2019,10,4)})
actualDictionary.update({'IBM': dt(2019,10,5)})
"
).GetAttr("actualDictionary").ConvertToDictionary<string, DateTime>();
Assert.AreEqual(3, actualDictionary.Count);
var expectedDictionary = new Dictionary<string, DateTime>
{
{"SPY", new DateTime(2019,10,3) },
{"QQQ", new DateTime(2019,10,4) },
{"IBM", new DateTime(2019,10,5) },
};
foreach (var kvp in expectedDictionary)
{
Assert.IsTrue(actualDictionary.ContainsKey(kvp.Key));
var actual = actualDictionary[kvp.Key];
Assert.AreEqual(kvp.Value, actual);
}
}
}
[Test]
public void PyObjectDictionaryConvertToDictionary_FailNotDictionary()
{
using (Py.GIL())
{
var pyObject = PythonEngine.ModuleFromString(
"PyObjectDictionaryConvertToDictionary_FailNotDictionary",
"actualDictionary = list()"
).GetAttr("actualDictionary");
Assert.Throws<ArgumentException>(() => pyObject.ConvertToDictionary<string, DateTime>());
}
}
[Test]
public void PyObjectDictionaryConvertToDictionary_FailWrongItemType()
{
using (Py.GIL())
{
var pyObject = PythonEngine.ModuleFromString(
"PyObjectDictionaryConvertToDictionary_FailWrongItemType",
@"
actualDictionary = dict()
actualDictionary.update({'SPY': 3})
actualDictionary.update({'QQQ': 4})
actualDictionary.update({'IBM': 5})
"
).GetAttr("actualDictionary");
Assert.Throws<ArgumentException>(() => pyObject.ConvertToDictionary<string, DateTime>());
}
}
[Test]
public void BatchByDoesNotDropItems()
{
var list = new List<int> {1, 2, 3, 4, 5};
var by2 = list.BatchBy(2).ToList();
Assert.AreEqual(3, by2.Count);
Assert.AreEqual(2, by2[0].Count);
Assert.AreEqual(2, by2[1].Count);
Assert.AreEqual(1, by2[2].Count);
CollectionAssert.AreEqual(list, by2.SelectMany(x => x));
}
[Test]
public void ToOrderTicketCreatesCorrectTicket()
{
var orderRequest = new SubmitOrderRequest(OrderType.Limit, SecurityType.Equity, Symbols.USDJPY, 1000, 0, 1.11m, DateTime.Now, "Pepe");
var order = Order.CreateOrder(orderRequest);
order.Status = OrderStatus.Submitted;
order.Id = 11;
var orderTicket = order.ToOrderTicket(null);
Assert.AreEqual(order.Id, orderTicket.OrderId);
Assert.AreEqual(order.Quantity, orderTicket.Quantity);
Assert.AreEqual(order.Status, orderTicket.Status);
Assert.AreEqual(order.Type, orderTicket.OrderType);
Assert.AreEqual(order.Symbol, orderTicket.Symbol);
Assert.AreEqual(order.Tag, orderTicket.Tag);
Assert.AreEqual(order.Time, orderTicket.Time);
Assert.AreEqual(order.SecurityType, orderTicket.SecurityType);
}
[TestCase(4000, "4K")]
[TestCase(4103, "4.1K")]
[TestCase(40000, "40K")]
[TestCase(45321, "45.3K")]
[TestCase(654321, "654K")]
[TestCase(600031, "600K")]
[TestCase(1304303, "1.3M")]
[TestCase(2600000, "2.6M")]
[TestCase(26000000, "26M")]
[TestCase(260000000, "260M")]
[TestCase(2600000000, "2.6B")]
[TestCase(26000000000, "26B")]
public void ToFinancialFigures(double number, string expected)
{
var value = ((decimal)number).ToFinancialFigures();
Assert.AreEqual(expected, value);
}
[Test]
public void DecimalTruncateTo3DecimalPlaces()
{
var value = 10.999999m;
Assert.AreEqual(10.999m, value.TruncateTo3DecimalPlaces());
}
[Test]
public void DecimalTruncateTo3DecimalPlacesDoesNotThrowException()
{
var value = decimal.MaxValue;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
value = decimal.MinValue;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
value = decimal.MaxValue - 1;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
value = decimal.MinValue + 1;
Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces());
}
[Test]
public void DecimalAllowExponentTests()
{
const string strWithExponent = "5e-5";
Assert.AreEqual(strWithExponent.ToDecimalAllowExponent(), 0.00005);
Assert.AreNotEqual(strWithExponent.ToDecimal(), 0.00005);
Assert.AreEqual(strWithExponent.ToDecimal(), 10275);
}
[Test]
public void DateRulesToFunc()
{
var dateRules = new DateRules(new SecurityManager(
new TimeKeeper(new DateTime(2015, 1, 1), DateTimeZone.Utc)), DateTimeZone.Utc);
var first = new DateTime(2015, 1, 10);
var second = new DateTime(2015, 1, 30);
var dateRule = dateRules.On(first, second);
var func = dateRule.ToFunc();
Assert.AreEqual(first, func(new DateTime(2015, 1, 1)));
Assert.AreEqual(first, func(new DateTime(2015, 1, 5)));
Assert.AreEqual(second, func(first));
Assert.AreEqual(Time.EndOfTime, func(second));
Assert.AreEqual(Time.EndOfTime, func(second));
}
[Test]
[TestCase(OptionRight.Call, true, OrderDirection.Sell)]
[TestCase(OptionRight.Call, false, OrderDirection.Buy)]
[TestCase(OptionRight.Put, true, OrderDirection.Buy)]
[TestCase(OptionRight.Put, false, OrderDirection.Sell)]
public void GetsExerciseDirection(OptionRight right, bool isShort, OrderDirection expected)
{
var actual = right.GetExerciseDirection(isShort);
Assert.AreEqual(expected, actual);
}
[Test]
public void AppliesScalingToEquityTickQuotes()
{
// This test ensures that all Ticks with TickType == TickType.Quote have adjusted BidPrice and AskPrice.
// Relevant issue: https://github.com/QuantConnect/Lean/issues/4788
var algo = new QCAlgorithm();
var dataFeed = new NullDataFeed();
algo.SubscriptionManager = new SubscriptionManager();
algo.SubscriptionManager.SetDataManager(new DataManager(
dataFeed,
new UniverseSelection(
algo,
new SecurityService(
new CashBook(),
MarketHoursDatabase.FromDataFolder(),
SymbolPropertiesDatabase.FromDataFolder(),
algo,
null,
null
),
new DataPermissionManager(),
TestGlobals.DataProvider
),
algo,
new TimeKeeper(DateTime.UtcNow),
MarketHoursDatabase.FromDataFolder(),
false,
null,
new DataPermissionManager()
));
using (var zipDataCacheProvider = new ZipDataCacheProvider(TestGlobals.DataProvider))
{
algo.HistoryProvider = new SubscriptionDataReaderHistoryProvider();
algo.HistoryProvider.Initialize(
new HistoryProviderInitializeParameters(
null,
null,
null,
zipDataCacheProvider,
TestGlobals.MapFileProvider,
TestGlobals.FactorFileProvider,
(_) => {},
false,
new DataPermissionManager()));
algo.SetStartDate(DateTime.UtcNow.AddDays(-1));
var history = algo.History(new[] { Symbols.IBM }, new DateTime(2013, 10, 7), new DateTime(2013, 10, 8), Resolution.Tick).ToList();
Assert.AreEqual(57460, history.Count);
foreach (var slice in history)
{
if (!slice.Ticks.ContainsKey(Symbols.IBM))
{
continue;
}
foreach (var tick in slice.Ticks[Symbols.IBM])
{
if (tick.BidPrice != 0)
{
Assert.LessOrEqual(Math.Abs(tick.Value - tick.BidPrice), 0.05);
}
if (tick.AskPrice != 0)
{
Assert.LessOrEqual(Math.Abs(tick.Value - tick.AskPrice), 0.05);
}
}
}
}
}
[Test]
[TestCase(PositionSide.Long, OrderDirection.Buy)]
[TestCase(PositionSide.Short, OrderDirection.Sell)]
[TestCase(PositionSide.None, OrderDirection.Hold)]
public void ToOrderDirection(PositionSide side, OrderDirection expected)
{
Assert.AreEqual(expected, side.ToOrderDirection());
}
[Test]
[TestCase(OrderDirection.Buy, PositionSide.Long, false)]
[TestCase(OrderDirection.Buy, PositionSide.Short, true)]
[TestCase(OrderDirection.Buy, PositionSide.None, false)]
[TestCase(OrderDirection.Sell, PositionSide.Long, true)]
[TestCase(OrderDirection.Sell, PositionSide.Short, false)]
[TestCase(OrderDirection.Sell, PositionSide.None, false)]
[TestCase(OrderDirection.Hold, PositionSide.Long, false)]
[TestCase(OrderDirection.Hold, PositionSide.Short, false)]
[TestCase(OrderDirection.Hold, PositionSide.None, false)]
public void Closes(OrderDirection direction, PositionSide side, bool expected)
{
Assert.AreEqual(expected, direction.Closes(side));
}
[Test]
public void ListEquals()
{
var left = new[] {1, 2, 3};
var right = new[] {1, 2, 3};
Assert.IsTrue(left.ListEquals(right));
right[2] = 4;
Assert.IsFalse(left.ListEquals(right));
}
[Test]
public void GetListHashCode()
{
var ints1 = new[] {1, 2, 3};
var ints2 = new[] {1, 3, 2};
var longs = new[] {1L, 2L, 3L};
var decimals = new[] {1m, 2m, 3m};
// ordering dependent
Assert.AreNotEqual(ints1.GetListHashCode(), ints2.GetListHashCode());
Assert.AreEqual(ints1.GetListHashCode(), decimals.GetListHashCode());
// known type collision - long has same hash code as int within the int range
// we could take a hash of typeof(T) but this would require ListEquals to enforce exact types
// and we would prefer to allow typeof(T)'s GetHashCode and Equals to make this determination.
Assert.AreEqual(ints1.GetListHashCode(), longs.GetListHashCode());
// deterministic
Assert.AreEqual(ints1.GetListHashCode(), new[] {1, 2, 3}.GetListHashCode());
}
[Test]
[TestCase("0.999", "0.0001", "0.999")]
[TestCase("0.999", "0.001", "0.999")]
[TestCase("0.999", "0.01", "1.000")]
[TestCase("0.999", "0.1", "1.000")]
[TestCase("0.999", "1", "1.000")]
[TestCase("0.999", "2", "0")]
[TestCase("1.0", "0.15", "1.05")]
[TestCase("1.05", "0.15", "1.05")]
[TestCase("0.975", "0.15", "1.05")]
[TestCase("-0.975", "0.15", "-1.05")]
[TestCase("-1.0", "0.15", "-1.05")]
[TestCase("-1.05", "0.15", "-1.05")]
public void DiscretelyRoundBy(string valueString, string quantaString, string expectedString)
{
var value = decimal.Parse(valueString, CultureInfo.InvariantCulture);
var quanta = decimal.Parse(quantaString, CultureInfo.InvariantCulture);
var expected = decimal.Parse(expectedString, CultureInfo.InvariantCulture);
var actual = value.DiscretelyRoundBy(quanta);
Assert.AreEqual(expected, actual);
}
private PyObject ConvertToPyObject(object value)
{
using (Py.GIL())
{
return value.ToPython();
}
}
private class Super<T>
{
}
private class Derived1 : Super<int>
{
}
private class Derived2 : Derived1
{
}
private static Security CreateSecurity(Symbol symbol)
{
var entry = MarketHoursDatabase.FromDataFolder()
.GetEntry(symbol.ID.Market, symbol, symbol.SecurityType);
return new Security(symbol,
entry.ExchangeHours,
new Cash(Currencies.USD, 0, 1),
SymbolProperties.GetDefault(Currencies.USD),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache()
);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XenAPI
{
/// <summary>
/// A user of the system
/// First published in XenServer 4.0.
/// </summary>
public partial class User : XenObject<User>
{
public User()
{
}
public User(string uuid,
string short_name,
string fullname,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.short_name = short_name;
this.fullname = fullname;
this.other_config = other_config;
}
/// <summary>
/// Creates a new User from a Proxy_User.
/// </summary>
/// <param name="proxy"></param>
public User(Proxy_User proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(User update)
{
uuid = update.uuid;
short_name = update.short_name;
fullname = update.fullname;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_User proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
short_name = proxy.short_name == null ? null : (string)proxy.short_name;
fullname = proxy.fullname == null ? null : (string)proxy.fullname;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_User ToProxy()
{
Proxy_User result_ = new Proxy_User();
result_.uuid = uuid ?? "";
result_.short_name = short_name ?? "";
result_.fullname = fullname ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new User from a Hashtable.
/// </summary>
/// <param name="table"></param>
public User(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
short_name = Marshalling.ParseString(table, "short_name");
fullname = Marshalling.ParseString(table, "fullname");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(User other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._short_name, other._short_name) &&
Helper.AreEqual2(this._fullname, other._fullname) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, User server)
{
if (opaqueRef == null)
{
Proxy_User p = this.ToProxy();
return session.proxy.user_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_fullname, server._fullname))
{
User.set_fullname(session, opaqueRef, _fullname);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
User.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given user.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static User get_record(Session session, string _user)
{
return new User((Proxy_User)session.proxy.user_get_record(session.uuid, _user ?? "").parse());
}
/// <summary>
/// Get a reference to the user instance with the specified UUID.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> get_by_uuid(Session session, string _uuid)
{
return XenRef<User>.Create(session.proxy.user_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> create(Session session, User _record)
{
return XenRef<User>.Create(session.proxy.user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_create(Session session, User _record)
{
return XenRef<Task>.Create(session.proxy.async_user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static void destroy(Session session, string _user)
{
session.proxy.user_destroy(session.uuid, _user ?? "").parse();
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_destroy(Session session, string _user)
{
return XenRef<Task>.Create(session.proxy.async_user_destroy(session.uuid, _user ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_uuid(Session session, string _user)
{
return (string)session.proxy.user_get_uuid(session.uuid, _user ?? "").parse();
}
/// <summary>
/// Get the short_name field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_short_name(Session session, string _user)
{
return (string)session.proxy.user_get_short_name(session.uuid, _user ?? "").parse();
}
/// <summary>
/// Get the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_fullname(Session session, string _user)
{
return (string)session.proxy.user_get_fullname(session.uuid, _user ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static Dictionary<string, string> get_other_config(Session session, string _user)
{
return Maps.convert_from_proxy_string_string(session.proxy.user_get_other_config(session.uuid, _user ?? "").parse());
}
/// <summary>
/// Set the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_fullname">New value to set</param>
public static void set_fullname(Session session, string _user, string _fullname)
{
session.proxy.user_set_fullname(session.uuid, _user ?? "", _fullname ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _user, Dictionary<string, string> _other_config)
{
session.proxy.user_set_other_config(session.uuid, _user ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _user, string _key, string _value)
{
session.proxy.user_add_to_other_config(session.uuid, _user ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given user. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _user, string _key)
{
session.proxy.user_remove_from_other_config(session.uuid, _user ?? "", _key ?? "").parse();
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// short name (e.g. userid)
/// </summary>
public virtual string short_name
{
get { return _short_name; }
set
{
if (!Helper.AreEqual(value, _short_name))
{
_short_name = value;
Changed = true;
NotifyPropertyChanged("short_name");
}
}
}
private string _short_name;
/// <summary>
/// full name
/// </summary>
public virtual string fullname
{
get { return _fullname; }
set
{
if (!Helper.AreEqual(value, _fullname))
{
_fullname = value;
Changed = true;
NotifyPropertyChanged("fullname");
}
}
}
private string _fullname;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
// 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar
{
/// <summary>
/// The controller for navigation bars.
/// </summary>
/// <remarks>
/// The threading model for this class is simple: all non-static members are affinitized to the
/// UI thread.
/// </remarks>
internal partial class NavigationBarController : ForegroundThreadAffinitizedObject, INavigationBarController
{
private readonly INavigationBarPresenter _presenter;
private readonly ITextBuffer _subjectBuffer;
private readonly IWaitIndicator _waitIndicator;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly WorkspaceRegistration _workspaceRegistration;
/// <summary>
/// If we have pushed a full list to the presenter in response to a focus event, this
/// contains the version stamp of the list that was pushed. It is null if the last thing
/// pushed to the list was due to a caret move or file change.
/// </summary>
private VersionStamp? _versionStampOfFullListPushedToPresenter = null;
private bool _disconnected = false;
private Workspace _workspace;
public NavigationBarController(
INavigationBarPresenter presenter,
ITextBuffer subjectBuffer,
IWaitIndicator waitIndicator,
IAsynchronousOperationListener asyncListener)
{
_presenter = presenter;
_subjectBuffer = subjectBuffer;
_waitIndicator = waitIndicator;
_asyncListener = asyncListener;
_workspaceRegistration = Workspace.GetWorkspaceRegistration(subjectBuffer.AsTextContainer());
_workspaceRegistration.WorkspaceChanged += OnWorkspaceRegistrationChanged;
presenter.CaretMoved += OnCaretMoved;
presenter.ViewFocused += OnViewFocused;
presenter.DropDownFocused += OnDropDownFocused;
presenter.ItemSelected += OnItemSelected;
subjectBuffer.PostChanged += OnSubjectBufferPostChanged;
// Initialize the tasks to be an empty model so we never have to deal with a null case.
_modelTask = Task.FromResult(
new NavigationBarModel(
SpecializedCollections.EmptyList<NavigationBarItem>(),
default(VersionStamp),
null));
_selectedItemInfoTask = Task.FromResult(new NavigationBarSelectedTypeAndMember(null, null));
if (_workspaceRegistration.Workspace != null)
{
ConnectToWorkspace(_workspaceRegistration.Workspace);
}
}
private void OnWorkspaceRegistrationChanged(object sender, EventArgs e)
{
DisconnectFromWorkspace();
var newWorkspace = _workspaceRegistration.Workspace;
if (newWorkspace != null)
{
ConnectToWorkspace(newWorkspace);
}
}
private void ConnectToWorkspace(Workspace workspace)
{
AssertIsForeground();
// If we disconnected before the workspace ever connected, just disregard
if (_disconnected)
{
return;
}
_workspace = workspace;
_workspace.WorkspaceChanged += this.OnWorkspaceChanged;
// For the first time you open the file, we'll start immediately
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
private void DisconnectFromWorkspace()
{
if (_workspace != null)
{
_workspace.WorkspaceChanged -= this.OnWorkspaceChanged;
_workspace = null;
}
}
public void Disconnect()
{
AssertIsForeground();
DisconnectFromWorkspace();
_subjectBuffer.PostChanged -= OnSubjectBufferPostChanged;
_presenter.CaretMoved -= OnCaretMoved;
_presenter.ViewFocused -= OnViewFocused;
_presenter.DropDownFocused -= OnDropDownFocused;
_presenter.ItemSelected -= OnItemSelected;
_presenter.Disconnect();
_workspaceRegistration.WorkspaceChanged -= OnWorkspaceRegistrationChanged;
_disconnected = true;
// Cancel off any remaining background work
_modelTaskCancellationSource.Cancel();
_selectedItemInfoTaskCancellationSource.Cancel();
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
// We're getting an event for a workspace we already disconnected from
if (args.NewSolution.Workspace != _workspace)
{
return;
}
// If the displayed project is being renamed, retrigger the update
if (args.Kind == WorkspaceChangeKind.ProjectChanged && args.ProjectId != null)
{
var oldProject = args.OldSolution.GetProject(args.ProjectId);
var newProject = args.NewSolution.GetProject(args.ProjectId);
if (oldProject.Name != newProject.Name)
{
var currentContextDocumentId = _workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (currentContextDocumentId != null && currentContextDocumentId.ProjectId == args.ProjectId)
{
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
}
}
if (args.Kind == WorkspaceChangeKind.DocumentChanged &&
args.OldSolution == args.NewSolution)
{
var currentContextDocumentId = _workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (currentContextDocumentId != null && currentContextDocumentId == args.DocumentId)
{
// The context has changed, so update everything.
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
}
}
private void OnSubjectBufferPostChanged(object sender, EventArgs e)
{
AssertIsForeground();
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: TaggerConstants.MediumDelay, selectedItemUpdateDelay: 0, updateUIWhenDone: true);
}
private void OnCaretMoved(object sender, EventArgs e)
{
AssertIsForeground();
StartSelectedItemUpdateTask(delay: TaggerConstants.NearImmediateDelay, updateUIWhenDone: true);
}
private void OnViewFocused(object sender, EventArgs e)
{
AssertIsForeground();
StartSelectedItemUpdateTask(delay: TaggerConstants.ShortDelay, updateUIWhenDone: true);
}
private void OnDropDownFocused(object sender, EventArgs e)
{
AssertIsForeground();
// Refresh the drop downs to their full information
_waitIndicator.Wait(
EditorFeaturesResources.NavigationBars,
EditorFeaturesResources.RefreshingNavigationBars,
allowCancel: true,
action: context => UpdateDropDownsSynchronously(context.CancellationToken));
}
private void UpdateDropDownsSynchronously(CancellationToken cancellationToken)
{
AssertIsForeground();
// If the presenter already has the full list and the model is already complete, then we
// don't have to do any further computation nor push anything to the presenter
if (PresenterAlreadyHaveUpToDateFullList(cancellationToken))
{
return;
}
// We need to ensure that all the state computation is up to date, so cancel any
// previous work and ensure the model is up to date
StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: false);
// Wait for the work to be complete. We'll wait with our cancellationToken, so if the
// user hits cancel we won't block them, but the computation can still continue
using (Logger.LogBlock(FunctionId.NavigationBar_UpdateDropDownsSynchronously_WaitForModel, cancellationToken))
{
_modelTask.Wait(cancellationToken);
}
using (Logger.LogBlock(FunctionId.NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo, cancellationToken))
{
_selectedItemInfoTask.Wait(cancellationToken);
}
IList<NavigationBarProjectItem> projectItems;
NavigationBarProjectItem selectedProjectItem;
GetProjectItems(out projectItems, out selectedProjectItem);
_presenter.PresentItems(
projectItems,
selectedProjectItem,
_modelTask.Result.Types,
_selectedItemInfoTask.Result.TypeItem,
_selectedItemInfoTask.Result.MemberItem);
_versionStampOfFullListPushedToPresenter = _modelTask.Result.SemanticVersionStamp;
}
private void GetProjectItems(out IList<NavigationBarProjectItem> projectItems, out NavigationBarProjectItem selectedProjectItem)
{
var documents = _subjectBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges();
if (!documents.Any())
{
projectItems = SpecializedCollections.EmptyList<NavigationBarProjectItem>();
selectedProjectItem = null;
return;
}
projectItems = documents.Select(d =>
new NavigationBarProjectItem(
d.Project.Name,
GetProjectGlyph(d.Project),
workspace: d.Project.Solution.Workspace,
documentId: d.Id,
language: d.Project.Language)).OrderBy(projectItem => projectItem.Text).ToList();
projectItems.Do(i => i.InitializeTrackingSpans(_subjectBuffer.CurrentSnapshot));
var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
selectedProjectItem = document != null
? projectItems.FirstOrDefault(p => p.Text == document.Project.Name) ?? projectItems.First()
: projectItems.First();
}
private Glyph GetProjectGlyph(Project project)
{
// TODO: Get the glyph from the hierarchy
return project.Language == LanguageNames.CSharp ? Glyph.CSharpProject : Glyph.BasicProject;
}
/// <summary>
/// Check if the presenter has already been pushed the full model that corresponds to the
/// current buffer's project version stamp.
/// </summary>
private bool PresenterAlreadyHaveUpToDateFullList(CancellationToken cancellationToken)
{
AssertIsForeground();
// If it doesn't have a full list pushed, then of course not
if (_versionStampOfFullListPushedToPresenter == null)
{
return false;
}
var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
return document.Project.GetDependentSemanticVersionAsync(cancellationToken).WaitAndGetResult(cancellationToken) == _versionStampOfFullListPushedToPresenter;
}
private void PushSelectedItemsToPresenter(NavigationBarSelectedTypeAndMember selectedItems)
{
AssertIsForeground();
var oldLeft = selectedItems.TypeItem;
var oldRight = selectedItems.MemberItem;
NavigationBarItem newLeft = null;
NavigationBarItem newRight = null;
var listOfLeft = new List<NavigationBarItem>();
var listOfRight = new List<NavigationBarItem>();
if (oldRight != null)
{
newRight = new NavigationBarPresentedItem(oldRight.Text, oldRight.Glyph, oldRight.Spans, oldRight.ChildItems, oldRight.Bolded, oldRight.Grayed || selectedItems.ShowMemberItemGrayed);
newRight.TrackingSpans = oldRight.TrackingSpans;
listOfRight.Add(newRight);
}
if (oldLeft != null)
{
newLeft = new NavigationBarPresentedItem(oldLeft.Text, oldLeft.Glyph, oldLeft.Spans, listOfRight, oldLeft.Bolded, oldLeft.Grayed || selectedItems.ShowTypeItemGrayed);
newLeft.TrackingSpans = oldLeft.TrackingSpans;
listOfLeft.Add(newLeft);
}
IList<NavigationBarProjectItem> projectItems;
NavigationBarProjectItem selectedProjectItem;
GetProjectItems(out projectItems, out selectedProjectItem);
_presenter.PresentItems(
projectItems,
selectedProjectItem,
listOfLeft,
newLeft,
newRight);
_versionStampOfFullListPushedToPresenter = null;
}
private void OnItemSelected(object sender, NavigationBarItemSelectedEventArgs e)
{
AssertIsForeground();
_waitIndicator.Wait(
EditorFeaturesResources.NavigationBars,
EditorFeaturesResources.RefreshingNavigationBars,
allowCancel: true,
action: context => ProcessItemSelectionSynchronously(e.Item, context.CancellationToken));
}
/// <summary>
/// Process the selection of an item synchronously inside a wait context.
/// </summary>
/// <param name="item">The selected item.</param>
/// <param name="cancellationToken">A cancellation token from the wait context.</param>
private void ProcessItemSelectionSynchronously(NavigationBarItem item, CancellationToken cancellationToken)
{
AssertIsForeground();
var presentedItem = item as NavigationBarPresentedItem;
if (presentedItem != null)
{
// Presented items are not navigable, but they may be selected due to a race
// documented in Bug #1174848. Protect all INavigationBarItemService implementers
// from this by ignoring these selections here.
return;
}
var projectItem = item as NavigationBarProjectItem;
if (projectItem != null)
{
projectItem.SwitchToContext();
// TODO: navigate to document / focus text view
}
else
{
var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var languageService = document.Project.LanguageServices.GetService<INavigationBarItemService>();
NavigateToItem(item, document, _subjectBuffer.CurrentSnapshot, languageService, cancellationToken);
}
}
// Now that the edit has been done, refresh to make sure everything is up-to-date. At
// this point, we now use CancellationToken.None to ensure we're properly refreshed.
UpdateDropDownsSynchronously(CancellationToken.None);
}
private void NavigateToItem(NavigationBarItem item, Document document, ITextSnapshot snapshot, INavigationBarItemService languageService, CancellationToken cancellationToken)
{
item.Spans = item.TrackingSpans.Select(ts => ts.GetSpan(snapshot).Span.ToTextSpan()).ToList();
languageService.NavigateToItem(document, item, _presenter.TryGetCurrentView(), cancellationToken);
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Indicators.Algo
File: IIndicatorValue.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Indicators
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Candles;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// The indicator value, based on which it will renew its value, as well as value, containing result of indicator calculation.
/// </summary>
public interface IIndicatorValue : IComparable<IIndicatorValue>, IComparable
{
/// <summary>
/// Indicator.
/// </summary>
IIndicator Indicator { get; }
/// <summary>
/// No indicator value.
/// </summary>
bool IsEmpty { get; }
/// <summary>
/// Is the value final (indicator finalizes its value and will not be changed anymore in the given point of time).
/// </summary>
bool IsFinal { get; set; }
/// <summary>
/// Whether the indicator is set.
/// </summary>
bool IsFormed { get; }
/// <summary>
/// The input value.
/// </summary>
IIndicatorValue InputValue { get; set; }
/// <summary>
/// Does value support data type, required for the indicator.
/// </summary>
/// <param name="valueType">The data type, operated by indicator.</param>
/// <returns><see langword="true" />, if data type is supported, otherwise, <see langword="false" />.</returns>
bool IsSupport(Type valueType);
/// <summary>
/// To get the value by the data type.
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <returns>Value.</returns>
T GetValue<T>();
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
IIndicatorValue SetValue<T>(IIndicator indicator, T value);
}
/// <summary>
/// The base class for the indicator value.
/// </summary>
public abstract class BaseIndicatorValue : IIndicatorValue
{
/// <summary>
/// Initialize <see cref="BaseIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
protected BaseIndicatorValue(IIndicator indicator)
{
Indicator = indicator ?? throw new ArgumentNullException(nameof(indicator));
IsFormed = indicator.IsFormed;
}
/// <inheritdoc />
public IIndicator Indicator { get; }
/// <inheritdoc />
public abstract bool IsEmpty { get; set; }
/// <inheritdoc />
public abstract bool IsFinal { get; set; }
/// <inheritdoc />
public bool IsFormed { get; }
/// <inheritdoc />
public abstract IIndicatorValue InputValue { get; set; }
/// <inheritdoc />
public abstract bool IsSupport(Type valueType);
/// <inheritdoc />
public abstract T GetValue<T>();
/// <inheritdoc />
public abstract IIndicatorValue SetValue<T>(IIndicator indicator, T value);
/// <inheritdoc />
public abstract int CompareTo(IIndicatorValue other);
/// <inheritdoc />
int IComparable.CompareTo(object other)
{
var value = other as IIndicatorValue;
if (other == null)
throw new ArgumentException(LocalizedStrings.Str911, nameof(other));
return CompareTo(value);
}
}
/// <summary>
/// The base value of the indicator, operating with one data type.
/// </summary>
/// <typeparam name="TValue">Value type.</typeparam>
public class SingleIndicatorValue<TValue> : BaseIndicatorValue
{
/// <summary>
/// Initializes a new instance of the <see cref="SingleIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public SingleIndicatorValue(IIndicator indicator, TValue value)
: base(indicator)
{
Value = value;
IsEmpty = value.IsNull();
}
/// <summary>
/// Initializes a new instance of the <see cref="SingleIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public SingleIndicatorValue(IIndicator indicator)
: base(indicator)
{
IsEmpty = true;
}
/// <summary>
/// Value.
/// </summary>
public TValue Value { get; }
/// <inheritdoc />
public override bool IsEmpty { get; set; }
/// <inheritdoc />
public override bool IsFinal { get; set; }
/// <inheritdoc />
public override IIndicatorValue InputValue { get; set; }
/// <inheritdoc />
public override bool IsSupport(Type valueType) => valueType == typeof(TValue);
/// <inheritdoc />
public override T GetValue<T>()
{
ThrowIfEmpty();
return Value.To<T>();
}
/// <inheritdoc />
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return new SingleIndicatorValue<T>(indicator, value) { IsFinal = IsFinal, InputValue = this };
}
private void ThrowIfEmpty()
{
if (IsEmpty)
throw new InvalidOperationException(LocalizedStrings.Str910);
}
/// <inheritdoc />
public override int CompareTo(IIndicatorValue other) => Value.Compare(other.GetValue<TValue>());
/// <inheritdoc />
public override string ToString() => IsEmpty ? "Empty" : Value.ToString();
}
/// <summary>
/// The indicator value, operating with data type <see cref="decimal"/>.
/// </summary>
public class DecimalIndicatorValue : SingleIndicatorValue<decimal>
{
/// <summary>
/// Initializes a new instance of the <see cref="DecimalIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public DecimalIndicatorValue(IIndicator indicator, decimal value)
: base(indicator, value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DecimalIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public DecimalIndicatorValue(IIndicator indicator)
: base(indicator)
{
}
/// <inheritdoc />
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return typeof(T) == typeof(decimal)
? new DecimalIndicatorValue(indicator, value.To<decimal>()) { IsFinal = IsFinal, InputValue = this }
: base.SetValue(indicator, value);
}
}
/// <summary>
/// The indicator value, operating with data type <see cref="Candle"/>.
/// </summary>
public class CandleIndicatorValue : SingleIndicatorValue<Candle>
{
private readonly Func<Candle, decimal> _getPart;
/// <summary>
/// Initializes a new instance of the <see cref="CandleIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public CandleIndicatorValue(IIndicator indicator, Candle value)
: this(indicator, value, ByClose)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CandleIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <param name="getPart">The candle converter, through which its parameter can be got. By default, the <see cref="CandleIndicatorValue.ByClose"/> is used.</param>
public CandleIndicatorValue(IIndicator indicator, Candle value, Func<Candle, decimal> getPart)
: base(indicator, value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_getPart = getPart ?? throw new ArgumentNullException(nameof(getPart));
IsFinal = value.State == CandleStates.Finished;
}
/// <summary>
/// Initializes a new instance of the <see cref="CandleIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
private CandleIndicatorValue(IIndicator indicator)
: base(indicator)
{
}
/// <summary>
/// The converter, taking from candle closing price <see cref="Candle.ClosePrice"/>.
/// </summary>
public static readonly Func<Candle, decimal> ByClose = c => c.ClosePrice;
/// <summary>
/// The converter, taking from candle opening price <see cref="Candle.OpenPrice"/>.
/// </summary>
public static readonly Func<Candle, decimal> ByOpen = c => c.OpenPrice;
/// <summary>
/// The converter, taking from candle middle of the body (<see cref="Candle.OpenPrice"/> + <see cref="Candle.ClosePrice"/>) / 2.
/// </summary>
public static readonly Func<Candle, decimal> ByMiddle = c => (c.ClosePrice + c.OpenPrice) / 2;
/// <inheritdoc />
public override bool IsSupport(Type valueType) => valueType == typeof(decimal) || base.IsSupport(valueType);
/// <inheritdoc />
public override T GetValue<T>()
{
var candle = base.GetValue<Candle>();
return typeof(T) == typeof(decimal) ? _getPart(candle).To<T>() : candle.To<T>();
}
/// <inheritdoc />
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return value is Candle candle
? new CandleIndicatorValue(indicator, candle) { InputValue = this }
: value.IsNull() ? new CandleIndicatorValue(indicator) : base.SetValue(indicator, value);
}
}
/// <summary>
/// The indicator value, operating with data type <see cref="MarketDepth"/>.
/// </summary>
public class MarketDepthIndicatorValue : SingleIndicatorValue<MarketDepth>
{
private readonly Func<MarketDepth, decimal?> _getPart;
/// <summary>
/// Initializes a new instance of the <see cref="MarketDepthIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="depth">Market depth.</param>
public MarketDepthIndicatorValue(IIndicator indicator, MarketDepth depth)
: this(indicator, depth, ByMiddle)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MarketDepthIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="depth">Market depth.</param>
/// <param name="getPart">The order book converter, through which its parameter can be got. By default, the <see cref="MarketDepthIndicatorValue.ByMiddle"/> is used.</param>
public MarketDepthIndicatorValue(IIndicator indicator, MarketDepth depth, Func<MarketDepth, decimal?> getPart)
: base(indicator, depth)
{
if (depth == null)
throw new ArgumentNullException(nameof(depth));
_getPart = getPart ?? throw new ArgumentNullException(nameof(getPart));
}
/// <summary>
/// The converter, taking from the order book the best bid price <see cref="MarketDepth.BestBid"/>.
/// </summary>
public static readonly Func<MarketDepth, decimal?> ByBestBid = d => d.BestBid2?.Price;
/// <summary>
/// The converter, taking from the order book the best offer price <see cref="MarketDepth.BestAsk"/>.
/// </summary>
public static readonly Func<MarketDepth, decimal?> ByBestAsk = d => d.BestAsk2?.Price;
/// <summary>
/// The converter, taking from the order book the middle of the spread <see cref="MarketDepthPair.MiddlePrice"/>.
/// </summary>
public static readonly Func<MarketDepth, decimal?> ByMiddle = d => d.BestPair?.MiddlePrice;
/// <inheritdoc />
public override bool IsSupport(Type valueType)
{
return valueType == typeof(decimal) || base.IsSupport(valueType);
}
/// <inheritdoc />
public override T GetValue<T>()
{
var depth = base.GetValue<MarketDepth>();
return typeof(T) == typeof(decimal) ? (_getPart(depth) ?? 0).To<T>() : depth.To<T>();
}
/// <inheritdoc />
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return new MarketDepthIndicatorValue(indicator, base.GetValue<MarketDepth>(), _getPart)
{
IsFinal = IsFinal,
InputValue = this
};
}
}
/// <summary>
/// The value of the indicator, operating with pair <see ref="Tuple{TValue, TValue}" />.
/// </summary>
/// <typeparam name="TValue">Value type.</typeparam>
public class PairIndicatorValue<TValue> : SingleIndicatorValue<Tuple<TValue, TValue>>
{
/// <summary>
/// Initializes a new instance of the <see cref="PairIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public PairIndicatorValue(IIndicator indicator, Tuple<TValue, TValue> value)
: base(indicator, value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PairIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public PairIndicatorValue(IIndicator indicator)
: base(indicator)
{
}
/// <inheritdoc />
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return new PairIndicatorValue<TValue>(indicator, GetValue<Tuple<TValue, TValue>>())
{
IsFinal = IsFinal,
InputValue = this
};
}
}
/// <summary>
/// The complex value of the indicator <see cref="IComplexIndicator"/>, derived as result of calculation.
/// </summary>
public class ComplexIndicatorValue : BaseIndicatorValue
{
/// <summary>
/// Initializes a new instance of the <see cref="ComplexIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public ComplexIndicatorValue(IIndicator indicator)
: base(indicator)
{
InnerValues = new Dictionary<IIndicator, IIndicatorValue>();
}
/// <inheritdoc />
public override bool IsEmpty { get; set; }
/// <inheritdoc />
public override bool IsFinal { get; set; }
/// <inheritdoc />
public override IIndicatorValue InputValue { get; set; }
/// <summary>
/// Embedded values.
/// </summary>
public IDictionary<IIndicator, IIndicatorValue> InnerValues { get; }
/// <inheritdoc />
public override bool IsSupport(Type valueType) => InnerValues.Any(v => v.Value.IsSupport(valueType));
/// <inheritdoc />
public override T GetValue<T>() => throw new NotSupportedException();
/// <inheritdoc />
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value) => throw new NotSupportedException();
/// <inheritdoc />
public override int CompareTo(IIndicatorValue other) => throw new NotSupportedException();
}
}
| |
using System.Runtime.CompilerServices;
namespace System.Interop.OpenGL
{
#if CODE_ANALYSIS
[IgnoreNamespace, Imported]
#endif
public abstract class GL33
{
// GL_VERSION_3_0
public const uint COMPARE_REF_TO_TEXTURE = 0x884E;
public const uint CLIP_DISTANCE0 = 0x3000;
public const uint CLIP_DISTANCE1 = 0x3001;
public const uint CLIP_DISTANCE2 = 0x3002;
public const uint CLIP_DISTANCE3 = 0x3003;
public const uint CLIP_DISTANCE4 = 0x3004;
public const uint CLIP_DISTANCE5 = 0x3005;
public const uint CLIP_DISTANCE6 = 0x3006;
public const uint CLIP_DISTANCE7 = 0x3007;
public const uint MAX_CLIP_DISTANCES = 0x0D32;
public const uint MAJOR_VERSION = 0x821B;
public const uint MINOR_VERSION = 0x821C;
public const uint NUM_EXTENSIONS = 0x821D;
public const uint CONTEXT_FLAGS = 0x821E;
public const uint DEPTH_BUFFER = 0x8223;
public const uint STENCIL_BUFFER = 0x8224;
public const uint COMPRESSED_RED = 0x8225;
public const uint COMPRESSED_RG = 0x8226;
public const uint CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT = 0x0001;
public const uint RGBA32F = 0x8814;
public const uint RGB32F = 0x8815;
public const uint RGBA16F = 0x881A;
public const uint RGB16F = 0x881B;
public const uint VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD;
public const uint MAX_ARRAY_TEXTURE_LAYERS = 0x88FF;
public const uint MIN_PROGRAM_TEXEL_OFFSET = 0x8904;
public const uint MAX_PROGRAM_TEXEL_OFFSET = 0x8905;
public const uint CLAMP_READ_COLOR = 0x891C;
public const uint FIXED_ONLY = 0x891D;
public const uint MAX_VARYING_COMPONENTS = 0x8B4B;
public const uint TEXTURE_1D_ARRAY = 0x8C18;
public const uint PROXY_TEXTURE_1D_ARRAY = 0x8C19;
public const uint TEXTURE_2D_ARRAY = 0x8C1A;
public const uint PROXY_TEXTURE_2D_ARRAY = 0x8C1B;
public const uint TEXTURE_BINDING_1D_ARRAY = 0x8C1C;
public const uint TEXTURE_BINDING_2D_ARRAY = 0x8C1D;
public const uint R11F_G11F_B10F = 0x8C3A;
public const uint UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;
public const uint RGB9_E5 = 0x8C3D;
public const uint UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;
public const uint TEXTURE_SHARED_SIZE = 0x8C3F;
public const uint TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76;
public const uint TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F;
public const uint MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80;
public const uint TRANSFORM_FEEDBACK_VARYINGS = 0x8C83;
public const uint TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84;
public const uint TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85;
public const uint PRIMITIVES_GENERATED = 0x8C87;
public const uint TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88;
public const uint RASTERIZER_DISCARD = 0x8C89;
public const uint MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A;
public const uint MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B;
public const uint INTERLEAVED_ATTRIBS = 0x8C8C;
public const uint SEPARATE_ATTRIBS = 0x8C8D;
public const uint TRANSFORM_FEEDBACK_BUFFER = 0x8C8E;
public const uint TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F;
public const uint RGBA32UI = 0x8D70;
public const uint RGB32UI = 0x8D71;
public const uint RGBA16UI = 0x8D76;
public const uint RGB16UI = 0x8D77;
public const uint RGBA8UI = 0x8D7C;
public const uint RGB8UI = 0x8D7D;
public const uint RGBA32I = 0x8D82;
public const uint RGB32I = 0x8D83;
public const uint RGBA16I = 0x8D88;
public const uint RGB16I = 0x8D89;
public const uint RGBA8I = 0x8D8E;
public const uint RGB8I = 0x8D8F;
public const uint RED_INTEGER = 0x8D94;
public const uint GREEN_INTEGER = 0x8D95;
public const uint BLUE_INTEGER = 0x8D96;
public const uint RGB_INTEGER = 0x8D98;
public const uint RGBA_INTEGER = 0x8D99;
public const uint BGR_INTEGER = 0x8D9A;
public const uint BGRA_INTEGER = 0x8D9B;
public const uint SAMPLER_1D_ARRAY = 0x8DC0;
public const uint SAMPLER_2D_ARRAY = 0x8DC1;
public const uint SAMPLER_1D_ARRAY_SHADOW = 0x8DC3;
public const uint SAMPLER_2D_ARRAY_SHADOW = 0x8DC4;
public const uint SAMPLER_CUBE_SHADOW = 0x8DC5;
public const uint UNSIGNED_INT_VEC2 = 0x8DC6;
public const uint UNSIGNED_INT_VEC3 = 0x8DC7;
public const uint UNSIGNED_INT_VEC4 = 0x8DC8;
public const uint INT_SAMPLER_1D = 0x8DC9;
public const uint INT_SAMPLER_2D = 0x8DCA;
public const uint INT_SAMPLER_3D = 0x8DCB;
public const uint INT_SAMPLER_CUBE = 0x8DCC;
public const uint INT_SAMPLER_1D_ARRAY = 0x8DCE;
public const uint INT_SAMPLER_2D_ARRAY = 0x8DCF;
public const uint UNSIGNED_INT_SAMPLER_1D = 0x8DD1;
public const uint UNSIGNED_INT_SAMPLER_2D = 0x8DD2;
public const uint UNSIGNED_INT_SAMPLER_3D = 0x8DD3;
public const uint UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4;
public const uint UNSIGNED_INT_SAMPLER_1D_ARRAY = 0x8DD6;
public const uint UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7;
public const uint QUERY_WAIT = 0x8E13;
public const uint QUERY_NO_WAIT = 0x8E14;
public const uint QUERY_BY_REGION_WAIT = 0x8E15;
public const uint QUERY_BY_REGION_NO_WAIT = 0x8E16;
public const uint BUFFER_ACCESS_FLAGS = 0x911F;
public const uint BUFFER_MAP_LENGTH = 0x9120;
public const uint BUFFER_MAP_OFFSET = 0x9121;
/* Reuse tokens from ARB_depth_buffer_float */
/* DEPTH_COMPONENT32F */
/* DEPTH32F_STENCIL8 */
/* FLOAT_32_UNSIGNED_INT_24_8_REV */
/* Reuse tokens from ARB_framebuffer_object */
/* INVALID_FRAMEBUFFER_OPERATION */
/* FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING */
/* FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE */
/* FRAMEBUFFER_ATTACHMENT_RED_SIZE */
/* FRAMEBUFFER_ATTACHMENT_GREEN_SIZE */
/* FRAMEBUFFER_ATTACHMENT_BLUE_SIZE */
/* FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE */
/* FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE */
/* FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE */
/* FRAMEBUFFER_DEFAULT */
/* FRAMEBUFFER_UNDEFINED */
/* DEPTH_STENCIL_ATTACHMENT */
/* INDEX */
/* MAX_RENDERBUFFER_SIZE */
/* DEPTH_STENCIL */
/* UNSIGNED_INT_24_8 */
/* DEPTH24_STENCIL8 */
/* TEXTURE_STENCIL_SIZE */
/* TEXTURE_RED_TYPE */
/* TEXTURE_GREEN_TYPE */
/* TEXTURE_BLUE_TYPE */
/* TEXTURE_ALPHA_TYPE */
/* TEXTURE_DEPTH_TYPE */
/* UNSIGNED_NORMALIZED */
/* FRAMEBUFFER_BINDING */
/* DRAW_FRAMEBUFFER_BINDING */
/* RENDERBUFFER_BINDING */
/* READ_FRAMEBUFFER */
/* DRAW_FRAMEBUFFER */
/* READ_FRAMEBUFFER_BINDING */
/* RENDERBUFFER_SAMPLES */
/* FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE */
/* FRAMEBUFFER_ATTACHMENT_OBJECT_NAME */
/* FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL */
/* FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE */
/* FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */
/* FRAMEBUFFER_COMPLETE */
/* FRAMEBUFFER_INCOMPLETE_ATTACHMENT */
/* FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT */
/* FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER */
/* FRAMEBUFFER_INCOMPLETE_READ_BUFFER */
/* FRAMEBUFFER_UNSUPPORTED */
/* MAX_COLOR_ATTACHMENTS */
/* COLOR_ATTACHMENT0 */
/* COLOR_ATTACHMENT1 */
/* COLOR_ATTACHMENT2 */
/* COLOR_ATTACHMENT3 */
/* COLOR_ATTACHMENT4 */
/* COLOR_ATTACHMENT5 */
/* COLOR_ATTACHMENT6 */
/* COLOR_ATTACHMENT7 */
/* COLOR_ATTACHMENT8 */
/* COLOR_ATTACHMENT9 */
/* COLOR_ATTACHMENT10 */
/* COLOR_ATTACHMENT11 */
/* COLOR_ATTACHMENT12 */
/* COLOR_ATTACHMENT13 */
/* COLOR_ATTACHMENT14 */
/* COLOR_ATTACHMENT15 */
/* DEPTH_ATTACHMENT */
/* STENCIL_ATTACHMENT */
/* FRAMEBUFFER */
/* RENDERBUFFER */
/* RENDERBUFFER_WIDTH */
/* RENDERBUFFER_HEIGHT */
/* RENDERBUFFER_INTERNAL_FORMAT */
/* STENCIL_INDEX1 */
/* STENCIL_INDEX4 */
/* STENCIL_INDEX8 */
/* STENCIL_INDEX16 */
/* RENDERBUFFER_RED_SIZE */
/* RENDERBUFFER_GREEN_SIZE */
/* RENDERBUFFER_BLUE_SIZE */
/* RENDERBUFFER_ALPHA_SIZE */
/* RENDERBUFFER_DEPTH_SIZE */
/* RENDERBUFFER_STENCIL_SIZE */
/* FRAMEBUFFER_INCOMPLETE_MULTISAMPLE */
/* MAX_SAMPLES */
/* Reuse tokens from ARB_framebuffer_sRGB */
/* FRAMEBUFFER_SRGB */
/* Reuse tokens from ARB_half_float_vertex */
/* HALF_FLOAT */
/* Reuse tokens from ARB_map_buffer_range */
/* MAP_READ_BIT */
/* MAP_WRITE_BIT */
/* MAP_INVALIDATE_RANGE_BIT */
/* MAP_INVALIDATE_BUFFER_BIT */
/* MAP_FLUSH_EXPLICIT_BIT */
/* MAP_UNSYNCHRONIZED_BIT */
/* Reuse tokens from ARB_texture_compression_rgtc */
/* COMPRESSED_RED_RGTC1 */
/* COMPRESSED_SIGNED_RED_RGTC1 */
/* COMPRESSED_RG_RGTC2 */
/* COMPRESSED_SIGNED_RG_RGTC2 */
/* Reuse tokens from ARB_texture_rg */
/* RG */
/* RG_INTEGER */
/* R8 */
/* R16 */
/* RG8 */
/* RG16 */
/* R16F */
/* R32F */
/* RG16F */
/* RG32F */
/* R8I */
/* R8UI */
/* R16I */
/* R16UI */
/* R32I */
/* R32UI */
/* RG8I */
/* RG8UI */
/* RG16I */
/* RG16UI */
/* RG32I */
/* RG32UI */
/* Reuse tokens from ARB_vertex_array_object */
/* VERTEX_ARRAY_BINDING */
// GL_VERSION_3_1
public const uint SAMPLER_2D_RECT = 0x8B63;
public const uint SAMPLER_2D_RECT_SHADOW = 0x8B64;
public const uint SAMPLER_BUFFER = 0x8DC2;
public const uint INT_SAMPLER_2D_RECT = 0x8DCD;
public const uint INT_SAMPLER_BUFFER = 0x8DD0;
public const uint UNSIGNED_INT_SAMPLER_2D_RECT = 0x8DD5;
public const uint UNSIGNED_INT_SAMPLER_BUFFER = 0x8DD8;
public const uint TEXTURE_BUFFER = 0x8C2A;
public const uint MAX_TEXTURE_BUFFER_SIZE = 0x8C2B;
public const uint TEXTURE_BINDING_BUFFER = 0x8C2C;
public const uint TEXTURE_BUFFER_DATA_STORE_BINDING = 0x8C2D;
public const uint TEXTURE_BUFFER_FORMAT = 0x8C2E;
public const uint TEXTURE_RECTANGLE = 0x84F5;
public const uint TEXTURE_BINDING_RECTANGLE = 0x84F6;
public const uint PROXY_TEXTURE_RECTANGLE = 0x84F7;
public const uint MAX_RECTANGLE_TEXTURE_SIZE = 0x84F8;
public const uint RED_SNORM = 0x8F90;
public const uint RG_SNORM = 0x8F91;
public const uint RGB_SNORM = 0x8F92;
public const uint RGBA_SNORM = 0x8F93;
public const uint R8_SNORM = 0x8F94;
public const uint RG8_SNORM = 0x8F95;
public const uint RGB8_SNORM = 0x8F96;
public const uint RGBA8_SNORM = 0x8F97;
public const uint R16_SNORM = 0x8F98;
public const uint RG16_SNORM = 0x8F99;
public const uint RGB16_SNORM = 0x8F9A;
public const uint RGBA16_SNORM = 0x8F9B;
public const uint SIGNED_NORMALIZED = 0x8F9C;
public const uint PRIMITIVE_RESTART = 0x8F9D;
public const uint PRIMITIVE_RESTART_INDEX = 0x8F9E;
/* Reuse tokens from ARB_copy_buffer */
/* COPY_READ_BUFFER */
/* COPY_WRITE_BUFFER */
/* Reuse tokens from ARB_draw_instanced (none) */
/* Reuse tokens from ARB_uniform_buffer_object */
/* UNIFORM_BUFFER */
/* UNIFORM_BUFFER_BINDING */
/* UNIFORM_BUFFER_START */
/* UNIFORM_BUFFER_SIZE */
/* MAX_VERTEX_UNIFORM_BLOCKS */
/* MAX_FRAGMENT_UNIFORM_BLOCKS */
/* MAX_COMBINED_UNIFORM_BLOCKS */
/* MAX_UNIFORM_BUFFER_BINDINGS */
/* MAX_UNIFORM_BLOCK_SIZE */
/* MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS */
/* MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS */
/* UNIFORM_BUFFER_OFFSET_ALIGNMENT */
/* ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH */
/* ACTIVE_UNIFORM_BLOCKS */
/* UNIFORM_TYPE */
/* UNIFORM_SIZE */
/* UNIFORM_NAME_LENGTH */
/* UNIFORM_BLOCK_INDEX */
/* UNIFORM_OFFSET */
/* UNIFORM_ARRAY_STRIDE */
/* UNIFORM_MATRIX_STRIDE */
/* UNIFORM_IS_ROW_MAJOR */
/* UNIFORM_BLOCK_BINDING */
/* UNIFORM_BLOCK_DATA_SIZE */
/* UNIFORM_BLOCK_NAME_LENGTH */
/* UNIFORM_BLOCK_ACTIVE_UNIFORMS */
/* UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES */
/* UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER */
/* UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER */
/* INVALID_INDEX */
// GL_VERSION_3_2
public const uint CONTEXT_CORE_PROFILE_BIT = 0x00000001;
public const uint CONTEXT_COMPATIBILITY_PROFILE_BIT = 0x00000002;
public const uint LINES_ADJACENCY = 0x000A;
public const uint LINE_STRIP_ADJACENCY = 0x000B;
public const uint TRIANGLES_ADJACENCY = 0x000C;
public const uint TRIANGLE_STRIP_ADJACENCY = 0x000D;
public const uint PROGRAM_POINT_SIZE = 0x8642;
public const uint MAX_GEOMETRY_TEXTURE_IMAGE_UNITS = 0x8C29;
public const uint FRAMEBUFFER_ATTACHMENT_LAYERED = 0x8DA7;
public const uint FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = 0x8DA8;
public const uint GEOMETRY_SHADER = 0x8DD9;
public const uint GEOMETRY_VERTICES_OUT = 0x8916;
public const uint GEOMETRY_INPUT_TYPE = 0x8917;
public const uint GEOMETRY_OUTPUT_TYPE = 0x8918;
public const uint MAX_GEOMETRY_UNIFORM_COMPONENTS = 0x8DDF;
public const uint MAX_GEOMETRY_OUTPUT_VERTICES = 0x8DE0;
public const uint MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS = 0x8DE1;
public const uint MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122;
public const uint MAX_GEOMETRY_INPUT_COMPONENTS = 0x9123;
public const uint MAX_GEOMETRY_OUTPUT_COMPONENTS = 0x9124;
public const uint MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125;
public const uint CONTEXT_PROFILE_MASK = 0x9126;
/* MAX_VARYING_COMPONENTS */
/* FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */
/* Reuse tokens from ARB_depth_clamp */
/* DEPTH_CLAMP */
/* Reuse tokens from ARB_draw_elements_base_vertex (none) */
/* Reuse tokens from ARB_fragment_coord_conventions (none) */
/* Reuse tokens from ARB_provoking_vertex */
/* QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION */
/* FIRST_VERTEX_CONVENTION */
/* LAST_VERTEX_CONVENTION */
/* PROVOKING_VERTEX */
/* Reuse tokens from ARB_seamless_cube_map */
/* TEXTURE_CUBE_MAP_SEAMLESS */
/* Reuse tokens from ARB_sync */
/* MAX_SERVER_WAIT_TIMEOUT */
/* OBJECT_TYPE */
/* SYNC_CONDITION */
/* SYNC_STATUS */
/* SYNC_FLAGS */
/* SYNC_FENCE */
/* SYNC_GPU_COMMANDS_COMPLETE */
/* UNSIGNALED */
/* SIGNALED */
/* ALREADY_SIGNALED */
/* TIMEOUT_EXPIRED */
/* CONDITION_SATISFIED */
/* WAIT_FAILED */
/* TIMEOUT_IGNORED */
/* SYNC_FLUSH_COMMANDS_BIT */
/* TIMEOUT_IGNORED */
/* Reuse tokens from ARB_texture_multisample */
/* SAMPLE_POSITION */
/* SAMPLE_MASK */
/* SAMPLE_MASK_VALUE */
/* MAX_SAMPLE_MASK_WORDS */
/* TEXTURE_2D_MULTISAMPLE */
/* PROXY_TEXTURE_2D_MULTISAMPLE */
/* TEXTURE_2D_MULTISAMPLE_ARRAY */
/* PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY */
/* TEXTURE_BINDING_2D_MULTISAMPLE */
/* TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY */
/* TEXTURE_SAMPLES */
/* TEXTURE_FIXED_SAMPLE_LOCATIONS */
/* SAMPLER_2D_MULTISAMPLE */
/* INT_SAMPLER_2D_MULTISAMPLE */
/* UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE */
/* SAMPLER_2D_MULTISAMPLE_ARRAY */
/* INT_SAMPLER_2D_MULTISAMPLE_ARRAY */
/* UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY */
/* MAX_COLOR_TEXTURE_SAMPLES */
/* MAX_DEPTH_TEXTURE_SAMPLES */
/* MAX_INTEGER_SAMPLES */
/* Don't need to reuse tokens from ARB_vertex_array_bgra since they're already in 1.2 core */
// GL_VERSION_3_3
public const uint VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE;
/* Reuse tokens from ARB_blend_func_extended */
/* SRC1_COLOR */
/* ONE_MINUS_SRC1_COLOR */
/* ONE_MINUS_SRC1_ALPHA */
/* MAX_DUAL_SOURCE_DRAW_BUFFERS */
/* Reuse tokens from ARB_explicit_attrib_location (none) */
/* Reuse tokens from ARB_occlusion_query2 */
/* ANY_SAMPLES_PASSED */
/* Reuse tokens from ARB_sampler_objects */
/* SAMPLER_BINDING */
/* Reuse tokens from ARB_shader_bit_encoding (none) */
/* Reuse tokens from ARB_texture_rgb10_a2ui */
/* RGB10_A2UI */
/* Reuse tokens from ARB_texture_swizzle */
/* TEXTURE_SWIZZLE_R */
/* TEXTURE_SWIZZLE_G */
/* TEXTURE_SWIZZLE_B */
/* TEXTURE_SWIZZLE_A */
/* TEXTURE_SWIZZLE_RGBA */
/* Reuse tokens from ARB_timer_query */
/* TIME_ELAPSED */
/* TIMESTAMP */
/* Reuse tokens from ARB_vertex_type_2_10_10_10_rev */
/* INT_2_10_10_10_REV */
}
}
| |
using System;
using BACnet.Types;
using BACnet.Types.Schemas;
namespace BACnet.Ashrae
{
public abstract partial class EventParameter
{
public abstract Tags Tag { get; }
public bool IsChangeOfBitstring { get { return this.Tag == Tags.ChangeOfBitstring; } }
public ChangeOfBitstring AsChangeOfBitstring { get { return (ChangeOfBitstring)this; } }
public static EventParameter NewChangeOfBitstring(uint timeDelay, BitString56 bitmask, ReadOnlyArray<BitString56> listOfBitstringValues)
{
return new ChangeOfBitstring(timeDelay, bitmask, listOfBitstringValues);
}
public bool IsChangeOfState { get { return this.Tag == Tags.ChangeOfState; } }
public ChangeOfState AsChangeOfState { get { return (ChangeOfState)this; } }
public static EventParameter NewChangeOfState(uint timeDelay, ReadOnlyArray<PropertyStates> listOfValues)
{
return new ChangeOfState(timeDelay, listOfValues);
}
public bool IsChangeOfValue { get { return this.Tag == Tags.ChangeOfValue; } }
public ChangeOfValue AsChangeOfValue { get { return (ChangeOfValue)this; } }
public static EventParameter NewChangeOfValue(uint timeDelay, COVCriteria covCriteria)
{
return new ChangeOfValue(timeDelay, covCriteria);
}
public bool IsCommandFailure { get { return this.Tag == Tags.CommandFailure; } }
public CommandFailure AsCommandFailure { get { return (CommandFailure)this; } }
public static EventParameter NewCommandFailure(uint timeDelay, DeviceObjectPropertyReference feedbackPropertyReference)
{
return new CommandFailure(timeDelay, feedbackPropertyReference);
}
public bool IsFloatingLimit { get { return this.Tag == Tags.FloatingLimit; } }
public FloatingLimit AsFloatingLimit { get { return (FloatingLimit)this; } }
public static EventParameter NewFloatingLimit(uint timeDelay, DeviceObjectPropertyReference setpointReference, float lowDiffLimit, float highDiffLimit, float deadband)
{
return new FloatingLimit(timeDelay, setpointReference, lowDiffLimit, highDiffLimit, deadband);
}
public bool IsOutOfRange { get { return this.Tag == Tags.OutOfRange; } }
public OutOfRange AsOutOfRange { get { return (OutOfRange)this; } }
public static EventParameter NewOutOfRange(uint timeDelay, float lowLimit, float highLimit, float deadband)
{
return new OutOfRange(timeDelay, lowLimit, highLimit, deadband);
}
public bool IsChangeOfLifeSafety { get { return this.Tag == Tags.ChangeOfLifeSafety; } }
public ChangeOfLifeSafety AsChangeOfLifeSafety { get { return (ChangeOfLifeSafety)this; } }
public static EventParameter NewChangeOfLifeSafety(uint timeDelay, ReadOnlyArray<LifeSafetyState> listOfLifeSafetyAlarmValues, ReadOnlyArray<LifeSafetyState> listOfAlarmValues, DeviceObjectPropertyReference modePropertyReference)
{
return new ChangeOfLifeSafety(timeDelay, listOfLifeSafetyAlarmValues, listOfAlarmValues, modePropertyReference);
}
public bool IsExtended { get { return this.Tag == Tags.Extended; } }
public Extended AsExtended { get { return (Extended)this; } }
public static EventParameter NewExtended(uint vendorId, uint extendedEventType, ReadOnlyArray<ExtendedParameter> parameters)
{
return new Extended(vendorId, extendedEventType, parameters);
}
public bool IsBufferReady { get { return this.Tag == Tags.BufferReady; } }
public BufferReady AsBufferReady { get { return (BufferReady)this; } }
public static EventParameter NewBufferReady(uint notificationThreshold, uint previousNotificationCount)
{
return new BufferReady(notificationThreshold, previousNotificationCount);
}
public bool IsUnsignedRange { get { return this.Tag == Tags.UnsignedRange; } }
public UnsignedRange AsUnsignedRange { get { return (UnsignedRange)this; } }
public static EventParameter NewUnsignedRange(uint timeDelay, uint lowLimit, uint highLimit)
{
return new UnsignedRange(timeDelay, lowLimit, highLimit);
}
public static readonly ISchema Schema = new ChoiceSchema(false,
new FieldSchema("ChangeOfBitstring", 0, Value<ChangeOfBitstring>.Schema),
new FieldSchema("ChangeOfState", 1, Value<ChangeOfState>.Schema),
new FieldSchema("ChangeOfValue", 2, Value<ChangeOfValue>.Schema),
new FieldSchema("CommandFailure", 3, Value<CommandFailure>.Schema),
new FieldSchema("FloatingLimit", 4, Value<FloatingLimit>.Schema),
new FieldSchema("OutOfRange", 5, Value<OutOfRange>.Schema),
new FieldSchema("ChangeOfLifeSafety", 8, Value<ChangeOfLifeSafety>.Schema),
new FieldSchema("Extended", 9, Value<Extended>.Schema),
new FieldSchema("BufferReady", 10, Value<BufferReady>.Schema),
new FieldSchema("UnsignedRange", 11, Value<UnsignedRange>.Schema));
public static EventParameter Load(IValueStream stream)
{
EventParameter ret = null;
Tags tag = (Tags)stream.EnterChoice();
switch(tag)
{
case Tags.ChangeOfBitstring:
ret = Value<ChangeOfBitstring>.Load(stream);
break;
case Tags.ChangeOfState:
ret = Value<ChangeOfState>.Load(stream);
break;
case Tags.ChangeOfValue:
ret = Value<ChangeOfValue>.Load(stream);
break;
case Tags.CommandFailure:
ret = Value<CommandFailure>.Load(stream);
break;
case Tags.FloatingLimit:
ret = Value<FloatingLimit>.Load(stream);
break;
case Tags.OutOfRange:
ret = Value<OutOfRange>.Load(stream);
break;
case Tags.ChangeOfLifeSafety:
ret = Value<ChangeOfLifeSafety>.Load(stream);
break;
case Tags.Extended:
ret = Value<Extended>.Load(stream);
break;
case Tags.BufferReady:
ret = Value<BufferReady>.Load(stream);
break;
case Tags.UnsignedRange:
ret = Value<UnsignedRange>.Load(stream);
break;
default:
throw new Exception();
}
stream.LeaveChoice();
return ret;
}
public static void Save(IValueSink sink, EventParameter value)
{
sink.EnterChoice((byte)value.Tag);
switch(value.Tag)
{
case Tags.ChangeOfBitstring:
Value<ChangeOfBitstring>.Save(sink, (ChangeOfBitstring)value);
break;
case Tags.ChangeOfState:
Value<ChangeOfState>.Save(sink, (ChangeOfState)value);
break;
case Tags.ChangeOfValue:
Value<ChangeOfValue>.Save(sink, (ChangeOfValue)value);
break;
case Tags.CommandFailure:
Value<CommandFailure>.Save(sink, (CommandFailure)value);
break;
case Tags.FloatingLimit:
Value<FloatingLimit>.Save(sink, (FloatingLimit)value);
break;
case Tags.OutOfRange:
Value<OutOfRange>.Save(sink, (OutOfRange)value);
break;
case Tags.ChangeOfLifeSafety:
Value<ChangeOfLifeSafety>.Save(sink, (ChangeOfLifeSafety)value);
break;
case Tags.Extended:
Value<Extended>.Save(sink, (Extended)value);
break;
case Tags.BufferReady:
Value<BufferReady>.Save(sink, (BufferReady)value);
break;
case Tags.UnsignedRange:
Value<UnsignedRange>.Save(sink, (UnsignedRange)value);
break;
default:
throw new Exception();
}
sink.LeaveChoice();
}
public enum Tags : byte
{
ChangeOfBitstring = 0,
ChangeOfState = 1,
ChangeOfValue = 2,
CommandFailure = 3,
FloatingLimit = 4,
OutOfRange = 5,
ChangeOfLifeSafety = 6,
Extended = 7,
BufferReady = 8,
UnsignedRange = 9
}
public partial class ChangeOfBitstring : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfBitstring; } }
public uint TimeDelay { get; private set; }
public BitString56 Bitmask { get; private set; }
public ReadOnlyArray<BitString56> ListOfBitstringValues { get; private set; }
public ChangeOfBitstring(uint timeDelay, BitString56 bitmask, ReadOnlyArray<BitString56> listOfBitstringValues)
{
this.TimeDelay = timeDelay;
this.Bitmask = bitmask;
this.ListOfBitstringValues = listOfBitstringValues;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("Bitmask", 1, Value<BitString56>.Schema),
new FieldSchema("ListOfBitstringValues", 2, Value<ReadOnlyArray<BitString56>>.Schema));
public static new ChangeOfBitstring Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var bitmask = Value<BitString56>.Load(stream);
var listOfBitstringValues = Value<ReadOnlyArray<BitString56>>.Load(stream);
stream.LeaveSequence();
return new ChangeOfBitstring(timeDelay, bitmask, listOfBitstringValues);
}
public static void Save(IValueSink sink, ChangeOfBitstring value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<BitString56>.Save(sink, value.Bitmask);
Value<ReadOnlyArray<BitString56>>.Save(sink, value.ListOfBitstringValues);
sink.LeaveSequence();
}
}
public partial class ChangeOfState : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfState; } }
public uint TimeDelay { get; private set; }
public ReadOnlyArray<PropertyStates> ListOfValues { get; private set; }
public ChangeOfState(uint timeDelay, ReadOnlyArray<PropertyStates> listOfValues)
{
this.TimeDelay = timeDelay;
this.ListOfValues = listOfValues;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("ListOfValues", 1, Value<ReadOnlyArray<PropertyStates>>.Schema));
public static new ChangeOfState Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var listOfValues = Value<ReadOnlyArray<PropertyStates>>.Load(stream);
stream.LeaveSequence();
return new ChangeOfState(timeDelay, listOfValues);
}
public static void Save(IValueSink sink, ChangeOfState value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<ReadOnlyArray<PropertyStates>>.Save(sink, value.ListOfValues);
sink.LeaveSequence();
}
}
public partial class ChangeOfValue : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfValue; } }
public uint TimeDelay { get; private set; }
public COVCriteria CovCriteria { get; private set; }
public ChangeOfValue(uint timeDelay, COVCriteria covCriteria)
{
this.TimeDelay = timeDelay;
this.CovCriteria = covCriteria;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("CovCriteria", 1, Value<COVCriteria>.Schema));
public static new ChangeOfValue Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var covCriteria = Value<COVCriteria>.Load(stream);
stream.LeaveSequence();
return new ChangeOfValue(timeDelay, covCriteria);
}
public static void Save(IValueSink sink, ChangeOfValue value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<COVCriteria>.Save(sink, value.CovCriteria);
sink.LeaveSequence();
}
}
public partial class CommandFailure : EventParameter
{
public override Tags Tag { get { return Tags.CommandFailure; } }
public uint TimeDelay { get; private set; }
public DeviceObjectPropertyReference FeedbackPropertyReference { get; private set; }
public CommandFailure(uint timeDelay, DeviceObjectPropertyReference feedbackPropertyReference)
{
this.TimeDelay = timeDelay;
this.FeedbackPropertyReference = feedbackPropertyReference;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("FeedbackPropertyReference", 1, Value<DeviceObjectPropertyReference>.Schema));
public static new CommandFailure Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var feedbackPropertyReference = Value<DeviceObjectPropertyReference>.Load(stream);
stream.LeaveSequence();
return new CommandFailure(timeDelay, feedbackPropertyReference);
}
public static void Save(IValueSink sink, CommandFailure value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<DeviceObjectPropertyReference>.Save(sink, value.FeedbackPropertyReference);
sink.LeaveSequence();
}
}
public partial class FloatingLimit : EventParameter
{
public override Tags Tag { get { return Tags.FloatingLimit; } }
public uint TimeDelay { get; private set; }
public DeviceObjectPropertyReference SetpointReference { get; private set; }
public float LowDiffLimit { get; private set; }
public float HighDiffLimit { get; private set; }
public float Deadband { get; private set; }
public FloatingLimit(uint timeDelay, DeviceObjectPropertyReference setpointReference, float lowDiffLimit, float highDiffLimit, float deadband)
{
this.TimeDelay = timeDelay;
this.SetpointReference = setpointReference;
this.LowDiffLimit = lowDiffLimit;
this.HighDiffLimit = highDiffLimit;
this.Deadband = deadband;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("SetpointReference", 1, Value<DeviceObjectPropertyReference>.Schema),
new FieldSchema("LowDiffLimit", 2, Value<float>.Schema),
new FieldSchema("HighDiffLimit", 3, Value<float>.Schema),
new FieldSchema("Deadband", 4, Value<float>.Schema));
public static new FloatingLimit Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var setpointReference = Value<DeviceObjectPropertyReference>.Load(stream);
var lowDiffLimit = Value<float>.Load(stream);
var highDiffLimit = Value<float>.Load(stream);
var deadband = Value<float>.Load(stream);
stream.LeaveSequence();
return new FloatingLimit(timeDelay, setpointReference, lowDiffLimit, highDiffLimit, deadband);
}
public static void Save(IValueSink sink, FloatingLimit value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<DeviceObjectPropertyReference>.Save(sink, value.SetpointReference);
Value<float>.Save(sink, value.LowDiffLimit);
Value<float>.Save(sink, value.HighDiffLimit);
Value<float>.Save(sink, value.Deadband);
sink.LeaveSequence();
}
}
public partial class OutOfRange : EventParameter
{
public override Tags Tag { get { return Tags.OutOfRange; } }
public uint TimeDelay { get; private set; }
public float LowLimit { get; private set; }
public float HighLimit { get; private set; }
public float Deadband { get; private set; }
public OutOfRange(uint timeDelay, float lowLimit, float highLimit, float deadband)
{
this.TimeDelay = timeDelay;
this.LowLimit = lowLimit;
this.HighLimit = highLimit;
this.Deadband = deadband;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("LowLimit", 1, Value<float>.Schema),
new FieldSchema("HighLimit", 2, Value<float>.Schema),
new FieldSchema("Deadband", 3, Value<float>.Schema));
public static new OutOfRange Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var lowLimit = Value<float>.Load(stream);
var highLimit = Value<float>.Load(stream);
var deadband = Value<float>.Load(stream);
stream.LeaveSequence();
return new OutOfRange(timeDelay, lowLimit, highLimit, deadband);
}
public static void Save(IValueSink sink, OutOfRange value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<float>.Save(sink, value.LowLimit);
Value<float>.Save(sink, value.HighLimit);
Value<float>.Save(sink, value.Deadband);
sink.LeaveSequence();
}
}
public partial class ChangeOfLifeSafety : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfLifeSafety; } }
public uint TimeDelay { get; private set; }
public ReadOnlyArray<LifeSafetyState> ListOfLifeSafetyAlarmValues { get; private set; }
public ReadOnlyArray<LifeSafetyState> ListOfAlarmValues { get; private set; }
public DeviceObjectPropertyReference ModePropertyReference { get; private set; }
public ChangeOfLifeSafety(uint timeDelay, ReadOnlyArray<LifeSafetyState> listOfLifeSafetyAlarmValues, ReadOnlyArray<LifeSafetyState> listOfAlarmValues, DeviceObjectPropertyReference modePropertyReference)
{
this.TimeDelay = timeDelay;
this.ListOfLifeSafetyAlarmValues = listOfLifeSafetyAlarmValues;
this.ListOfAlarmValues = listOfAlarmValues;
this.ModePropertyReference = modePropertyReference;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("ListOfLifeSafetyAlarmValues", 1, Value<ReadOnlyArray<LifeSafetyState>>.Schema),
new FieldSchema("ListOfAlarmValues", 2, Value<ReadOnlyArray<LifeSafetyState>>.Schema),
new FieldSchema("ModePropertyReference", 3, Value<DeviceObjectPropertyReference>.Schema));
public static new ChangeOfLifeSafety Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var listOfLifeSafetyAlarmValues = Value<ReadOnlyArray<LifeSafetyState>>.Load(stream);
var listOfAlarmValues = Value<ReadOnlyArray<LifeSafetyState>>.Load(stream);
var modePropertyReference = Value<DeviceObjectPropertyReference>.Load(stream);
stream.LeaveSequence();
return new ChangeOfLifeSafety(timeDelay, listOfLifeSafetyAlarmValues, listOfAlarmValues, modePropertyReference);
}
public static void Save(IValueSink sink, ChangeOfLifeSafety value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<ReadOnlyArray<LifeSafetyState>>.Save(sink, value.ListOfLifeSafetyAlarmValues);
Value<ReadOnlyArray<LifeSafetyState>>.Save(sink, value.ListOfAlarmValues);
Value<DeviceObjectPropertyReference>.Save(sink, value.ModePropertyReference);
sink.LeaveSequence();
}
}
public partial class Extended : EventParameter
{
public override Tags Tag { get { return Tags.Extended; } }
public uint VendorId { get; private set; }
public uint ExtendedEventType { get; private set; }
public ReadOnlyArray<ExtendedParameter> Parameters { get; private set; }
public Extended(uint vendorId, uint extendedEventType, ReadOnlyArray<ExtendedParameter> parameters)
{
this.VendorId = vendorId;
this.ExtendedEventType = extendedEventType;
this.Parameters = parameters;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("VendorId", 0, Value<uint>.Schema),
new FieldSchema("ExtendedEventType", 1, Value<uint>.Schema),
new FieldSchema("Parameters", 2, Value<ReadOnlyArray<ExtendedParameter>>.Schema));
public static new Extended Load(IValueStream stream)
{
stream.EnterSequence();
var vendorId = Value<uint>.Load(stream);
var extendedEventType = Value<uint>.Load(stream);
var parameters = Value<ReadOnlyArray<ExtendedParameter>>.Load(stream);
stream.LeaveSequence();
return new Extended(vendorId, extendedEventType, parameters);
}
public static void Save(IValueSink sink, Extended value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.VendorId);
Value<uint>.Save(sink, value.ExtendedEventType);
Value<ReadOnlyArray<ExtendedParameter>>.Save(sink, value.Parameters);
sink.LeaveSequence();
}
}
public partial class BufferReady : EventParameter
{
public override Tags Tag { get { return Tags.BufferReady; } }
public uint NotificationThreshold { get; private set; }
public uint PreviousNotificationCount { get; private set; }
public BufferReady(uint notificationThreshold, uint previousNotificationCount)
{
this.NotificationThreshold = notificationThreshold;
this.PreviousNotificationCount = previousNotificationCount;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("NotificationThreshold", 0, Value<uint>.Schema),
new FieldSchema("PreviousNotificationCount", 1, Value<uint>.Schema));
public static new BufferReady Load(IValueStream stream)
{
stream.EnterSequence();
var notificationThreshold = Value<uint>.Load(stream);
var previousNotificationCount = Value<uint>.Load(stream);
stream.LeaveSequence();
return new BufferReady(notificationThreshold, previousNotificationCount);
}
public static void Save(IValueSink sink, BufferReady value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.NotificationThreshold);
Value<uint>.Save(sink, value.PreviousNotificationCount);
sink.LeaveSequence();
}
}
public partial class UnsignedRange : EventParameter
{
public override Tags Tag { get { return Tags.UnsignedRange; } }
public uint TimeDelay { get; private set; }
public uint LowLimit { get; private set; }
public uint HighLimit { get; private set; }
public UnsignedRange(uint timeDelay, uint lowLimit, uint highLimit)
{
this.TimeDelay = timeDelay;
this.LowLimit = lowLimit;
this.HighLimit = highLimit;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("LowLimit", 1, Value<uint>.Schema),
new FieldSchema("HighLimit", 2, Value<uint>.Schema));
public static new UnsignedRange Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var lowLimit = Value<uint>.Load(stream);
var highLimit = Value<uint>.Load(stream);
stream.LeaveSequence();
return new UnsignedRange(timeDelay, lowLimit, highLimit);
}
public static void Save(IValueSink sink, UnsignedRange value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<uint>.Save(sink, value.LowLimit);
Value<uint>.Save(sink, value.HighLimit);
sink.LeaveSequence();
}
}
}
}
| |
using Gtk;
using Gdk;
using Pango;
using System;
using System.Xml;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Moscrif.IDE.Completion;
namespace Moscrif.IDE.Controls
{
[Flags()]
public enum KeyActions
{
None = 0,
Process = 1,
Ignore = 2,
CloseWindow = 4,
Complete = 8
}
public class ListWindow : Gtk.Window
{
internal VScrollbar scrollbar;
ListWidget list;
Widget footer;
VBox vbox;
StringBuilder word = new StringBuilder();
int curPos;
public List<int> FilteredItems {
get {
return list.filteredItems;
}
}
public ListWindow () : base(Gtk.WindowType.Popup)
{
vbox = new VBox ();
HBox box = new HBox ();
list = new ListWidget (this);
list.SelectionChanged += new EventHandler (OnSelectionChanged);
list.ScrollEvent += new ScrollEventHandler (OnScrolled);
box.PackStart (list, true, true, 0);
this.BorderWidth = 1;
scrollbar = new VScrollbar (null);
scrollbar.ValueChanged += new EventHandler (OnScrollChanged);
box.PackStart (scrollbar, false, false, 0);
list.ButtonPressEvent += delegate(object o, ButtonPressEventArgs args) {
if (args.Event.Button == 1 && args.Event.Type == Gdk.EventType.TwoButtonPress)
DoubleClick ();
};
list.WordsFiltered += delegate {
UpdateScrollBar ();
};
list.SizeAllocated += delegate {
UpdateScrollBar ();
};
vbox.PackStart (box, true, true, 0);
Add (vbox);
this.AutoSelect = true;
this.TypeHint = WindowTypeHint.Menu;
this.ShowAll();
}
protected virtual void DoubleClick ()
{
}
public void ShowFooter (Widget w)
{
HideFooter ();
vbox.PackStart (w, false, false, 0);
footer = w;
}
public void HideFooter ()
{
if (footer != null) {
vbox.Remove (footer);
footer = null;
}
}
protected void Reset (bool clearWord)
{
if (clearWord) {
word = new StringBuilder ();
curPos = 0;
}
list.Reset ();
if (DataProvider != null)
ResetSizes ();
}
protected int curXPos, curYPos;
public void ResetSizes ()
{
list.CompletionString = PartialWord;
if (list.filteredItems.Count == 0 && !list.PreviewCompletionString) {
Hide ();
} else {
if (IsRealized && !Visible)
Show ();
}
int width = list.WidthRequest;
int height = list.HeightRequest + (footer != null ? footer.Allocation.Height : 0);
SetSizeRequest (width, height);
if (IsRealized)
Resize (width, height);
}
void UpdateScrollBar ()
{
double pageSize = Math.Max (0, list.VisibleRows);
double upper = Math.Max (0, list.filteredItems.Count - 1);
scrollbar.Adjustment.SetBounds (0, upper, 1, pageSize, pageSize);
if (pageSize >= upper) {
this.scrollbar.Value = -1;
this.scrollbar.Visible = false;
} else {
this.scrollbar.Value = list.Page;
this.scrollbar.Visible = true;
}
}
public IListDataProvider DataProvider {
get;
set;
}
public string CurrentCompletionText {
get {
if (list.SelectionIndex != -1 && list.AutoSelect)
return DataProvider.GetCompletionText (list.SelectionIndex);
return null;
}
}
public int SelectionIndex {
get { return list.SelectionIndex; }
}
public bool AutoSelect {
get { return list.AutoSelect; }
set { list.AutoSelect = value; }
}
public bool SelectionEnabled {
get { return list.SelectionEnabled; }
}
public bool AutoCompleteEmptyMatch {
get { return list.AutoCompleteEmptyMatch; }
set { list.AutoCompleteEmptyMatch = value; }
}
public string DefaultCompletionString {
get {
return list.DefaultCompletionString;
}
set {
list.DefaultCompletionString = value;
}
}
public string PartialWord {
get { return word.ToString (); }
set {
string newword = value;
if (newword.Trim ().Length == 0)
return;
if (word.ToString () != newword) {
word = new StringBuilder (newword);
curPos = newword.Length;
UpdateWordSelection ();
}
}
}
public string CurrentPartialWord {
get {
return !string.IsNullOrEmpty (PartialWord) ? PartialWord : DefaultCompletionString;
}
}
public bool IsUniqueMatch {
get {
/* int pos = list.Selection + 1;
if (DataProvider.ItemCount > pos &&
DataProvider.GetText (pos).ToLower ().StartsWith (CurrentPartialWord.ToLower ()) ||
!(DataProvider.GetText (list.Selection).ToLower ().StartsWith (CurrentPartialWord.ToLower ())))
return false;
*/
return list.filteredItems.Count == 1;
}
}
public ListWidget List {
get { return list; }
}
public bool CompleteWithSpaceOrPunctuation {
get;
set;
}
public KeyActions ProcessKey (Gdk.Key key, char keyChar, Gdk.ModifierType modifier)
{
switch (key) {
case Gdk.Key.Home:
List.Selection = 0;
return KeyActions.Ignore;
case Gdk.Key.End:
List.Selection = List.filteredItems.Count - 1;
return KeyActions.Ignore;
case Gdk.Key.Up:
if ((modifier & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) {
if (!SelectionEnabled /*&& !CompletionWindowManager.ForceSuggestionMode*/)
AutoCompleteEmptyMatch = AutoSelect = true;
if (!List.InCategoryMode) {
List.InCategoryMode = true;
return KeyActions.Ignore;
}
//List.MoveToCategory (-1);
return KeyActions.Ignore;
}
if (SelectionEnabled && list.filteredItems.Count < 2)
return KeyActions.CloseWindow | KeyActions.Process;
if (!SelectionEnabled /*&& !CompletionWindowManager.ForceSuggestionMode*/) {
AutoCompleteEmptyMatch = AutoSelect = true;
} else {
list.MoveCursor (-1);
}
return KeyActions.Ignore;
case Gdk.Key.Down:
if ((modifier & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) {
if (!SelectionEnabled /*&& !CompletionWindowManager.ForceSuggestionMode*/)
AutoCompleteEmptyMatch = AutoSelect = true;
if (!List.InCategoryMode) {
List.InCategoryMode = true;
return KeyActions.Ignore;
}
//List.MoveToCategory (1);
return KeyActions.Ignore;
}
if (SelectionEnabled && list.filteredItems.Count < 2)
return KeyActions.CloseWindow | KeyActions.Process;
if (!SelectionEnabled /*&& !CompletionWindowManager.ForceSuggestionMode*/) {
AutoCompleteEmptyMatch = AutoSelect = true;
} else {
list.MoveCursor (1);
}
return KeyActions.Ignore;
case Gdk.Key.Page_Up:
if (list.filteredItems.Count < 2)
return KeyActions.CloseWindow | KeyActions.Process;
list.MoveCursor (-(list.VisibleRows - 1));
return KeyActions.Ignore;
case Gdk.Key.Page_Down:
if (list.filteredItems.Count < 2)
return KeyActions.CloseWindow | KeyActions.Process;
list.MoveCursor (list.VisibleRows - 1);
return KeyActions.Ignore;
case Gdk.Key.Left:
//if (curPos == 0) return KeyActions.CloseWindow | KeyActions.Process;
//curPos--;
return KeyActions.Process;
case Gdk.Key.BackSpace:
if (curPos == 0 || (modifier & Gdk.ModifierType.ControlMask) != 0)
return KeyActions.CloseWindow | KeyActions.Process;
curPos--;
word.Remove (curPos, 1);
ResetSizes ();
UpdateWordSelection ();
if (word.Length == 0)
return KeyActions.CloseWindow | KeyActions.Process;
return KeyActions.Process;
case Gdk.Key.Right:
//if (curPos == word.Length) return KeyActions.CloseWindow | KeyActions.Process;
//curPos++;
return KeyActions.Process;
case Gdk.Key.Caps_Lock:
case Gdk.Key.Num_Lock:
case Gdk.Key.Scroll_Lock:
return KeyActions.Ignore;
case Gdk.Key.Tab:
//tab always completes current item even if selection is disabled
if (!AutoSelect)
AutoSelect = true;
goto case Gdk.Key.Return;
case Gdk.Key.Return:
case Gdk.Key.ISO_Enter:
case Gdk.Key.Key_3270_Enter:
case Gdk.Key.KP_Enter:
return (!list.AutoSelect ? KeyActions.Process : (KeyActions.Complete | KeyActions.Ignore)) | KeyActions.CloseWindow;
case Gdk.Key.Escape:
return KeyActions.CloseWindow | KeyActions.Ignore;
case Gdk.Key.Control_L:
case Gdk.Key.Control_R:
case Gdk.Key.Alt_L:
case Gdk.Key.Alt_R:
case Gdk.Key.Shift_L:
case Gdk.Key.Shift_R:
case Gdk.Key.ISO_Level3_Shift:
// AltGr
return KeyActions.Process;
}
if (keyChar == '\0')
return KeyActions.Process;
if (keyChar == ' ' && (modifier & ModifierType.ShiftMask) == ModifierType.ShiftMask)
return KeyActions.CloseWindow | KeyActions.Process;
//don't input letters/punctuation etc when non-shift modifiers are active
bool nonShiftModifierActive = ((Gdk.ModifierType.ControlMask | Gdk.ModifierType.MetaMask
| Gdk.ModifierType.Mod1Mask | Gdk.ModifierType.SuperMask)
& modifier) != 0;
if (nonShiftModifierActive)
return KeyActions.Ignore;
const string commitChars = " <>()[]{}=";
if (System.Char.IsLetterOrDigit (keyChar) || keyChar == '_') {
word.Insert (curPos, keyChar);
ResetSizes ();
UpdateWordSelection ();
curPos++;
return KeyActions.Process;
} else if (System.Char.IsPunctuation (keyChar) || commitChars.Contains (keyChar)) {
//punctuation is only accepted if it actually matches an item in the list
word.Insert (curPos, keyChar);
bool hasMismatches;
int match = FindMatchedEntry (CurrentPartialWord, out hasMismatches);
if (match >= 0 && !hasMismatches && keyChar != '<') {
ResetSizes ();
UpdateWordSelection ();
curPos++;
return KeyActions.Process;
} else {
word.Remove (curPos, 1);
}
if (CompleteWithSpaceOrPunctuation && list.SelectionEnabled)
return KeyActions.Complete | KeyActions.Process | KeyActions.CloseWindow;
return KeyActions.CloseWindow | KeyActions.Process;
}
return KeyActions.CloseWindow | KeyActions.Process;
}
public void UpdateWordSelection ()
{
SelectEntry (CurrentPartialWord);
}
//note: finds the full match, or the best partial match
//returns -1 if there is no match at all
class WordComparer : IComparer <KeyValuePair<int, string>>
{
string filterWord;
public WordComparer (string filterWord)
{
this.filterWord = filterWord ?? "";
}
public int Compare (KeyValuePair<int, string> xpair, KeyValuePair<int, string> ypair)
{
string x = xpair.Value;
string y = ypair.Value;
int[] xMatches = ListWidget.Match (filterWord, x) ?? new int[0];
int[] yMatches = ListWidget.Match (filterWord, y) ?? new int[0];
if (xMatches.Length < yMatches.Length)
return 1;
if (xMatches.Length > yMatches.Length)
return -1;
int xExact = 0;
int yExact = 0;
for (int i = 0; i < filterWord.Length; i++) {
if (i < xMatches.Length && filterWord[i] == x[xMatches[i]])
xExact++;
if (i < yMatches.Length && filterWord[i] == y[yMatches[i]])
yExact++;
}
if (xExact < yExact)
return 1;
if (xExact > yExact)
return -1;
// favor words where the match starts sooner
if (xMatches.Length > 0 && yMatches.Length > 0 && xMatches[0] != yMatches[0])
return xMatches[0].CompareTo (yMatches[0]);
int xIndex = xpair.Key;
int yIndex = ypair.Key;
if (x.Length == y.Length)
return xIndex.CompareTo (yIndex);
return x.Length.CompareTo (y.Length);
}
}
protected int FindMatchedEntry (string partialWord, out bool hasMismatches)
{
// default - word with highest match rating in the list.
hasMismatches = true;
int idx = -1;
List<KeyValuePair<int, string>> words = new List<KeyValuePair<int, string>> ();
if (!string.IsNullOrEmpty (partialWord)) {
for (int i = 0; i < list.filteredItems.Count; i++) {
int index = list.filteredItems[i];
string text = DataProvider.GetCompletionText (index);
//Console.WriteLine("partialWord->"+partialWord);
//Console.WriteLine("text->"+text);
if (!ListWidget.Matches (partialWord, text))
continue;
words.Add (new KeyValuePair <int,string> (i, text));
}
}
ListWindow.WordComparer comparer = new WordComparer (partialWord);
if (words.Count > 0) {
words.Sort (comparer);
idx = words[0].Key;
hasMismatches = false;
// exact match found.
if (words[0].Value.ToUpper () == (partialWord ?? "").ToUpper ())
return idx;
}
if (string.IsNullOrEmpty (partialWord) || partialWord.Length <= 2) {
// Search for history matches.
for (int i = 0; i < wordHistory.Count; i++) {
string historyWord = wordHistory[i];
if (ListWidget.Matches (partialWord, historyWord)) {
for (int xIndex = 0; xIndex < list.filteredItems.Count; xIndex++) {
string currentWord = DataProvider.GetCompletionText (list.filteredItems[xIndex]);
if (currentWord == historyWord) {
idx = xIndex;
break;
}
}
}
}
}
return idx;
}
static List<string> wordHistory = new List<string> ();
const int maxHistoryLength = 500;
protected void AddWordToHistory (string word)
{
if (!wordHistory.Contains (word)) {
wordHistory.Add (word);
while (wordHistory.Count > maxHistoryLength)
wordHistory.RemoveAt (0);
} else {
wordHistory.Remove (word);
wordHistory.Add (word);
}
}
public static void ClearHistory ()
{
wordHistory.Clear ();
}
void SelectEntry (int n)
{
if (n >= 0)
list.Selection = n;
}
public virtual void SelectEntry (string s)
{
list.FilterWords ();
/* // disable this, because we select now the last selected entry by default (word history mode)
//when the list is empty, disable the selection or users get annoyed by it accepting
//the top entry automatically
if (string.IsNullOrEmpty (s)) {
ResetSizes ();
list.Selection = 0;
return;
}*/
bool hasMismatches;
int matchedIndex = FindMatchedEntry (s, out hasMismatches);
ResetSizes ();
SelectEntry (matchedIndex);
}
void OnScrollChanged (object o, EventArgs args)
{
list.Page = (int)scrollbar.Value;
}
void OnScrolled (object o, ScrollEventArgs args)
{
switch (args.Event.Direction) {
case ScrollDirection.Up:
scrollbar.Value--;
break;
case ScrollDirection.Down:
scrollbar.Value++;
break;
}
}
void OnSelectionChanged (object o, EventArgs args)
{
scrollbar.Value = list.Page;
OnSelectionChanged ();
}
protected virtual void OnSelectionChanged ()
{
}
protected override bool OnExposeEvent (Gdk.EventExpose args)
{
base.OnExposeEvent (args);
int winWidth, winHeight;
this.GetSize (out winWidth, out winHeight);
this.GdkWindow.DrawRectangle (this.Style.ForegroundGC (StateType.Insensitive), false, 0, 0, winWidth - 1, winHeight - 1);
return true;
}
public int TextOffset {
get { return list.TextOffset + (int)this.BorderWidth; }
}
}
public interface IListDataProvider
{
int ItemCount { get; }
string GetText (int n);
string GetMarkup (int n);
//CompletionCategory GetCompletionCategory (int n);
bool HasMarkup (int n);
string GetCompletionText (int n);
string GetDescription (int n);
Gdk.Pixbuf GetIcon (int n);
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicTextureModule")]
public class DynamicTextureModule : ISharedRegionModule, IDynamicTextureManager
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int DISP_EXPIRE = 1;
public const int DISP_TEMP = 2;
private const int ALL_SIDES = -1;
/// <summary>
/// Record dynamic textures that we can reuse for a given data and parameter combination rather than
/// regenerate.
/// </summary>
/// <remarks>
/// Key is string.Format("{0}{1}", data
/// </remarks>
private Cache m_reuseableDynamicTextures;
private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>();
private Dictionary<string, IDynamicTextureRender> RenderPlugins =
new Dictionary<string, IDynamicTextureRender>();
private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>();
/// <summary>
/// This constructor is only here because of the Unit Tests...
/// Don't use it.
/// </summary>
public DynamicTextureModule()
{
m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
}
/// <summary>
/// If false, then textures which have a low data size are not reused when ReuseTextures = true.
/// </summary>
/// <remarks>
/// LL viewers 3.3.4 and before appear to not fully render textures pulled from the viewer cache if those
/// textures have a relatively high pixel surface but a small data size. Typically, this appears to happen
/// if the data size is smaller than the viewer's discard level 2 size estimate. So if this is setting is
/// false, textures smaller than the calculation in IsSizeReuseable are always regenerated rather than reused
/// to work around this problem.</remarks>
public bool ReuseLowDataTextures { get; set; }
/// <summary>
/// If true then where possible dynamic textures are reused.
/// </summary>
public bool ReuseTextures { get; set; }
#region IDynamicTextureManager Members
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer)
{
return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, SetBlending,
(int)(DISP_TEMP | DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face)
{
if (!RenderPlugins.ContainsKey(contentType))
return UUID.Zero;
Scene scene;
RegisteredScenes.TryGetValue(simID, out scene);
if (scene == null)
return UUID.Zero;
SceneObjectPart part = scene.GetSceneObjectPart(primID);
if (part == null)
return UUID.Zero;
// If we want to reuse dynamic textures then we have to ignore any request from the caller to expire
// them.
if (ReuseTextures)
disp = disp & ~DISP_EXPIRE;
DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID;
updater.PrimID = primID;
updater.ContentType = contentType;
updater.BodyData = data;
updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue;
updater.Face = face;
updater.Url = "Local image";
updater.Disp = disp;
object objReusableTextureUUID = null;
if (ReuseTextures && !updater.BlendWithOldTexture)
{
string reuseableTextureKey = GenerateReusableTextureKey(data, extraParams);
objReusableTextureUUID = m_reuseableDynamicTextures.Get(reuseableTextureKey);
if (objReusableTextureUUID != null)
{
// If something else has removed this temporary asset from the cache, detect and invalidate
// our cached uuid.
if (scene.AssetService.GetMetadata(objReusableTextureUUID.ToString()) == null)
{
m_reuseableDynamicTextures.Invalidate(reuseableTextureKey);
objReusableTextureUUID = null;
}
}
}
// We cannot reuse a dynamic texture if the data is going to be blended with something already there.
if (objReusableTextureUUID == null)
{
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
// m_log.DebugFormat(
// "[DYNAMIC TEXTURE MODULE]: Requesting generation of new dynamic texture for {0} in {1}",
// part.Name, part.ParentGroup.Scene.Name);
RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
}
else
{
// m_log.DebugFormat(
// "[DYNAMIC TEXTURE MODULE]: Reusing cached texture {0} for {1} in {2}",
// objReusableTextureUUID, part.Name, part.ParentGroup.Scene.Name);
// No need to add to updaters as the texture is always the same. Not that this functionality
// apppears to be implemented anyway.
updater.UpdatePart(part, (UUID)objReusableTextureUUID);
}
return updater.UpdaterID;
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer)
{
return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureURL(simID, primID, contentType, url,
extraParams, updateTimer, SetBlending,
(int)(DISP_TEMP | DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending,
int disp, byte AlphaValue, int face)
{
if (RenderPlugins.ContainsKey(contentType))
{
DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID;
updater.PrimID = primID;
updater.ContentType = contentType;
updater.Url = url;
updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue;
updater.Face = face;
updater.Disp = disp;
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
return updater.UpdaterID;
}
return UUID.Zero;
}
public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
if (RenderPlugins.ContainsKey(contentType))
{
RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize);
}
}
public void RegisterRender(string handleType, IDynamicTextureRender render)
{
if (!RenderPlugins.ContainsKey(handleType))
{
RenderPlugins.Add(handleType, render);
}
}
/// <summary>
/// Called by code which actually renders the dynamic texture to supply texture data.
/// </summary>
/// <param name="updaterId"></param>
/// <param name="texture"></param>
public void ReturnData(UUID updaterId, IDynamicTexture texture)
{
DynamicTextureUpdater updater = null;
lock (Updaters)
{
if (Updaters.ContainsKey(updaterId))
{
updater = Updaters[updaterId];
}
}
if (updater != null)
{
if (RegisteredScenes.ContainsKey(updater.SimUUID))
{
Scene scene = RegisteredScenes[updater.SimUUID];
UUID newTextureID = updater.DataReceived(texture.Data, scene);
if (ReuseTextures
&& !updater.BlendWithOldTexture
&& texture.IsReuseable
&& (ReuseLowDataTextures || IsDataSizeReuseable(texture)))
{
m_reuseableDynamicTextures.Store(
GenerateReusableTextureKey(texture.InputCommands, texture.InputParams), newTextureID);
}
}
}
if (updater.UpdateTimer == 0)
{
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Remove(updater.UpdaterID);
}
}
}
}
private string GenerateReusableTextureKey(string data, string extraParams)
{
return string.Format("{0}{1}", data, extraParams);
}
/// <summary>
/// Determines whether the texture is reuseable based on its data size.
/// </summary>
/// <remarks>
/// This is a workaround for a viewer bug where very small data size textures relative to their pixel size
/// are not redisplayed properly when pulled from cache. The calculation here is based on the typical discard
/// level of 2, a 'rate' of 0.125 and 4 components (which makes for a factor of 0.5).
/// </remarks>
/// <returns></returns>
private bool IsDataSizeReuseable(IDynamicTexture texture)
{
// Console.WriteLine("{0} {1}", texture.Size.Width, texture.Size.Height);
int discardLevel2DataThreshold = (int)Math.Ceiling((texture.Size.Width >> 2) * (texture.Size.Height >> 2) * 0.5);
// m_log.DebugFormat(
// "[DYNAMIC TEXTURE MODULE]: Discard level 2 threshold {0}, texture data length {1}",
// discardLevel2DataThreshold, texture.Data.Length);
return discardLevel2DataThreshold < texture.Data.Length;
}
#endregion IDynamicTextureManager Members
#region ISharedRegionModule Members
public string Name
{
get { return "DynamicTextureModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
{
RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
scene.RegisterModuleInterface<IDynamicTextureManager>(this);
}
}
public void Close()
{
}
public void Initialise(IConfigSource config)
{
IConfig texturesConfig = config.Configs["Textures"];
if (texturesConfig != null)
{
ReuseTextures = texturesConfig.GetBoolean("ReuseDynamicTextures", false);
ReuseLowDataTextures = texturesConfig.GetBoolean("ReuseDynamicLowDataTextures", false);
if (ReuseTextures)
{
m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
}
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
RegisteredScenes.Remove(scene.RegionInfo.RegionID);
}
#endregion ISharedRegionModule Members
#region Nested type: DynamicTextureUpdater
public class DynamicTextureUpdater
{
public bool BlendWithOldTexture = false;
public string BodyData;
public string ContentType;
public int Disp;
public int Face;
public byte FrontAlpha = 255;
public string Params;
public UUID PrimID;
public bool SetNewFrontAlpha = false;
public UUID SimUUID;
public UUID UpdaterID;
public int UpdateTimer;
public string Url;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public DynamicTextureUpdater()
{
UpdateTimer = 0;
BodyData = null;
}
/// <summary>
/// Called once new texture data has been received for this updater.
/// </summary>
/// <param name="data"></param>
/// <param name="scene"></param>
/// <param name="isReuseable">True if the data given is reuseable.</param>
/// <returns>The asset UUID given to the incoming data.</returns>
public UUID DataReceived(byte[] data, Scene scene)
{
SceneObjectPart part = scene.GetSceneObjectPart(PrimID);
if (part == null || data == null || data.Length <= 1)
{
string msg =
String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
return UUID.Zero;
}
byte[] assetData = null;
AssetBase oldAsset = null;
if (BlendWithOldTexture)
{
Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
if (defaultFace != null)
{
oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());
if (oldAsset != null)
assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
}
}
if (assetData == null)
{
assetData = new byte[data.Length];
Array.Copy(data, assetData, data.Length);
}
// Create a new asset for user
AssetBase asset
= new AssetBase(
UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
scene.RegionInfo.RegionID.ToString());
asset.Data = assetData;
asset.Description = String.Format("URL image : {0}", Url);
if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
asset.Description = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
asset.Local = true; // dynamic images aren't saved in the assets server
asset.Temporary = ((Disp & DISP_TEMP) != 0);
scene.AssetService.Store(asset); // this will only save the asset in the local asset cache
IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
if (cacheLayerDecode != null)
{
if (!cacheLayerDecode.Decode(asset.FullID, asset.Data))
m_log.WarnFormat(
"[DYNAMIC TEXTURE MODULE]: Decoding of dynamically generated asset {0} for {1} in {2} failed",
asset.ID, part.Name, part.ParentGroup.Scene.Name);
}
UUID oldID = UpdatePart(part, asset.FullID);
if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
{
if (oldAsset == null)
oldAsset = scene.AssetService.Get(oldID.ToString());
if (oldAsset != null)
{
if (oldAsset.Temporary)
{
scene.AssetService.Delete(oldID.ToString());
}
}
}
return asset.FullID;
}
public Bitmap MergeBitMaps(Bitmap front, Bitmap back)
{
Bitmap joint;
Graphics jG;
joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb);
jG = Graphics.FromImage(joint);
jG.DrawImage(back, 0, 0, back.Width, back.Height);
jG.DrawImage(front, 0, 0, back.Width, back.Height);
return joint;
}
/// <summary>
/// Update the given part with the new texture.
/// </summary>
/// <returns>
/// The old texture UUID.
/// </returns>
public UUID UpdatePart(SceneObjectPart part, UUID textureID)
{
UUID oldID;
lock (part)
{
// mostly keep the values from before
Primitive.TextureEntry tmptex = part.Shape.Textures;
// FIXME: Need to return the appropriate ID if only a single face is replaced.
oldID = tmptex.DefaultTexture.TextureID;
if (Face == ALL_SIDES)
{
oldID = tmptex.DefaultTexture.TextureID;
tmptex.DefaultTexture.TextureID = textureID;
}
else
{
try
{
Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
texface.TextureID = textureID;
tmptex.FaceTextures[Face] = texface;
}
catch (Exception)
{
tmptex.DefaultTexture.TextureID = textureID;
}
}
// I'm pretty sure we always want to force this to true
// I'm pretty sure noone whats to set fullbright true if it wasn't true before.
// tmptex.DefaultTexture.Fullbright = true;
part.UpdateTextureEntry(tmptex.GetBytes());
}
return oldID;
}
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha)
{
ManagedImage managedImage;
Image image;
if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image))
{
Bitmap image1 = new Bitmap(image);
if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image))
{
Bitmap image2 = new Bitmap(image);
if (setNewAlpha)
SetAlpha(ref image1, newAlpha);
Bitmap joint = MergeBitMaps(image1, image2);
byte[] result = new byte[0];
try
{
result = OpenJPEG.EncodeFromImage(joint, true);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
e.Message, e.StackTrace);
}
return result;
}
}
return null;
}
private void SetAlpha(ref Bitmap b, byte alpha)
{
for (int w = 0; w < b.Width; w++)
{
for (int h = 0; h < b.Height; h++)
{
b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h)));
}
}
}
}
#endregion Nested type: DynamicTextureUpdater
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.BlogClient ;
using OpenLiveWriter.PostEditor ;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.PostEditor.Configuration.Wizard;
namespace OpenLiveWriter.PostEditor.Configuration.Settings
{
/// <summary>
/// Summary description for AccountPanel.
/// </summary>
public class AccountPanel : WeblogSettingsPanel
{
private System.Windows.Forms.TextBox textBoxWeblogName;
private System.Windows.Forms.Label labelName;
private System.Windows.Forms.GroupBox groupBoxConfiguration;
private System.Windows.Forms.GroupBox groupBoxName;
private System.Windows.Forms.Button buttonEditConfiguration;
private System.Windows.Forms.Label labelWeblogProvider;
private System.Windows.Forms.Label labelHomepageUrl;
private System.Windows.Forms.Label labelUsername;
private System.Windows.Forms.Label labelPassword;
private System.Windows.Forms.TextBox textBoxWeblogProvider;
private System.Windows.Forms.TextBox textBoxHomepageUrl;
private System.Windows.Forms.TextBox textBoxUsername;
private System.Windows.Forms.TextBox textBoxPassword;
private System.Windows.Forms.LinkLabel linkLabelViewCapabilities;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public AccountPanel()
: base()
{
InitializeComponent() ;
UpdateStrings();
}
public AccountPanel(TemporaryBlogSettings targetBlogSettings, TemporaryBlogSettings editableBlogSettings)
: base(targetBlogSettings, editableBlogSettings)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
UpdateStrings();
PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Configuration.Settings.Images.AccountPanelBitmap.png") ;
textBoxPassword.PasswordChar = Res.PasswordChar;
InitializeSettings() ;
// event handlers
textBoxWeblogName.TextChanged +=new EventHandler(textBoxWeblogName_TextChanged);
buttonEditConfiguration.Click +=new EventHandler(buttonEditConfiguration_Click);
textBoxHomepageUrl.RightToLeft = System.Windows.Forms.RightToLeft.No;
if (BidiHelper.IsRightToLeft)
textBoxHomepageUrl.TextAlign = HorizontalAlignment.Right;
}
private void UpdateStrings()
{
this.groupBoxName.Text = Res.Get(StringId.Name);
this.groupBoxConfiguration.Text = Res.Get(StringId.Configuration);
this.labelName.Text = Res.Get(StringId.WeblogName);
this.labelWeblogProvider.Text = Res.Get(StringId.WeblogProvider);
this.labelHomepageUrl.Text = Res.Get(StringId.HomepageUrl);
this.labelUsername.Text = Res.Get(StringId.Username);
this.labelPassword.Text = Res.Get(StringId.Password);
//this.labelCapabilities.Text = Res.Get(StringId.Capabilities);
this.linkLabelViewCapabilities.Text = Res.Get(StringId.ViewWeblogCapabilities);
this.buttonEditConfiguration.Text = Res.Get(StringId.UpdateAccountConfiguration);
this.PanelName = Res.Get(StringId.AccountPanel);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
DisplayHelper.AutoFitSystemButton(buttonEditConfiguration);
}
private void InitializeSettings()
{
WeblogName = TemporaryBlogSettings.BlogName ;
textBoxWeblogProvider.Text = TemporaryBlogSettings.ServiceName ;
textBoxHomepageUrl.Text = TemporaryBlogSettings.HomepageUrl ;
textBoxUsername.Text = TemporaryBlogSettings.Credentials.Username ;
textBoxPassword.Text = TemporaryBlogSettings.Credentials.Password ;
}
public override bool PrepareSave(SwitchToPanel switchToPanel)
{
// validate that we have a post api url
if ( WeblogName == String.Empty )
{
switchToPanel() ;
DisplayMessage.Show( MessageId.RequiredFieldOmitted, FindForm(), TextHelper.StripAmpersands(Res.Get(StringId.WeblogName)) ) ;
textBoxWeblogName.Focus();
return false ;
}
return true ;
}
private void textBoxWeblogName_TextChanged(object sender, EventArgs e)
{
TemporaryBlogSettings.BlogName = WeblogName ;
TemporaryBlogSettingsModified = true ;
}
private void buttonEditConfiguration_Click(object sender, EventArgs e)
{
// make a copy of the temporary settings to edit
TemporaryBlogSettings blogSettings = TemporaryBlogSettings.Clone() as TemporaryBlogSettings ;
// edit account info
if ( WeblogConfigurationWizardController.EditTemporarySettings(FindForm(), blogSettings) )
{
// go ahead and save the settings back
TemporaryBlogSettings.CopyFrom(blogSettings);
// note that settings have been modified
TemporaryBlogSettingsModified = true ;
// reset ui
InitializeSettings() ;
}
}
private string WeblogName
{
get
{
return textBoxWeblogName.Text.Trim() ;
}
set
{
textBoxWeblogName.Text = value ;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBoxWeblogName = new System.Windows.Forms.TextBox();
this.labelName = new System.Windows.Forms.Label();
this.labelWeblogProvider = new System.Windows.Forms.Label();
this.labelHomepageUrl = new System.Windows.Forms.Label();
this.labelUsername = new System.Windows.Forms.Label();
this.groupBoxConfiguration = new System.Windows.Forms.GroupBox();
this.linkLabelViewCapabilities = new System.Windows.Forms.LinkLabel();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.textBoxUsername = new System.Windows.Forms.TextBox();
this.textBoxHomepageUrl = new System.Windows.Forms.TextBox();
this.textBoxWeblogProvider = new System.Windows.Forms.TextBox();
this.buttonEditConfiguration = new System.Windows.Forms.Button();
this.labelPassword = new System.Windows.Forms.Label();
this.groupBoxName = new System.Windows.Forms.GroupBox();
this.groupBoxConfiguration.SuspendLayout();
this.groupBoxName.SuspendLayout();
this.SuspendLayout();
//
// textBoxWeblogName
//
this.textBoxWeblogName.Location = new System.Drawing.Point(16, 37);
this.textBoxWeblogName.Name = "textBoxWeblogName";
this.textBoxWeblogName.Size = new System.Drawing.Size(316, 20);
this.textBoxWeblogName.TabIndex = 1;
this.textBoxWeblogName.Text = "";
//
// labelName
//
this.labelName.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelName.Location = new System.Drawing.Point(16, 19);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(144, 16);
this.labelName.TabIndex = 0;
this.labelName.Text = "&Weblog Name:";
//
// labelWeblogProvider
//
this.labelWeblogProvider.AutoSize = true;
this.labelWeblogProvider.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelWeblogProvider.Location = new System.Drawing.Point(16, 24);
this.labelWeblogProvider.Name = "labelWeblogProvider";
this.labelWeblogProvider.Size = new System.Drawing.Size(50, 16);
this.labelWeblogProvider.TabIndex = 0;
this.labelWeblogProvider.Text = "Provider:";
//
// labelHomepageUrl
//
this.labelHomepageUrl.AutoSize = true;
this.labelHomepageUrl.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelHomepageUrl.Location = new System.Drawing.Point(16, 72);
this.labelHomepageUrl.Name = "labelHomepageUrl";
this.labelHomepageUrl.Size = new System.Drawing.Size(63, 16);
this.labelHomepageUrl.TabIndex = 2;
this.labelHomepageUrl.Text = "Homepage:";
//
// labelUsername
//
this.labelUsername.AutoSize = true;
this.labelUsername.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelUsername.Location = new System.Drawing.Point(16, 120);
this.labelUsername.Name = "labelUsername";
this.labelUsername.Size = new System.Drawing.Size(60, 16);
this.labelUsername.TabIndex = 4;
this.labelUsername.Text = "Username:";
//
// groupBoxConfiguration
//
this.groupBoxConfiguration.Controls.Add(this.linkLabelViewCapabilities);
this.groupBoxConfiguration.Controls.Add(this.textBoxPassword);
this.groupBoxConfiguration.Controls.Add(this.textBoxUsername);
this.groupBoxConfiguration.Controls.Add(this.textBoxHomepageUrl);
this.groupBoxConfiguration.Controls.Add(this.textBoxWeblogProvider);
this.groupBoxConfiguration.Controls.Add(this.buttonEditConfiguration);
this.groupBoxConfiguration.Controls.Add(this.labelPassword);
this.groupBoxConfiguration.Controls.Add(this.labelWeblogProvider);
this.groupBoxConfiguration.Controls.Add(this.labelHomepageUrl);
this.groupBoxConfiguration.Controls.Add(this.labelUsername);
this.groupBoxConfiguration.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxConfiguration.Location = new System.Drawing.Point(8, 115);
this.groupBoxConfiguration.Name = "groupBoxConfiguration";
this.groupBoxConfiguration.Size = new System.Drawing.Size(345, 291);
this.groupBoxConfiguration.TabIndex = 2;
this.groupBoxConfiguration.TabStop = false;
this.groupBoxConfiguration.Text = "Configuration";
//
// linkLabelViewCapabilities
//
this.linkLabelViewCapabilities.AutoSize = true;
this.linkLabelViewCapabilities.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.linkLabelViewCapabilities.Location = new System.Drawing.Point(16, 216);
this.linkLabelViewCapabilities.Name = "linkLabelViewCapabilities";
this.linkLabelViewCapabilities.Size = new System.Drawing.Size(91, 16);
this.linkLabelViewCapabilities.TabIndex = 9;
this.linkLabelViewCapabilities.TabStop = true;
this.linkLabelViewCapabilities.Text = "View Capabilities";
this.linkLabelViewCapabilities.LinkBehavior = LinkBehavior.HoverUnderline;
this.linkLabelViewCapabilities.LinkColor = SystemColors.HotTrack;
this.linkLabelViewCapabilities.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelViewCapabilities_LinkClicked);
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(16, 184);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.PasswordChar = '*';
this.textBoxPassword.ReadOnly = true;
this.textBoxPassword.Size = new System.Drawing.Size(316, 20);
this.textBoxPassword.TabIndex = 7;
this.textBoxPassword.TabStop = false;
this.textBoxPassword.Text = "xxxxxxxxxx";
//
// textBoxUsername
//
this.textBoxUsername.Location = new System.Drawing.Point(16, 136);
this.textBoxUsername.Name = "textBoxUsername";
this.textBoxUsername.ReadOnly = true;
this.textBoxUsername.Size = new System.Drawing.Size(316, 20);
this.textBoxUsername.TabIndex = 5;
this.textBoxUsername.TabStop = false;
this.textBoxUsername.Text = "";
//
// textBoxHomepageUrl
//
this.textBoxHomepageUrl.Location = new System.Drawing.Point(16, 88);
this.textBoxHomepageUrl.Name = "textBoxHomepageUrl";
this.textBoxHomepageUrl.ReadOnly = true;
this.textBoxHomepageUrl.Size = new System.Drawing.Size(316, 20);
this.textBoxHomepageUrl.TabIndex = 3;
this.textBoxHomepageUrl.TabStop = false;
this.textBoxHomepageUrl.Text = "";
//
// textBoxWeblogProvider
//
this.textBoxWeblogProvider.Location = new System.Drawing.Point(16, 40);
this.textBoxWeblogProvider.Name = "textBoxWeblogProvider";
this.textBoxWeblogProvider.ReadOnly = true;
this.textBoxWeblogProvider.Size = new System.Drawing.Size(316, 20);
this.textBoxWeblogProvider.TabIndex = 1;
this.textBoxWeblogProvider.TabStop = false;
this.textBoxWeblogProvider.Text = "Blogger";
//
// buttonEditConfiguration
//
this.buttonEditConfiguration.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonEditConfiguration.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonEditConfiguration.Location = new System.Drawing.Point(154, 255);
this.buttonEditConfiguration.Name = "buttonEditConfiguration";
this.buttonEditConfiguration.Size = new System.Drawing.Size(178, 23);
this.buttonEditConfiguration.TabIndex = 10;
this.buttonEditConfiguration.Text = "&Update Account Configuration...";
//
// labelPassword
//
this.labelPassword.AutoSize = true;
this.labelPassword.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelPassword.Location = new System.Drawing.Point(16, 168);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(57, 16);
this.labelPassword.TabIndex = 6;
this.labelPassword.Text = "Password:";
//
// groupBoxName
//
this.groupBoxName.Controls.Add(this.textBoxWeblogName);
this.groupBoxName.Controls.Add(this.labelName);
this.groupBoxName.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxName.Location = new System.Drawing.Point(8, 32);
this.groupBoxName.Name = "groupBoxName";
this.groupBoxName.Size = new System.Drawing.Size(345, 77);
this.groupBoxName.TabIndex = 1;
this.groupBoxName.TabStop = false;
this.groupBoxName.Text = "Name";
//
// AccountPanel
//
this.Controls.Add(this.groupBoxName);
this.Controls.Add(this.groupBoxConfiguration);
this.Name = "AccountPanel";
this.PanelName = "Account";
this.Size = new System.Drawing.Size(370, 425);
this.Controls.SetChildIndex(this.groupBoxConfiguration, 0);
this.Controls.SetChildIndex(this.groupBoxName, 0);
this.groupBoxConfiguration.ResumeLayout(false);
this.groupBoxName.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void linkLabelViewCapabilities_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
using ( Blog blog = new Blog(TemporaryBlogSettings) )
{
using ( WeblogCapabilitiesForm form = new WeblogCapabilitiesForm(blog.ClientOptions) )
form.ShowDialog(FindForm()) ;
}
}
}
}
| |
// 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.Reflection;
using System.Runtime.Loader;
using System.IO;
namespace My
{
public class CustomAssemblyLoadContext : AssemblyLoadContext
{
public CustomAssemblyLoadContext() : base()
{
}
}
}
public class Program
{
private static bool passed = true;
public static void Assert(bool value, string message = "none")
{
if (!value)
{
Console.WriteLine("FAIL! " + message);
passed = false;
}
}
public static bool AssembliesContainAssembly(AssemblyLoadContext alc, Assembly a)
{
foreach (Assembly b in alc.Assemblies)
{
if (a == b)
{
return true;
}
}
return false;
}
public static bool PropertyAllContainsContext(AssemblyLoadContext alc)
{
foreach (AssemblyLoadContext c in AssemblyLoadContext.All)
{
if (alc == c)
{
return true;
}
}
return false;
}
public static void DefaultName()
{
try
{
Console.WriteLine("DefaultName()");
AssemblyLoadContext alc = AssemblyLoadContext.Default;
Assert(alc == AssemblyLoadContext.GetLoadContext(typeof(Program).Assembly));
Assert(PropertyAllContainsContext(alc));
Assert(AssembliesContainAssembly(alc, typeof(Program).Assembly));
Console.WriteLine(alc.Name);
Assert(alc.Name == "Default");
Console.WriteLine(alc.GetType().ToString());
Assert(alc.GetType().ToString() == "System.Runtime.Loader.DefaultAssemblyLoadContext");
Console.WriteLine(alc.ToString());
Assert(alc.ToString().Contains("\"Default"));
Assert(alc.ToString().Contains("\" System.Runtime.Loader.DefaultAssemblyLoadContext"));
Assert(alc.ToString().Contains(" #"));
}
catch (Exception e)
{
Assert(false, e.ToString());
}
}
public static void AssemblyLoadFileName()
{
try
{
Console.WriteLine("AssemblyLoadFileName()");
String path = typeof(Program).Assembly.Location;
Assembly a = Assembly.LoadFile(path);
Assert(a != typeof(Program).Assembly);
AssemblyLoadContext alc = AssemblyLoadContext.GetLoadContext(a);
Assert(PropertyAllContainsContext(alc));
Assert(AssembliesContainAssembly(alc, a));
Assert(alc != AssemblyLoadContext.Default);
Console.WriteLine(alc.Name);
Assert(alc.Name == String.Format("Assembly.LoadFile({0})", path));
Console.WriteLine(alc.GetType().ToString());
Assert(alc.GetType().ToString() == "System.Runtime.Loader.IndividualAssemblyLoadContext");
Console.WriteLine(alc.ToString());
Assert(alc.ToString().Contains("\"" + String.Format("Assembly.LoadFile({0})", path)));
Assert(alc.ToString().Contains("\" System.Runtime.Loader.IndividualAssemblyLoadContext"));
Assert(alc.ToString().Contains(" #"));
}
catch (Exception e)
{
Assert(false, e.ToString());
}
}
public static void AssemblyLoadByteArrayName()
{
#if runDisabled // This test case fails when the assembly is a ready2run image
try
{
Console.WriteLine("AssemblyLoadByteArrayName()");
String path = typeof(Program).Assembly.Location;
Byte [] byteArray = System.IO.File.ReadAllBytes(path);
Assembly a = Assembly.Load(byteArray);
AssemblyLoadContext alc = AssemblyLoadContext.GetLoadContext(a);
Assert(PropertyAllContainsContext(alc));
Assert(AssembliesContainAssembly(alc, a));
Console.WriteLine(alc.Name);
Assert(alc.Name == "Assembly.Load(byte[], ...)");
Console.WriteLine(alc.GetType().ToString());
Assert(alc.GetType().ToString() == "System.Runtime.Loader.IndividualAssemblyLoadContext");
Console.WriteLine(alc.ToString());
Assert(alc.ToString().Contains("\"Assembly.Load(byte[], ...)\""));
Assert(alc.ToString().Contains("\" System.Runtime.Loader.IndividualAssemblyLoadContext"));
Assert(alc.ToString().Contains(" #"));
}
catch (Exception e)
{
Assert(false, e.ToString());
}
#endif
}
public static void CustomWOName()
{
try
{
Console.WriteLine("CustomWOName()");
// ALC should be a concrete class
AssemblyLoadContext alc = new My.CustomAssemblyLoadContext();
Assert(PropertyAllContainsContext(alc));
Console.WriteLine(alc.Name);
Assert(alc.Name == null);
Console.WriteLine(alc.GetType().ToString());
Assert(alc.GetType().ToString() == "My.CustomAssemblyLoadContext");
Console.WriteLine(alc.ToString());
Assert(alc.ToString().Contains("\"\" "));
Assert(alc.ToString().Contains("\" My.CustomAssemblyLoadContext"));
Assert(alc.ToString().Contains(" #"));
}
catch (Exception e)
{
Assert(false, e.ToString());
}
}
public static void CustomName()
{
try
{
Console.WriteLine("CustomName()");
// ALC should be a concrete class
AssemblyLoadContext alc = new AssemblyLoadContext("CustomName");
Assert(PropertyAllContainsContext(alc));
Console.WriteLine(alc.Name);
Assert(alc.Name == "CustomName");
Console.WriteLine(alc.GetType().ToString());
Assert(alc.GetType().ToString() == "System.Runtime.Loader.AssemblyLoadContext");
Console.WriteLine(alc.ToString());
Assert(alc.ToString().Contains("\"CustomName"));
Assert(alc.ToString().Contains("\" System.Runtime.Loader.AssemblyLoadContext"));
Assert(alc.ToString().Contains(" #"));
}
catch (Exception e)
{
Assert(false, e.ToString());
}
}
public static int Main()
{
foreach (AssemblyLoadContext alc in AssemblyLoadContext.All)
{
Console.WriteLine(alc.ToString());
foreach (Assembly a in alc.Assemblies)
{
Console.WriteLine(a.ToString());
}
}
DefaultName();
AssemblyLoadFileName();
AssemblyLoadByteArrayName();
CustomWOName();
CustomName();
foreach (AssemblyLoadContext alc in AssemblyLoadContext.All)
{
Console.WriteLine(alc.ToString());
foreach (Assembly a in alc.Assemblies)
{
Console.WriteLine(a.ToString());
}
}
if (passed)
{
Console.WriteLine("Test PASSED!");
return 100;
}
else
{
Console.WriteLine("Test FAILED!");
return -1;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, 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.
//-----------------------------------------------------------------------------
///
$SSAOPostFx::overallStrength = 2.0;
// TODO: Add small/large param docs.
// The small radius SSAO settings.
$SSAOPostFx::sRadius = 0.1;
$SSAOPostFx::sStrength = 6.0;
$SSAOPostFx::sDepthMin = 0.1;
$SSAOPostFx::sDepthMax = 1.0;
$SSAOPostFx::sDepthPow = 1.0;
$SSAOPostFx::sNormalTol = 0.0;
$SSAOPostFx::sNormalPow = 1.0;
// The large radius SSAO settings.
$SSAOPostFx::lRadius = 1.0;
$SSAOPostFx::lStrength = 10.0;
$SSAOPostFx::lDepthMin = 0.2;
$SSAOPostFx::lDepthMax = 2.0;
$SSAOPostFx::lDepthPow = 0.2;
$SSAOPostFx::lNormalTol = -0.5;
$SSAOPostFx::lNormalPow = 2.0;
/// Valid values: 0, 1, 2
$SSAOPostFx::quality = 0;
///
$SSAOPostFx::blurDepthTol = 0.001;
///
$SSAOPostFx::blurNormalTol = 0.95;
///
$SSAOPostFx::targetScale = "0.5 0.5";
function SSAOPostFx::onAdd( %this )
{
%this.wasVis = "Uninitialized";
%this.quality = "Uninitialized";
}
function SSAOPostFx::preProcess( %this )
{
if ( $SSAOPostFx::quality !$= %this.quality )
{
%this.quality = mClamp( mRound( $SSAOPostFx::quality ), 0, 2 );
%this.setShaderMacro( "QUALITY", %this.quality );
}
%this.targetScale = $SSAOPostFx::targetScale;
}
function SSAOPostFx::setShaderConsts( %this )
{
%this.setShaderConst( "$overallStrength", $SSAOPostFx::overallStrength );
// Abbreviate is s-small l-large.
%this.setShaderConst( "$sRadius", $SSAOPostFx::sRadius );
%this.setShaderConst( "$sStrength", $SSAOPostFx::sStrength );
%this.setShaderConst( "$sDepthMin", $SSAOPostFx::sDepthMin );
%this.setShaderConst( "$sDepthMax", $SSAOPostFx::sDepthMax );
%this.setShaderConst( "$sDepthPow", $SSAOPostFx::sDepthPow );
%this.setShaderConst( "$sNormalTol", $SSAOPostFx::sNormalTol );
%this.setShaderConst( "$sNormalPow", $SSAOPostFx::sNormalPow );
%this.setShaderConst( "$lRadius", $SSAOPostFx::lRadius );
%this.setShaderConst( "$lStrength", $SSAOPostFx::lStrength );
%this.setShaderConst( "$lDepthMin", $SSAOPostFx::lDepthMin );
%this.setShaderConst( "$lDepthMax", $SSAOPostFx::lDepthMax );
%this.setShaderConst( "$lDepthPow", $SSAOPostFx::lDepthPow );
%this.setShaderConst( "$lNormalTol", $SSAOPostFx::lNormalTol );
%this.setShaderConst( "$lNormalPow", $SSAOPostFx::lNormalPow );
%blur = %this->blurY;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurX;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurY2;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurX2;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
}
function SSAOPostFx::onEnabled( %this )
{
// This tells the AL shaders to reload and sample
// from our #ssaoMask texture target.
$AL::UseSSAOMask = true;
return true;
}
function SSAOPostFx::onDisabled( %this )
{
$AL::UseSSAOMask = false;
}
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( SSAOStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerWrapLinear;
samplerStates[2] = SamplerClampPoint;
};
singleton GFXStateBlockData( SSAOBlurStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton ShaderData( SSAOShader )
{
DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl";
DXPixelShaderFile = "shaders/common/postFx/ssao/SSAO_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl";
OGLPixelShaderFile = "shaders/common/postFx/ssao/gl/SSAO_P.glsl";
samplerNames[0] = "$deferredMap";
samplerNames[1] = "$randNormalTex";
samplerNames[2] = "$powTable";
pixVersion = 3.0;
};
singleton ShaderData( SSAOBlurYShader )
{
DXVertexShaderFile = "shaders/common/postFx/ssao/SSAO_Blur_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/ssao/SSAO_Blur_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/ssao/gl/SSAO_Blur_V.glsl";
OGLPixelShaderFile = "shaders/common/postFx/ssao/gl/SSAO_Blur_P.glsl";
samplerNames[0] = "$occludeMap";
samplerNames[1] = "$deferredMap";
pixVersion = 3.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( SSAOBlurXShader : SSAOBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
singleton PostEffect( SSAOPostFx )
{
allowReflectPass = false;
renderTime = "PFXBeforeBin";
renderBin = "AL_LightBinMgr";
renderPriority = 10;
shader = SSAOShader;
stateBlock = SSAOStateBlock;
texture[0] = "#deferred";
texture[1] = "./noise.png";
texture[2] = "#ssao_pow_table";
target = "$outTex";
targetScale = "0.5 0.5";
targetViewport = "PFXTargetViewport_NamedInTexture0";
singleton PostEffect()
{
internalName = "blurY";
shader = SSAOBlurYShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurX";
shader = SSAOBlurXShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurY2";
shader = SSAOBlurYShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurX2";
shader = SSAOBlurXShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#deferred";
// We write to a mask texture which is then
// read by the lighting shaders to mask ambient.
target = "#ssaoMask";
};
};
/// Just here for debug visualization of the
/// SSAO mask texture used during lighting.
singleton PostEffect( SSAOVizPostFx )
{
allowReflectPass = false;
shader = PFX_PassthruShader;
stateBlock = PFX_DefaultStateBlock;
texture[0] = "#ssaoMask";
target = "$backbuffer";
};
singleton ShaderData( SSAOPowTableShader )
{
DXVertexShaderFile = "shaders/common/postFx/ssao/SSAO_PowerTable_V.hlsl";
DXPixelShaderFile = "shaders/common/postFx/ssao/SSAO_PowerTable_P.hlsl";
OGLVertexShaderFile = "shaders/common/postFx/ssao/gl/SSAO_PowerTable_V.glsl";
OGLPixelShaderFile = "shaders/common/postFx/ssao/gl/SSAO_PowerTable_P.glsl";
pixVersion = 2.0;
};
singleton PostEffect( SSAOPowTablePostFx )
{
shader = SSAOPowTableShader;
stateBlock = PFX_DefaultStateBlock;
renderTime = "PFXTexGenOnDemand";
target = "#ssao_pow_table";
targetFormat = "GFXFormatR16F";
targetSize = "256 1";
};
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.VisualStudio;
namespace Microsoft.VisualStudio.Project
{
public class ImageHandler : IDisposable
{
private ImageList imageList;
private List<IntPtr> iconHandles;
private static volatile object Mutex;
private bool isDisposed;
/// <summary>
/// Initializes the <see cref="RDTListener"/> class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static ImageHandler()
{
Mutex = new object();
}
/// <summary>
/// Builds an empty ImageHandler object.
/// </summary>
public ImageHandler()
{
}
/// <summary>
/// Builds an ImageHandler object from a Stream providing the bitmap that
/// stores the images for the image list.
/// </summary>
public ImageHandler(Stream resourceStream)
{
if(null == resourceStream)
{
throw new ArgumentNullException("resourceStream");
}
imageList = Utilities.GetImageList(resourceStream);
}
/// <summary>
/// Builds an ImageHandler object from an ImageList object.
/// </summary>
public ImageHandler(ImageList list)
{
if(null == list)
{
throw new ArgumentNullException("list");
}
imageList = list;
}
/// <summary>
/// Closes the ImageHandler object freeing its resources.
/// </summary>
public void Close()
{
if(null != iconHandles)
{
foreach(IntPtr hnd in iconHandles)
{
if(hnd != IntPtr.Zero)
{
NativeMethods.DestroyIcon(hnd);
}
}
iconHandles = null;
}
if(null != imageList)
{
imageList.Dispose();
imageList = null;
}
}
/// <summary>
/// Add an image to the ImageHandler.
/// </summary>
/// <param name="image">the image object to be added.</param>
public void AddImage(Image image)
{
if(null == image)
{
throw new ArgumentNullException("image");
}
if(null == imageList)
{
imageList = new ImageList();
}
imageList.Images.Add(image);
if(null != iconHandles)
{
iconHandles.Add(IntPtr.Zero);
}
}
/// <summary>
/// Get or set the ImageList object for this ImageHandler.
/// </summary>
public ImageList ImageList
{
get { return imageList; }
set
{
Close();
imageList = value;
}
}
/// <summary>
/// Returns the handle to an icon build from the image of index
/// iconIndex in the image list.
/// </summary>
public IntPtr GetIconHandle(int iconIndex)
{
// Verify that the object is in a consistent state.
if((null == imageList))
{
throw new InvalidOperationException();
}
// Make sure that the list of handles is initialized.
if(null == iconHandles)
{
InitHandlesList();
}
// Verify that the index is inside the expected range.
if((iconIndex < 0) || (iconIndex >= iconHandles.Count))
{
throw new ArgumentOutOfRangeException("iconIndex");
}
// Check if the icon is in the cache.
if(IntPtr.Zero == iconHandles[iconIndex])
{
Bitmap bitmap = imageList.Images[iconIndex] as Bitmap;
// If the image is not a bitmap, then we can not build the icon,
// so we have to return a null handle.
if(null == bitmap)
{
return IntPtr.Zero;
}
iconHandles[iconIndex] = bitmap.GetHicon();
}
return iconHandles[iconIndex];
}
private void InitHandlesList()
{
iconHandles = new List<IntPtr>(imageList.Images.Count);
for(int i = 0; i < imageList.Images.Count; ++i)
{
iconHandles.Add(IntPtr.Zero);
}
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void Dispose(bool disposing)
{
if(!this.isDisposed)
{
lock(Mutex)
{
if(disposing)
{
this.imageList.Dispose();
}
this.isDisposed = true;
}
}
}
}
}
| |
/*
* 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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Provides a means of distributing output from enumerators from a dedicated separate thread
/// </summary>
public class BaseDataExchange
{
private int _sleepInterval = 1;
private volatile bool _isStopping = false;
private Func<Exception, bool> _isFatalError;
private readonly string _name;
private readonly object _enumeratorsWriteLock = new object();
private readonly ConcurrentDictionary<Symbol, DataHandler> _dataHandlers;
private ConcurrentDictionary<Symbol, EnumeratorHandler> _enumerators;
/// <summary>
/// Gets or sets how long this thread will sleep when no data is available
/// </summary>
public int SleepInterval
{
get { return _sleepInterval; }
set { if (value > -1) _sleepInterval = value; }
}
/// <summary>
/// Gets a name for this exchange
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseDataExchange"/>
/// </summary>
/// <param name="name">A name for this exchange</param>
/// <param name="enumerators">The enumerators to fanout</param>
public BaseDataExchange(string name)
{
_name = name;
_isFatalError = x => false;
_dataHandlers = new ConcurrentDictionary<Symbol, DataHandler>();
_enumerators = new ConcurrentDictionary<Symbol, EnumeratorHandler>();
}
/// <summary>
/// Adds the enumerator to this exchange. If it has already been added
/// then it will remain registered in the exchange only once
/// </summary>
/// <param name="handler">The handler to use when this symbol's data is encountered</param>
public void AddEnumerator(EnumeratorHandler handler)
{
_enumerators[handler.Symbol] = handler;
}
/// <summary>
/// Adds the enumerator to this exchange. If it has already been added
/// then it will remain registered in the exchange only once
/// </summary>
/// <param name="symbol">A unique symbol used to identify this enumerator</param>
/// <param name="enumerator">The enumerator to be added</param>
/// <param name="shouldMoveNext">Function used to determine if move next should be called on this
/// enumerator, defaults to always returning true</param>
/// <param name="enumeratorFinished">Delegate called when the enumerator move next returns false</param>
public void AddEnumerator(Symbol symbol, IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<EnumeratorHandler> enumeratorFinished = null)
{
var enumeratorHandler = new EnumeratorHandler(symbol, enumerator, shouldMoveNext);
if (enumeratorFinished != null)
{
enumeratorHandler.EnumeratorFinished += (sender, args) => enumeratorFinished(args);
}
AddEnumerator(enumeratorHandler);
}
/// <summary>
/// Sets the specified function as the error handler. This function
/// returns true if it is a fatal error and queue consumption should
/// cease.
/// </summary>
/// <param name="isFatalError">The error handling function to use when an
/// error is encountered during queue consumption. Returns true if queue
/// consumption should be stopped, returns false if queue consumption should
/// continue</param>
public void SetErrorHandler(Func<Exception, bool> isFatalError)
{
// default to false;
_isFatalError = isFatalError ?? (x => false);
}
/// <summary>
/// Sets the specified hander function to handle data for the handler's symbol
/// </summary>
/// <param name="handler">The handler to use when this symbol's data is encountered</param>
/// <returns>An identifier that can be used to remove this handler</returns>
public void SetDataHandler(DataHandler handler)
{
_dataHandlers[handler.Symbol] = handler;
}
/// <summary>
/// Sets the specified hander function to handle data for the handler's symbol
/// </summary>
/// <param name="symbol">The symbol whose data is to be handled</param>
/// <param name="handler">The handler to use when this symbol's data is encountered</param>
/// <returns>An identifier that can be used to remove this handler</returns>
public void SetDataHandler(Symbol symbol, Action<BaseData> handler)
{
var dataHandler = new DataHandler(symbol);
dataHandler.DataEmitted += (sender, args) => handler(args);
SetDataHandler(dataHandler);
}
/// <summary>
/// Removes the handler with the specified identifier
/// </summary>
/// <param name="symbol">The symbol to remove handlers for</param>
public bool RemoveDataHandler(Symbol symbol)
{
DataHandler handler;
return _dataHandlers.TryRemove(symbol, out handler);
}
/// <summary>
/// Removes and returns enumerator handler with the specified symbol.
/// The removed handler is returned, null if not found
/// </summary>
public EnumeratorHandler RemoveEnumerator(Symbol symbol)
{
EnumeratorHandler handler;
if (_enumerators.TryRemove(symbol, out handler))
{
handler.OnEnumeratorFinished();
handler.Enumerator.Dispose();
}
return handler;
}
/// <summary>
/// Begins consumption of the wrapped <see cref="IDataQueueHandler"/> on
/// a separate thread
/// </summary>
/// <param name="token">A cancellation token used to signal to stop</param>
public void Start(CancellationToken? token = null)
{
Log.Trace("BaseDataExchange({0}) Starting...", Name);
_isStopping = false;
ConsumeEnumerators(token ?? CancellationToken.None);
}
/// <summary>
/// Ends consumption of the wrapped <see cref="IDataQueueHandler"/>
/// </summary>
public void Stop()
{
Log.Trace("BaseDataExchange({0}) Stopping...", Name);
_isStopping = true;
}
/// <summary> Entry point for queue consumption </summary>
/// <param name="token">A cancellation token used to signal to stop</param>
/// <remarks> This function only returns after <see cref="Stop"/> is called or the token is cancelled</remarks>
private void ConsumeEnumerators(CancellationToken token)
{
while (true)
{
if (_isStopping || token.IsCancellationRequested)
{
_isStopping = true;
var request = token.IsCancellationRequested ? "Cancellation requested" : "Stop requested";
Log.Trace("BaseDataExchange({0}).ConsumeQueue(): {1}. Exiting...", Name, request);
return;
}
try
{
// call move next each enumerator and invoke the appropriate handlers
var handled = false;
foreach (var kvp in _enumerators)
{
var enumeratorHandler = kvp.Value;
var enumerator = enumeratorHandler.Enumerator;
// check to see if we should advance this enumerator
if (!enumeratorHandler.ShouldMoveNext()) continue;
if (!enumerator.MoveNext())
{
enumeratorHandler.OnEnumeratorFinished();
enumeratorHandler.Enumerator.Dispose();
_enumerators.TryRemove(enumeratorHandler.Symbol, out enumeratorHandler);
continue;
}
if (enumerator.Current == null) continue;
// if the enumerator is configured to handle it, then do it, don't pass to data handlers
if (enumeratorHandler.HandlesData)
{
handled = true;
enumeratorHandler.HandleData(enumerator.Current);
continue;
}
// invoke the correct handler
DataHandler dataHandler;
if (_dataHandlers.TryGetValue(enumerator.Current.Symbol, out dataHandler))
{
handled = true;
dataHandler.OnDataEmitted(enumerator.Current);
}
}
// if we didn't handle anything on this past iteration, take a nap
if (!handled && _sleepInterval != 0)
{
Thread.Sleep(_sleepInterval);
}
}
catch (Exception err)
{
Log.Error(err);
if (_isFatalError(err))
{
Log.Trace("BaseDataExchange({0}).ConsumeQueue(): Fatal error encountered. Exiting...", Name);
return;
}
}
}
}
/// <summary>
/// Handler used to handle data emitted from enumerators
/// </summary>
public class DataHandler
{
/// <summary>
/// Event fired when MoveNext returns true and Current is non-null
/// </summary>
public event EventHandler<BaseData> DataEmitted;
/// <summary>
/// The symbol this handler handles
/// </summary>
public readonly Symbol Symbol;
/// <summary>
/// Initializes a new instance of the <see cref="DataHandler"/> class
/// </summary>
/// <param name="symbol">The symbol whose data is to be handled</param>
public DataHandler(Symbol symbol)
{
Symbol = symbol;
}
/// <summary>
/// Event invocator for the <see cref="DataEmitted"/> event
/// </summary>
/// <param name="data">The data being emitted</param>
public void OnDataEmitted(BaseData data)
{
var handler = DataEmitted;
if (handler != null) handler(this, data);
}
}
/// <summary>
/// Handler used to manage a single enumerator's move next/end of stream behavior
/// </summary>
public class EnumeratorHandler
{
private readonly Func<bool> _shouldMoveNext;
private readonly Action<BaseData> _handleData;
/// <summary>
/// Event fired when MoveNext returns false
/// </summary>
public event EventHandler<EnumeratorHandler> EnumeratorFinished;
/// <summary>
/// A unique symbol used to identify this enumerator
/// </summary>
public readonly Symbol Symbol;
/// <summary>
/// The enumerator this handler handles
/// </summary>
public readonly IEnumerator<BaseData> Enumerator;
/// <summary>
/// Determines whether or not this handler is to be used for handling the
/// data emitted. This is useful when enumerators are not for a single symbol,
/// such is the case with universe subscriptions
/// </summary>
public readonly bool HandlesData;
/// <summary>
/// Initializes a new instance of the <see cref="EnumeratorHandler"/> class
/// </summary>
/// <param name="symbol">The symbol to identify this enumerator</param>
/// <param name="enumerator">The enumeator this handler handles</param>
/// <param name="shouldMoveNext">Predicate function used to determine if we should call move next
/// on the symbol's enumerator</param>
/// <param name="handleData">Handler for data if HandlesData=true</param>
public EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<BaseData> handleData = null)
{
Symbol = symbol;
Enumerator = enumerator;
HandlesData = handleData != null;
_handleData = handleData ?? (data => { });
_shouldMoveNext = shouldMoveNext ?? (() => true);
}
/// <summary>
/// Initializes a new instance of the <see cref="EnumeratorHandler"/> class
/// </summary>
/// <param name="symbol">The symbol to identify this enumerator</param>
/// <param name="enumerator">The enumeator this handler handles</param>
/// <param name="handlesData">True if this handler will handle the data, false otherwise</param>
protected EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, bool handlesData)
{
Symbol = symbol;
HandlesData = handlesData;
Enumerator = enumerator;
_handleData = data => { };
_shouldMoveNext = () => true;
}
/// <summary>
/// Event invocator for the <see cref="EnumeratorFinished"/> event
/// </summary>
public virtual void OnEnumeratorFinished()
{
var handler = EnumeratorFinished;
if (handler != null) handler(this, this);
}
/// <summary>
/// Returns true if this enumerator should move next
/// </summary>
public virtual bool ShouldMoveNext()
{
return _shouldMoveNext();
}
/// <summary>
/// Handles the specified data.
/// </summary>
/// <param name="data">The data to be handled</param>
public virtual void HandleData(BaseData data)
{
_handleData(data);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace RFIDLIB
{
#if REMOVED
public delegate void RFIDLIB_EVENT_CALLBACK(UIntPtr wparam, UIntPtr lparam); //stdcall
class rfidlib_def
{
// Air protocol id
public const int RFID_APL_UNKNOWN_ID = 0;
public const int RFID_APL_ISO15693_ID = 1;
public const int RFID_APL_ISO14443A_ID = 2;
// ISO15693 Tag type id
public const int RFID_UNKNOWN_PICC_ID = 0;
public const int RFID_ISO15693_PICC_ICODE_SLI_ID = 1;
public const int RFID_ISO15693_PICC_TI_HFI_PLUS_ID = 2;
public const int RFID_ISO15693_PICC_ST_M24LRXX_ID = 3; /* ST M24 serial */
public const int RFID_ISO15693_PICC_FUJ_MB89R118C_ID = 4;
public const int RFID_ISO15693_PICC_ST_M24LR64_ID = 5;
public const int RFID_ISO15693_PICC_ST_M24LR16E_ID = 6;
public const int RFID_ISO15693_PICC_ICODE_SLIX_ID = 7;
public const int RFID_ISO15693_PICC_TIHFI_STANDARD_ID = 8;
public const int RFID_ISO15693_PICC_TIHFI_PRO_ID = 9;
public const int RFID_ISO15693_PICC_ICODE_SLIX2_ID = 10;
public const int RFID_ISO15693_PICC_CIT83128_ID = 11;
//ISO14443a tag type id
public const int RFID_ISO14443A_PICC_NXP_ULTRALIGHT_ID = 1;
public const int RFID_ISO14443A_PICC_NXP_MIFARE_S50_ID = 2;
public const int RFID_ISO14443A_PICC_NXP_MIFARE_S70_ID = 3;
//Inventory type
public const int AI_TYPE_NEW = 1; // new antenna inventory (reset RF power)
public const int AI_TYPE_CONTINUE = 2; // continue antenna inventory ;
// Move position
public const int RFID_NO_SEEK = 0; // No seeking
public const int RFID_SEEK_FIRST = 1; // Seek first
public const int RFID_SEEK_NEXT = 2; // Seek next
public const int RFID_SEEK_LAST = 3; // Seek last
/*
usb enum information
*/
public const int HID_ENUM_INF_TYPE_SERIALNUM = 1;
public const int HID_ENUM_INF_TYPE_DRIVERPATH = 2;
public const int INVEN_STOP_TRIGGER_TYPE_Tms = 0;
public const int INVEN_STOP_TRIGGER_TYPE_N_attempt = 1;
public const int INVEN_STOP_TRIGGER_TYPE_N_found = 2;
public const int INVEN_STOP_TRIGGER_TYPE_TIMEOUT = 3;
/*
* Open connection string
*/
public const string CONNSTR_NAME_RDTYPE = "RDType";
public const string CONNSTR_NAME_COMMTYPE = "CommType";
public const string CONNSTR_NAME_COMMTYPE_COM = "COM";
public const string CONNSTR_NAME_COMMTYPE_USB = "USB";
public const string CONNSTR_NAME_COMMTYPE_NET = "NET";
//HID Param
public const string CONNSTR_NAME_HIDADDRMODE = "AddrMode";
public const string CONNSTR_NAME_HIDSERNUM = "SerNum";
//COM Param
public const string CONNSTR_NAME_COMNAME = "COMName";
public const string CONNSTR_NAME_COMBARUD = "BaudRate";
public const string CONNSTR_NAME_COMFRAME = "Frame";
public const string CONNSTR_NAME_BUSADDR = "BusAddr";
//TCP,UDP
public const string CONNSTR_NAME_REMOTEIP = "RemoteIP";
public const string CONNSTR_NAME_REMOTEPORT = "RemotePort";
public const string CONNSTR_NAME_LOCALIP = "LocalIP";
/*
* Get loaded reader driver option
*/
public const string LOADED_RDRDVR_OPT_CATALOG = "CATALOG";
public const string LOADED_RDRDVR_OPT_NAME = "NAME";
public const string LOADED_RDRDVR_OPT_ID = "ID";
public const string LOADED_RDRDVR_OPT_COMMTYPESUPPORTED = "COMM_TYPE_SUPPORTED";
/*
* Reader driver type
*/
public const string RDRDVR_TYPE_READER = "Reader";// general reader
public const string RDRDVR_TYPE_MTGATE = "MTGate";// meeting gate
public const string RDRDVR_TYPE_LSGATE = "LSGate";// Library secure gate
/* supported product type */
public const byte COMMTYPE_COM_EN = 0x01;
public const byte COMMTYPE_USB_EN = 0x02;
public const byte COMMTYPE_NET_EN = 0x04;
//iso18000p6C session
public const byte ISO18000p6C_S0 = 0;
public const byte ISO18000p6C_S1 = 1;
public const byte ISO18000p6C_S2 = 2;
public const byte ISO18000p6C_S3 = 3;
//iso18000p6c target
public const byte ISO18000p6C_TARGET_A = 0x00;
public const byte ISO18000p6C_TARGET_B = 0x01;
//iso18000p6C Q
public const byte ISO18000p6C_Dynamic_Q = 0xff;
public const UInt32 ISO18000p6C_META_BIT_MASK_EPC = 0x01;
public const UInt32 ISO18000P6C_META_BIT_MASK_TIMESTAMP = 0x02;
public const UInt32 ISO18000P6C_META_BIT_MASK_FREQUENCY = 0x04;
public const UInt32 ISO18000p6C_META_BIT_MASK_RSSI = 0x08;
public const UInt32 ISO18000P6C_META_BIT_MASK_READCOUNT = 0x10;
public const UInt32 ISO18000P6C_META_BIT_MASK_TAGDATA = 0x20;
}
#endif
public delegate void RFIDLIB_EVENT_CALLBACK(UIntPtr wparam, UIntPtr lparam); //stdcall
class rfidlib_def
{
// Air protocol id
public const int RFID_APL_UNKNOWN_ID = 0;
public const int RFID_APL_ISO15693_ID = 1;
public const int RFID_APL_ISO14443A_ID = 2;
// ISO15693 Tag type id
public const int RFID_UNKNOWN_PICC_ID = 0;
public const int RFID_ISO15693_PICC_ICODE_SLI_ID = 1;
public const int RFID_ISO15693_PICC_TI_HFI_PLUS_ID = 2;
public const int RFID_ISO15693_PICC_ST_M24LRXX_ID = 3; /* ST M24 serial */
public const int RFID_ISO15693_PICC_FUJ_MB89R118C_ID = 4;
public const int RFID_ISO15693_PICC_ST_M24LR64_ID = 5;
public const int RFID_ISO15693_PICC_ST_M24LR16E_ID = 6;
public const int RFID_ISO15693_PICC_ICODE_SLIX_ID = 7;
public const int RFID_ISO15693_PICC_TIHFI_STANDARD_ID = 8;
public const int RFID_ISO15693_PICC_TIHFI_PRO_ID = 9;
public const int RFID_ISO15693_PICC_ICODE_SLIX2_ID = 10;
public const int RFID_ISO15693_PICC_CIT83128_ID = 11;
//ISO14443a tag type id
public const int RFID_ISO14443A_PICC_NXP_ULTRALIGHT_ID = 1;
public const int RFID_ISO14443A_PICC_NXP_MIFARE_S50_ID = 2;
public const int RFID_ISO14443A_PICC_NXP_MIFARE_S70_ID = 3;
//Inventory type
public const int AI_TYPE_NEW = 1; // new antenna inventory (reset RF power)
public const int AI_TYPE_CONTINUE = 2; // continue antenna inventory ;
// Move position
public const int RFID_NO_SEEK = 0; // No seeking
public const int RFID_SEEK_FIRST = 1; // Seek first
public const int RFID_SEEK_NEXT = 2; // Seek next
public const int RFID_SEEK_LAST = 3; // Seek last
/*
usb enum information
*/
public const int HID_ENUM_INF_TYPE_SERIALNUM = 1;
public const int HID_ENUM_INF_TYPE_DRIVERPATH = 2;
public const int INVEN_STOP_TRIGGER_TYPE_Tms = 0;
public const int INVEN_STOP_TRIGGER_TYPE_N_attempt = 1;
public const int INVEN_STOP_TRIGGER_TYPE_N_found = 2;
public const int INVEN_STOP_TRIGGER_TYPE_TIMEOUT = 3;
/*
* Open connection string
*/
public const string CONNSTR_NAME_RDTYPE = "RDType";
public const string CONNSTR_NAME_COMMTYPE = "CommType";
public const string CONNSTR_NAME_COMMTYPE_COM = "COM";
public const string CONNSTR_NAME_COMMTYPE_USB = "USB";
public const string CONNSTR_NAME_COMMTYPE_NET = "NET";
//HID Param
public const string CONNSTR_NAME_HIDADDRMODE = "AddrMode";
public const string CONNSTR_NAME_HIDSERNUM = "SerNum";
//COM Param
public const string CONNSTR_NAME_COMNAME = "COMName";
public const string CONNSTR_NAME_COMBARUD = "BaudRate";
public const string CONNSTR_NAME_COMFRAME = "Frame";
public const string CONNSTR_NAME_BUSADDR = "BusAddr";
//TCP,UDP
public const string CONNSTR_NAME_REMOTEIP = "RemoteIP";
public const string CONNSTR_NAME_REMOTEPORT = "RemotePort";
public const string CONNSTR_NAME_LOCALIP = "LocalIP";
/*
* Get loaded reader driver option
*/
public const string LOADED_RDRDVR_OPT_CATALOG = "CATALOG";
public const string LOADED_RDRDVR_OPT_NAME = "NAME";
public const string LOADED_RDRDVR_OPT_ID = "ID";
public const string LOADED_RDRDVR_OPT_COMMTYPESUPPORTED = "COMM_TYPE_SUPPORTED";
/*
* Reader driver type
*/
public const string RDRDVR_TYPE_READER = "Reader";// general reader
public const string RDRDVR_TYPE_MTGATE = "MTGate";// meeting gate
public const string RDRDVR_TYPE_LSGATE = "LSGate";// Library secure gate
/* supported product type */
public const byte COMMTYPE_COM_EN = 0x01;
public const byte COMMTYPE_USB_EN = 0x02;
public const byte COMMTYPE_NET_EN = 0x04;
//iso18000p6C session
public const byte ISO18000p6C_S0 = 0;
public const byte ISO18000p6C_S1 = 1;
public const byte ISO18000p6C_S2 = 2;
public const byte ISO18000p6C_S3 = 3;
//ISO18000p6C Memory bank
public const uint ISO18000p6C_MEM_BANK_RFU = 0x00;
public const uint ISO18000p6C_MEM_BANK_EPC = 0x01;
public const uint ISO18000p6C_MEM_BANK_TID = 0x02;
public const uint ISO18000p6C_MEM_BANK_USER = 0x03;
//iso18000p6c target
public const byte ISO18000p6C_TARGET_A = 0x00;
public const byte ISO18000p6C_TARGET_B = 0x01;
//iso18000p6C Q
public const byte ISO18000p6C_Dynamic_Q = 0xff;
public const UInt32 ISO18000p6C_META_BIT_MASK_EPC = 0x01;
public const UInt32 ISO18000P6C_META_BIT_MASK_TIMESTAMP = 0x02;
public const UInt32 ISO18000P6C_META_BIT_MASK_FREQUENCY = 0x04;
public const UInt32 ISO18000p6C_META_BIT_MASK_RSSI = 0x08;
public const UInt32 ISO18000P6C_META_BIT_MASK_READCOUNT = 0x10;
public const UInt32 ISO18000P6C_META_BIT_MASK_TAGDATA = 0x20;
public const uint ISO18000p6C_SELECT_TARGET_INV_S0 = 0x00;
public const uint ISO18000p6C_SELECT_TARGET_INV_S1 = 0x01;
public const uint ISO18000p6C_SELECT_TARGET_INV_S2 = 0x02;
public const uint ISO18000p6C_SELECT_TARGET_INV_S3 = 0x03;
public const uint ISO18000p6C_SELECT_TARGET_INV_SL = 0x04;
}
}
| |
// Keep this file CodeMaid organised and cleaned
using ClosedXML.Excel;
using ClosedXML.Excel.CalcEngine;
using ClosedXML.Excel.CalcEngine.Exceptions;
using NUnit.Framework;
using System;
using System.Linq;
namespace ClosedXML.Tests.Excel.CalcEngine
{
[TestFixture]
public class StatisticalTests
{
private double tolerance = 1e-6;
private XLWorkbook workbook;
[Test]
public void Average()
{
double value;
value = workbook.Evaluate("AVERAGE(-27.5,93.93,64.51,-70.56)").CastTo<double>();
Assert.AreEqual(15.095, value, tolerance);
var ws = workbook.Worksheets.First();
value = ws.Evaluate("AVERAGE(G3:G45)").CastTo<double>();
Assert.AreEqual(49.3255814, value, tolerance);
Assert.That(() => ws.Evaluate("AVERAGE(D3:D45)"), Throws.TypeOf<ApplicationException>());
}
[Test]
public void Count()
{
var ws = workbook.Worksheets.First();
int value;
value = ws.Evaluate(@"=COUNT(D3:D45)").CastTo<int>();
Assert.AreEqual(0, value);
value = ws.Evaluate(@"=COUNT(G3:G45)").CastTo<int>();
Assert.AreEqual(43, value);
value = ws.Evaluate(@"=COUNT(G:G)").CastTo<int>();
Assert.AreEqual(43, value);
value = workbook.Evaluate(@"=COUNT(Data!G:G)").CastTo<int>();
Assert.AreEqual(43, value);
}
[Test]
public void CountA()
{
var ws = workbook.Worksheets.First();
int value;
value = ws.Evaluate(@"=COUNTA(D3:D45)").CastTo<int>();
Assert.AreEqual(43, value);
value = ws.Evaluate(@"=COUNTA(G3:G45)").CastTo<int>();
Assert.AreEqual(43, value);
value = ws.Evaluate(@"=COUNTA(G:G)").CastTo<int>();
Assert.AreEqual(44, value);
value = workbook.Evaluate(@"=COUNTA(Data!G:G)").CastTo<int>();
Assert.AreEqual(44, value);
}
[Test]
public void CountBlank()
{
var ws = workbook.Worksheets.First();
int value;
value = ws.Evaluate(@"=COUNTBLANK(B:B)").CastTo<int>();
Assert.AreEqual(1048532, value);
value = ws.Evaluate(@"=COUNTBLANK(D43:D49)").CastTo<int>();
Assert.AreEqual(4, value);
value = ws.Evaluate(@"=COUNTBLANK(E3:E45)").CastTo<int>();
Assert.AreEqual(0, value);
value = ws.Evaluate(@"=COUNTBLANK(A1)").CastTo<int>();
Assert.AreEqual(1, value);
Assert.Throws<NoValueAvailableException>(() => workbook.Evaluate(@"=COUNTBLANK(E3:E45)"));
Assert.Throws<ExpressionParseException>(() => ws.Evaluate(@"=COUNTBLANK()"));
Assert.Throws<ExpressionParseException>(() => ws.Evaluate(@"=COUNTBLANK(A3:A45,E3:E45)"));
}
[Test]
public void CountIf()
{
var ws = workbook.Worksheets.First();
int value;
value = ws.Evaluate(@"=COUNTIF(D3:D45,""Central"")").CastTo<int>();
Assert.AreEqual(24, value);
value = ws.Evaluate(@"=COUNTIF(D:D,""Central"")").CastTo<int>();
Assert.AreEqual(24, value);
value = workbook.Evaluate(@"=COUNTIF(Data!D:D,""Central"")").CastTo<int>();
Assert.AreEqual(24, value);
}
[TestCase(@"=COUNTIF(Data!E:E, ""J*"")", 13)]
[TestCase(@"=COUNTIF(Data!E:E, ""*i*"")", 21)]
[TestCase(@"=COUNTIF(Data!E:E, ""*in*"")", 9)]
[TestCase(@"=COUNTIF(Data!E:E, ""*i*l"")", 9)]
[TestCase(@"=COUNTIF(Data!E:E, ""*i?e*"")", 9)]
[TestCase(@"=COUNTIF(Data!E:E, ""*o??s*"")", 10)]
[TestCase(@"=COUNTIF(Data!X1:X1000, """")", 1000)]
[TestCase(@"=COUNTIF(Data!E1:E44, """")", 1)]
public void CountIf_ConditionWithWildcards(string formula, int expectedResult)
{
var ws = workbook.Worksheets.First();
int value = ws.Evaluate(formula).CastTo<int>();
Assert.AreEqual(expectedResult, value);
}
[TestCase(@"=COUNTIF(A1:A10, 1)", 1)]
[TestCase(@"=COUNTIF(A1:A10, 2.0)", 1)]
[TestCase(@"=COUNTIF(A1:A10, ""3"")", 2)]
[TestCase(@"=COUNTIF(A1:A10, 3)", 2)]
[TestCase(@"=COUNTIF(A1:A10, 43831)", 1)]
[TestCase(@"=COUNTIF(A1:A10, DATE(2020, 1, 1))", 1)]
[TestCase(@"=COUNTIF(A1:A10, TRUE)", 1)]
public void CountIf_MixedData(string formula, int expected)
{
// We follow to Excel's convention.
// Excel treats 1 and TRUE as unequal, but 3 and "3" as equal
// LibreOffice Calc handles some SUMIF and COUNTIF differently, e.g. it treats 1 and TRUE as equal, but 3 and "3" differently
var ws = workbook.Worksheet("MixedData");
Assert.AreEqual(expected, ws.Evaluate(formula));
}
[TestCase("x", @"=COUNTIF(A1:A1, ""?"")", 1)]
[TestCase("x", @"=COUNTIF(A1:A1, ""~?"")", 0)]
[TestCase("?", @"=COUNTIF(A1:A1, ""~?"")", 1)]
[TestCase("~?", @"=COUNTIF(A1:A1, ""~?"")", 0)]
[TestCase("~?", @"=COUNTIF(A1:A1, ""~~~?"")", 1)]
[TestCase("?", @"=COUNTIF(A1:A1, ""~~?"")", 0)]
[TestCase("~?", @"=COUNTIF(A1:A1, ""~~?"")", 1)]
[TestCase("~x", @"=COUNTIF(A1:A1, ""~~?"")", 1)]
[TestCase("*", @"=COUNTIF(A1:A1, ""~*"")", 1)]
[TestCase("~*", @"=COUNTIF(A1:A1, ""~*"")", 0)]
[TestCase("~*", @"=COUNTIF(A1:A1, ""~~~*"")", 1)]
[TestCase("*", @"=COUNTIF(A1:A1, ""~~*"")", 0)]
[TestCase("~*", @"=COUNTIF(A1:A1, ""~~*"")", 1)]
[TestCase("~x", @"=COUNTIF(A1:A1, ""~~*"")", 1)]
[TestCase("~xyz", @"=COUNTIF(A1:A1, ""~~*"")", 1)]
public void CountIf_MoreWildcards(string cellContent, string formula, int expectedResult)
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
ws.Cell(1, 1).Value = cellContent;
Assert.AreEqual(expectedResult, (double)ws.Evaluate(formula));
}
}
[TestCase("=COUNTIFS(B1:D1, \"=Yes\")", 1)]
[TestCase("=COUNTIFS(B1:B4, \"=Yes\", C1:C4, \"=Yes\")", 2)]
[TestCase("= COUNTIFS(B4:D4, \"=Yes\", B2:D2, \"=Yes\")", 1)]
public void CountIfs_ReferenceExample1FromExcelDocumentations(
string formula,
int expectedOutcome)
{
using (var wb = new XLWorkbook())
{
wb.ReferenceStyle = XLReferenceStyle.A1;
var ws = wb.AddWorksheet("Sheet1");
ws.Cell(1, 1).Value = "Davidoski";
ws.Cell(1, 2).Value = "Yes";
ws.Cell(1, 3).Value = "No";
ws.Cell(1, 4).Value = "No";
ws.Cell(2, 1).Value = "Burke";
ws.Cell(2, 2).Value = "Yes";
ws.Cell(2, 3).Value = "Yes";
ws.Cell(2, 4).Value = "No";
ws.Cell(3, 1).Value = "Sundaram";
ws.Cell(3, 2).Value = "Yes";
ws.Cell(3, 3).Value = "Yes";
ws.Cell(3, 4).Value = "Yes";
ws.Cell(4, 1).Value = "Levitan";
ws.Cell(4, 2).Value = "No";
ws.Cell(4, 3).Value = "Yes";
ws.Cell(4, 4).Value = "Yes";
Assert.AreEqual(expectedOutcome, ws.Evaluate(formula));
}
}
[Test]
public void CountIfs_SingleCondition()
{
var ws = workbook.Worksheets.First();
int value;
value = ws.Evaluate(@"=COUNTIFS(D3:D45,""Central"")").CastTo<int>();
Assert.AreEqual(24, value);
value = ws.Evaluate(@"=COUNTIFS(D:D,""Central"")").CastTo<int>();
Assert.AreEqual(24, value);
value = workbook.Evaluate(@"=COUNTIFS(Data!D:D,""Central"")").CastTo<int>();
Assert.AreEqual(24, value);
}
[TestCase(@"=COUNTIFS(Data!E:E, ""J*"")", 13)]
[TestCase(@"=COUNTIFS(Data!E:E, ""*i*"")", 21)]
[TestCase(@"=COUNTIFS(Data!E:E, ""*in*"")", 9)]
[TestCase(@"=COUNTIFS(Data!E:E, ""*i*l"")", 9)]
[TestCase(@"=COUNTIFS(Data!E:E, ""*i?e*"")", 9)]
[TestCase(@"=COUNTIFS(Data!E:E, ""*o??s*"")", 10)]
[TestCase(@"=COUNTIFS(Data!X1:X1000, """")", 1000)]
[TestCase(@"=COUNTIFS(Data!E1:E44, """")", 1)]
public void CountIfs_SingleConditionWithWildcards(string formula, int expectedResult)
{
var ws = workbook.Worksheets.First();
int value = ws.Evaluate(formula).CastTo<int>();
Assert.AreEqual(expectedResult, value);
}
[OneTimeTearDown]
public void Dispose()
{
workbook.Dispose();
}
[TestCase(@"H3:H45", ExpectedResult = 7.51126069234216)]
[TestCase(@"H:H", ExpectedResult = 7.51126069234216)]
[TestCase(@"Data!H:H", ExpectedResult = 7.51126069234216)]
[TestCase(@"H3:H10", ExpectedResult = 5.26214814727941)]
[TestCase(@"H3:H20", ExpectedResult = 7.01281435054797)]
[TestCase(@"H3:H30", ExpectedResult = 7.00137389296182)]
[TestCase(@"H3:H3", ExpectedResult = 1.99)]
[TestCase(@"H10:H20", ExpectedResult = 8.37855107505682)]
[TestCase(@"H15:H20", ExpectedResult = 15.8927310267677)]
[TestCase(@"H20:H30", ExpectedResult = 7.14321227391814)]
[DefaultFloatingPointTolerance(1e-12)]
public double Geomean(string sourceValue)
{
return workbook.Worksheets.First().Evaluate($"=GEOMEAN({sourceValue})").CastTo<double>();
}
[TestCase("D3:D45", typeof(NumberException), "No numeric parameters.")]
[TestCase("-1, 0, 3", typeof(NumberException), "Incorrect parameters. Use only positive numbers in your data.")]
public void Geomean_IncorrectCases(string sourceValue, Type exceptionType, string exceptionMessage)
{
var ws = workbook.Worksheets.First();
Assert.Throws(
Is.TypeOf(exceptionType).And.Message.EqualTo(exceptionMessage),
() => ws.Evaluate($"=GEOMEAN({sourceValue})"));
}
[SetUp]
public void Init()
{
// Make sure tests run on a deterministic culture
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
workbook = SetupWorkbook();
}
[TestCase(@"H3:H45", ExpectedResult = 94145.5271162791)]
[TestCase(@"H:H", ExpectedResult = 94145.5271162791)]
[TestCase(@"Data!H:H", ExpectedResult = 94145.5271162791)]
[TestCase(@"H3:H10", ExpectedResult = 411.5)]
[TestCase(@"H3:H20", ExpectedResult = 13604.2067611111)]
[TestCase(@"H3:H30", ExpectedResult = 14231.0694)]
[TestCase(@"H3:H3", ExpectedResult = 0)]
[TestCase(@"H10:H20", ExpectedResult = 12713.7600909091)]
[TestCase(@"H15:H20", ExpectedResult = 10827.2200833333)]
[TestCase(@"H20:H30", ExpectedResult = 477.132272727273)]
[DefaultFloatingPointTolerance(1e-10)]
public double DevSq(string sourceValue)
{
return workbook.Worksheets.First().Evaluate($"=DEVSQ({sourceValue})").CastTo<double>();
}
[TestCase("D3:D45", typeof(CellValueException), "No numeric parameters.")]
public void Devsq_IncorrectCases(string sourceValue, Type exceptionType, string exceptionMessage)
{
var ws = workbook.Worksheets.First();
Assert.Throws(
Is.TypeOf(exceptionType).And.Message.EqualTo(exceptionMessage),
() => ws.Evaluate($"=DEVSQ({sourceValue})"));
}
[TestCase(0, ExpectedResult = 0)]
[TestCase(0.2, ExpectedResult = 0.202732554054082)]
[TestCase(0.25, ExpectedResult = 0.255412811882995)]
[TestCase(0.3296001056, ExpectedResult = 0.342379555936801)]
[TestCase(-0.36, ExpectedResult = -0.37688590118819)]
[TestCase(-0.000003, ExpectedResult = -0.00000299999999998981)]
[TestCase(-0.063453535345348, ExpectedResult = -0.0635389037459617)]
[TestCase(0.559015883901589171354964, ExpectedResult = 0.631400600322212)]
[TestCase(0.2691496, ExpectedResult = 0.275946780611959)]
[TestCase(-0.10674142, ExpectedResult = -0.107149608461448)]
[DefaultFloatingPointTolerance(1e-12)]
public double Fisher(double sourceValue)
{
return XLWorkbook.EvaluateExpr($"=FISHER({sourceValue})").CastTo<double>();
}
// TODO : the string case will be treated correctly when Coercion is implemented better
//[TestCase("asdf", typeof(CellValueException), "Parameter non numeric.")]
[TestCase("5", typeof(NumberException), "Incorrect value. Should be: -1 > x < 1.")]
[TestCase("-1", typeof(NumberException), "Incorrect value. Should be: -1 > x < 1.")]
[TestCase("1", typeof(NumberException), "Incorrect value. Should be: -1 > x < 1.")]
public void Fisher_IncorrectCases(string sourceValue, Type exceptionType, string exceptionMessage)
{
Assert.Throws(
Is.TypeOf(exceptionType).And.Message.EqualTo(exceptionMessage),
() => XLWorkbook.EvaluateExpr($"=FISHER({sourceValue})"));
}
[Test]
public void Max()
{
var ws = workbook.Worksheets.First();
int value;
value = ws.Evaluate(@"=MAX(D3:D45)").CastTo<int>();
Assert.AreEqual(0, value);
value = ws.Evaluate(@"=MAX(G3:G45)").CastTo<int>();
Assert.AreEqual(96, value);
value = ws.Evaluate(@"=MAX(G:G)").CastTo<int>();
Assert.AreEqual(96, value);
value = workbook.Evaluate(@"=MAX(Data!G:G)").CastTo<int>();
Assert.AreEqual(96, value);
}
[Test]
public void Min()
{
var ws = workbook.Worksheets.First();
int value;
value = ws.Evaluate(@"=MIN(D3:D45)").CastTo<int>();
Assert.AreEqual(0, value);
value = ws.Evaluate(@"=MIN(G3:G45)").CastTo<int>();
Assert.AreEqual(2, value);
value = ws.Evaluate(@"=MIN(G:G)").CastTo<int>();
Assert.AreEqual(2, value);
value = workbook.Evaluate(@"=MIN(Data!G:G)").CastTo<int>();
Assert.AreEqual(2, value);
}
[Test]
public void StDev()
{
var ws = workbook.Worksheets.First();
double value;
Assert.That(() => ws.Evaluate(@"=STDEV(D3:D45)"), Throws.TypeOf<ApplicationException>());
value = ws.Evaluate(@"=STDEV(H3:H45)").CastTo<double>();
Assert.AreEqual(47.34511769, value, tolerance);
value = ws.Evaluate(@"=STDEV(H:H)").CastTo<double>();
Assert.AreEqual(47.34511769, value, tolerance);
value = workbook.Evaluate(@"=STDEV(Data!H:H)").CastTo<double>();
Assert.AreEqual(47.34511769, value, tolerance);
}
[Test]
public void StDevP()
{
var ws = workbook.Worksheets.First();
double value;
Assert.That(() => ws.Evaluate(@"=STDEVP(D3:D45)"), Throws.InvalidOperationException);
value = ws.Evaluate(@"=STDEVP(H3:H45)").CastTo<double>();
Assert.AreEqual(46.79135458, value, tolerance);
value = ws.Evaluate(@"=STDEVP(H:H)").CastTo<double>();
Assert.AreEqual(46.79135458, value, tolerance);
value = workbook.Evaluate(@"=STDEVP(Data!H:H)").CastTo<double>();
Assert.AreEqual(46.79135458, value, tolerance);
}
[TestCase(@"=SUMIF(A1:A10, 1, A1:A10)", 1)]
[TestCase(@"=SUMIF(A1:A10, 2.0, A1:A10)", 2)]
[TestCase(@"=SUMIF(A1:A10, 3, A1:A10)", 3)]
[TestCase(@"=SUMIF(A1:A10, ""3"", A1:A10)", 3)]
[TestCase(@"=SUMIF(A1:A10, 43831, A1:A10)", 43831)]
[TestCase(@"=SUMIF(A1:A10, DATE(2020, 1, 1), A1:A10)", 43831)]
[TestCase(@"=SUMIF(A1:A10, TRUE, A1:A10)", 0)]
public void SumIf_MixedData(string formula, double expected)
{
// We follow to Excel's convention.
// Excel treats 1 and TRUE as unequal, but 3 and "3" as equal
// LibreOffice Calc handles some SUMIF and COUNTIF differently, e.g. it treats 1 and TRUE as equal, but 3 and "3" differently
var ws = workbook.Worksheet("MixedData");
Assert.AreEqual(expected, ws.Evaluate(formula));
}
[Test]
[TestCase("COUNT(G:I,G:G,H:I)", 258d, Description = "COUNT overlapping columns")]
[TestCase("COUNT(6:8,6:6,7:8)", 30d, Description = "COUNT overlapping rows")]
[TestCase("COUNTBLANK(H:J)", 3145640d, Description = "COUNTBLANK columns")]
[TestCase("COUNTBLANK(7:9)", 49128d, Description = "COUNTBLANK rows")]
[TestCase("COUNT(1:1048576)", 216d, Description = "COUNT worksheet")]
[TestCase("COUNTBLANK(1:1048576)", 17179868831d, Description = "COUNTBLANK worksheet")]
[TestCase("SUM(H:J)", 20501.15d, Description = "SUM columns")]
[TestCase("SUM(4:5)", 85366.12d, Description = "SUM rows")]
[TestCase("SUMIF(G:G,50,H:H)", 24.98d, Description = "SUMIF columns")]
[TestCase("SUMIF(G23:G52,\"\",H3:H32)", 53.24d, Description = "SUMIF ranges")]
[TestCase("SUMIFS(H:H,G:G,50,I:I,\">900\")", 19.99d, Description = "SUMIFS columns")]
public void TallySkipsEmptyCells(string formulaA1, double expectedResult)
{
using (var wb = SetupWorkbook())
{
var ws = wb.Worksheets.First();
//Let's pre-initialize cells we need so they didn't affect the result
ws.Range("A1:J45").Style.Fill.BackgroundColor = XLColor.Amber;
ws.Cell("ZZ1000").Value = 1;
int initialCount = (ws as XLWorksheet).Internals.CellsCollection.Count;
var actualResult = (double)ws.Evaluate(formulaA1);
int cellsCount = (ws as XLWorksheet).Internals.CellsCollection.Count;
Assert.AreEqual(expectedResult, actualResult, tolerance);
Assert.AreEqual(initialCount, cellsCount);
}
}
[Test]
public void Var()
{
var ws = workbook.Worksheets.First();
double value;
Assert.That(() => ws.Evaluate(@"=VAR(D3:D45)"), Throws.InvalidOperationException);
value = ws.Evaluate(@"=VAR(H3:H45)").CastTo<double>();
Assert.AreEqual(2241.560169, value, tolerance);
value = ws.Evaluate(@"=VAR(H:H)").CastTo<double>();
Assert.AreEqual(2241.560169, value, tolerance);
value = workbook.Evaluate(@"=VAR(Data!H:H)").CastTo<double>();
Assert.AreEqual(2241.560169, value, tolerance);
}
[Test]
public void VarP()
{
var ws = workbook.Worksheets.First();
double value;
Assert.That(() => ws.Evaluate(@"=VARP(D3:D45)"), Throws.InvalidOperationException);
value = ws.Evaluate(@"=VARP(H3:H45)").CastTo<double>();
Assert.AreEqual(2189.430863, value, tolerance);
value = ws.Evaluate(@"=VARP(H:H)").CastTo<double>();
Assert.AreEqual(2189.430863, value, tolerance);
value = workbook.Evaluate(@"=VARP(Data!H:H)").CastTo<double>();
Assert.AreEqual(2189.430863, value, tolerance);
}
private XLWorkbook SetupWorkbook()
{
var wb = new XLWorkbook();
var ws1 = wb.AddWorksheet("Data");
var data = new object[]
{
new {Id=1, OrderDate = DateTime.Parse("2015-01-06"), Region = "East", Rep = "Jones", Item = "Pencil", Units = 95, UnitCost = 1.99, Total = 189.05 },
new {Id=2, OrderDate = DateTime.Parse("2015-01-23"), Region = "Central", Rep = "Kivell", Item = "Binder", Units = 50, UnitCost = 19.99, Total = 999.5},
new {Id=3, OrderDate = DateTime.Parse("2015-02-09"), Region = "Central", Rep = "Jardine", Item = "Pencil", Units = 36, UnitCost = 4.99, Total = 179.64},
new {Id=4, OrderDate = DateTime.Parse("2015-02-26"), Region = "Central", Rep = "Gill", Item = "Pen", Units = 27, UnitCost = 19.99, Total = 539.73},
new {Id=5, OrderDate = DateTime.Parse("2015-03-15"), Region = "West", Rep = "Sorvino", Item = "Pencil", Units = 56, UnitCost = 2.99, Total = 167.44},
new {Id=6, OrderDate = DateTime.Parse("2015-04-01"), Region = "East", Rep = "Jones", Item = "Binder", Units = 60, UnitCost = 4.99, Total = 299.4},
new {Id=7, OrderDate = DateTime.Parse("2015-04-18"), Region = "Central", Rep = "Andrews", Item = "Pencil", Units = 75, UnitCost = 1.99, Total = 149.25},
new {Id=8, OrderDate = DateTime.Parse("2015-05-05"), Region = "Central", Rep = "Jardine", Item = "Pencil", Units = 90, UnitCost = 4.99, Total = 449.1},
new {Id=9, OrderDate = DateTime.Parse("2015-05-22"), Region = "West", Rep = "Thompson", Item = "Pencil", Units = 32, UnitCost = 1.99, Total = 63.68},
new {Id=10, OrderDate = DateTime.Parse("2015-06-08"), Region = "East", Rep = "Jones", Item = "Binder", Units = 60, UnitCost = 8.99, Total = 539.4},
new {Id=11, OrderDate = DateTime.Parse("2015-06-25"), Region = "Central", Rep = "Morgan", Item = "Pencil", Units = 90, UnitCost = 4.99, Total = 449.1},
new {Id=12, OrderDate = DateTime.Parse("2015-07-12"), Region = "East", Rep = "Howard", Item = "Binder", Units = 29, UnitCost = 1.99, Total = 57.71},
new {Id=13, OrderDate = DateTime.Parse("2015-07-29"), Region = "East", Rep = "Parent", Item = "Binder", Units = 81, UnitCost = 19.99, Total = 1619.19},
new {Id=14, OrderDate = DateTime.Parse("2015-08-15"), Region = "East", Rep = "Jones", Item = "Pencil", Units = 35, UnitCost = 4.99, Total = 174.65},
new {Id=15, OrderDate = DateTime.Parse("2015-09-01"), Region = "Central", Rep = "Smith", Item = "Desk", Units = 2, UnitCost = 125, Total = 250},
new {Id=16, OrderDate = DateTime.Parse("2015-09-18"), Region = "East", Rep = "Jones", Item = "Pen Set", Units = 16, UnitCost = 15.99, Total = 255.84},
new {Id=17, OrderDate = DateTime.Parse("2015-10-05"), Region = "Central", Rep = "Morgan", Item = "Binder", Units = 28, UnitCost = 8.99, Total = 251.72},
new {Id=18, OrderDate = DateTime.Parse("2015-10-22"), Region = "East", Rep = "Jones", Item = "Pen", Units = 64, UnitCost = 8.99, Total = 575.36},
new {Id=19, OrderDate = DateTime.Parse("2015-11-08"), Region = "East", Rep = "Parent", Item = "Pen", Units = 15, UnitCost = 19.99, Total = 299.85},
new {Id=20, OrderDate = DateTime.Parse("2015-11-25"), Region = "Central", Rep = "Kivell", Item = "Pen Set", Units = 96, UnitCost = 4.99, Total = 479.04},
new {Id=21, OrderDate = DateTime.Parse("2015-12-12"), Region = "Central", Rep = "Smith", Item = "Pencil", Units = 67, UnitCost = 1.29, Total = 86.43},
new {Id=22, OrderDate = DateTime.Parse("2015-12-29"), Region = "East", Rep = "Parent", Item = "Pen Set", Units = 74, UnitCost = 15.99, Total = 1183.26},
new {Id=23, OrderDate = DateTime.Parse("2016-01-15"), Region = "Central", Rep = "Gill", Item = "Binder", Units = 46, UnitCost = 8.99, Total = 413.54},
new {Id=24, OrderDate = DateTime.Parse("2016-02-01"), Region = "Central", Rep = "Smith", Item = "Binder", Units = 87, UnitCost = 15, Total = 1305},
new {Id=25, OrderDate = DateTime.Parse("2016-02-18"), Region = "East", Rep = "Jones", Item = "Binder", Units = 4, UnitCost = 4.99, Total = 19.96},
new {Id=26, OrderDate = DateTime.Parse("2016-03-07"), Region = "West", Rep = "Sorvino", Item = "Binder", Units = 7, UnitCost = 19.99, Total = 139.93},
new {Id=27, OrderDate = DateTime.Parse("2016-03-24"), Region = "Central", Rep = "Jardine", Item = "Pen Set", Units = 50, UnitCost = 4.99, Total = 249.5},
new {Id=28, OrderDate = DateTime.Parse("2016-04-10"), Region = "Central", Rep = "Andrews", Item = "Pencil", Units = 66, UnitCost = 1.99, Total = 131.34},
new {Id=29, OrderDate = DateTime.Parse("2016-04-27"), Region = "East", Rep = "Howard", Item = "Pen", Units = 96, UnitCost = 4.99, Total = 479.04},
new {Id=30, OrderDate = DateTime.Parse("2016-05-14"), Region = "Central", Rep = "Gill", Item = "Pencil", Units = 53, UnitCost = 1.29, Total = 68.37},
new {Id=31, OrderDate = DateTime.Parse("2016-05-31"), Region = "Central", Rep = "Gill", Item = "Binder", Units = 80, UnitCost = 8.99, Total = 719.2},
new {Id=32, OrderDate = DateTime.Parse("2016-06-17"), Region = "Central", Rep = "Kivell", Item = "Desk", Units = 5, UnitCost = 125, Total = 625},
new {Id=33, OrderDate = DateTime.Parse("2016-07-04"), Region = "East", Rep = "Jones", Item = "Pen Set", Units = 62, UnitCost = 4.99, Total = 309.38},
new {Id=34, OrderDate = DateTime.Parse("2016-07-21"), Region = "Central", Rep = "Morgan", Item = "Pen Set", Units = 55, UnitCost = 12.49, Total = 686.95},
new {Id=35, OrderDate = DateTime.Parse("2016-08-07"), Region = "Central", Rep = "Kivell", Item = "Pen Set", Units = 42, UnitCost = 23.95, Total = 1005.9},
new {Id=36, OrderDate = DateTime.Parse("2016-08-24"), Region = "West", Rep = "Sorvino", Item = "Desk", Units = 3, UnitCost = 275, Total = 825},
new {Id=37, OrderDate = DateTime.Parse("2016-09-10"), Region = "Central", Rep = "Gill", Item = "Pencil", Units = 7, UnitCost = 1.29, Total = 9.03},
new {Id=38, OrderDate = DateTime.Parse("2016-09-27"), Region = "West", Rep = "Sorvino", Item = "Pen", Units = 76, UnitCost = 1.99, Total = 151.24},
new {Id=39, OrderDate = DateTime.Parse("2016-10-14"), Region = "West", Rep = "Thompson", Item = "Binder", Units = 57, UnitCost = 19.99, Total = 1139.43},
new {Id=40, OrderDate = DateTime.Parse("2016-10-31"), Region = "Central", Rep = "Andrews", Item = "Pencil", Units = 14, UnitCost = 1.29, Total = 18.06},
new {Id=41, OrderDate = DateTime.Parse("2016-11-17"), Region = "Central", Rep = "Jardine", Item = "Binder", Units = 11, UnitCost = 4.99, Total = 54.89},
new {Id=42, OrderDate = DateTime.Parse("2016-12-04"), Region = "Central", Rep = "Jardine", Item = "Binder", Units = 94, UnitCost = 19.99, Total = 1879.06},
new {Id=43, OrderDate = DateTime.Parse("2016-12-21"), Region = "Central", Rep = "Andrews", Item = "Binder", Units = 28, UnitCost = 4.99, Total = 139.72}
};
ws1.FirstCell()
.CellBelow()
.CellRight()
.InsertTable(data, "Table1");
var ws2 = wb.AddWorksheet("MixedData");
ws2.FirstCell().InsertData(new object[] { 1, 2.0, "3", 3, new DateTime(2020, 1, 1), true, new TimeSpan(10, 5, 30, 10) });
return wb;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for FileOperations.
/// </summary>
public static partial class FileOperationsExtensions
{
/// <summary>
/// Deletes the specified task file from the compute node where the task ran.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to delete.
/// </param>
/// <param name='filePath'>
/// The path to the task file or directory that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath parameter
/// represents a directory instead of a file, you can set recursive to true to
/// delete the directory and all of the files and subdirectories in it. If
/// recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static FileDeleteFromTaskHeaders DeleteFromTask(this IFileOperations operations, string jobId, string taskId, string filePath, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions))
{
return operations.DeleteFromTaskAsync(jobId, taskId, filePath, recursive, fileDeleteFromTaskOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified task file from the compute node where the task ran.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to delete.
/// </param>
/// <param name='filePath'>
/// The path to the task file or directory that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath parameter
/// represents a directory instead of a file, you can set recursive to true to
/// delete the directory and all of the files and subdirectories in it. If
/// recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FileDeleteFromTaskHeaders> DeleteFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string filePath, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteFromTaskWithHttpMessagesAsync(jobId, taskId, filePath, recursive, fileDeleteFromTaskOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to retrieve.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static Stream GetFromTask(this IFileOperations operations, string jobId, string taskId, string filePath, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions))
{
return operations.GetFromTaskAsync(jobId, taskId, filePath, fileGetFromTaskOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to retrieve.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Stream> GetFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string filePath, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetFromTaskWithHttpMessagesAsync(jobId, taskId, filePath, fileGetFromTaskOptions, null, cancellationToken).ConfigureAwait(false);
_result.Request.Dispose();
return _result.Body;
}
/// <summary>
/// Gets the properties of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to get the properties of.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the properties of.
/// </param>
/// <param name='fileGetPropertiesFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static FileGetPropertiesFromTaskHeaders GetPropertiesFromTask(this IFileOperations operations, string jobId, string taskId, string filePath, FileGetPropertiesFromTaskOptions fileGetPropertiesFromTaskOptions = default(FileGetPropertiesFromTaskOptions))
{
return operations.GetPropertiesFromTaskAsync(jobId, taskId, filePath, fileGetPropertiesFromTaskOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the properties of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to get the properties of.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the properties of.
/// </param>
/// <param name='fileGetPropertiesFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FileGetPropertiesFromTaskHeaders> GetPropertiesFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string filePath, FileGetPropertiesFromTaskOptions fileGetPropertiesFromTaskOptions = default(FileGetPropertiesFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPropertiesFromTaskWithHttpMessagesAsync(jobId, taskId, filePath, fileGetPropertiesFromTaskOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Deletes the specified file from the compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node from which you want to delete the file.
/// </param>
/// <param name='filePath'>
/// The path to the file or directory that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath parameter
/// represents a directory instead of a file, you can set recursive to true to
/// delete the directory and all of the files and subdirectories in it. If
/// recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static FileDeleteFromComputeNodeHeaders DeleteFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string filePath, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions))
{
return operations.DeleteFromComputeNodeAsync(poolId, nodeId, filePath, recursive, fileDeleteFromComputeNodeOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified file from the compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node from which you want to delete the file.
/// </param>
/// <param name='filePath'>
/// The path to the file or directory that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath parameter
/// represents a directory instead of a file, you can set recursive to true to
/// delete the directory and all of the files and subdirectories in it. If
/// recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FileDeleteFromComputeNodeHeaders> DeleteFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string filePath, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, filePath, recursive, fileDeleteFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Returns the content of the specified compute node file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the compute node file that you want to get the content of.
/// </param>
/// <param name='fileGetFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static Stream GetFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string filePath, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions))
{
return operations.GetFromComputeNodeAsync(poolId, nodeId, filePath, fileGetFromComputeNodeOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the content of the specified compute node file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the compute node file that you want to get the content of.
/// </param>
/// <param name='fileGetFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Stream> GetFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string filePath, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, filePath, fileGetFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false);
_result.Request.Dispose();
return _result.Body;
}
/// <summary>
/// Gets the properties of the specified compute node file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the compute node file that you want to get the properties of.
/// </param>
/// <param name='fileGetPropertiesFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static FileGetPropertiesFromComputeNodeHeaders GetPropertiesFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string filePath, FileGetPropertiesFromComputeNodeOptions fileGetPropertiesFromComputeNodeOptions = default(FileGetPropertiesFromComputeNodeOptions))
{
return operations.GetPropertiesFromComputeNodeAsync(poolId, nodeId, filePath, fileGetPropertiesFromComputeNodeOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the properties of the specified compute node file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the compute node file that you want to get the properties of.
/// </param>
/// <param name='fileGetPropertiesFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FileGetPropertiesFromComputeNodeHeaders> GetPropertiesFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string filePath, FileGetPropertiesFromComputeNodeOptions fileGetPropertiesFromComputeNodeOptions = default(FileGetPropertiesFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPropertiesFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, filePath, fileGetPropertiesFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of the task directory. This parameter can be used
/// in combination with the filter parameter to list specific type of files.
/// </param>
/// <param name='fileListFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<NodeFile> ListFromTask(this IFileOperations operations, string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions))
{
return operations.ListFromTaskAsync(jobId, taskId, recursive, fileListFromTaskOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of the task directory. This parameter can be used
/// in combination with the filter parameter to list specific type of files.
/// </param>
/// <param name='fileListFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NodeFile>> ListFromTaskAsync(this IFileOperations operations, string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListFromTaskWithHttpMessagesAsync(jobId, taskId, recursive, fileListFromTaskOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<NodeFile> ListFromComputeNode(this IFileOperations operations, string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions))
{
return operations.ListFromComputeNodeAsync(poolId, nodeId, recursive, fileListFromComputeNodeOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NodeFile>> ListFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, recursive, fileListFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromTaskNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<NodeFile> ListFromTaskNext(this IFileOperations operations, string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions))
{
return operations.ListFromTaskNextAsync(nextPageLink, fileListFromTaskNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromTaskNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NodeFile>> ListFromTaskNextAsync(this IFileOperations operations, string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListFromTaskNextWithHttpMessagesAsync(nextPageLink, fileListFromTaskNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromComputeNodeNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<NodeFile> ListFromComputeNodeNext(this IFileOperations operations, string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions))
{
return operations.ListFromComputeNodeNextAsync(nextPageLink, fileListFromComputeNodeNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromComputeNodeNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NodeFile>> ListFromComputeNodeNextAsync(this IFileOperations operations, string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListFromComputeNodeNextWithHttpMessagesAsync(nextPageLink, fileListFromComputeNodeNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections;
using System.Text;
#if !(MF_FRAMEWORK_VERSION_V4_2 && MF_FRAMEWORK_VERSION_V4_3)
using System.Globalization;
#endif
/*
* Copyright by Mario Vernari, Cet Electronics
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Cet.MicroJSON
{
public static class JsonHelpers
{
/// <summary>
/// Define the whitespace-equivalent characters
/// </summary>
private const string WhiteSpace = " \u0009\u000A\u000D";
/// <summary>
/// Parse a JSON-string to a specific DOM
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static JToken Parse(string text)
{
var rd = new JSonReader(text);
var ctx = new JsonParserContext(rd)
.ConsumeWhiteSpace()
.First(true, JsonHelpers.ConsumeObject, JsonHelpers.ConsumeArray);
return (JToken)ctx.Result;
}
/// <summary>
/// Serialize the specific DOM to a JSON-string
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string Serialize(JToken source)
{
var sb = new StringBuilder();
source.Serialize(sb);
return sb.ToString();
}
/// <summary>
/// Consume an arbitrary number of whitespace characters
/// </summary>
/// <param name="ctx"></param>
/// <returns></returns>
private static JsonParserContext ConsumeWhiteSpace(
this JsonParserContext ctx
)
{
JSonReader src = ctx.Begin();
for (int p = src.Position, len = src.Text.Length; p < len; p++)
{
if (WhiteSpace.IndexOf(src.Text[p]) < 0)
{
src.Position = p;
break;
}
}
return ctx;
}
/// <summary>
/// Consume any character (at least one) in the specified set
/// </summary>
/// <param name="ctx"></param>
/// <param name="charset"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeAnyChar(
this JsonParserContext ctx,
string charset,
bool throws
)
{
JSonReader src = ctx.Begin();
char c;
if (charset.IndexOf(c = src.Text[src.Position]) >= 0)
{
src.Position++;
ctx.SetResult(c);
}
else if (throws)
{
throw new JsonParseException("Expected char not found.");
}
return ctx;
}
/// <summary>
/// Consume all the characters in the specified sequence
/// </summary>
/// <param name="ctx"></param>
/// <param name="sequence"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeAllChars(
this JsonParserContext ctx,
string sequence,
bool throws
)
{
JSonReader src = ctx.Begin();
for (int q = 0, p = src.Position; q < sequence.Length; q++, p++)
{
if (src.Text[p] != sequence[q])
{
if (throws)
{
throw new JsonParseException("Expected char not found.");
}
return ctx;
}
}
src.Position += sequence.Length;
ctx.SetResult(sequence);
return ctx;
}
/// <summary>
/// Consume a JSON object
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeObject(
this JsonParserContext ctx,
bool throws
)
{
if (ctx.ConsumeWhiteSpace().ConsumeAnyChar("{", throws).IsSucceeded)
{
var jctr = new JObject();
bool shouldThrow = false;
do
{
ctx.Begin();
if (ctx.ConsumeString(shouldThrow).IsSucceeded)
{
var name = (string)(JValue)ctx.Result;
ctx.ConsumeWhiteSpace()
.ConsumeAnyChar(":", true)
.ConsumeValue(true);
jctr.Add(name, (JToken)ctx.Result);
}
shouldThrow = true;
}
while ((char)ctx.ConsumeWhiteSpace().ConsumeAnyChar(",}", true).Result == ',');
ctx.SetResult(jctr);
}
return ctx;
}
/// <summary>
/// Consume a JSON array
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeArray(
this JsonParserContext ctx,
bool throws
)
{
if (ctx.ConsumeWhiteSpace().ConsumeAnyChar("[", throws).IsSucceeded)
{
var jctr = new JArray();
bool shouldThrow = false;
do
{
ctx.Begin();
if (ctx.ConsumeValue(shouldThrow).IsSucceeded)
jctr.Add((JToken)ctx.Result);
shouldThrow = true;
}
while ((char)ctx.ConsumeWhiteSpace().ConsumeAnyChar(",]", true).Result == ',');
ctx.SetResult(jctr);
}
return ctx;
}
/// <summary>
/// Consume any suitable JSON value token
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeValue(
this JsonParserContext ctx,
bool throws
)
{
return ctx.First(
throws,
JsonHelpers.ConsumeString,
JsonHelpers.ConsumeNumber,
JsonHelpers.ConsumeObject,
JsonHelpers.ConsumeArray,
JsonHelpers.ConsumeBoolean,
JsonHelpers.ConsumeNull
);
}
/// <summary>
/// Consume a JSON numeric token
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeNumber(
this JsonParserContext ctx,
bool throws
)
{
const string Leading = "-0123456789";
const string Allowed = Leading + ".Ee+";
if (ctx.ConsumeWhiteSpace().ConsumeAnyChar(Leading, throws).IsSucceeded)
{
JSonReader src = ctx.Begin();
for (int p = src.Position, len = src.Text.Length; p < len; p++)
{
if (Allowed.IndexOf(src.Text[p]) < 0)
{
ctx.SetResult(
new JValue { BoxedValue = double.Parse(src.Text.Substring(src.Position - 1, p - src.Position + 1)) }
);
src.Position = p;
break;
}
}
}
return ctx;
}
/// <summary>
/// Consume a JSON string token
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeString(
this JsonParserContext ctx,
bool throws
)
{
if (ctx.ConsumeWhiteSpace().ConsumeAnyChar("\"", throws).IsSucceeded)
{
JSonReader src = ctx.Begin();
for (int p = src.Position, len = src.Text.Length; p < len; p++)
{
if ((src.Text[p]) == '"')
{
ctx.SetResult(
new JValue { BoxedValue = src.Text.Substring(src.Position, p - src.Position) }
);
src.Position = p + 1;
break;
}
}
}
return ctx;
}
/// <summary>
/// Consume a JSON boolean token
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeBoolean(
this JsonParserContext ctx,
bool throws
)
{
if (ctx.ConsumeWhiteSpace().ConsumeAnyChar("ft", throws).IsSucceeded)
{
bool flag = (char)ctx.Result == 't';
ctx.ConsumeAllChars(flag ? "rue" : "alse", true);
ctx.SetResult(
new JValue { BoxedValue = flag }
);
}
return ctx;
}
/// <summary>
/// Consume the JSON "null" token
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
private static JsonParserContext ConsumeNull(
this JsonParserContext ctx,
bool throws
)
{
if (ctx.ConsumeWhiteSpace().ConsumeAnyChar("n", throws).IsSucceeded)
{
ctx.ConsumeAllChars("ull", true);
ctx.SetResult(
new JValue { BoxedValue = null }
);
}
return ctx;
}
/// <summary>
/// Yield the consumption of the current context to a series of possible parsers
/// The control will pass to the first one able to manage the source.
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <param name="funcs"></param>
/// <returns></returns>
private static JsonParserContext First(
this JsonParserContext ctx,
bool throws,
params JsonParseDelegate[] funcs
)
{
for (int i = 0; i < funcs.Length; i++)
{
if (funcs[i](ctx, false).IsSucceeded)
{
return ctx;
}
}
if (throws)
{
throw new JsonParseException("Unmatched handler for context.");
}
else
{
return ctx;
}
}
/// <summary>
/// Delegate used for the "smart" matching pattern selection
/// </summary>
/// <param name="ctx"></param>
/// <param name="throws"></param>
/// <returns></returns>
internal delegate JsonParserContext JsonParseDelegate(JsonParserContext ctx, bool throws);
}
/// <summary>
/// Trivial string reader
/// </summary>
internal class JSonReader
{
public JSonReader(string text)
{
this.Text = text;
}
public readonly string Text;
public int Position;
}
/// <summary>
/// Context data used by the parser
/// </summary>
internal class JsonParserContext
{
public JsonParserContext(JSonReader source)
{
this._source = source;
}
private readonly JSonReader _source;
public bool IsSucceeded { get; private set; }
public object Result { get; private set; }
public JSonReader Begin()
{
this.Result = null;
this.IsSucceeded = false;
return this._source;
}
public void SetResult(object result)
{
this.Result = result;
this.IsSucceeded = true;
}
}
/// <summary>
/// JSON parser specific exception thrown in case of error
/// </summary>
public class JsonParseException
: Exception
{
public JsonParseException(string message)
: base(message)
{
}
}
/// <summary>
/// Abstract base for any elemento of the JSON DOM
/// </summary>
public abstract class JToken
{
protected JToken() { }
internal abstract void Serialize(StringBuilder sb);
#region String conversion operators
public static implicit operator JToken(string value)
{
return new JValue { BoxedValue = value };
}
public static implicit operator string(JToken value)
{
var jval = value as JValue;
if (jval != null)
{
if (jval.BoxedValue is string == false)
throw new InvalidCastException();
return (string)jval.BoxedValue;
}
throw new InvalidCastException();
}
#endregion
#region Numeric conversion operator
public static implicit operator JToken(double value)
{
return new JValue { BoxedValue = value };
}
public static implicit operator JToken(int value)
{
return new JValue { BoxedValue = (double)value };
}
public static implicit operator double(JToken value)
{
var jval = value as JValue;
if (jval != null)
{
if (jval.BoxedValue is double == false)
throw new InvalidCastException();
return (double)jval.BoxedValue;
}
throw new InvalidCastException();
}
#endregion
#region Boolean conversion operator
public static implicit operator JToken(bool value)
{
return new JValue { BoxedValue = value };
}
public static implicit operator bool(JToken value)
{
var jval = value as JValue;
if (jval != null)
{
if (jval.BoxedValue is bool == false)
throw new InvalidCastException();
return (bool)jval.BoxedValue;
}
throw new InvalidCastException();
}
#endregion
}
/// <summary>
/// Represent a valued-node of the JSON DOM
/// </summary>
public class JValue
: JToken
{
internal object BoxedValue;
public object RawValue { get { return this.BoxedValue; } }
internal override void Serialize(StringBuilder sb)
{
if (this.BoxedValue == null)
{
sb.Append("null");
}
else if (this.BoxedValue is bool)
{
sb.Append((bool)this.BoxedValue ? "true" : "false");
}
else if (this.BoxedValue is double)
{
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
sb.Append(((double)this.BoxedValue).ToString());
#else
sb.Append(((double)this.BoxedValue).ToString(CultureInfo.InvariantCulture));
#endif
}
else if (this.BoxedValue is string)
{
sb.Append('"');
sb.Append((string)this.BoxedValue);
sb.Append('"');
}
else
{
throw new NotSupportedException();
}
}
}
/// <summary>
/// Represent a key-value pair instance used for the JSON object bag
/// </summary>
public class JProperty
: JToken
{
public JProperty(
string name,
JToken value
)
{
this.Name = name;
this.Value = value;
}
public readonly string Name;
public JToken Value;
internal override void Serialize(StringBuilder sb)
{
sb.Append('"');
sb.Append(this.Name);
if (this.Value != null)
{
sb.Append("\":");
this.Value.Serialize(sb);
}
else
{
sb.Append("\":null");
}
}
}
/// <summary>
/// Represent a JSON object
/// </summary>
public class JObject
: JToken, IEnumerable
{
private const int ChunkSize = 8;
private static readonly JProperty[] Empty = new JProperty[0];
private JProperty[] _items = Empty;
private int _itemCount;
/// <summary>
/// Add a keyed-value to the object's bag
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <remarks>You cannot use a key that is already existent in the bag</remarks>
public void Add(string name, JToken value)
{
if (this.IndexOf(name) > 0)
throw new ArgumentException("Duplicate key.");
if (this._itemCount >= this._items.Length)
{
var old = this._items;
Array.Copy(
old,
this._items = new JProperty[this._itemCount + ChunkSize],
this._itemCount
);
}
this._items[this._itemCount++] = new JProperty(name, value);
}
/// <summary>
/// Get an existent keyed-value from the bag.
/// When set, the value replaces the existent entry, or is added if not present.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public JToken this[string name]
{
get
{
return this._items[this.IndexOf(name)].Value;
}
set
{
int index;
if ((index = this.IndexOf(name)) >= 0)
{
this._items[index].Value = value;
}
else
{
this.Add(name, value);
}
}
}
private int IndexOf(string name)
{
for (int i = 0; i < this._itemCount; i++)
{
if (this._items[i].Name == name)
return i;
}
return -1;
}
internal override void Serialize(StringBuilder sb)
{
sb.Append('{');
for (int i = 0; i < this._itemCount; i++)
{
if (i > 0) sb.Append(',');
this._items[i].Serialize(sb);
}
sb.Append('}');
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < this._itemCount; i++)
{
yield return this._items[i];
}
}
}
/// <summary>
/// Represent a JSON array
/// </summary>
public class JArray
: JToken, IEnumerable
{
private ArrayList _items = new ArrayList();
/// <summary>
/// Add an object at the end of the collection
/// </summary>
/// <param name="item"></param>
public void Add(JToken item)
{
this.Insert(
this._items.Count,
item
);
}
/// <summary>
/// Insert an object at the specified position
/// </summary>
/// <param name="position"></param>
/// <param name="item"></param>
public void Insert(
int position,
JToken item
)
{
this._items.Insert(
position,
item
);
}
/// <summary>
/// Get the value stored at the specified position.
/// When set, the value replaces the existent entry.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public JToken this[int index]
{
get { return (JToken)this._items[index]; }
set { this._items[index] = value; }
}
/// <summary>
/// Remove the entry at the specified position
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index)
{
this._items.RemoveAt(index);
}
public IEnumerator GetEnumerator()
{
return this._items.GetEnumerator();
}
internal override void Serialize(StringBuilder sb)
{
sb.Append('[');
for (int i = 0, count = this._items.Count; i < count; i++)
{
if (i > 0) sb.Append(',');
JToken item;
if ((item = (JToken)this._items[i]) != null)
{
item.Serialize(sb);
}
else
{
sb.Append("null");
}
}
sb.Append(']');
}
}
}
| |
namespace Microsoft.Extensions.DependencyInjection
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#if AI_ASPNETCORE_WEB
using Microsoft.ApplicationInsights.AspNetCore;
using Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.Tracing;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
#else
using Microsoft.ApplicationInsights.WorkerService;
using Microsoft.ApplicationInsights.WorkerService.Implementation.Tracing;
#endif
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.EventCounterCollector;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using Microsoft.ApplicationInsights.WindowsServer;
using Microsoft.ApplicationInsights.WindowsServer.Channel.Implementation;
using Microsoft.Extensions.Options;
/// <summary>
/// Initializes TelemetryConfiguration based on values in <see cref="ApplicationInsightsServiceOptions"/>
/// and registered <see cref="ITelemetryInitializer"/>s and <see cref="ITelemetryModule"/>s.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "This class is instantiated by Dependency Injection.")]
internal class TelemetryConfigurationOptionsSetup : IConfigureOptions<TelemetryConfiguration>
{
private readonly ApplicationInsightsServiceOptions applicationInsightsServiceOptions;
private readonly IEnumerable<ITelemetryInitializer> initializers;
private readonly IEnumerable<ITelemetryModule> modules;
private readonly ITelemetryChannel telemetryChannel;
private readonly IEnumerable<ITelemetryProcessorFactory> telemetryProcessorFactories;
private readonly IEnumerable<ITelemetryModuleConfigurator> telemetryModuleConfigurators;
private readonly IApplicationIdProvider applicationIdProvider;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryConfigurationOptionsSetup"/> class.
/// </summary>
/// <param name="serviceProvider">Instance of IServiceProvider.</param>
/// <param name="applicationInsightsServiceOptions">Instance of IOptions<ApplicationInsightsServiceOptions>.</param>
/// <param name="initializers">Instance of IEnumerable<ITelemetryInitializer>.</param>
/// <param name="modules">Instance of IEnumerable<ITelemetryModule>.</param>
/// <param name="telemetryProcessorFactories">Instance of IEnumerable<ITelemetryProcessorFactory>.</param>
/// <param name="telemetryModuleConfigurators">Instance of IEnumerable<ITelemetryModuleConfigurator>.</param>
public TelemetryConfigurationOptionsSetup(
IServiceProvider serviceProvider,
IOptions<ApplicationInsightsServiceOptions> applicationInsightsServiceOptions,
IEnumerable<ITelemetryInitializer> initializers,
IEnumerable<ITelemetryModule> modules,
IEnumerable<ITelemetryProcessorFactory> telemetryProcessorFactories,
IEnumerable<ITelemetryModuleConfigurator> telemetryModuleConfigurators)
{
this.applicationInsightsServiceOptions = applicationInsightsServiceOptions.Value;
this.initializers = initializers;
this.modules = modules;
this.telemetryProcessorFactories = telemetryProcessorFactories;
this.telemetryModuleConfigurators = telemetryModuleConfigurators;
this.telemetryChannel = serviceProvider.GetService<ITelemetryChannel>();
this.applicationIdProvider = serviceProvider.GetService<IApplicationIdProvider>();
}
/// <inheritdoc />
public void Configure(TelemetryConfiguration configuration)
{
try
{
if (this.applicationInsightsServiceOptions.InstrumentationKey != null)
{
configuration.InstrumentationKey = this.applicationInsightsServiceOptions.InstrumentationKey;
}
if (this.telemetryModuleConfigurators.Any())
{
foreach (ITelemetryModuleConfigurator telemetryModuleConfigurator in this.telemetryModuleConfigurators)
{
ITelemetryModule telemetryModule = this.modules.FirstOrDefault((module) => module.GetType() == telemetryModuleConfigurator.TelemetryModuleType);
if (telemetryModule != null)
{
telemetryModuleConfigurator.Configure(telemetryModule, this.applicationInsightsServiceOptions);
}
else
{
#if AI_ASPNETCORE_WEB
AspNetCoreEventSource.Instance.UnableToFindModuleToConfigure(telemetryModuleConfigurator.TelemetryModuleType.ToString());
#else
WorkerServiceEventSource.Instance.UnableToFindModuleToConfigure(telemetryModuleConfigurator.TelemetryModuleType.ToString());
#endif
}
}
}
if (this.telemetryProcessorFactories.Any())
{
foreach (ITelemetryProcessorFactory processorFactory in this.telemetryProcessorFactories)
{
configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.Use(processorFactory.Create);
}
}
// Fallback to default channel (InMemoryChannel) created by base sdk if no channel is found in DI
configuration.TelemetryChannel = this.telemetryChannel ?? configuration.TelemetryChannel;
(configuration.TelemetryChannel as ITelemetryModule)?.Initialize(configuration);
this.AddAutoCollectedMetricExtractor(configuration);
this.AddQuickPulse(configuration);
this.AddSampling(configuration);
this.DisableHeartBeatIfConfigured();
configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.Build();
configuration.TelemetryProcessorChainBuilder.Build();
if (this.applicationInsightsServiceOptions.DeveloperMode != null)
{
configuration.TelemetryChannel.DeveloperMode = this.applicationInsightsServiceOptions.DeveloperMode;
}
if (this.applicationInsightsServiceOptions.EndpointAddress != null)
{
configuration.TelemetryChannel.EndpointAddress = this.applicationInsightsServiceOptions.EndpointAddress;
}
// Need to set connection string before calling Initialize() on the Modules and Processors.
if (this.applicationInsightsServiceOptions.ConnectionString != null)
{
configuration.ConnectionString = this.applicationInsightsServiceOptions.ConnectionString;
}
foreach (ITelemetryInitializer initializer in this.initializers)
{
configuration.TelemetryInitializers.Add(initializer);
}
// Find the DiagnosticsTelemetryModule, this is needed to initialize AzureInstanceMetadataTelemetryModule and AppServicesHeartbeatTelemetryModule.
DiagnosticsTelemetryModule diagModule =
(this.applicationInsightsServiceOptions.EnableDiagnosticsTelemetryModule && this.applicationInsightsServiceOptions.EnableHeartbeat)
? this.modules.OfType<DiagnosticsTelemetryModule>().FirstOrDefault()
: null;
// Checks ApplicationInsightsServiceOptions and disable TelemetryModules if explicitly disabled.
foreach (ITelemetryModule module in this.modules)
{
// If any of the modules are disabled explicitly using aioptions,
// do not initialize them and dispose if disposable.
// The option of not adding a module to DI if disabled
// cannot be done to maintain backward compatibility.
// So this approach of adding all modules to DI, but selectively
// disable those modules which user has disabled is chosen.
if (module is DiagnosticsTelemetryModule)
{
if (!this.applicationInsightsServiceOptions.EnableDiagnosticsTelemetryModule)
{
DisposeIfDisposable(module);
continue;
}
}
// DependencyTrackingTelemetryModule
if (module is DependencyTrackingTelemetryModule)
{
if (!this.applicationInsightsServiceOptions.EnableDependencyTrackingTelemetryModule)
{
DisposeIfDisposable(module);
continue;
}
}
#if AI_ASPNETCORE_WEB
// RequestTrackingTelemetryModule
if (module is RequestTrackingTelemetryModule)
{
if (!this.applicationInsightsServiceOptions.EnableRequestTrackingTelemetryModule)
{
DisposeIfDisposable(module);
continue;
}
}
#endif
// EventCounterCollectionModule
if (module is EventCounterCollectionModule)
{
if (!this.applicationInsightsServiceOptions.EnableEventCounterCollectionModule)
{
DisposeIfDisposable(module);
continue;
}
}
// PerformanceCollectorModule
if (module is PerformanceCollectorModule)
{
if (!this.applicationInsightsServiceOptions.EnablePerformanceCounterCollectionModule)
{
DisposeIfDisposable(module);
continue;
}
}
// AppServicesHeartbeatTelemetryModule
if (module is AppServicesHeartbeatTelemetryModule appServicesHeartbeatTelemetryModule)
{
if (!this.applicationInsightsServiceOptions.EnableAppServicesHeartbeatTelemetryModule)
{
DisposeIfDisposable(module);
continue;
}
else if (diagModule != null)
{
// diagModule is set to Null above if (applicationInsightsServiceOptions.EnableDiagnosticsTelemetryModule || this.applicationInsightsServiceOptions.EnableHeartbeat) == false.
appServicesHeartbeatTelemetryModule.HeartbeatPropertyManager = diagModule;
}
}
// AzureInstanceMetadataTelemetryModule
if (module is AzureInstanceMetadataTelemetryModule azureInstanceMetadataTelemetryModule)
{
if (!this.applicationInsightsServiceOptions.EnableAzureInstanceMetadataTelemetryModule)
{
DisposeIfDisposable(module);
continue;
}
else if (diagModule != null)
{
// diagModule is set to Null above if (applicationInsightsServiceOptions.EnableDiagnosticsTelemetryModule || this.applicationInsightsServiceOptions.EnableHeartbeat) == false.
azureInstanceMetadataTelemetryModule.HeartbeatPropertyManager = diagModule;
}
}
// QuickPulseTelemetryModule
if (module is QuickPulseTelemetryModule)
{
if (!this.applicationInsightsServiceOptions.EnableQuickPulseMetricStream)
{
DisposeIfDisposable(module);
continue;
}
}
try
{
module.Initialize(configuration);
}
catch (Exception ex)
{
#if AI_ASPNETCORE_WEB
AspNetCoreEventSource.Instance.TelemetryModuleInitialziationSetupFailure(module.GetType().FullName, ex.ToInvariantString());
#else
WorkerServiceEventSource.Instance.TelemetryModuleInitialziationSetupFailure(module.GetType().FullName, ex.ToInvariantString());
#endif
}
}
foreach (ITelemetryProcessor processor in configuration.TelemetryProcessors)
{
if (processor is ITelemetryModule module)
{
module.Initialize(configuration);
}
}
// Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule depends on this nullable configuration to support Correlation.
configuration.ApplicationIdProvider = this.applicationIdProvider;
#if AI_ASPNETCORE_WEB
AspNetCoreEventSource.Instance.LogInformational("Successfully configured TelemetryConfiguration.");
#else
WorkerServiceEventSource.Instance.LogInformational("Successfully configured TelemetryConfiguration.");
#endif
}
catch (Exception ex)
{
#if AI_ASPNETCORE_WEB
AspNetCoreEventSource.Instance.TelemetryConfigurationSetupFailure(ex.ToInvariantString());
#else
WorkerServiceEventSource.Instance.TelemetryConfigurationSetupFailure(ex.ToInvariantString());
#endif
}
}
private static void DisposeIfDisposable(ITelemetryModule module)
{
if (module is IDisposable)
{
(module as IDisposable).Dispose();
}
}
private void AddQuickPulse(TelemetryConfiguration configuration)
{
if (this.applicationInsightsServiceOptions.EnableQuickPulseMetricStream)
{
if (this.modules.FirstOrDefault((module) => module.GetType() == typeof(QuickPulseTelemetryModule)) is QuickPulseTelemetryModule quickPulseModule)
{
QuickPulseTelemetryProcessor processor = null;
configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.Use((next) =>
{
processor = new QuickPulseTelemetryProcessor(next);
quickPulseModule.RegisterTelemetryProcessor(processor);
return processor;
});
}
else
{
#if AI_ASPNETCORE_WEB
AspNetCoreEventSource.Instance.UnableToFindModuleToConfigure("QuickPulseTelemetryModule");
#else
WorkerServiceEventSource.Instance.UnableToFindModuleToConfigure("QuickPulseTelemetryModule");
#endif
}
}
}
private void AddSampling(TelemetryConfiguration configuration)
{
if (this.applicationInsightsServiceOptions.EnableAdaptiveSampling)
{
AdaptiveSamplingPercentageEvaluatedCallback samplingCallback = (ratePerSecond, currentPercentage, newPercentage, isChanged, estimatorSettings) =>
{
if (isChanged)
{
configuration.SetLastObservedSamplingPercentage(SamplingTelemetryItemTypes.Request, newPercentage);
}
};
SamplingPercentageEstimatorSettings settings = new SamplingPercentageEstimatorSettings();
settings.MaxTelemetryItemsPerSecond = 5;
configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.UseAdaptiveSampling(settings, samplingCallback, excludedTypes: "Event");
configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.UseAdaptiveSampling(5, includedTypes: "Event");
}
}
private void AddAutoCollectedMetricExtractor(TelemetryConfiguration configuration)
{
if (this.applicationInsightsServiceOptions.AddAutoCollectedMetricExtractor)
{
configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.Use(next => new AutocollectedMetricsExtractor(next));
}
}
private void DisableHeartBeatIfConfigured()
{
// Disable heartbeat if user sets it (by default it is on)
if (!this.applicationInsightsServiceOptions.EnableHeartbeat)
{
foreach (var module in this.modules)
{
if (module is IHeartbeatPropertyManager hbeatMan)
{
hbeatMan.IsHeartbeatEnabled = false;
}
}
}
}
}
}
| |
//
// PodcastService.cs
//
// Authors:
// Mike Urbanski <michael.c.urbanski@gmail.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Michael C. Urbanski
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mono.Unix;
using Hyena;
using Banshee.Base;
using Banshee.ServiceStack;
using Migo.TaskCore;
using Migo.Syndication;
using Migo.DownloadCore;
using Banshee.Networking;
using Banshee.MediaEngine;
using Banshee.Podcasting.Gui;
using Banshee.Podcasting.Data;
using Banshee.Collection.Database;
using Banshee.Configuration;
namespace Banshee.Podcasting
{
public partial class PodcastService : IExtensionService, IDisposable, IDelayedInitializeService
{
private readonly string tmp_download_path = Paths.Combine (Paths.ExtensionCacheRoot, "podcasting", "partial-downloads");
private uint refresh_timeout_id = 0;
private bool disposed;
private DownloadManager download_manager;
private DownloadManagerInterface download_manager_iface;
private FeedsManager feeds_manager;
private PodcastSource source;
//private PodcastImportManager import_manager;
private readonly object sync = new object ();
public PodcastService ()
{
Migo.Net.AsyncWebClient.DefaultUserAgent = Banshee.Web.Browser.UserAgent;
}
private void MigrateLegacyIfNeeded ()
{
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) == 0) {
if (ServiceManager.DbConnection.TableExists ("Podcasts") &&
ServiceManager.DbConnection.Query<int> ("select count(*) from podcastsyndications") == 0) {
Hyena.Log.Information ("Migrating Podcast Feeds and Items");
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastSyndications (FeedID, Title, Url, Link,
Description, ImageUrl, LastBuildDate, AutoDownload, IsSubscribed)
SELECT
PodcastFeedID,
Title,
FeedUrl,
Link,
Description,
Image,
strftime(""%s"", LastUpdated),
SyncPreference,
1
FROM PodcastFeeds
");
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastItems (ItemID, FeedID, Title, Link, PubDate,
Description, Author, Active, Guid)
SELECT
PodcastID,
PodcastFeedID,
Title,
Link,
strftime(""%s"", PubDate),
Description,
Author,
Active,
Url
FROM Podcasts
");
// Note: downloaded*3 is because the value was 0 or 1, but is now 0 or 3 (FeedDownloadStatus.None/Downloaded)
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastEnclosures (ItemID, LocalPath, Url, MimeType, FileSize, DownloadStatus)
SELECT
PodcastID,
LocalPath,
Url,
MimeType,
Length,
Downloaded*3
FROM Podcasts
");
// Finally, move podcast items from the Music Library to the Podcast source
int [] primary_source_ids = new int [] { ServiceManager.SourceManager.MusicLibrary.DbId };
int moved = 0;
foreach (FeedEnclosure enclosure in FeedEnclosure.Provider.FetchAllMatching ("LocalPath IS NOT NULL AND LocalPath != ''")) {
SafeUri uri = new SafeUri (enclosure.LocalPath);
int track_id = DatabaseTrackInfo.GetTrackIdForUri (uri, primary_source_ids);
if (track_id > 0) {
PodcastTrackInfo pi = new PodcastTrackInfo (DatabaseTrackInfo.Provider.FetchSingle (track_id));
pi.Item = enclosure.Item;
pi.Track.PrimarySourceId = source.DbId;
pi.SyncWithFeedItem ();
pi.Track.Save (false);
moved++;
}
}
if (moved > 0) {
ServiceManager.SourceManager.MusicLibrary.Reload ();
source.Reload ();
}
Hyena.Log.Information ("Done Migrating Podcast Feeds and Items");
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 1);
}
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 3) {
// We were using the Link as the fallback if the actual Guid was missing, but that was a poor choice
// since it is not always unique. We now use the title and pubdate combined.
ServiceManager.DbConnection.Execute ("UPDATE PodcastItems SET Guid = NULL");
foreach (FeedItem item in FeedItem.Provider.FetchAll ()) {
item.Guid = null;
if (item.Feed == null || FeedItem.Exists (item.Feed.DbId, item.Guid)) {
item.Delete (false);
} else {
item.Save ();
}
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 3);
}
// Intentionally skpping 4 here because this needs to get run again for anybody who ran it
// before it was fixed, but only once if you never ran it
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 5) {
ReplaceNewlines ("CoreTracks", "Title");
ReplaceNewlines ("CoreTracks", "TitleLowered");
ReplaceNewlines ("PodcastItems", "Title");
ReplaceNewlines ("PodcastItems", "Description");
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 5);
}
// Initialize the new StrippedDescription field
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 6) {
foreach (FeedItem item in FeedItem.Provider.FetchAll ()) {
item.UpdateStrippedDescription ();
item.Save ();
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 6);
}
}
private void MigrateDownloadCache ()
{
string old_download_dir = Path.Combine (Paths.ApplicationData, "downloads");
if (Directory.Exists (old_download_dir)) {
foreach (string old_subdir in Directory.GetDirectories (old_download_dir)) {
string subdir_name = Path.GetFileName (old_subdir);
string new_subdir = Path.Combine (tmp_download_path, subdir_name);
Directory.Move (old_subdir, new_subdir);
}
Directory.Delete (old_download_dir);
}
}
private void ReplaceNewlines (string table, string column)
{
string cmd = String.Format ("UPDATE {0} SET {1}=replace({1}, ?, ?)", table, column);
ServiceManager.DbConnection.Execute (cmd, "\r\n", String.Empty);
ServiceManager.DbConnection.Execute (cmd, "\n", String.Empty);
ServiceManager.DbConnection.Execute (cmd, "\r", String.Empty);
}
public void Initialize ()
{
}
public void DelayedInitialize ()
{
download_manager = new DownloadManager (2, tmp_download_path);
download_manager_iface = new DownloadManagerInterface (download_manager);
download_manager_iface.Initialize ();
feeds_manager = new FeedsManager (ServiceManager.DbConnection, download_manager, null);
// Migrate data from 0.13.2 podcast tables, if they exist
MigrateLegacyIfNeeded ();
// Move incomplete downloads to the new cache location
try {
MigrateDownloadCache ();
} catch (Exception e) {
Hyena.Log.Exception ("Couldn't migrate podcast download cache", e);
}
source = new PodcastSource ();
ServiceManager.SourceManager.AddSource (source);
InitializeInterface ();
ThreadAssist.SpawnFromMain (delegate {
feeds_manager.PodcastStorageDirectory = source.BaseDirectory;
feeds_manager.FeedManager.ItemAdded += OnItemAdded;
feeds_manager.FeedManager.ItemChanged += OnItemChanged;
feeds_manager.FeedManager.ItemRemoved += OnItemRemoved;
feeds_manager.FeedManager.FeedsChanged += OnFeedsChanged;
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 7) {
Banshee.Library.LibrarySource music_lib = ServiceManager.SourceManager.MusicLibrary;
if (music_lib != null) {
string old_path = Path.Combine (music_lib.BaseDirectory, "Podcasts");
string new_path = source.BaseDirectory;
SafeUri old_uri = new SafeUri (old_path);
SafeUri new_uri = new SafeUri (new_path);
if (old_path != null && new_path != null && old_path != new_path &&
Banshee.IO.Directory.Exists (old_path) && !Banshee.IO.Directory.Exists (new_path)) {
Banshee.IO.Directory.Move (new SafeUri (old_path), new SafeUri (new_path));
ServiceManager.DbConnection.Execute (String.Format (
"UPDATE {0} SET LocalPath = REPLACE(LocalPath, ?, ?) WHERE LocalPath IS NOT NULL",
FeedEnclosure.Provider.TableName), old_path, new_path);
ServiceManager.DbConnection.Execute (
"UPDATE CoreTracks SET Uri = REPLACE(Uri, ?, ?) WHERE Uri LIKE 'file://%' AND PrimarySourceId = ?",
old_uri.AbsoluteUri, new_uri.AbsoluteUri, source.DbId);
Hyena.Log.DebugFormat ("Moved Podcasts from {0} to {1}", old_path, new_path);
}
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 7);
}
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange);
ServiceManager.Get<DBusCommandService> ().ArgumentPushed += OnCommandLineArgument;
RefreshFeeds ();
// Every 10 minutes try to refresh again
refresh_timeout_id = Application.RunTimeout (1000 * 60 * 10, RefreshFeeds);
ServiceManager.Get<Network> ().StateChanged += OnNetworkStateChanged;
});
source.UpdateFeedMessages ();
}
private void OnNetworkStateChanged (object o, NetworkStateChangedArgs args)
{
RefreshFeeds ();
}
bool disposing;
public void Dispose ()
{
lock (sync) {
if (disposing | disposed) {
return;
} else {
disposing = true;
}
}
Application.IdleTimeoutRemove (refresh_timeout_id);
refresh_timeout_id = 0;
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
ServiceManager.Get<DBusCommandService> ().ArgumentPushed -= OnCommandLineArgument;
ServiceManager.Get<Network> ().StateChanged -= OnNetworkStateChanged;
if (download_manager_iface != null) {
download_manager_iface.Dispose ();
download_manager_iface = null;
}
if (feeds_manager != null) {
feeds_manager.Dispose ();
feeds_manager = null;
}
if (download_manager != null) {
download_manager.Dispose ();
download_manager = null;
}
DisposeInterface ();
lock (sync) {
disposing = false;
disposed = true;
}
}
private bool RefreshFeeds ()
{
if (!ServiceManager.Get<Network> ().Connected)
return true;
Hyena.Log.Debug ("Refreshing any podcasts that haven't been updated in over an hour");
Banshee.Kernel.Scheduler.Schedule (new Banshee.Kernel.DelegateJob (delegate {
DateTime now = DateTime.Now;
foreach (Feed feed in Feed.Provider.FetchAll ()) {
if (feed.IsSubscribed && (now - feed.LastDownloadTime).TotalHours > 1) {
feed.Update ();
RefreshArtworkFor (feed);
}
}
}));
return true;
}
private void OnCommandLineArgument (string argument, object value, bool isFile)
{
if (isFile) {
ProcessFile (argument, null);
} else if (argument == "podcast") {
var podcast = Hyena.Json.JsonObject.FromString (value as string);
if (podcast != null) {
ProcessFile ((string)podcast["uri"], (string)podcast["name"]);
}
}
}
private void ProcessFile (string uri, string title)
{
if (String.IsNullOrEmpty (uri)) {
return;
}
if (uri.Contains ("opml") || uri.EndsWith (".miro") || uri.EndsWith (".democracy")) {
// Handle OPML files
try {
OpmlParser opml_parser = new OpmlParser (uri, true);
foreach (string feed in opml_parser.Feeds) {
ProcessFile (feed, title);
}
} catch (Exception e) {
Log.Exception (e);
}
} else if (uri.Contains ("xml") || uri.Contains ("rss") || uri.Contains ("feed") || uri.StartsWith ("itpc") || uri.StartsWith ("pcast")) {
// Handle normal XML/RSS URLs
if (uri.StartsWith ("feed://") || uri.StartsWith ("itpc://")) {
uri = String.Format ("http://{0}", uri.Substring (7));
} else if (uri.StartsWith ("pcast://")) {
uri = String.Format ("http://{0}", uri.Substring (8));
}
AddFeed (uri, title);
} else if (uri.StartsWith ("itms://")) {
// Handle iTunes podcast URLs
System.Threading.ThreadPool.QueueUserWorkItem (delegate {
try {
var feed = new ItmsPodcast (uri);
if (feed.FeedUrl != null) {
ThreadAssist.ProxyToMain (delegate {
AddFeed (feed.FeedUrl, feed.Title ?? title);
});
}
} catch (Exception e) {
Hyena.Log.Exception (e);
}
});
}
}
private void AddFeed (string uri, string title)
{
// TODO replace autodownload w/ actual default preference
FeedsManager.Instance.FeedManager.CreateFeed (uri, title, FeedAutoDownload.None);
source.NotifyUser ();
source.UpdateFeedMessages ();
}
private void RefreshArtworkFor (Feed feed)
{
if (!String.IsNullOrEmpty (feed.ImageUrl) && !CoverArtSpec.CoverExists (PodcastService.ArtworkIdFor (feed))) {
Banshee.Kernel.Scheduler.Schedule (new PodcastImageFetchJob (feed), Banshee.Kernel.JobPriority.BelowNormal);
}
}
private DatabaseTrackInfo GetTrackByItemId (long item_id)
{
return DatabaseTrackInfo.Provider.FetchFirstMatching ("PrimarySourceID = ? AND ExternalID = ?", source.DbId, item_id);
}
private void OnItemAdded (FeedItem item)
{
if (item.Enclosure != null) {
DatabaseTrackInfo track = new DatabaseTrackInfo ();
track.ExternalId = item.DbId;
track.PrimarySource = source;
(track.ExternalObject as PodcastTrackInfo).SyncWithFeedItem ();
track.Save (false);
RefreshArtworkFor (item.Feed);
} else {
// We're only interested in items that have enclosures
item.Delete (false);
}
}
private void OnItemRemoved (FeedItem item)
{
DatabaseTrackInfo track = GetTrackByItemId (item.DbId);
if (track != null) {
DatabaseTrackInfo.Provider.Delete (track);
}
}
internal static bool IgnoreItemChanges = false;
private void OnItemChanged (FeedItem item)
{
if (IgnoreItemChanges) {
return;
}
DatabaseTrackInfo track = GetTrackByItemId (item.DbId);
if (track != null) {
PodcastTrackInfo pi = track.ExternalObject as PodcastTrackInfo;
if (pi != null) {
pi.SyncWithFeedItem ();
track.Save (true);
}
}
}
private void OnFeedsChanged (object o, EventArgs args)
{
source.Reload ();
source.NotifyTracksChanged ();
source.UpdateFeedMessages ();
}
/*private void OnFeedAddedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Add (args.Feed);
}
}
private void OnFeedRemovedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Remove (args.Feed);
args.Feed.Delete ();
}
}
private void OnFeedRenamedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Sort ();
}
}
private void OnFeedUpdatingHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Reload ();
}
}
private void OnFeedDownloadCountChangedHandler (object sender, FeedDownloadCountChangedEventArgs args)
{
lock (sync) {
source.FeedModel.Reload ();
}
}*/
/*private void OnFeedItemAddedHandler (object sender, FeedItemEventArgs args)
{
lock (sync) {
if (args.Item != null) {
AddFeedItem (args.Item);
} else if (args.Items != null) {
foreach (FeedItem item in args.Items) {
AddFeedItem (item);
}
}
}
}*/
public void AddFeedItem (FeedItem item)
{
if (item.Enclosure != null) {
PodcastTrackInfo pi = new PodcastTrackInfo (new DatabaseTrackInfo (), item);
pi.Track.PrimarySource = source;
pi.Track.Save (true);
source.NotifyUser ();
} else {
item.Delete (false);
}
}
/*private void OnFeedItemRemovedHandler (object sender, FeedItemEventArgs e)
{
lock (sync) {
if (e.Item != null) {
PodcastItem.DeleteWithFeedId (e.Item.DbId);
} else if (e.Items != null) {
foreach (FeedItem fi in e.Items) {
PodcastItem.DeleteWithFeedId (fi.DbId);
}
}
source.Reload ();
}
}
private void OnFeedItemCountChanged (object sender,
FeedItemCountChangedEventArgs e)
{
//UpdateCount ();
}*/
/*private void OnFeedDownloadCompletedHandler (object sender,
FeedDownloadCompletedEventArgs e)
{
lock (sync) {
Feed f = feedDict[e.Feed.DbId];
if (e.Error == FeedDownloadError.None) {
if (String.IsNullOrEmpty(e.Feed.LocalEnclosurePath)) {
e.Feed.LocalEnclosurePath = Path.Combine (
tmp_enclosure_path, SanitizeName (e.Feed.Name)
);
}
if (f.AutoDownload != FeedAutoDownload.None) {
ReadOnlyCollection<FeedItem> items = e.Feed.Items;
if (items != null) {
if (f.AutoDownload == FeedAutoDownload.One &&
items.Count > 0) {
items[0].Enclosure.AsyncDownload ();
} else {
foreach (FeedItem fi in items) {
fi.Enclosure.AsyncDownload ();
}
}
}
}
}
source.Reload ();
}
}*/
/*private void OnTaskAssociated (object sender, EventArgs e)
{
lock (sync) {
source.Reload ();
}
}
private void OnTaskStatusChanged (object sender,
TaskStatusChangedEventArgs e)
{
lock (sync) {
source.Reload ();
}
}
private void TaskStartedHandler (object sender,
TaskEventArgs<HttpFileDownloadTask> e)
{
lock (sync) {
source.Reload ();
}
}
private void OnTaskStoppedHandler (object sender,
TaskEventArgs<HttpFileDownloadTask> e)
{
// TODO merge
lock (sync) {
if (e.Task != null && e.Task.Status == TaskStatus.Succeeded) {
FeedEnclosure enc = e.Task.UserState as FeedEnclosure;
if (enc != null) {
FeedItem item = enc.Item;
DatabaseTrackInfo track = null;
if (itemDict.ContainsKey (item.DbId)) {
PodcastItem pi = itemDict[item.DbId];
track = import_manager.ImportPodcast (enc.LocalPath);
if (track != null) {
pi.Track = track;
pi.New = true;
pi.Save ();
}
item.IsRead = true;
}
}
}
source.Reload ();
}
}*/
private void OnPlayerEvent (PlayerEventArgs args)
{
lock (sync) {
//source.Reload ();
}
}
public static string ArtworkIdFor (Feed feed)
{
string digest = Banshee.Base.CoverArtSpec.Digest (feed.Title);
return digest == null ? null : String.Format ("podcast-{0}", digest);
}
// Via Monopod
/*private static string SanitizeName (string s)
{
// remove /, : and \ from names
return s.Replace ('/', '_').Replace ('\\', '_').Replace (':', '_').Replace (' ', '_');
}*/
public string ServiceName {
get { return "PodcastService"; }
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Text;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
class TypeParser {
class Type {
public const int Ptr = -1;
public const int ByRef = -2;
public const int SzArray = -3;
public string type_fullname;
public string [] nested_names;
public int arity;
public int [] specs;
public Type [] generic_arguments;
public string assembly;
}
readonly string fullname;
readonly int length;
int position;
TypeParser (string fullname)
{
this.fullname = fullname;
this.length = fullname.Length;
}
Type ParseType (bool fq_name)
{
var type = new Type ();
type.type_fullname = ParsePart ();
type.nested_names = ParseNestedNames ();
if (TryGetArity (type))
type.generic_arguments = ParseGenericArguments (type.arity);
type.specs = ParseSpecs ();
if (fq_name)
type.assembly = ParseAssemblyName ();
return type;
}
static bool TryGetArity (Type type)
{
int arity = 0;
TryAddArity (type.type_fullname, ref arity);
var nested_names = type.nested_names;
if (!nested_names.IsNullOrEmpty ()) {
for (int i = 0; i < nested_names.Length; i++)
TryAddArity (nested_names [i], ref arity);
}
type.arity = arity;
return arity > 0;
}
static bool TryGetArity (string name, out int arity)
{
arity = 0;
var index = name.LastIndexOf ('`');
if (index == -1)
return false;
return ParseInt32 (name.Substring (index + 1), out arity);
}
static bool ParseInt32 (string value, out int result)
{
#if CF
try {
result = int.Parse (value);
return true;
} catch {
result = 0;
return false;
}
#else
return int.TryParse (value, out result);
#endif
}
static void TryAddArity (string name, ref int arity)
{
int type_arity;
if (!TryGetArity (name, out type_arity))
return;
arity += type_arity;
}
string ParsePart ()
{
var part = new StringBuilder ();
while (position < length && !IsDelimiter (fullname [position])) {
if (fullname [position] == '\\')
position++;
part.Append (fullname [position++]);
}
return part.ToString ();
}
static bool IsDelimiter (char chr)
{
return "+,[]*&".IndexOf (chr) != -1;
}
void TryParseWhiteSpace ()
{
while (position < length && Char.IsWhiteSpace (fullname [position]))
position++;
}
string [] ParseNestedNames ()
{
string [] nested_names = null;
while (TryParse ('+'))
Add (ref nested_names, ParsePart ());
return nested_names;
}
bool TryParse (char chr)
{
if (position < length && fullname [position] == chr) {
position++;
return true;
}
return false;
}
static void Add<T> (ref T [] array, T item)
{
if (array == null) {
array = new [] { item };
return;
}
array = array.Resize (array.Length + 1);
array [array.Length - 1] = item;
}
int [] ParseSpecs ()
{
int [] specs = null;
while (position < length) {
switch (fullname [position]) {
case '*':
position++;
Add (ref specs, Type.Ptr);
break;
case '&':
position++;
Add (ref specs, Type.ByRef);
break;
case '[':
position++;
switch (fullname [position]) {
case ']':
position++;
Add (ref specs, Type.SzArray);
break;
case '*':
position++;
Add (ref specs, 1);
break;
default:
var rank = 1;
while (TryParse (','))
rank++;
Add (ref specs, rank);
TryParse (']');
break;
}
break;
default:
return specs;
}
}
return specs;
}
Type [] ParseGenericArguments (int arity)
{
Type [] generic_arguments = null;
if (position == length || fullname [position] != '[')
return generic_arguments;
TryParse ('[');
for (int i = 0; i < arity; i++) {
var fq_argument = TryParse ('[');
Add (ref generic_arguments, ParseType (fq_argument));
if (fq_argument)
TryParse (']');
TryParse (',');
TryParseWhiteSpace ();
}
TryParse (']');
return generic_arguments;
}
string ParseAssemblyName ()
{
if (!TryParse (','))
return string.Empty;
TryParseWhiteSpace ();
var start = position;
while (position < length) {
var chr = fullname [position];
if (chr == '[' || chr == ']')
break;
position++;
}
return fullname.Substring (start, position - start);
}
public static TypeReference ParseType (ModuleDefinition module, string fullname)
{
if (string.IsNullOrEmpty (fullname))
return null;
var parser = new TypeParser (fullname);
return GetTypeReference (module, parser.ParseType (true));
}
static TypeReference GetTypeReference (ModuleDefinition module, Type type_info)
{
TypeReference type;
if (!TryGetDefinition (module, type_info, out type))
type = CreateReference (type_info, module, GetMetadataScope (module, type_info));
return CreateSpecs (type, type_info);
}
static TypeReference CreateSpecs (TypeReference type, Type type_info)
{
type = TryCreateGenericInstanceType (type, type_info);
var specs = type_info.specs;
if (specs.IsNullOrEmpty ())
return type;
for (int i = 0; i < specs.Length; i++) {
switch (specs [i]) {
case Type.Ptr:
type = new PointerType (type);
break;
case Type.ByRef:
type = new ByReferenceType (type);
break;
case Type.SzArray:
type = new ArrayType (type);
break;
default:
var array = new ArrayType (type);
array.Dimensions.Clear ();
for (int j = 0; j < specs [i]; j++)
array.Dimensions.Add (new ArrayDimension ());
type = array;
break;
}
}
return type;
}
static TypeReference TryCreateGenericInstanceType (TypeReference type, Type type_info)
{
var generic_arguments = type_info.generic_arguments;
if (generic_arguments.IsNullOrEmpty ())
return type;
var instance = new GenericInstanceType (type);
var instance_arguments = instance.GenericArguments;
for (int i = 0; i < generic_arguments.Length; i++)
instance_arguments.Add (GetTypeReference (type.Module, generic_arguments [i]));
return instance;
}
public static void SplitFullName (string fullname, out string @namespace, out string name)
{
var last_dot = fullname.LastIndexOf ('.');
if (last_dot == -1) {
@namespace = string.Empty;
name = fullname;
} else {
@namespace = fullname.Substring (0, last_dot);
name = fullname.Substring (last_dot + 1);
}
}
static TypeReference CreateReference (Type type_info, ModuleDefinition module, IMetadataScope scope)
{
string @namespace, name;
SplitFullName (type_info.type_fullname, out @namespace, out name);
var type = new TypeReference (@namespace, name, module, scope);
MetadataSystem.TryProcessPrimitiveTypeReference (type);
AdjustGenericParameters (type);
var nested_names = type_info.nested_names;
if (nested_names.IsNullOrEmpty ())
return type;
for (int i = 0; i < nested_names.Length; i++) {
type = new TypeReference (string.Empty, nested_names [i], module, null) {
DeclaringType = type,
};
AdjustGenericParameters (type);
}
return type;
}
static void AdjustGenericParameters (TypeReference type)
{
int arity;
if (!TryGetArity (type.Name, out arity))
return;
for (int i = 0; i < arity; i++)
type.GenericParameters.Add (new GenericParameter (type));
}
static IMetadataScope GetMetadataScope (ModuleDefinition module, Type type_info)
{
if (string.IsNullOrEmpty (type_info.assembly))
return module.TypeSystem.CoreLibrary;
AssemblyNameReference match;
var reference = AssemblyNameReference.Parse (type_info.assembly);
return module.TryGetAssemblyNameReference (reference, out match)
? match
: reference;
}
static bool TryGetDefinition (ModuleDefinition module, Type type_info, out TypeReference type)
{
type = null;
if (!TryCurrentModule (module, type_info))
return false;
var typedef = module.GetType (type_info.type_fullname);
if (typedef == null)
return false;
var nested_names = type_info.nested_names;
if (!nested_names.IsNullOrEmpty ()) {
for (int i = 0; i < nested_names.Length; i++)
typedef = typedef.GetNestedType (nested_names [i]);
}
type = typedef;
return true;
}
static bool TryCurrentModule (ModuleDefinition module, Type type_info)
{
if (string.IsNullOrEmpty (type_info.assembly))
return true;
if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly)
return true;
return false;
}
public static string ToParseable (TypeReference type)
{
if (type == null)
return null;
var name = new StringBuilder ();
AppendType (type, name, true, true);
return name.ToString ();
}
static void AppendNamePart (string part, StringBuilder name)
{
foreach (var c in part) {
if (IsDelimiter (c))
name.Append ('\\');
name.Append (c);
}
}
static void AppendType (TypeReference type, StringBuilder name, bool fq_name, bool top_level)
{
var declaring_type = type.DeclaringType;
if (declaring_type != null) {
AppendType (declaring_type, name, false, top_level);
name.Append ('+');
}
var @namespace = type.Namespace;
if (!string.IsNullOrEmpty (@namespace)) {
AppendNamePart (@namespace, name);
name.Append ('.');
}
AppendNamePart (type.GetElementType ().Name, name);
if (!fq_name)
return;
if (type.IsTypeSpecification ())
AppendTypeSpecification ((TypeSpecification) type, name);
if (RequiresFullyQualifiedName (type, top_level)) {
name.Append (", ");
name.Append (GetScopeFullName (type));
}
}
static string GetScopeFullName (TypeReference type)
{
var scope = type.Scope;
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
return ((AssemblyNameReference) scope).FullName;
case MetadataScopeType.ModuleDefinition:
return ((ModuleDefinition) scope).Assembly.Name.FullName;
}
throw new ArgumentException ();
}
static void AppendTypeSpecification (TypeSpecification type, StringBuilder name)
{
if (type.ElementType.IsTypeSpecification ())
AppendTypeSpecification ((TypeSpecification) type.ElementType, name);
switch (type.etype) {
case ElementType.Ptr:
name.Append ('*');
break;
case ElementType.ByRef:
name.Append ('&');
break;
case ElementType.SzArray:
case ElementType.Array:
var array = (ArrayType) type;
if (array.IsVector) {
name.Append ("[]");
} else {
name.Append ('[');
for (int i = 1; i < array.Rank; i++)
name.Append (',');
name.Append (']');
}
break;
case ElementType.GenericInst:
var instance = (GenericInstanceType) type;
var arguments = instance.GenericArguments;
name.Append ('[');
for (int i = 0; i < arguments.Count; i++) {
if (i > 0)
name.Append (',');
var argument = arguments [i];
var requires_fqname = argument.Scope != argument.Module;
if (requires_fqname)
name.Append ('[');
AppendType (argument, name, true, false);
if (requires_fqname)
name.Append (']');
}
name.Append (']');
break;
default:
return;
}
}
static bool RequiresFullyQualifiedName (TypeReference type, bool top_level)
{
if (type.Scope == type.Module)
return false;
if (type.Scope.Name == "mscorlib" && top_level)
return false;
return true;
}
}
}
| |
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* 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 FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// This stores a monotonically increasing set of <c>Term, TermInfo</c> pairs in a
/// Directory. Pairs are accessed either by <see cref="Term"/> or by ordinal position the
/// set.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("(4.0) this class has been replaced by FormatPostingsTermsDictReader, except for reading old segments.")]
internal sealed class TermInfosReader : IDisposable
{
private readonly Directory directory;
private readonly string segment;
private readonly FieldInfos fieldInfos;
private readonly DisposableThreadLocal<ThreadResources> threadResources = new DisposableThreadLocal<ThreadResources>();
private readonly SegmentTermEnum origEnum;
private readonly long size;
private readonly TermInfosReaderIndex index;
private readonly int indexLength;
private readonly int totalIndexInterval;
private const int DEFAULT_CACHE_SIZE = 1024;
// Just adds term's ord to TermInfo
public sealed class TermInfoAndOrd : TermInfo
{
internal readonly long termOrd;
public TermInfoAndOrd(TermInfo ti, long termOrd)
: base(ti)
{
Debug.Assert(termOrd >= 0);
this.termOrd = termOrd;
}
}
private class CloneableTerm : DoubleBarrelLRUCache.CloneableKey
{
internal Term term;
public CloneableTerm(Term t)
{
this.term = t;
}
public override bool Equals(object other)
{
CloneableTerm t = (CloneableTerm)other;
return this.term.Equals(t.term);
}
public override int GetHashCode()
{
return term.GetHashCode();
}
public override object Clone()
{
return new CloneableTerm(term);
}
}
private readonly DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd> termsCache = new DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd>(DEFAULT_CACHE_SIZE);
/// <summary>
/// Per-thread resources managed by ThreadLocal.
/// </summary>
private sealed class ThreadResources
{
internal SegmentTermEnum termEnum;
}
internal TermInfosReader(Directory dir, string seg, FieldInfos fis, IOContext context, int indexDivisor)
{
bool success = false;
if (indexDivisor < 1 && indexDivisor != -1)
{
throw new System.ArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor);
}
try
{
directory = dir;
segment = seg;
fieldInfos = fis;
origEnum = new SegmentTermEnum(directory.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), context), fieldInfos, false);
size = origEnum.size;
if (indexDivisor != -1)
{
// Load terms index
totalIndexInterval = origEnum.indexInterval * indexDivisor;
string indexFileName = IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
SegmentTermEnum indexEnum = new SegmentTermEnum(directory.OpenInput(indexFileName, context), fieldInfos, true);
try
{
index = new TermInfosReaderIndex(indexEnum, indexDivisor, dir.FileLength(indexFileName), totalIndexInterval);
indexLength = index.Length;
}
finally
{
indexEnum.Dispose();
}
}
else
{
// Do not load terms index:
totalIndexInterval = -1;
index = null;
indexLength = -1;
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
Dispose();
}
}
}
public int SkipInterval
{
get
{
return origEnum.skipInterval;
}
}
public int MaxSkipLevels
{
get
{
return origEnum.maxSkipLevels;
}
}
public void Dispose()
{
IOUtils.Dispose(origEnum, threadResources);
}
/// <summary>
/// Returns the number of term/value pairs in the set.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
internal long Count
{
get { return size; }
}
private ThreadResources GetThreadResources()
{
ThreadResources resources = threadResources.Get();
if (resources == null)
{
resources = new ThreadResources();
resources.termEnum = Terms();
threadResources.Set(resources);
}
return resources;
}
private static readonly IComparer<BytesRef> legacyComparer = BytesRef.UTF8SortedAsUTF16Comparer;
private int CompareAsUTF16(Term term1, Term term2)
{
if (term1.Field.Equals(term2.Field, StringComparison.Ordinal))
{
return legacyComparer.Compare(term1.Bytes, term2.Bytes);
}
else
{
return term1.Field.CompareToOrdinal(term2.Field);
}
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
internal TermInfo Get(Term term)
{
return Get(term, false);
}
/// <summary>
/// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary>
private TermInfo Get(Term term, bool mustSeekEnum)
{
if (size == 0)
{
return null;
}
EnsureIndexIsRead();
TermInfoAndOrd tiOrd = termsCache.Get(new CloneableTerm(term));
ThreadResources resources = GetThreadResources();
if (!mustSeekEnum && tiOrd != null)
{
return tiOrd;
}
return SeekEnum(resources.termEnum, term, tiOrd, true);
}
public void CacheCurrentTerm(SegmentTermEnum enumerator)
{
termsCache.Put(new CloneableTerm(enumerator.Term()), new TermInfoAndOrd(enumerator.termInfo, enumerator.position));
}
internal static Term DeepCopyOf(Term other)
{
return new Term(other.Field, BytesRef.DeepCopyOf(other.Bytes));
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, bool useCache)
{
if (useCache)
{
return SeekEnum(enumerator, term, termsCache.Get(new CloneableTerm(DeepCopyOf(term))), useCache);
}
else
{
return SeekEnum(enumerator, term, null, useCache);
}
}
internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, TermInfoAndOrd tiOrd, bool useCache)
{
if (size == 0)
{
return null;
}
// optimize sequential access: first try scanning cached enum w/o seeking
if (enumerator.Term() != null && ((enumerator.Prev() != null && CompareAsUTF16(term, enumerator.Prev()) > 0) || CompareAsUTF16(term, enumerator.Term()) >= 0)) // term is at or past current
{
int enumOffset = (int)(enumerator.position / totalIndexInterval) + 1;
if (indexLength == enumOffset || index.CompareTo(term, enumOffset) < 0) // but before end of block
{
// no need to seek
TermInfo ti;
int numScans = enumerator.ScanTo(term);
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti = enumerator.termInfo;
if (numScans > 1)
{
// we only want to put this TermInfo into the cache if
// scanEnum skipped more than one dictionary entry.
// this prevents RangeQueries or WildcardQueries to
// wipe out the cache when they iterate over a large numbers
// of terms in order
if (tiOrd == null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti, enumerator.position));
}
}
else
{
Debug.Assert(SameTermInfo(ti, tiOrd, enumerator));
Debug.Assert(enumerator.position == tiOrd.termOrd);
}
}
}
else
{
ti = null;
}
return ti;
}
}
// random-access: must seek
int indexPos;
if (tiOrd != null)
{
indexPos = (int)(tiOrd.termOrd / totalIndexInterval);
}
else
{
// Must do binary search:
indexPos = index.GetIndexOffset(term);
}
index.SeekEnum(enumerator, indexPos);
enumerator.ScanTo(term);
TermInfo ti_;
if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0)
{
ti_ = enumerator.termInfo;
if (tiOrd == null)
{
if (useCache)
{
termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti_, enumerator.position));
}
}
else
{
Debug.Assert(SameTermInfo(ti_, tiOrd, enumerator));
Debug.Assert(enumerator.position == tiOrd.termOrd);
}
}
else
{
ti_ = null;
}
return ti_;
}
// called only from asserts
private bool SameTermInfo(TermInfo ti1, TermInfo ti2, SegmentTermEnum enumerator)
{
if (ti1.DocFreq != ti2.DocFreq)
{
return false;
}
if (ti1.FreqPointer != ti2.FreqPointer)
{
return false;
}
if (ti1.ProxPointer != ti2.ProxPointer)
{
return false;
}
// skipOffset is only valid when docFreq >= skipInterval:
if (ti1.DocFreq >= enumerator.skipInterval && ti1.SkipOffset != ti2.SkipOffset)
{
return false;
}
return true;
}
private void EnsureIndexIsRead()
{
if (index == null)
{
throw new InvalidOperationException("terms index was not loaded when this reader was created");
}
}
/// <summary>
/// Returns the position of a <see cref="Term"/> in the set or -1. </summary>
internal long GetPosition(Term term)
{
if (size == 0)
{
return -1;
}
EnsureIndexIsRead();
int indexOffset = index.GetIndexOffset(term);
SegmentTermEnum enumerator = GetThreadResources().termEnum;
index.SeekEnum(enumerator, indexOffset);
while (CompareAsUTF16(term, enumerator.Term()) > 0 && enumerator.Next())
{
}
if (CompareAsUTF16(term, enumerator.Term()) == 0)
{
return enumerator.position;
}
else
{
return -1;
}
}
/// <summary>
/// Returns an enumeration of all the <see cref="Term"/>s and <see cref="TermInfo"/>s in the set. </summary>
public SegmentTermEnum Terms()
{
return (SegmentTermEnum)origEnum.Clone();
}
/// <summary>
/// Returns an enumeration of terms starting at or after the named term. </summary>
public SegmentTermEnum Terms(Term term)
{
Get(term, true);
return (SegmentTermEnum)GetThreadResources().termEnum.Clone();
}
internal long RamBytesUsed()
{
return index == null ? 0 : index.RamBytesUsed();
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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 Autofac;
using Autofac.Builder;
using log4net;
using MindTouch.Aws;
using MindTouch.Dream.Test;
using MindTouch.Dream.Test.Aws;
using MindTouch.Extensions.Time;
using MindTouch.Tasking;
using MindTouch.Xml;
using Moq;
using NUnit.Framework;
namespace MindTouch.Dream.Storage.Test {
[TestFixture]
public class AwsS3PrivateStorageTests {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private DreamHostInfo _hostInfo;
private Mock<IAwsS3Client> _s3ClientMock;
private MockServiceInfo _mockService;
private string _storageRoot;
private string _rootPath;
[TestFixtureSetUp]
public void Init() {
var config = new XDoc("config")
.Start("storage")
.Attr("type", "s3")
.Elem("root", "rootpath")
.Elem("bucket", "bucket")
.Elem("privatekey", "private")
.Elem("publickey", "public")
.End();
var builder = new ContainerBuilder();
builder.Register((c, p) => {
var s3Config = p.TypedAs<AwsS3ClientConfig>();
_rootPath = s3Config.RootPath;
Assert.AreEqual("default", s3Config.Endpoint.Name);
Assert.AreEqual("bucket", s3Config.Bucket);
Assert.AreEqual("private", s3Config.PrivateKey);
Assert.AreEqual("public", s3Config.PublicKey);
Assert.IsNull(_s3ClientMock, "storage already resolved");
_s3ClientMock = new Mock<IAwsS3Client>();
return _s3ClientMock.Object;
}).As<IAwsS3Client>().ServiceScoped();
_hostInfo = DreamTestHelper.CreateRandomPortHost(config, builder.Build(ContainerBuildOptions.None));
}
[SetUp]
public void Setup() {
_s3ClientMock = null;
_mockService = MockService.CreateMockServiceWithPrivateStorage(_hostInfo);
_storageRoot = _mockService.Service.Storage.Uri.LastSegment;
}
[Test]
public void Can_init() {
Assert.IsNotNull(_s3ClientMock);
Assert.AreEqual("rootpath/" + _storageRoot, _rootPath);
}
[Test]
public void Can_put_file_without_expiration_at_path() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo/bar", It.Is<AwsS3FileHandle>(y => y.ValidateFileHandle(data, null)))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_put_file_without_expiration_at_root() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo", It.Is<AwsS3FileHandle>(y => y.ValidateFileHandle(data, null)))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo").Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_put_file_with_expiration() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo/bar", It.Is<AwsS3FileHandle>(y => y.ValidateFileHandle(data, 10.Seconds())))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").With("ttl", 10).Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Put_at_directory_path_fails() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo/bar/", It.IsAny<AwsS3FileHandle>())).Throws(new Exception("bad puppy")).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsFalse(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_read_file() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar", false)).Returns(AwsTestHelpers.CreateFileInfo(data)).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Get(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
Assert.AreEqual(data, response.ToText());
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_head_file() {
var info = new AwsS3DataInfo(new AwsS3FileHandle() {
Expiration = null,
TimeToLive = null,
MimeType = MimeType.TEXT,
Modified = DateTime.UtcNow,
Size = 10,
});
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar", true)).Returns(info).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Head(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
Assert.AreEqual(10, response.ContentLength);
_s3ClientMock.VerifyAll();
}
[Test]
public void Reading_nonexisting_file_returns_Not_Found() {
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar", false)).Returns((AwsS3DataInfo)null).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Get(new Result<DreamMessage>())
);
Assert.IsFalse(response.IsSuccessful);
Assert.AreEqual(DreamStatus.NotFound, response.Status);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_list_directory() {
var doc = new XDoc("files").Elem("x", StringUtil.CreateAlphaNumericKey(10));
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar/", false)).Returns(new AwsS3DataInfo(doc)).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Get(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
Assert.AreEqual(doc.ToCompactString(), response.ToDocument().ToCompactString());
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_head_directory() {
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar/", true)).Returns(new AwsS3DataInfo(new XDoc("x"))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Head(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Listing_nonexisting_directory_returns_Not_Found() {
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar/", false)).Returns((AwsS3DataInfo)null).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Get(new Result<DreamMessage>())
);
Assert.IsFalse(response.IsSuccessful);
Assert.AreEqual(DreamStatus.NotFound, response.Status);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_delete_file() {
_s3ClientMock.Setup(x => x.Delete("foo/bar")).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Delete(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_delete_directory() {
_s3ClientMock.Setup(x => x.Delete("foo/bar/")).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Delete(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.PeerResolvers
{
using System;
using System.Collections.Generic;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
[ObsoleteAttribute ("PeerChannel feature is obsolete and will be removed in the future.", false)]
[ServiceBehavior(UseSynchronizationContext = false, InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class CustomPeerResolverService : IPeerResolverContract
{
internal enum RegistrationState
{
OK, Deleted
}
internal class RegistrationEntry
{
Guid clientId;
Guid registrationId;
string meshId;
DateTime expires;
PeerNodeAddress address;
RegistrationState state;
public RegistrationEntry(Guid clientId, Guid registrationId, string meshId, DateTime expires, PeerNodeAddress address)
{
this.ClientId = clientId;
this.RegistrationId = registrationId;
this.MeshId = meshId;
this.Expires = expires;
this.Address = address;
this.State = RegistrationState.OK;
}
public Guid ClientId
{
get { return clientId; }
set { clientId = value; }
}
public Guid RegistrationId
{
get { return registrationId; }
set { registrationId = value; }
}
public string MeshId
{
get { return meshId; }
set { meshId = value; }
}
public DateTime Expires
{
get { return expires; }
set { expires = value; }
}
public PeerNodeAddress Address
{
get { return address; }
set { address = value; }
}
public RegistrationState State
{
get { return state; }
set { state = value; }
}
}
internal class LiteLock
{
bool forWrite;
bool upgraded;
ReaderWriterLock locker;
TimeSpan timeout = TimeSpan.FromMinutes(1);
LockCookie lc;
LiteLock(ReaderWriterLock locker, bool forWrite)
{
this.locker = locker;
this.forWrite = forWrite;
}
public static void Acquire(out LiteLock liteLock, ReaderWriterLock locker)
{
Acquire(out liteLock, locker, false);
}
public static void Acquire(out LiteLock liteLock, ReaderWriterLock locker, bool forWrite)
{
LiteLock theLock = new LiteLock(locker, forWrite);
try { }
finally
{
if (forWrite)
{
locker.AcquireWriterLock(theLock.timeout);
}
else
{
locker.AcquireReaderLock(theLock.timeout);
}
liteLock = theLock;
}
}
public static void Release(LiteLock liteLock)
{
if (liteLock == null)
{
return;
}
if (liteLock.forWrite)
{
liteLock.locker.ReleaseWriterLock();
}
else
{
Fx.Assert(!liteLock.upgraded, "Can't release while upgraded!");
liteLock.locker.ReleaseReaderLock();
}
}
public void UpgradeToWriterLock()
{
Fx.Assert(!forWrite, "Invalid call to Upgrade!!");
Fx.Assert(!upgraded, "Already upgraded!");
try { }
finally
{
lc = locker.UpgradeToWriterLock(timeout);
upgraded = true;
}
}
public void DowngradeFromWriterLock()
{
Fx.Assert(!forWrite, "Invalid call to Downgrade!!");
if (upgraded)
{
locker.DowngradeFromWriterLock(ref lc);
upgraded = false;
}
}
}
internal class MeshEntry
{
Dictionary<Guid, RegistrationEntry> entryTable;
Dictionary<string, RegistrationEntry> service2EntryTable;
List<RegistrationEntry> entryList;
ReaderWriterLock gate;
internal MeshEntry()
{
EntryTable = new Dictionary<Guid, RegistrationEntry>();
Service2EntryTable = new Dictionary<string, RegistrationEntry>();
EntryList = new List<RegistrationEntry>();
Gate = new ReaderWriterLock();
}
public Dictionary<Guid, RegistrationEntry> EntryTable
{
get { return entryTable; }
set { entryTable = value; }
}
public Dictionary<string, RegistrationEntry> Service2EntryTable
{
get { return service2EntryTable; }
set { service2EntryTable = value; }
}
public List<RegistrationEntry> EntryList
{
get { return entryList; }
set { entryList = value; }
}
public ReaderWriterLock Gate
{
get { return gate; }
set { gate = value; }
}
}
Dictionary<string, MeshEntry> meshId2Entry = new Dictionary<string, MeshEntry>();
ReaderWriterLock gate;
TimeSpan timeout = TimeSpan.FromMinutes(1);
TimeSpan cleanupInterval = TimeSpan.FromMinutes(1);
TimeSpan refreshInterval = TimeSpan.FromMinutes(10);
bool controlShape;
bool isCleaning;
IOThreadTimer timer;
object thisLock = new object();
bool opened;
TimeSpan LockWait = TimeSpan.FromSeconds(5);
public CustomPeerResolverService()
{
isCleaning = false;
gate = new ReaderWriterLock();
}
public TimeSpan CleanupInterval
{
get
{
return cleanupInterval;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
lock (ThisLock)
{
ThrowIfOpened("Set CleanupInterval");
this.cleanupInterval = value;
}
}
}
public TimeSpan RefreshInterval
{
get
{
return refreshInterval;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
lock (ThisLock)
{
ThrowIfOpened("Set RefreshInterval");
this.refreshInterval = value;
}
}
}
public bool ControlShape
{
get
{
return this.controlShape;
}
set
{
lock (ThisLock)
{
ThrowIfOpened("Set ControlShape");
this.controlShape = value;
}
}
}
MeshEntry GetMeshEntry(string meshId) { return GetMeshEntry(meshId, true); }
MeshEntry GetMeshEntry(string meshId, bool createIfNotExists)
{
MeshEntry meshEntry = null;
LiteLock ll = null;
try
{
LiteLock.Acquire(out ll, gate);
if (!this.meshId2Entry.TryGetValue(meshId, out meshEntry) && createIfNotExists)
{
meshEntry = new MeshEntry();
try
{
ll.UpgradeToWriterLock();
meshId2Entry.Add(meshId, meshEntry);
}
finally
{
ll.DowngradeFromWriterLock();
}
}
}
finally
{
LiteLock.Release(ll);
}
Fx.Assert(meshEntry != null || !createIfNotExists, "GetMeshEntry failed to get an entry!");
return meshEntry;
}
public virtual RegisterResponseInfo Register(Guid clientId, string meshId, PeerNodeAddress address)
{
Guid registrationId = Guid.NewGuid();
DateTime expiry = DateTime.UtcNow + RefreshInterval;
RegistrationEntry entry = null;
MeshEntry meshEntry = null;
lock (ThisLock)
{
entry = new RegistrationEntry(clientId, registrationId, meshId, expiry, address);
meshEntry = GetMeshEntry(meshId);
if (meshEntry.Service2EntryTable.ContainsKey(address.ServicePath))
PeerExceptionHelper.ThrowInvalidOperation_DuplicatePeerRegistration(address.ServicePath);
LiteLock ll = null;
try
{
// meshEntry.gate can be held by this thread for write if this is coming from update
// else MUST not be held at all.
if (!meshEntry.Gate.IsWriterLockHeld)
{
LiteLock.Acquire(out ll, meshEntry.Gate, true);
}
meshEntry.EntryTable.Add(registrationId, entry);
meshEntry.EntryList.Add(entry);
meshEntry.Service2EntryTable.Add(address.ServicePath, entry);
}
finally
{
if (ll != null)
LiteLock.Release(ll);
}
}
return new RegisterResponseInfo(registrationId, RefreshInterval);
}
public virtual RegisterResponseInfo Register(RegisterInfo registerInfo)
{
if (registerInfo == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("registerInfo", SR.GetString(SR.PeerNullRegistrationInfo));
}
ThrowIfClosed("Register");
if (!registerInfo.HasBody() || String.IsNullOrEmpty(registerInfo.MeshId))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("registerInfo", SR.GetString(SR.PeerInvalidMessageBody, registerInfo));
}
return Register(registerInfo.ClientId, registerInfo.MeshId, registerInfo.NodeAddress);
}
public virtual RegisterResponseInfo Update(UpdateInfo updateInfo)
{
if (updateInfo == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("updateInfo", SR.GetString(SR.PeerNullRegistrationInfo));
}
ThrowIfClosed("Update");
if (!updateInfo.HasBody() || String.IsNullOrEmpty(updateInfo.MeshId) || updateInfo.NodeAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("updateInfo", SR.GetString(SR.PeerInvalidMessageBody, updateInfo));
}
Guid registrationId = updateInfo.RegistrationId;
RegistrationEntry entry;
MeshEntry meshEntry = GetMeshEntry(updateInfo.MeshId);
LiteLock ll = null;
//handle cases when Update ----s with Register.
if (updateInfo.RegistrationId == Guid.Empty || meshEntry == null)
return Register(updateInfo.ClientId, updateInfo.MeshId, updateInfo.NodeAddress);
//
// preserve locking order between ThisLock and the LiteLock.
lock (ThisLock)
{
try
{
LiteLock.Acquire(out ll, meshEntry.Gate);
if (!meshEntry.EntryTable.TryGetValue(updateInfo.RegistrationId, out entry))
{
try
{
// upgrade to writer lock
ll.UpgradeToWriterLock();
return Register(updateInfo.ClientId, updateInfo.MeshId, updateInfo.NodeAddress);
}
finally
{
ll.DowngradeFromWriterLock();
}
}
lock (entry)
{
entry.Address = updateInfo.NodeAddress;
entry.Expires = DateTime.UtcNow + this.RefreshInterval;
}
}
finally
{
LiteLock.Release(ll);
}
}
return new RegisterResponseInfo(registrationId, RefreshInterval);
}
public virtual ResolveResponseInfo Resolve(ResolveInfo resolveInfo)
{
if (resolveInfo == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("resolveInfo", SR.GetString(SR.PeerNullResolveInfo));
}
ThrowIfClosed("Resolve");
if (!resolveInfo.HasBody())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("resolveInfo", SR.GetString(SR.PeerInvalidMessageBody, resolveInfo));
}
int currentCount = 0;
int index = 0;
int maxEntries = resolveInfo.MaxAddresses;
ResolveResponseInfo response = new ResolveResponseInfo();
List<PeerNodeAddress> results = new List<PeerNodeAddress>();
List<RegistrationEntry> entries = null;
PeerNodeAddress address;
RegistrationEntry entry;
MeshEntry meshEntry = GetMeshEntry(resolveInfo.MeshId, false);
if (meshEntry != null)
{
LiteLock ll = null;
try
{
LiteLock.Acquire(out ll, meshEntry.Gate);
entries = meshEntry.EntryList;
if (entries.Count <= maxEntries)
{
foreach (RegistrationEntry e in entries)
{
results.Add(e.Address);
}
}
else
{
Random random = new Random();
while (currentCount < maxEntries)
{
index = random.Next(entries.Count);
entry = entries[index];
Fx.Assert(entry.State == RegistrationState.OK, "A deleted registration is still around!");
address = entry.Address;
if (!results.Contains(address))
results.Add(address);
currentCount++;
}
}
}
finally
{
LiteLock.Release(ll);
}
}
response.Addresses = results.ToArray();
return response;
}
public virtual void Unregister(UnregisterInfo unregisterInfo)
{
if (unregisterInfo == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("unregisterinfo", SR.GetString(SR.PeerNullRegistrationInfo));
}
ThrowIfClosed("Unregister");
if (!unregisterInfo.HasBody() || String.IsNullOrEmpty(unregisterInfo.MeshId) || unregisterInfo.RegistrationId == Guid.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("unregisterInfo", SR.GetString(SR.PeerInvalidMessageBody, unregisterInfo));
}
RegistrationEntry registration = null;
MeshEntry meshEntry = GetMeshEntry(unregisterInfo.MeshId, false);
//there could be a ---- that two different threads could be working on the same entry
//we wont optimize for that case.
LiteLock ll = null;
try
{
LiteLock.Acquire(out ll, meshEntry.Gate, true);
if (!meshEntry.EntryTable.TryGetValue(unregisterInfo.RegistrationId, out registration))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("unregisterInfo", SR.GetString(SR.PeerInvalidMessageBody, unregisterInfo));
meshEntry.EntryTable.Remove(unregisterInfo.RegistrationId);
meshEntry.EntryList.Remove(registration);
meshEntry.Service2EntryTable.Remove(registration.Address.ServicePath);
registration.State = RegistrationState.Deleted;
}
finally
{
LiteLock.Release(ll);
}
}
public virtual RefreshResponseInfo Refresh(RefreshInfo refreshInfo)
{
if (refreshInfo == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("refreshInfo", SR.GetString(SR.PeerNullRefreshInfo));
}
ThrowIfClosed("Refresh");
if (!refreshInfo.HasBody() || String.IsNullOrEmpty(refreshInfo.MeshId) || refreshInfo.RegistrationId == Guid.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("refreshInfo", SR.GetString(SR.PeerInvalidMessageBody, refreshInfo));
}
RefreshResult result = RefreshResult.RegistrationNotFound;
RegistrationEntry entry = null;
MeshEntry meshEntry = GetMeshEntry(refreshInfo.MeshId, false);
LiteLock ll = null;
if (meshEntry != null)
{
try
{
LiteLock.Acquire(out ll, meshEntry.Gate);
if (!meshEntry.EntryTable.TryGetValue(refreshInfo.RegistrationId, out entry))
return new RefreshResponseInfo(RefreshInterval, result);
lock (entry)
{
if (entry.State == RegistrationState.OK)
{
entry.Expires = DateTime.UtcNow + RefreshInterval;
result = RefreshResult.Success;
}
}
}
finally
{
LiteLock.Release(ll);
}
}
return new RefreshResponseInfo(RefreshInterval, result);
}
public virtual ServiceSettingsResponseInfo GetServiceSettings()
{
ThrowIfClosed("GetServiceSettings");
ServiceSettingsResponseInfo info = new ServiceSettingsResponseInfo(this.ControlShape);
return info;
}
public virtual void Open()
{
ThrowIfOpened("Open");
if (this.refreshInterval <= TimeSpan.Zero)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("RefreshInterval", SR.GetString(SR.RefreshIntervalMustBeGreaterThanZero, this.refreshInterval));
if (this.CleanupInterval <= TimeSpan.Zero)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("CleanupInterval", SR.GetString(SR.CleanupIntervalMustBeGreaterThanZero, this.cleanupInterval));
//check that we are good to open
timer = new IOThreadTimer(new Action<object>(CleanupActivity), null, false);
timer.Set(CleanupInterval);
opened = true;
}
public virtual void Close()
{
ThrowIfClosed("Close");
timer.Cancel();
opened = false;
}
internal virtual void CleanupActivity(object state)
{
if (!opened)
return;
if (!isCleaning)
{
lock (ThisLock)
{
if (!isCleaning)
{
isCleaning = true;
try
{
MeshEntry meshEntry = null;
//acquire a write lock. from the reader/writer lock can we postpone until no contention?
ICollection<string> keys = null;
LiteLock ll = null;
try
{
LiteLock.Acquire(out ll, gate);
keys = meshId2Entry.Keys;
}
finally
{
LiteLock.Release(ll);
}
foreach (string meshId in keys)
{
meshEntry = GetMeshEntry(meshId);
CleanupMeshEntry(meshEntry);
}
}
finally
{
isCleaning = false;
if (opened)
timer.Set(this.CleanupInterval);
}
}
}
}
}
//always call this from a readlock
void CleanupMeshEntry(MeshEntry meshEntry)
{
List<Guid> remove = new List<Guid>();
if (!opened)
return;
LiteLock ll = null;
try
{
LiteLock.Acquire(out ll, meshEntry.Gate, true);
foreach (KeyValuePair<Guid, RegistrationEntry> item in meshEntry.EntryTable)
{
if ((item.Value.Expires <= DateTime.UtcNow) || (item.Value.State == RegistrationState.Deleted))
{
remove.Add(item.Key);
meshEntry.EntryList.Remove(item.Value);
meshEntry.Service2EntryTable.Remove(item.Value.Address.ServicePath);
}
}
foreach (Guid id in remove)
{
meshEntry.EntryTable.Remove(id);
}
}
finally
{
LiteLock.Release(ll);
}
}
object ThisLock
{
get
{
return this.thisLock;
}
}
void ThrowIfOpened(string operation)
{
if (opened)
PeerExceptionHelper.ThrowInvalidOperation_NotValidWhenOpen(operation);
}
void ThrowIfClosed(string operation)
{
if (!opened)
PeerExceptionHelper.ThrowInvalidOperation_NotValidWhenClosed(operation);
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\CharacterMovementComponent.h:159
namespace UnrealEngine
{
[ManageType("ManageCharacterMovementComponent")]
public partial class ManageCharacterMovementComponent : UCharacterMovementComponent, IManageWrapper
{
public ManageCharacterMovementComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_AdjustFloorHeight(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_AdjustProxyCapsuleSize(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ApplyAccumulatedForces(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ApplyDownwardForce(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ApplyNetworkMovementMode(IntPtr self, byte receivedMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ApplyRepulsionForce(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ApplyVelocityBraking(IntPtr self, float deltaTime, float friction, float brakingDeceleration);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_CalcVelocity(IntPtr self, float deltaTime, float friction, bool bFluid, float brakingDeceleration);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ClearAccumulatedForces(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ClientAckGoodMove(IntPtr self, float timeStamp);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ClientAckGoodMove_Implementation(IntPtr self, float timeStamp);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_Crouch(IntPtr self, bool bClientSimulation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_DisableMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ForceReplicationUpdate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_MaintainHorizontalGroundVelocity(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_MaybeSaveBaseLocation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_MaybeUpdateBasedMovement(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_NotifyJumpApex(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnClientTimeStampResetDetected(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnTimeDiscrepancyDetected(IntPtr self, float currentTimeDiscrepancy, float lifetimeRawTimeDiscrepancy, float lifetime, float currentMoveError);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PerformMovement(IntPtr self, float deltaTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PhysCustom(IntPtr self, float deltaTime, int iterations);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PhysFalling(IntPtr self, float deltaTime, int iterations);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PhysFlying(IntPtr self, float deltaTime, int iterations);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PhysicsRotation(IntPtr self, float deltaTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PhysNavWalking(IntPtr self, float deltaTime, int iterations);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PhysSwimming(IntPtr self, float deltaTime, int iterations);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PhysWalking(IntPtr self, float deltaTime, int iterations);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SaveBaseLocation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SetDefaultMovementMode(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SetNavWalkingPhysics(IntPtr self, bool bEnable);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SimulateMovement(IntPtr self, float deltaTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SmoothClientPosition(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_StartNewPhysics(IntPtr self, float deltaTime, int iterations);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UnCrouch(IntPtr self, bool bClientSimulation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateBasedMovement(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateCharacterStateAfterMovement(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateCharacterStateBeforeMovement(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateFloorFromAdjustment(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateFromCompressedFlags(IntPtr self, byte flags);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateProxyAcceleration(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_StopActiveMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnTeleported(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SetPlaneConstraintEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SnapUpdatedComponentToPlane(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_StopMovementImmediately(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateComponentVelocity(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UpdateTickRegistration(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UCharacterMovementComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Adjust distance from floor, trying to maintain a slight offset from the floor when walking (based on CurrentFloor).
/// </summary>
public override void AdjustFloorHeight()
=> E__Supper__UCharacterMovementComponent_AdjustFloorHeight(this);
/// <summary>
/// Adjust the size of the capsule on simulated proxies, to avoid overlaps due to replication rounding.
/// <para>Changes to the capsule size on the proxy should set bShrinkProxyCapsule=true and possibly call AdjustProxyCapsuleSize() immediately if applicable. </para>
/// </summary>
protected override void AdjustProxyCapsuleSize()
=> E__Supper__UCharacterMovementComponent_AdjustProxyCapsuleSize(this);
/// <summary>
/// Applies momentum accumulated through AddImpulse() and AddForce(), then clears those forces. Does *not* use ClearAccumulatedForces() since that would clear pending launch velocity as well.
/// </summary>
public override void ApplyAccumulatedForces(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_ApplyAccumulatedForces(this, deltaSeconds);
/// <summary>
/// Applies downward force when walking on top of physics objects.
/// </summary>
/// <param name="deltaSeconds">Time elapsed since last frame.</param>
public override void ApplyDownwardForce(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_ApplyDownwardForce(this, deltaSeconds);
public override void ApplyNetworkMovementMode(byte receivedMode)
=> E__Supper__UCharacterMovementComponent_ApplyNetworkMovementMode(this, receivedMode);
/// <summary>
/// Applies repulsion force to all touched components.
/// </summary>
public override void ApplyRepulsionForce(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_ApplyRepulsionForce(this, deltaSeconds);
/// <summary>
/// Slows towards stop.
/// </summary>
protected override void ApplyVelocityBraking(float deltaTime, float friction, float brakingDeceleration)
=> E__Supper__UCharacterMovementComponent_ApplyVelocityBraking(this, deltaTime, friction, brakingDeceleration);
/// <summary>
/// Updates Velocity and Acceleration based on the current state, applying the effects of friction and acceleration or deceleration. Does not apply gravity.
/// <para>This is used internally during movement updates. Normally you don't need to call this from outside code, but you might want to use it for custom movement modes. </para>
/// </summary>
/// <param name="deltaTime">time elapsed since last frame.</param>
/// <param name="friction">coefficient of friction when not accelerating, or in the direction opposite acceleration.</param>
/// <param name="bFluid">true if moving through a fluid, causing Friction to always be applied regardless of acceleration.</param>
/// <param name="brakingDeceleration">deceleration applied when not accelerating, or when exceeding max velocity.</param>
public override void CalcVelocity(float deltaTime, float friction, bool bFluid, float brakingDeceleration)
=> E__Supper__UCharacterMovementComponent_CalcVelocity(this, deltaTime, friction, bFluid, brakingDeceleration);
/// <summary>
/// Clears forces accumulated through AddImpulse() and AddForce(), and also pending launch velocity.
/// </summary>
public override void ClearAccumulatedForces()
=> E__Supper__UCharacterMovementComponent_ClearAccumulatedForces(this);
/// <summary>
/// If no client adjustment is needed after processing received ServerMove(), ack the good move so client can remove it from SavedMoves
/// </summary>
public override void ClientAckGoodMove(float timeStamp)
=> E__Supper__UCharacterMovementComponent_ClientAckGoodMove(this, timeStamp);
public override void ClientAckGoodMove_Implementation(float timeStamp)
=> E__Supper__UCharacterMovementComponent_ClientAckGoodMove_Implementation(this, timeStamp);
/// <summary>
/// Checks if new capsule size fits (no encroachment), and call CharacterOwner->OnStartCrouch() if successful.
/// <para>In general you should set bWantsToCrouch instead to have the crouch persist during movement, or just use the crouch functions on the owning Character. </para>
/// </summary>
/// <param name="bClientSimulation">true when called when bIsCrouched is replicated to non owned clients, to update collision cylinder and offset.</param>
public override void Crouch(bool bClientSimulation)
=> E__Supper__UCharacterMovementComponent_Crouch(this, bClientSimulation);
/// <summary>
/// Make movement impossible (sets movement mode to MOVE_None).
/// </summary>
public override void DisableMovement()
=> E__Supper__UCharacterMovementComponent_DisableMovement(this);
/// <summary>
/// Force a client update by making it appear on the server that the client hasn't updated in a long time.
/// </summary>
public override void ForceReplicationUpdate()
=> E__Supper__UCharacterMovementComponent_ForceReplicationUpdate(this);
/// <summary>
/// Adjusts velocity when walking so that Z velocity is zero.
/// <para>When bMaintainHorizontalGroundVelocity is false, also rescales the velocity vector to maintain the original magnitude, but in the horizontal direction. </para>
/// </summary>
protected override void MaintainHorizontalGroundVelocity()
=> E__Supper__UCharacterMovementComponent_MaintainHorizontalGroundVelocity(this);
/// <summary>
/// Call SaveBaseLocation() if not deferring updates (bDeferUpdateBasedMovement is false).
/// </summary>
public override void MaybeSaveBaseLocation()
=> E__Supper__UCharacterMovementComponent_MaybeSaveBaseLocation(this);
/// <summary>
/// Update or defer updating of position based on Base movement
/// </summary>
public override void MaybeUpdateBasedMovement(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_MaybeUpdateBasedMovement(this, deltaSeconds);
/// <summary>
/// Called if bNotifyApex is true and character has just passed the apex of its jump.
/// </summary>
public override void NotifyJumpApex()
=> E__Supper__UCharacterMovementComponent_NotifyJumpApex(this);
/// <summary>
/// Called by UCharacterMovementComponent::VerifyClientTimeStamp() when a client timestamp reset has been detected and is valid.
/// </summary>
protected override void OnClientTimeStampResetDetected()
=> E__Supper__UCharacterMovementComponent_OnClientTimeStampResetDetected(this);
/// <summary>
/// Called by UCharacterMovementComponent::ProcessClientTimeStampForTimeDiscrepancy() (on server) when the time from client moves
/// <para>significantly differs from the server time, indicating potential time manipulation by clients (speed hacks, significant network </para>
/// issues, client performance problems)
/// <para>by MovementTimeDiscrepancy config variables in AGameNetworkManager, and is the value with which </para>
/// we test against to trigger this function. This is reset when MovementTimeDiscrepancy resolution
/// <para>is enabled </para>
/// and does NOT get affected by MovementTimeDiscrepancy resolution, and is useful as a longer-term
/// <para>view of how the given client is performing. High magnitude unbounded error points to </para>
/// intentional tampering by a client vs. occasional "naturally caused" spikes in error due to
/// <para>burst packet loss/performance hitches </para>
/// of LifetimeUnboundedError)
/// <para>current move that has caused TimeDiscrepancy to accumulate enough to trigger detection. </para>
/// </summary>
/// <param name="currentTimeDiscrepancy">Accumulated time difference between client ServerMove and server time - this is bounded</param>
/// <param name="lifetimeRawTimeDiscrepancy">Accumulated time difference between client ServerMove and server time - this is unbounded</param>
/// <param name="lifetime">Game time over which LifetimeRawTimeDiscrepancy has accrued (useful for determining severity</param>
/// <param name="currentMoveError">Time difference between client ServerMove and how much time has passed on the server for the</param>
protected override void OnTimeDiscrepancyDetected(float currentTimeDiscrepancy, float lifetimeRawTimeDiscrepancy, float lifetime, float currentMoveError)
=> E__Supper__UCharacterMovementComponent_OnTimeDiscrepancyDetected(this, currentTimeDiscrepancy, lifetimeRawTimeDiscrepancy, lifetime, currentMoveError);
/// <summary>
/// Perform movement on an autonomous client
/// </summary>
protected override void PerformMovement(float deltaTime)
=> E__Supper__UCharacterMovementComponent_PerformMovement(this, deltaTime);
/// <summary>
/// @note Movement update functions should only be called through StartNewPhysics()
/// </summary>
protected override void PhysCustom(float deltaTime, int iterations)
=> E__Supper__UCharacterMovementComponent_PhysCustom(this, deltaTime, iterations);
/// <summary>
/// Handle falling movement.
/// </summary>
public override void PhysFalling(float deltaTime, int iterations)
=> E__Supper__UCharacterMovementComponent_PhysFalling(this, deltaTime, iterations);
/// <summary>
/// @note Movement update functions should only be called through StartNewPhysics()
/// </summary>
protected override void PhysFlying(float deltaTime, int iterations)
=> E__Supper__UCharacterMovementComponent_PhysFlying(this, deltaTime, iterations);
/// <summary>
/// Perform rotation over deltaTime
/// </summary>
public override void PhysicsRotation(float deltaTime)
=> E__Supper__UCharacterMovementComponent_PhysicsRotation(this, deltaTime);
/// <summary>
/// @note Movement update functions should only be called through StartNewPhysics()
/// </summary>
protected override void PhysNavWalking(float deltaTime, int iterations)
=> E__Supper__UCharacterMovementComponent_PhysNavWalking(this, deltaTime, iterations);
/// <summary>
/// @note Movement update functions should only be called through StartNewPhysics()
/// </summary>
protected override void PhysSwimming(float deltaTime, int iterations)
=> E__Supper__UCharacterMovementComponent_PhysSwimming(this, deltaTime, iterations);
/// <summary>
/// @note Movement update functions should only be called through StartNewPhysics()
/// </summary>
protected override void PhysWalking(float deltaTime, int iterations)
=> E__Supper__UCharacterMovementComponent_PhysWalking(this, deltaTime, iterations);
/// <summary>
/// Update OldBaseLocation and OldBaseQuat if there is a valid movement base, and store the relative location/rotation if necessary. Ignores bDeferUpdateBasedMovement and forces the update.
/// </summary>
public override void SaveBaseLocation()
=> E__Supper__UCharacterMovementComponent_SaveBaseLocation(this);
/// <summary>
/// Set movement mode to the default based on the current physics volume.
/// </summary>
public override void SetDefaultMovementMode()
=> E__Supper__UCharacterMovementComponent_SetDefaultMovementMode(this);
/// <summary>
/// Switch collision settings for NavWalking mode (ignore world collisions)
/// </summary>
protected override void SetNavWalkingPhysics(bool bEnable)
=> E__Supper__UCharacterMovementComponent_SetNavWalkingPhysics(this, bEnable);
/// <summary>
/// Simulate movement on a non-owning client. Called by SimulatedTick().
/// </summary>
protected override void SimulateMovement(float deltaTime)
=> E__Supper__UCharacterMovementComponent_SimulateMovement(this, deltaTime);
/// <summary>
/// Smooth mesh location for network interpolation, based on values set up by SmoothCorrection.
/// <para>Internally this simply calls SmoothClientPosition_Interpolate() then SmoothClientPosition_UpdateVisuals(). </para>
/// This function is not called when bNetworkSmoothingComplete is true.
/// </summary>
/// <param name="deltaSeconds">Time since last update.</param>
protected override void SmoothClientPosition(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_SmoothClientPosition(this, deltaSeconds);
/// <summary>
/// changes physics based on MovementMode
/// </summary>
public override void StartNewPhysics(float deltaTime, int iterations)
=> E__Supper__UCharacterMovementComponent_StartNewPhysics(this, deltaTime, iterations);
/// <summary>
/// Checks if default capsule size fits (no encroachment), and trigger OnEndCrouch() on the owner if successful.
/// </summary>
/// <param name="bClientSimulation">true when called when bIsCrouched is replicated to non owned clients, to update collision cylinder and offset.</param>
public override void UnCrouch(bool bClientSimulation)
=> E__Supper__UCharacterMovementComponent_UnCrouch(this, bClientSimulation);
/// <summary>
/// Update position based on Base movement
/// </summary>
public override void UpdateBasedMovement(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_UpdateBasedMovement(this, deltaSeconds);
/// <summary>
/// Update the character state in PerformMovement after the position change. Some rotation updates happen after this.
/// </summary>
public override void UpdateCharacterStateAfterMovement(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_UpdateCharacterStateAfterMovement(this, deltaSeconds);
/// <summary>
/// Update the character state in PerformMovement right before doing the actual position change
/// </summary>
public override void UpdateCharacterStateBeforeMovement(float deltaSeconds)
=> E__Supper__UCharacterMovementComponent_UpdateCharacterStateBeforeMovement(this, deltaSeconds);
/// <summary>
/// React to instantaneous change in position. Invalidates cached floor recomputes it if possible if there is a current movement base.
/// </summary>
public override void UpdateFloorFromAdjustment()
=> E__Supper__UCharacterMovementComponent_UpdateFloorFromAdjustment(this);
/// <summary>
/// Unpack compressed flags from a saved move and set state accordingly. See FSavedMove_Character.
/// </summary>
protected override void UpdateFromCompressedFlags(byte flags)
=> E__Supper__UCharacterMovementComponent_UpdateFromCompressedFlags(this, flags);
/// <summary>
/// Used during SimulateMovement for proxies, this computes a new value for Acceleration before running proxy simulation.
/// <para>The base implementation simply derives a value from the normalized Velocity value, which may help animations that want some indication of the direction of movement. </para>
/// Proxies don't implement predictive acceleration by default so this value is not used for the actual simulation.
/// </summary>
public override void UpdateProxyAcceleration()
=> E__Supper__UCharacterMovementComponent_UpdateProxyAcceleration(this);
/// <summary>
/// Stops applying further movement (usually zeros acceleration).
/// </summary>
public override void StopActiveMovement()
=> E__Supper__UCharacterMovementComponent_StopActiveMovement(this);
/// <summary>
/// Called by owning Actor upon successful teleport from AActor::TeleportTo().
/// </summary>
public override void OnTeleported()
=> E__Supper__UCharacterMovementComponent_OnTeleported(this);
/// <summary>
/// Sets whether or not the plane constraint is enabled.
/// </summary>
public override void SetPlaneConstraintEnabled(bool bEnabled)
=> E__Supper__UCharacterMovementComponent_SetPlaneConstraintEnabled(this, bEnabled);
/// <summary>
/// Snap the updated component to the plane constraint, if enabled.
/// </summary>
public override void SnapUpdatedComponentToPlane()
=> E__Supper__UCharacterMovementComponent_SnapUpdatedComponentToPlane(this);
/// <summary>
/// Stops movement immediately (zeroes velocity, usually zeros acceleration for components with acceleration).
/// </summary>
public override void StopMovementImmediately()
=> E__Supper__UCharacterMovementComponent_StopMovementImmediately(this);
/// <summary>
/// Update ComponentVelocity of UpdatedComponent. This needs to be called by derived classes at the end of an update whenever Velocity has changed.
/// </summary>
public override void UpdateComponentVelocity()
=> E__Supper__UCharacterMovementComponent_UpdateComponentVelocity(this);
/// <summary>
/// Update tick registration state, determined by bAutoUpdateTickRegistration. Called by SetUpdatedComponent.
/// </summary>
public override void UpdateTickRegistration()
=> E__Supper__UCharacterMovementComponent_UpdateTickRegistration(this);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__UCharacterMovementComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__UCharacterMovementComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__UCharacterMovementComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__UCharacterMovementComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__UCharacterMovementComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__UCharacterMovementComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__UCharacterMovementComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__UCharacterMovementComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__UCharacterMovementComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__UCharacterMovementComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__UCharacterMovementComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__UCharacterMovementComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__UCharacterMovementComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__UCharacterMovementComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__UCharacterMovementComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__UCharacterMovementComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__UCharacterMovementComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__UCharacterMovementComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__UCharacterMovementComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__UCharacterMovementComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__UCharacterMovementComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__UCharacterMovementComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__UCharacterMovementComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__UCharacterMovementComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__UCharacterMovementComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UCharacterMovementComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UCharacterMovementComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UCharacterMovementComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UCharacterMovementComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UCharacterMovementComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UCharacterMovementComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UCharacterMovementComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UCharacterMovementComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UCharacterMovementComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UCharacterMovementComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UCharacterMovementComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UCharacterMovementComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UCharacterMovementComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UCharacterMovementComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UCharacterMovementComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageCharacterMovementComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageCharacterMovementComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageCharacterMovementComponent>(PtrDesc);
}
}
}
| |
// 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.
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Buffers.Text
{
public static partial class Utf8Parser
{
unsafe static bool TryParseBoolean(byte* text, int length, out bool value)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
unsafe static bool TryParseBoolean(byte* text, int length, out bool value, out int bytesConsumed)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
bytesConsumed = 4;
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
bytesConsumed = 5;
value = false;
return true;
}
}
}
bytesConsumed = 0;
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<byte> text, out bool value)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<byte> text, out bool value, out int bytesConsumed)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
bytesConsumed = 4;
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
bytesConsumed = 5;
value = false;
return true;
}
}
}
bytesConsumed = 0;
value = default;
return false;
}
}
public static partial class Utf16Parser
{
unsafe static bool TryParseBoolean(char* text, int length, out bool value)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
unsafe static bool TryParseBoolean(char* text, int length, out bool value, out int charactersConsumed)
{
if (length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
charactersConsumed = 4;
value = true;
return true;
}
if (length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
charactersConsumed = 5;
value = false;
return true;
}
}
}
charactersConsumed = 0;
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<char> text, out bool value)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
// No need to set consumed
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
// No need to set consumed
value = false;
return true;
}
}
}
// No need to set consumed
value = default;
return false;
}
public static bool TryParseBoolean(ReadOnlySpan<char> text, out bool value, out int charactersConsumed)
{
if (text.Length >= 4)
{
if ((text[0] == 'T' || text[0] == 't') &&
(text[1] == 'R' || text[1] == 'r') &&
(text[2] == 'U' || text[2] == 'u') &&
(text[3] == 'E' || text[3] == 'e'))
{
charactersConsumed = 4;
value = true;
return true;
}
if (text.Length >= 5)
{
if ((text[0] == 'F' || text[0] == 'f') &&
(text[1] == 'A' || text[1] == 'a') &&
(text[2] == 'L' || text[2] == 'l') &&
(text[3] == 'S' || text[3] == 's') &&
(text[4] == 'E' || text[4] == 'e'))
{
charactersConsumed = 5;
value = false;
return true;
}
}
}
charactersConsumed = 0;
value = default;
return false;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Extensions;
using osu.Game.Graphics;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Screens.Menu;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament.Components
{
public class SongBar : CompositeDrawable
{
private APIBeatmap beatmap;
public const float HEIGHT = 145 / 2f;
[Resolved]
private IBindable<RulesetInfo> ruleset { get; set; }
public APIBeatmap Beatmap
{
set
{
if (beatmap == value)
return;
beatmap = value;
update();
}
}
private LegacyMods mods;
public LegacyMods Mods
{
get => mods;
set
{
mods = value;
update();
}
}
private FillFlowContainer flow;
private bool expanded;
public bool Expanded
{
get => expanded;
set
{
expanded = value;
flow.Direction = expanded ? FillDirection.Full : FillDirection.Vertical;
}
}
// Todo: This is a hack for https://github.com/ppy/osu-framework/issues/3617 since this container is at the very edge of the screen and potentially initially masked away.
protected override bool ComputeIsMaskedAway(RectangleF maskingBounds) => false;
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
flow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
LayoutDuration = 500,
LayoutEasing = Easing.OutQuint,
Direction = FillDirection.Full,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
}
};
Expanded = true;
}
private void update()
{
if (beatmap == null)
{
flow.Clear();
return;
}
double bpm = beatmap.BPM;
double length = beatmap.Length;
string hardRockExtra = "";
string srExtra = "";
float ar = beatmap.Difficulty.ApproachRate;
if ((mods & LegacyMods.HardRock) > 0)
{
hardRockExtra = "*";
srExtra = "*";
}
if ((mods & LegacyMods.DoubleTime) > 0)
{
// temporary local calculation (taken from OsuDifficultyCalculator)
double preempt = (int)IBeatmapDifficultyInfo.DifficultyRange(ar, 1800, 1200, 450) / 1.5;
ar = (float)(preempt > 1200 ? (1800 - preempt) / 120 : (1200 - preempt) / 150 + 5);
bpm *= 1.5f;
length /= 1.5f;
srExtra = "*";
}
(string heading, string content)[] stats;
switch (ruleset.Value.OnlineID)
{
default:
stats = new (string heading, string content)[]
{
("CS", $"{beatmap.Difficulty.CircleSize:0.#}{hardRockExtra}"),
("AR", $"{ar:0.#}{hardRockExtra}"),
("OD", $"{beatmap.Difficulty.OverallDifficulty:0.#}{hardRockExtra}"),
};
break;
case 1:
case 3:
stats = new (string heading, string content)[]
{
("OD", $"{beatmap.Difficulty.OverallDifficulty:0.#}{hardRockExtra}"),
("HP", $"{beatmap.Difficulty.DrainRate:0.#}{hardRockExtra}")
};
break;
case 2:
stats = new (string heading, string content)[]
{
("CS", $"{beatmap.Difficulty.CircleSize:0.#}{hardRockExtra}"),
("AR", $"{ar:0.#}"),
};
break;
}
flow.Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = HEIGHT,
Width = 0.5f,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Children = new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new DiffPiece(stats),
new DiffPiece(("Star Rating", $"{beatmap.StarRating:0.#}{srExtra}"))
}
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new DiffPiece(("Length", length.ToFormattedDuration().ToString())),
new DiffPiece(("BPM", $"{bpm:0.#}")),
}
},
new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
Alpha = 0.1f,
},
new OsuLogo
{
Triangles = false,
Scale = new Vector2(0.08f),
Margin = new MarginPadding(50),
X = -10,
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
},
}
},
},
}
}
}
},
new TournamentBeatmapPanel(beatmap)
{
RelativeSizeAxes = Axes.X,
Width = 0.5f,
Height = HEIGHT,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
}
};
}
public class DiffPiece : TextFlowContainer
{
public DiffPiece(params (string heading, string content)[] tuples)
{
Margin = new MarginPadding { Horizontal = 15, Vertical = 1 };
AutoSizeAxes = Axes.Both;
static void cp(SpriteText s, bool bold)
{
s.Font = OsuFont.Torus.With(weight: bold ? FontWeight.Bold : FontWeight.Regular, size: 15);
}
for (int i = 0; i < tuples.Length; i++)
{
(string heading, string content) = tuples[i];
if (i > 0)
{
AddText(" / ", s =>
{
cp(s, false);
s.Spacing = new Vector2(-2, 0);
});
}
AddText(new TournamentSpriteText { Text = heading }, s => cp(s, false));
AddText(" ", s => cp(s, false));
AddText(new TournamentSpriteText { Text = content }, s => cp(s, true));
}
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace Pathfinding {
/** Editor for GraphUpdateScene */
[CustomEditor(typeof(GraphUpdateScene))]
[CanEditMultipleObjects]
public class GraphUpdateSceneEditor : Editor {
int selectedPoint = -1;
const float pointGizmosRadius = 0.09F;
static Color PointColor = new Color(1, 0.36F, 0, 0.6F);
static Color PointSelectedColor = new Color(1, 0.24F, 0, 1.0F);
SerializedProperty points, updatePhysics, updateErosion, convex;
SerializedProperty minBoundsHeight, applyOnStart, applyOnScan;
SerializedProperty modifyWalkable, walkableValue, penaltyDelta, modifyTag, tagValue;
SerializedProperty resetPenaltyOnPhysics, legacyMode;
GraphUpdateScene[] scripts;
void OnEnable () {
// Find all properties
points = serializedObject.FindProperty("points");
updatePhysics = serializedObject.FindProperty("updatePhysics");
resetPenaltyOnPhysics = serializedObject.FindProperty("resetPenaltyOnPhysics");
updateErosion = serializedObject.FindProperty("updateErosion");
convex = serializedObject.FindProperty("convex");
minBoundsHeight = serializedObject.FindProperty("minBoundsHeight");
applyOnStart = serializedObject.FindProperty("applyOnStart");
applyOnScan = serializedObject.FindProperty("applyOnScan");
modifyWalkable = serializedObject.FindProperty("modifyWalkability");
walkableValue = serializedObject.FindProperty("setWalkability");
penaltyDelta = serializedObject.FindProperty("penaltyDelta");
modifyTag = serializedObject.FindProperty("modifyTag");
tagValue = serializedObject.FindProperty("setTag");
legacyMode = serializedObject.FindProperty("legacyMode");
}
public override void OnInspectorGUI () {
serializedObject.Update();
// Get a list of inspected components
scripts = new GraphUpdateScene[targets.Length];
targets.CopyTo(scripts, 0);
EditorGUI.BeginChangeCheck();
// Make sure no point arrays are null
for (int i = 0; i < scripts.Length; i++) {
scripts[i].points = scripts[i].points ?? new Vector3[0];
}
if (!points.hasMultipleDifferentValues && points.arraySize == 0) {
if (scripts[0].GetComponent<PolygonCollider2D>() != null) {
EditorGUILayout.HelpBox("Using polygon collider shape", MessageType.Info);
} else if (scripts[0].GetComponent<Collider>() != null || scripts[0].GetComponent<Collider2D>() != null) {
EditorGUILayout.HelpBox("No points, using collider.bounds", MessageType.Info);
} else if (scripts[0].GetComponent<Renderer>() != null) {
EditorGUILayout.HelpBox("No points, using renderer.bounds", MessageType.Info);
} else {
EditorGUILayout.HelpBox("No points and no collider or renderer attached, will not affect anything\nPoints can be added using the transform tool and holding shift", MessageType.Warning);
}
}
DrawPointsField();
EditorGUI.indentLevel = 0;
DrawPhysicsField();
EditorGUILayout.PropertyField(updateErosion, new GUIContent("Update Erosion", "Recalculate erosion for grid graphs.\nSee online documentation for more info"));
DrawConvexField();
// Minimum bounds height is not applied when using the bounds from a collider or renderer
if (points.hasMultipleDifferentValues || points.arraySize > 0) {
EditorGUILayout.PropertyField(minBoundsHeight, new GUIContent("Min Bounds Height", "Defines a minimum height to be used for the bounds of the GUO.\nUseful if you define points in 2D (which would give height 0)"));
if (!minBoundsHeight.hasMultipleDifferentValues) {
minBoundsHeight.floatValue = Mathf.Max(minBoundsHeight.floatValue, 0.1f);
}
}
EditorGUILayout.PropertyField(applyOnStart, new GUIContent("Apply On Start"));
EditorGUILayout.PropertyField(applyOnScan, new GUIContent("Apply On Scan"));
DrawWalkableField();
DrawPenaltyField();
DrawTagField();
EditorGUILayout.Separator();
if (legacyMode.hasMultipleDifferentValues || legacyMode.boolValue) {
EditorGUILayout.HelpBox("Legacy mode is enabled because you have upgraded from an earlier version of the A* Pathfinding Project. " +
"Disabling legacy mode is recommended but you may have to tweak the point locations or object rotation in some cases", MessageType.Warning);
if (GUILayout.Button("Disable Legacy Mode")) {
for (int i = 0; i < scripts.Length; i++) {
scripts[i].DisableLegacyMode();
}
}
}
if (scripts.Length == 1 && scripts[0].points.Length >= 3) {
var size = scripts[0].GetBounds().size;
if (Mathf.Min(Mathf.Min(Mathf.Abs(size.x), Mathf.Abs(size.y)), Mathf.Abs(size.z)) < 0.05f) {
EditorGUILayout.HelpBox("The bounding box is very thin. Your shape might be oriented incorrectly. The shape will be projected down on the XZ plane in local space. Rotate this object " +
"so that the local XZ plane corresponds to the plane in which you want to create your shape. For example if you want to create your shape in the XY plane then " +
"this object should have the rotation (-90,0,0). You will need to recreate your shape after rotating this object.", MessageType.Warning);
}
}
if (GUILayout.Button("Clear all points")) {
for (int i = 0; i < scripts.Length; i++) {
Undo.RecordObject(scripts[i], "Clear points");
scripts[i].points = new Vector3[0];
scripts[i].RecalcConvex();
}
}
serializedObject.ApplyModifiedProperties();
if (EditorGUI.EndChangeCheck()) {
for (int i = 0; i < scripts.Length; i++) {
EditorUtility.SetDirty(scripts[i]);
}
// Repaint the scene view if necessary
if (!Application.isPlaying || EditorApplication.isPaused) SceneView.RepaintAll();
}
}
void DrawPointsField () {
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(points, true);
if (EditorGUI.EndChangeCheck()) {
serializedObject.ApplyModifiedProperties();
for (int i = 0; i < scripts.Length; i++) {
scripts[i].RecalcConvex();
}
HandleUtility.Repaint();
}
}
void DrawPhysicsField () {
EditorGUILayout.PropertyField(updatePhysics, new GUIContent("Update Physics", "Perform similar calculations on the nodes as during scan.\n" +
"Grid Graphs will update the position of the nodes and also check walkability using collision.\nSee online documentation for more info."));
if (!updatePhysics.hasMultipleDifferentValues && updatePhysics.boolValue) {
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(resetPenaltyOnPhysics, new GUIContent("Reset Penalty On Physics", "Will reset the penalty to the default value during the update."));
EditorGUI.indentLevel--;
}
}
void DrawConvexField () {
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(convex, new GUIContent("Convex", "Sets if only the convex hull of the points should be used or the whole polygon"));
if (EditorGUI.EndChangeCheck()) {
serializedObject.ApplyModifiedProperties();
for (int i = 0; i < scripts.Length; i++) {
scripts[i].RecalcConvex();
}
HandleUtility.Repaint();
}
}
void DrawWalkableField () {
EditorGUILayout.PropertyField(modifyWalkable, new GUIContent("Modify walkability", "If true, walkability of all nodes will be modified"));
if (!modifyWalkable.hasMultipleDifferentValues && modifyWalkable.boolValue) {
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(walkableValue, new GUIContent("Walkability Value", "Nodes' walkability will be set to this value"));
EditorGUI.indentLevel--;
}
}
void DrawPenaltyField () {
EditorGUILayout.PropertyField(penaltyDelta, new GUIContent("Penalty Delta", "A penalty will be added to the nodes, usually you need very large values, at least 1000-10000.\n" +
"A higher penalty will mean that agents will try to avoid those nodes."));
if (!penaltyDelta.hasMultipleDifferentValues && penaltyDelta.intValue < 0) {
EditorGUILayout.HelpBox("Be careful when lowering the penalty. Negative penalties are not supported and will instead underflow and get really high.\n" +
"You can set an initial penalty on graphs (see their settings) and then lower them like this to get regions which are easier to traverse.", MessageType.Warning);
}
}
void DrawTagField () {
EditorGUILayout.PropertyField(modifyTag, new GUIContent("Modify Tag", "Should the tags of the nodes be modified"));
if (!modifyTag.hasMultipleDifferentValues && modifyTag.boolValue) {
EditorGUI.indentLevel++;
EditorGUI.showMixedValue = tagValue.hasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
var newTag = EditorGUILayoutx.TagField("Tag Value", tagValue.intValue);
if (EditorGUI.EndChangeCheck()) {
tagValue.intValue = newTag;
}
EditorGUI.indentLevel--;
}
if (GUILayout.Button("Tags can be used to restrict which units can walk on what ground. Click here for more info", "HelpBox")) {
Application.OpenURL(AstarUpdateChecker.GetURL("tags"));
}
}
static void SphereCap (int controlID, Vector3 position, Quaternion rotation, float size) {
#if UNITY_5_5_OR_NEWER
Handles.SphereHandleCap(controlID, position, rotation, size, Event.current.type);
#else
Handles.SphereCap(controlID, position, rotation, size);
#endif
}
public void OnSceneGUI () {
var script = target as GraphUpdateScene;
// Don't allow editing unless it is the active object
if (Selection.activeGameObject != script.gameObject || script.legacyMode) return;
// Make sure the points array is not null
if (script.points == null) {
script.points = new Vector3[0];
EditorUtility.SetDirty(script);
}
List<Vector3> points = Pathfinding.Util.ListPool<Vector3>.Claim();
points.AddRange(script.points);
Matrix4x4 invMatrix = script.transform.worldToLocalMatrix;
Matrix4x4 matrix = script.transform.localToWorldMatrix;
for (int i = 0; i < points.Count; i++) points[i] = matrix.MultiplyPoint3x4(points[i]);
if (Tools.current != Tool.View && Event.current.type == EventType.Layout) {
for (int i = 0; i < script.points.Length; i++) {
HandleUtility.AddControl(-i - 1, HandleUtility.DistanceToLine(points[i], points[i]));
}
}
if (Tools.current != Tool.View)
HandleUtility.AddDefaultControl(0);
for (int i = 0; i < points.Count; i++) {
if (i == selectedPoint && Tools.current == Tool.Move) {
Handles.color = PointSelectedColor;
SphereCap(-i-1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i])*pointGizmosRadius*2);
Vector3 pre = points[i];
Vector3 post = Handles.PositionHandle(points[i], Quaternion.identity);
if (pre != post) {
Undo.RecordObject(script, "Moved Point");
script.points[i] = invMatrix.MultiplyPoint3x4(post);
}
} else {
Handles.color = PointColor;
SphereCap(-i-1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i])*pointGizmosRadius);
}
}
if (Event.current.type == EventType.MouseDown) {
int pre = selectedPoint;
selectedPoint = -(HandleUtility.nearestControl+1);
if (pre != selectedPoint) GUI.changed = true;
}
if (Event.current.shift && Tools.current == Tool.Move) {
HandleUtility.Repaint();
if (((int)Event.current.modifiers & (int)EventModifiers.Alt) != 0) {
if (Event.current.type == EventType.MouseDown && selectedPoint >= 0 && selectedPoint < points.Count) {
Undo.RecordObject(script, "Removed Point");
var arr = new List<Vector3>(script.points);
arr.RemoveAt(selectedPoint);
points.RemoveAt(selectedPoint);
script.points = arr.ToArray();
GUI.changed = true;
} else if (points.Count > 0) {
var index = -(HandleUtility.nearestControl+1);
if (index >= 0 && index < points.Count) {
Handles.color = Color.red;
SphereCap(0, points[index], Quaternion.identity, HandleUtility.GetHandleSize(points[index])*2f*pointGizmosRadius);
}
}
} else {
// Find the closest segment
int insertionIndex = points.Count;
float minDist = float.PositiveInfinity;
for (int i = 0; i < points.Count; i++) {
float dist = HandleUtility.DistanceToLine(points[i], points[(i+1)%points.Count]);
if (dist < minDist) {
insertionIndex = i + 1;
minDist = dist;
}
}
var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
System.Object hit = HandleUtility.RaySnap(ray);
Vector3 rayhit = Vector3.zero;
bool didHit = false;
if (hit != null) {
rayhit = ((RaycastHit)hit).point;
didHit = true;
} else {
var plane = new Plane(script.transform.up, script.transform.position);
float distance;
plane.Raycast(ray, out distance);
if (distance > 0) {
rayhit = ray.GetPoint(distance);
didHit = true;
}
}
if (didHit) {
if (Event.current.type == EventType.MouseDown) {
points.Insert(insertionIndex, rayhit);
Undo.RecordObject(script, "Added Point");
var arr = new List<Vector3>(script.points);
arr.Insert(insertionIndex, invMatrix.MultiplyPoint3x4(rayhit));
script.points = arr.ToArray();
GUI.changed = true;
} else if (points.Count > 0) {
Handles.color = Color.green;
Handles.DrawDottedLine(points[(insertionIndex-1 + points.Count) % points.Count], rayhit, 8);
Handles.DrawDottedLine(points[insertionIndex % points.Count], rayhit, 8);
SphereCap(0, rayhit, Quaternion.identity, HandleUtility.GetHandleSize(rayhit)*pointGizmosRadius);
// Project point down onto a plane
var zeroed = invMatrix.MultiplyPoint3x4(rayhit);
zeroed.y = 0;
Handles.color = new Color(1, 1, 1, 0.5f);
Handles.DrawDottedLine(matrix.MultiplyPoint3x4(zeroed), rayhit, 4);
}
}
}
if (Event.current.type == EventType.MouseDown) {
Event.current.Use();
}
}
// Make sure the convex hull stays up to date
script.RecalcConvex();
Pathfinding.Util.ListPool<Vector3>.Release(points);
if (GUI.changed) HandleUtility.Repaint();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Accessibility;
using ReactNative.Reflection;
using ReactNative.UIManager.Annotations;
using ReactNative.UIManager.Events;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Media3D;
namespace ReactNative.UIManager
{
/// <summary>
/// Base class that should be suitable for the majority of subclasses of <see cref="IViewManager"/>.
/// It provides support for base view props such as opacity, etc.
/// </summary>
/// <typeparam name="TFrameworkElement">Type of framework element.</typeparam>
/// <typeparam name="TLayoutShadowNode">Type of shadow node.</typeparam>
public abstract class BaseViewManager<TFrameworkElement, TLayoutShadowNode> :
ViewManager<TFrameworkElement, TLayoutShadowNode>
where TFrameworkElement : FrameworkElement
where TLayoutShadowNode : LayoutShadowNode
{
private readonly ViewKeyedDictionary<TFrameworkElement, DimensionBoundProperties> _dimensionBoundProperties =
new ViewKeyedDictionary<TFrameworkElement, DimensionBoundProperties>();
/// <summary>
/// Sets the 3D tranform on the <typeparamref name="TFrameworkElement"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="transforms">
/// The transform matrix or the list of transforms.
/// </param>
[ReactProp("transform")]
public void SetTransform(TFrameworkElement view, JArray transforms)
{
if (transforms == null)
{
var dimensionBoundProperties = GetDimensionBoundProperties(view);
if (dimensionBoundProperties?.MatrixTransform != null)
{
dimensionBoundProperties.MatrixTransform = null;
ResetProjectionMatrix(view);
ResetRenderTransform(view);
}
}
else
{
var dimensionBoundProperties = GetOrCreateDimensionBoundProperties(view);
dimensionBoundProperties.MatrixTransform = transforms;
var dimensions = GetDimensions(view);
SetProjectionMatrix(view, dimensions, transforms);
}
}
/// <summary>
/// Sets the opacity of the <typeparamref name="TFrameworkElement"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="opacity">The opacity value.</param>
[ReactProp(ViewProps.Opacity, DefaultDouble = 1.0)]
public void SetOpacity(TFrameworkElement view, double opacity)
{
view.Opacity = opacity;
}
/// <summary>
/// Sets the overflow prop for the <typeparamref name="TFrameworkElement"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="overflow">The overflow value.</param>
[ReactProp(ViewProps.Overflow)]
public void SetOverflow(TFrameworkElement view, string overflow)
{
if (overflow == ViewProps.Hidden)
{
var dimensionBoundProperties = GetOrCreateDimensionBoundProperties(view);
dimensionBoundProperties.OverflowHidden = true;
var dimensions = GetDimensions(view);
SetOverflowHidden(view, dimensions);
view.SizeChanged += OnSizeChanged;
}
else
{
view.SizeChanged -= OnSizeChanged;
var dimensionBoundProperties = GetDimensionBoundProperties(view);
if (dimensionBoundProperties != null && dimensionBoundProperties.OverflowHidden)
{
dimensionBoundProperties.OverflowHidden = false;
SetOverflowVisible(view);
}
}
}
/// <summary>
/// Sets the z-index of the element.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="zIndex">The z-index.</param>
[ReactProp("zIndex")]
public void SetZIndex(TFrameworkElement view, int zIndex)
{
Canvas.SetZIndex(view, zIndex);
}
/// <summary>
/// Sets the display mode of the element.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="display">The display mode.</param>
[ReactProp(ViewProps.Display)]
public void SetDisplay(TFrameworkElement view, string display)
{
view.Visibility = display == "none" ? Visibility.Collapsed : Visibility.Visible;
AccessibilityHelper.OnElementChanged(view, UIElement.VisibilityProperty);
}
/// <summary>
/// Sets the manipulation mode for the view.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="manipulationModes">The manipulation modes.</param>
[ReactProp("manipulationModes")]
public void SetManipulationModes(TFrameworkElement view, JArray manipulationModes)
{
if (manipulationModes == null)
{
view.ManipulationMode = ManipulationModes.System;
return;
}
var manipulationMode = ManipulationModes.System;
foreach (var modeString in manipulationModes)
{
Debug.Assert(modeString.Type == JTokenType.String);
var mode = EnumHelpers.Parse<ManipulationModes>(modeString.Value<string>());
manipulationMode |= mode;
}
view.ManipulationMode = manipulationMode;
}
/// <summary>
/// Sets the accessibility label of the element.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="label">The label.</param>
[ReactProp(ViewProps.AccessibilityLabel)]
public void SetAccessibilityLabel(TFrameworkElement view, string label)
{
AccessibilityHelper.SetAccessibilityLabel(view, label ?? "");
}
/// <summary>
/// Sets the accessibility live region.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="liveRegion">The live region.</param>
[ReactProp(ViewProps.AccessibilityLiveRegion)]
public void SetAccessibilityLiveRegion(TFrameworkElement view, string liveRegion)
{
var liveSetting = AutomationLiveSetting.Off;
switch (liveRegion)
{
case "polite":
liveSetting = AutomationLiveSetting.Polite;
break;
case "assertive":
liveSetting = AutomationLiveSetting.Assertive;
break;
}
AutomationProperties.SetLiveSetting(view, liveSetting);
AccessibilityHelper.AnnounceIfNeeded(view);
}
/// <summary>
/// Sets the test ID, i.e., the automation ID.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="testId">The test ID.</param>
[ReactProp("testID")]
public void SetTestId(TFrameworkElement view, string testId)
{
AutomationProperties.SetAutomationId(view, testId ?? "");
}
/// <summary>
/// Sets a tooltip for the view.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="tooltip">String to display in the tooltip.</param>
[ReactProp("tooltip")]
public void SetTooltip(TFrameworkElement view, string tooltip)
{
ToolTipService.SetToolTip(view, tooltip);
}
/// <summary>
/// Set the pointer events handling mode for the view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="pointerEventsValue">The pointerEvents mode.</param>
[ReactProp(ViewProps.PointerEvents)]
public void SetPointerEvents(TFrameworkElement view, string pointerEventsValue)
{
var pointerEvents = EnumHelpers.ParseNullable<PointerEvents>(pointerEventsValue) ?? PointerEvents.Auto;
view.SetPointerEvents(pointerEvents);
// When `pointerEvents: none`, set `IsHitTestVisible` to `false`.
view.IsHitTestVisible = pointerEvents != PointerEvents.None;
}
/// <summary>
/// Detects the presence of a various mouse view handler for the view.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="index">The prop index.</param>
/// <param name="handlerPresent">true if a mouse move handler is present.</param>
[ReactPropGroup(
"onMouseMove",
"onMouseMoveCapture",
"onMouseOver",
"onMouseOverCapture",
"onMouseOut",
"onMouseOutCapture",
"onMouseEnter",
"onMouseLeave")]
public void SetOnMouseHandler(TFrameworkElement view, int index, bool handlerPresent)
{
// The order of handler names HAS TO match order in ViewExtensions.MouseHandlerMask
view.SetMouseHandlerPresent((ViewExtensions.MouseHandlerMask)(1 << index), handlerPresent);
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup by the <see cref="IViewManager"/> subclass.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view.</param>
/// <remarks>
/// Be sure to call this base class method to register for pointer
/// entered and pointer exited events.
/// </remarks>
public override void OnDropViewInstance(ThemedReactContext reactContext, TFrameworkElement view)
{
_dimensionBoundProperties.Remove(view);
}
/// <summary>
/// Sets the dimensions of the view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="dimensions">The dimensions.</param>
public override void SetDimensions(TFrameworkElement view, Dimensions dimensions)
{
var dimensionBoundProperties = GetDimensionBoundProperties(view);
var matrixTransform = dimensionBoundProperties?.MatrixTransform;
var overflowHidden = dimensionBoundProperties?.OverflowHidden ?? false;
if (matrixTransform != null)
{
SetProjectionMatrix(view, dimensions, matrixTransform);
}
if (overflowHidden)
{
SetOverflowHidden(view, dimensions);
view.SizeChanged -= OnSizeChanged;
}
base.SetDimensions(view, dimensions);
if (overflowHidden)
{
view.SizeChanged += OnSizeChanged;
}
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
var view = (TFrameworkElement)sender;
view.Clip = new RectangleGeometry
{
Rect = new Rect(0, 0, e.NewSize.Width, e.NewSize.Height),
};
}
private DimensionBoundProperties GetDimensionBoundProperties(TFrameworkElement view)
{
if (!_dimensionBoundProperties.TryGetValue(view, out var properties))
{
properties = null;
}
return properties;
}
private DimensionBoundProperties GetOrCreateDimensionBoundProperties(TFrameworkElement view)
{
if (!_dimensionBoundProperties.TryGetValue(view, out var properties))
{
properties = new DimensionBoundProperties();
_dimensionBoundProperties.AddOrUpdate(view, properties);
}
return properties;
}
private static void SetProjectionMatrix(TFrameworkElement view, Dimensions dimensions, JArray transforms)
{
var transformMatrix = TransformHelper.ProcessTransform(transforms);
var translateMatrix = Matrix3D.Identity;
var translateBackMatrix = Matrix3D.Identity;
if (!double.IsNaN(dimensions.Width))
{
translateMatrix.OffsetX = -dimensions.Width / 2;
translateBackMatrix.OffsetX = dimensions.Width / 2;
}
if (!double.IsNaN(dimensions.Height))
{
translateMatrix.OffsetY = -dimensions.Height / 2;
translateBackMatrix.OffsetY = dimensions.Height / 2;
}
var projectionMatrix = translateMatrix * transformMatrix * translateBackMatrix;
ApplyProjection(view, projectionMatrix);
}
private static void ApplyProjection(TFrameworkElement view, Matrix3D projectionMatrix)
{
if (IsSimpleTranslationOnly(projectionMatrix))
{
ResetProjectionMatrix(view);
// We need to use a new instance of MatrixTransform because matrix
// updates to an existing MatrixTransform don't seem to take effect.
var transform = new MatrixTransform();
var matrix = transform.Matrix;
matrix.OffsetX = projectionMatrix.OffsetX;
matrix.OffsetY = projectionMatrix.OffsetY;
transform.Matrix = matrix;
view.RenderTransform = transform;
}
else
{
ResetRenderTransform(view);
var projection = EnsureProjection(view);
projection.ProjectionMatrix = projectionMatrix;
}
}
private static bool IsSimpleTranslationOnly(Matrix3D matrix)
{
// Matrix3D is a struct and passed-by-value. As such, we can modify
// the values in the matrix without affecting the caller.
matrix.OffsetX = matrix.OffsetY = 0;
return matrix.IsIdentity;
}
private static void ResetProjectionMatrix(TFrameworkElement view)
{
var projection = view.Projection;
var matrixProjection = projection as Matrix3DProjection;
if (projection != null && matrixProjection == null)
{
throw new InvalidOperationException("Unknown projection set on framework element.");
}
view.Projection = null;
}
private static void ResetRenderTransform(TFrameworkElement view)
{
var transform = view.RenderTransform;
var matrixTransform = transform as MatrixTransform;
if (transform != null && matrixTransform == null)
{
throw new InvalidOperationException("Unknown transform set on framework element.");
}
view.RenderTransform = null;
}
private static Matrix3DProjection EnsureProjection(FrameworkElement view)
{
var projection = view.Projection;
var matrixProjection = projection as Matrix3DProjection;
if (projection != null && matrixProjection == null)
{
throw new InvalidOperationException("Unknown projection set on framework element.");
}
if (matrixProjection == null)
{
matrixProjection = new Matrix3DProjection();
view.Projection = matrixProjection;
}
return matrixProjection;
}
private static void SetOverflowHidden(TFrameworkElement element, Dimensions dimensions)
{
if (double.IsNaN(dimensions.Width) || double.IsNaN(dimensions.Height))
{
element.Clip = null;
}
else
{
element.Clip = new RectangleGeometry
{
Rect = new Rect(0, 0, dimensions.Width, dimensions.Height),
};
}
}
private static void SetOverflowVisible(TFrameworkElement element)
{
element.Clip = null;
}
class DimensionBoundProperties
{
public bool OverflowHidden { get; set; }
public JArray MatrixTransform { get; set; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using Invio.Xunit;
using Xunit;
namespace Invio.Immutable {
[UnitTest]
public sealed class AggregatePropertyHandlerProviderTests : PropertyHandlerProviderTestsBase {
[Fact]
public void Constructor_NullProviders() {
// Act
var exception = Record.Exception(
() => new AggregatePropertyHandlerProvider(null)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Constructor_NullInProviders() {
// Arrange
var providers = ImmutableList.Create<IPropertyHandlerProvider>(
new DefaultPropertyHandlerProvider(),
null,
new DefaultPropertyHandlerProvider()
);
// Act
var exception = Record.Exception(
() => new AggregatePropertyHandlerProvider(providers)
);
// Assert
Assert.IsType<ArgumentException>(exception);
Assert.Equal(
"One or more of the providers was null." +
Environment.NewLine + "Parameter name: providers",
exception.Message
);
}
[Fact]
public void Create_NullInProviders() {
// Act
var exception = Record.Exception(
() => AggregatePropertyHandlerProvider.Create(
new DefaultPropertyHandlerProvider(),
null,
new DefaultPropertyHandlerProvider()
)
);
// Assert
Assert.IsType<ArgumentException>(exception);
Assert.Equal(
"One or more of the providers was null." +
Environment.NewLine + "Parameter name: providers",
exception.Message
);
}
public static IEnumerable<object[]> IsSupported_UsesInnerProviders_MemberData {
get {
yield return new object[] {
nameof(Fake.ObjectProperty),
ImmutableList.Create<IPropertyHandlerProvider>(
new EnumerablePropertyHandlerProvider(),
new StringPropertyHandlerProvider()
),
false
};
yield return new object[] {
nameof(Fake.EnumerableProperty),
ImmutableList.Create<IPropertyHandlerProvider>(
new StringPropertyHandlerProvider(),
new EnumerablePropertyHandlerProvider()
),
true
};
yield return new object[] {
nameof(Fake.ObjectProperty),
ImmutableList.Create<IPropertyHandlerProvider>(
new StringPropertyHandlerProvider(),
new EnumerablePropertyHandlerProvider(),
new DefaultPropertyHandlerProvider()
),
true
};
}
}
[Theory]
[MemberData(nameof(IsSupported_UsesInnerProviders_MemberData))]
public void IsSupported_UsesInnerProviders(
String propertyName,
IList<IPropertyHandlerProvider> providers,
bool expected) {
// Arrange
var property = typeof(Fake).GetProperty(propertyName);
var provider = this.CreateProvider(providers);
// Act
var actual = provider.IsSupported(property);
// Assert
Assert.Equal(expected, actual);
}
public static IEnumerable<object[]> Create_UsesInnerProviders_MemberData {
get {
yield return new object[] {
nameof(Fake.StringProperty),
ImmutableList.Create<IPropertyHandlerProvider>(
new StringPropertyHandlerProvider(),
new EnumerablePropertyHandlerProvider(),
new DefaultPropertyHandlerProvider()
),
typeof(StringPropertyHandler)
};
yield return new object[] {
nameof(Fake.EnumerableProperty),
ImmutableList.Create<IPropertyHandlerProvider>(
new StringPropertyHandlerProvider(),
new EnumerablePropertyHandlerProvider()
),
typeof(ListPropertyHandler)
};
yield return new object[] {
nameof(Fake.ObjectProperty),
ImmutableList.Create<IPropertyHandlerProvider>(
new StringPropertyHandlerProvider(),
new EnumerablePropertyHandlerProvider(),
new DefaultPropertyHandlerProvider()
),
typeof(DefaultPropertyHandler)
};
}
}
[Theory]
[MemberData(nameof(Create_UsesInnerProviders_MemberData))]
public void Create_UsesInnerProviders(
String propertyName,
IList<IPropertyHandlerProvider> providers,
Type expectedType) {
// Arrange
var property = typeof(Fake).GetProperty(propertyName);
var provider = this.CreateProvider(providers);
// Act
var handler = provider.Create(property);
// Assert
Assert.IsType(expectedType, handler);
}
[Fact]
public void Create_ThrowsIfUnsupported() {
// Arrange
var provider = this.CreateProvider();
var property = typeof(Fake).GetProperty(nameof(Fake.StringProperty));
// Act
var exception = Record.Exception(
() => provider.Create(property)
);
// Assert
Assert.IsType<NotSupportedException>(exception);
}
protected override IPropertyHandlerProvider CreateProvider() {
return this.CreateProvider(ImmutableList<IPropertyHandlerProvider>.Empty);
}
private IPropertyHandlerProvider CreateProvider(
IEnumerable<IPropertyHandlerProvider> providers) {
return new AggregatePropertyHandlerProvider(providers?.ToImmutableList());
}
private sealed class Fake : ImmutableBase<Fake> {
public IEnumerable EnumerableProperty { get; }
public String StringProperty { get; }
public Object ObjectProperty { get; }
public Fake(
IEnumerable enumerableProperty,
String stringProperty,
Object objectProperty) {
this.EnumerableProperty = enumerableProperty;
this.StringProperty = stringProperty;
this.ObjectProperty = objectProperty;
}
}
}
}
| |
//Apache2, 2012, Hernan J Gonzalez, https://github.com/leonbloy/pngcs
namespace Hjg.Pngcs
{
using Hjg.Pngcs.Chunks;
using Hjg.Pngcs.Zlib;
using System.Collections.Generic;
using System.IO;
using System;
/// <summary>
/// Reads a PNG image, line by line
/// </summary>
/// <remarks>
/// The typical reading sequence is as follows:
///
/// 1. At construction time, the header and IHDR chunk are read (basic image info)
///
/// 2 (Optional) you can set some global options: UnpackedMode CrcCheckDisabled
///
/// 3. (Optional) If you call GetMetadata() or or GetChunksLisk() before reading the pixels, the chunks before IDAT are automatically loaded and available
///
/// 4a. The rows are read, one by one, with the <tt>ReadRowXXX</tt> methods: (ReadRowInt() , ReadRowByte(), etc)
/// in order, from 0 to nrows-1 (you can skip or repeat rows, but not go backwards)
///
/// 4b. Alternatively, you can read all rows, or a subset, in a single call: see ReadRowsInt(), ReadRowsByte()
/// In general this consumes more memory, but for interlaced images this is equally efficient, and more so if reading a small subset of rows.
///
/// 5. Read of the last row automatically loads the trailing chunks, and ends the reader.
///
/// 6. End() forcibly finishes/aborts the reading and closes the stream
///
/// </remarks>
public class PngReader
{
/// <summary>
/// Basic image info, inmutable
/// </summary>
public ImageInfo ImgInfo { get; private set; }
/// <summary>
/// filename, or description - merely informative, can be empty
/// </summary>
protected readonly String filename;
/// <summary>
/// Strategy for chunk loading. Default: LOAD_CHUNK_ALWAYS
/// </summary>
public ChunkLoadBehaviour ChunkLoadBehaviour { get; set; }
/// <summary>
/// Should close the underlying Input Stream when ends?
/// </summary>
public bool ShouldCloseStream { get; set; }
/// <summary>
/// Maximum amount of bytes from ancillary chunks to load in memory
/// </summary>
/// <remarks>
/// Default: 5MB. 0: unlimited. If exceeded, chunks will be skipped
/// </remarks>
public long MaxBytesMetadata { get; set; }
/// <summary>
/// Maximum total bytes to read from stream
/// </summary>
/// <remarks>
/// Default: 200MB. 0: Unlimited. If exceeded, an exception will be thrown
/// </remarks>
public long MaxTotalBytesRead { get; set; }
/// <summary>
/// Maximum ancillary chunk size
/// </summary>
/// <remarks>
/// Default: 2MB, 0: unlimited. Chunks exceeding this size will be skipped (nor even CRC checked)
/// </remarks>
public int SkipChunkMaxSize { get; set; }
/// <summary>
/// Ancillary chunks to skip
/// </summary>
/// <remarks>
/// Default: { "fdAT" }. chunks with these ids will be skipped (nor even CRC checked)
/// </remarks>
public String[] SkipChunkIds { get; set; }
private Dictionary<string, int> skipChunkIdsSet = null; // lazily created
/// <summary>
/// A high level wrapper of a ChunksList : list of read chunks
/// </summary>
private readonly PngMetadata metadata;
/// <summary>
/// Read chunks
/// </summary>
private readonly ChunksList chunksList;
/// <summary>
/// buffer: last read line
/// </summary>
protected ImageLine imgLine;
/// <summary>
/// raw current row, as array of bytes,counting from 1 (index 0 is reserved for filter type)
/// </summary>
protected byte[] rowb;
/// <summary>
/// previuos raw row
/// </summary>
protected byte[] rowbprev; // rowb previous
/// <summary>
/// raw current row, after unfiltered
/// </summary>
protected byte[] rowbfilter;
// only set for interlaced PNG
public readonly bool interlaced;
private readonly PngDeinterlacer deinterlacer;
private bool crcEnabled = true;
// this only influences the 1-2-4 bitdepth format
private bool unpackedMode = false;
/// <summary>
/// number of chunk group (0-6) last read, or currently reading
/// </summary>
/// <remarks>see ChunksList.CHUNK_GROUP_NNN</remarks>
public int CurrentChunkGroup { get; private set; }
/// <summary>
/// last read row number
/// </summary>
protected int rowNum = -1; //
private long offset = 0; // offset in InputStream = bytes read
private int bytesChunksLoaded = 0; // bytes loaded from anciallary chunks
private readonly Stream inputStream;
internal AZlibInputStream idatIstream;
internal PngIDatChunkInputStream iIdatCstream;
protected Adler32 crctest; // If set to non null, it gets a CRC of the unfiltered bytes, to check for images equality
/// <summary>
/// Constructs a PngReader from a Stream, with no filename information
/// </summary>
/// <param name="inputStream"></param>
public PngReader(Stream inputStream)
: this(inputStream, "[NO FILENAME AVAILABLE]")
{
}
/// <summary>
/// Constructs a PNGReader objet from a opened Stream
/// </summary>
/// <remarks>The constructor reads the signature and first chunk (IDHR)<seealso cref="FileHelper.CreatePngReader(string)"/>
/// </remarks>
///
/// <param name="inputStream"></param>
/// <param name="filename">Optional, can be the filename or a description.</param>
public PngReader(Stream inputStream, String filename)
{
this.filename = (filename == null) ? "" : filename;
this.inputStream = inputStream;
this.chunksList = new ChunksList(null);
this.metadata = new PngMetadata(chunksList);
this.offset = 0;
// set default options
this.CurrentChunkGroup = -1;
this.ShouldCloseStream = true;
this.MaxBytesMetadata = 5 * 1024 * 1024;
this.MaxTotalBytesRead = 200 * 1024 * 1024; // 200MB
this.SkipChunkMaxSize = 2 * 1024 * 1024;
this.SkipChunkIds = new string[] { "fdAT" };
this.ChunkLoadBehaviour = Hjg.Pngcs.Chunks.ChunkLoadBehaviour.LOAD_CHUNK_ALWAYS;
// starts reading: signature
byte[] pngid = new byte[8];
PngHelperInternal.ReadBytes(inputStream, pngid, 0, pngid.Length);
offset += pngid.Length;
if (!PngCsUtils.arraysEqual(pngid, PngHelperInternal.PNG_ID_SIGNATURE))
throw new PngjInputException("Bad PNG signature");
CurrentChunkGroup = ChunksList.CHUNK_GROUP_0_IDHR;
// reads first chunk IDHR
int clen = PngHelperInternal.ReadInt4(inputStream);
offset += 4;
if (clen != 13)
throw new Exception("IDHR chunk len != 13 ?? " + clen);
byte[] chunkid = new byte[4];
PngHelperInternal.ReadBytes(inputStream, chunkid, 0, 4);
if (!PngCsUtils.arraysEqual4(chunkid, ChunkHelper.b_IHDR))
throw new PngjInputException("IHDR not found as first chunk??? ["
+ ChunkHelper.ToString(chunkid) + "]");
offset += 4;
PngChunkIHDR ihdr = (PngChunkIHDR)ReadChunk(chunkid, clen, false);
bool alpha = (ihdr.Colormodel & 0x04) != 0;
bool palette = (ihdr.Colormodel & 0x01) != 0;
bool grayscale = (ihdr.Colormodel == 0 || ihdr.Colormodel == 4);
// creates ImgInfo and imgLine, and allocates buffers
ImgInfo = new ImageInfo(ihdr.Cols, ihdr.Rows, ihdr.Bitspc, alpha, grayscale, palette);
rowb = new byte[ImgInfo.BytesPerRow + 1];
rowbprev = new byte[rowb.Length];
rowbfilter = new byte[rowb.Length];
interlaced = ihdr.Interlaced == 1;
deinterlacer = interlaced ? new PngDeinterlacer(ImgInfo) : null;
// some checks
if (ihdr.Filmeth != 0 || ihdr.Compmeth != 0 || (ihdr.Interlaced & 0xFFFE) != 0)
throw new PngjInputException("compmethod or filtermethod or interlaced unrecognized");
if (ihdr.Colormodel < 0 || ihdr.Colormodel > 6 || ihdr.Colormodel == 1
|| ihdr.Colormodel == 5)
throw new PngjInputException("Invalid colormodel " + ihdr.Colormodel);
if (ihdr.Bitspc != 1 && ihdr.Bitspc != 2 && ihdr.Bitspc != 4 && ihdr.Bitspc != 8
&& ihdr.Bitspc != 16)
throw new PngjInputException("Invalid bit depth " + ihdr.Bitspc);
}
private bool FirstChunksNotYetRead()
{
return CurrentChunkGroup < ChunksList.CHUNK_GROUP_1_AFTERIDHR;
}
/// <summary>
/// Internally called after having read the last line.
/// It reads extra chunks after IDAT, if present.
/// </summary>
private void ReadLastAndClose()
{
if (CurrentChunkGroup < ChunksList.CHUNK_GROUP_5_AFTERIDAT)
{
try
{
idatIstream.Close();
}
catch (Exception) { }
ReadLastChunks();
}
Close();
}
private void Close()
{
if (CurrentChunkGroup < ChunksList.CHUNK_GROUP_6_END)
{ // this could only happen if forced close
try
{
idatIstream.Close();
}
catch (Exception)
{
}
CurrentChunkGroup = ChunksList.CHUNK_GROUP_6_END;
}
if (ShouldCloseStream)
inputStream.Close();
}
private void UnfilterRow(int nbytes)
{
int ftn = rowbfilter[0];
FilterType ft = (FilterType)ftn;
switch (ft)
{
case Hjg.Pngcs.FilterType.FILTER_NONE:
UnfilterRowNone(nbytes);
break;
case Hjg.Pngcs.FilterType.FILTER_SUB:
UnfilterRowSub(nbytes);
break;
case Hjg.Pngcs.FilterType.FILTER_UP:
UnfilterRowUp(nbytes);
break;
case Hjg.Pngcs.FilterType.FILTER_AVERAGE:
UnfilterRowAverage(nbytes);
break;
case Hjg.Pngcs.FilterType.FILTER_PAETH:
UnfilterRowPaeth(nbytes);
break;
default:
throw new PngjInputException("Filter type " + ftn + " not implemented");
}
if (crctest != null)
crctest.Update(rowb, 1, nbytes);
}
private void UnfilterRowAverage(int nbytes)
{
int i, j, x;
for (j = 1 - ImgInfo.BytesPixel, i = 1; i <= nbytes; i++, j++)
{
x = (j > 0) ? rowb[j] : (byte)0;
rowb[i] = (byte)(rowbfilter[i] + (x + (rowbprev[i] & 0xFF)) / 2);
}
}
private void UnfilterRowNone(int nbytes)
{
for (int i = 1; i <= nbytes; i++)
{
rowb[i] = (byte)(rowbfilter[i]);
}
}
private void UnfilterRowPaeth(int nbytes)
{
int i, j, x, y;
for (j = 1 - ImgInfo.BytesPixel, i = 1; i <= nbytes; i++, j++)
{
x = (j > 0) ? rowb[j] : (byte)0;
y = (j > 0) ? rowbprev[j] : (byte)0;
rowb[i] = (byte)(rowbfilter[i] + PngHelperInternal.FilterPaethPredictor(x, rowbprev[i], y));
}
}
private void UnfilterRowSub(int nbytes)
{
int i, j;
for (i = 1; i <= ImgInfo.BytesPixel; i++)
{
rowb[i] = (byte)(rowbfilter[i]);
}
for (j = 1, i = ImgInfo.BytesPixel + 1; i <= nbytes; i++, j++)
{
rowb[i] = (byte)(rowbfilter[i] + rowb[j]);
}
}
private void UnfilterRowUp(int nbytes)
{
for (int i = 1; i <= nbytes; i++)
{
rowb[i] = (byte)(rowbfilter[i] + rowbprev[i]);
}
}
/// <summary>
/// Reads chunks before first IDAT. Position before: after IDHR (crc included)
/// Position after: just after the first IDAT chunk id Returns length of first
/// IDAT chunk , -1 if not found
/// </summary>
///
private void ReadFirstChunks()
{
if (!FirstChunksNotYetRead())
return;
int clen = 0;
bool found = false;
byte[] chunkid = new byte[4]; // it's important to reallocate in each
this.CurrentChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR;
while (!found)
{
clen = PngHelperInternal.ReadInt4(inputStream);
offset += 4;
if (clen < 0)
break;
PngHelperInternal.ReadBytes(inputStream, chunkid, 0, 4);
offset += 4;
if (PngCsUtils.arraysEqual4(chunkid, Hjg.Pngcs.Chunks.ChunkHelper.b_IDAT))
{
found = true;
this.CurrentChunkGroup = ChunksList.CHUNK_GROUP_4_IDAT;
// add dummy idat chunk to list
chunksList.AppendReadChunk(new PngChunkIDAT(ImgInfo, clen, offset - 8), CurrentChunkGroup);
break;
}
else if (PngCsUtils.arraysEqual4(chunkid, Hjg.Pngcs.Chunks.ChunkHelper.b_IEND))
{
throw new PngjInputException("END chunk found before image data (IDAT) at offset=" + offset);
}
String chunkids = ChunkHelper.ToString(chunkid);
if (chunkids.Equals(ChunkHelper.PLTE))
this.CurrentChunkGroup = ChunksList.CHUNK_GROUP_2_PLTE;
ReadChunk(chunkid, clen, false);
if (chunkids.Equals(ChunkHelper.PLTE))
this.CurrentChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE;
}
int idatLen = found ? clen : -1;
if (idatLen < 0)
throw new PngjInputException("first idat chunk not found!");
iIdatCstream = new PngIDatChunkInputStream(inputStream, idatLen, offset);
idatIstream = ZlibStreamFactory.createZlibInputStream(iIdatCstream, true);
if (!crcEnabled)
iIdatCstream.DisableCrcCheck();
}
/// <summary>
/// Reads (and processes ... up to a point) chunks after last IDAT.
/// </summary>
///
private void ReadLastChunks()
{
CurrentChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT;
// PngHelper.logdebug("idat ended? " + iIdatCstream.isEnded());
if (!iIdatCstream.IsEnded())
iIdatCstream.ForceChunkEnd();
int clen = iIdatCstream.GetLenLastChunk();
byte[] chunkid = iIdatCstream.GetIdLastChunk();
bool endfound = false;
bool first = true;
bool skip = false;
while (!endfound)
{
skip = false;
if (!first)
{
clen = PngHelperInternal.ReadInt4(inputStream);
offset += 4;
if (clen < 0)
throw new PngjInputException("bad len " + clen);
PngHelperInternal.ReadBytes(inputStream, chunkid, 0, 4);
offset += 4;
}
first = false;
if (PngCsUtils.arraysEqual4(chunkid, ChunkHelper.b_IDAT))
{
skip = true; // extra dummy (empty?) idat chunk, it can happen, ignore it
}
else if (PngCsUtils.arraysEqual4(chunkid, ChunkHelper.b_IEND))
{
CurrentChunkGroup = ChunksList.CHUNK_GROUP_6_END;
endfound = true;
}
ReadChunk(chunkid, clen, skip);
}
if (!endfound)
throw new PngjInputException("end chunk not found - offset=" + offset);
// PngHelper.logdebug("end chunk found ok offset=" + offset);
}
/// <summary>
/// Reads chunkd from input stream, adds to ChunksList, and returns it.
/// If it's skipped, a PngChunkSkipped object is created
/// </summary>
/// <returns></returns>
private PngChunk ReadChunk(byte[] chunkid, int clen, bool skipforced)
{
if (clen < 0) throw new PngjInputException("invalid chunk lenght: " + clen);
// skipChunksByIdSet is created lazyly, if fist IHDR has already been read
if (skipChunkIdsSet == null && CurrentChunkGroup > ChunksList.CHUNK_GROUP_0_IDHR)
{
skipChunkIdsSet = new Dictionary<string, int>();
if (SkipChunkIds != null)
foreach (string id in SkipChunkIds) skipChunkIdsSet.Add(id, 1);
}
String chunkidstr = ChunkHelper.ToString(chunkid);
PngChunk pngChunk = null;
bool critical = ChunkHelper.IsCritical(chunkidstr);
bool skip = skipforced;
if (MaxTotalBytesRead > 0 && clen + offset > MaxTotalBytesRead)
throw new PngjInputException("Maximum total bytes to read exceeeded: " + MaxTotalBytesRead + " offset:"
+ offset + " clen=" + clen);
// an ancillary chunks can be skipped because of several reasons:
if (CurrentChunkGroup > ChunksList.CHUNK_GROUP_0_IDHR && !ChunkHelper.IsCritical(chunkidstr))
skip = skip || (SkipChunkMaxSize > 0 && clen >= SkipChunkMaxSize) || skipChunkIdsSet.ContainsKey(chunkidstr)
|| (MaxBytesMetadata > 0 && clen > MaxBytesMetadata - bytesChunksLoaded)
|| !ChunkHelper.ShouldLoad(chunkidstr, ChunkLoadBehaviour);
if (skip)
{
PngHelperInternal.SkipBytes(inputStream, clen);
PngHelperInternal.ReadInt4(inputStream); // skip - we dont call PngHelperInternal.skipBytes(inputStream, clen + 4) for risk of overflow
pngChunk = new PngChunkSkipped(chunkidstr, ImgInfo, clen);
}
else
{
ChunkRaw chunk = new ChunkRaw(clen, chunkid, true);
chunk.ReadChunkData(inputStream, crcEnabled || critical);
pngChunk = PngChunk.Factory(chunk, ImgInfo);
if (!pngChunk.Crit)
{
bytesChunksLoaded += chunk.Len;
}
}
pngChunk.Offset = offset - 8L;
chunksList.AppendReadChunk(pngChunk, CurrentChunkGroup);
offset += clen + 4L;
return pngChunk;
}
/// <summary>
/// Logs/prints a warning.
/// </summary>
/// <remarks>
/// The default behaviour is print to stderr, but it can be overriden.
/// This happens rarely - most errors are fatal.
/// </remarks>
/// <param name="warn"></param>
internal void logWarn(String warn)
{
Console.Error.WriteLine(warn);
}
/// <summary>
/// Returns the ancillary chunks available
/// </summary>
/// <remarks>
/// If the rows have not yet still been read, this includes
/// only the chunks placed before the pixels (IDAT)
/// </remarks>
/// <returns>ChunksList</returns>
public ChunksList GetChunksList()
{
if (FirstChunksNotYetRead())
ReadFirstChunks();
return chunksList;
}
/// <summary>
/// Returns the ancillary chunks available
/// </summary>
/// <remarks>
/// see GetChunksList
/// </remarks>
/// <returns>PngMetadata</returns>
public PngMetadata GetMetadata()
{
if (FirstChunksNotYetRead())
ReadFirstChunks();
return metadata;
}
/// <summary>
/// reads the row using ImageLine as buffer
/// </summary>
///<param name="nrow">row number - just as a check</param>
/// <returns>the ImageLine that also is available inside this object</returns>
public ImageLine ReadRow(int nrow)
{
return imgLine == null || imgLine.SampleType != ImageLine.ESampleType.BYTE ? ReadRowInt(nrow) : ReadRowByte(nrow);
}
public ImageLine ReadRowInt(int nrow)
{
if (imgLine == null)
imgLine = new ImageLine(ImgInfo, ImageLine.ESampleType.INT, unpackedMode);
if (imgLine.Rown == nrow) // already read
return imgLine;
ReadRowInt(imgLine.Scanline, nrow);
imgLine.FilterUsed = (FilterType)rowbfilter[0];
imgLine.Rown = nrow;
return imgLine;
}
public ImageLine ReadRowByte(int nrow)
{
if (imgLine == null)
imgLine = new ImageLine(ImgInfo, ImageLine.ESampleType.BYTE, unpackedMode);
if (imgLine.Rown == nrow) // already read
return imgLine;
ReadRowByte(imgLine.ScanlineB, nrow);
imgLine.FilterUsed = (FilterType)rowbfilter[0];
imgLine.Rown = nrow;
return imgLine;
}
public int[] ReadRow(int[] buffer, int nrow)
{
return ReadRowInt(buffer, nrow);
}
public int[] ReadRowInt(int[] buffer, int nrow)
{
if (buffer == null)
buffer = new int[unpackedMode ? ImgInfo.SamplesPerRow : ImgInfo.SamplesPerRowPacked];
if (!interlaced)
{
if (nrow <= rowNum)
throw new PngjInputException("rows must be read in increasing order: " + nrow);
int bytesread = 0;
while (rowNum < nrow)
bytesread = ReadRowRaw(rowNum + 1); // read rows, perhaps skipping if necessary
decodeLastReadRowToInt(buffer, bytesread);
}
else
{ // interlaced
if (deinterlacer.getImageInt() == null)
deinterlacer.setImageInt(ReadRowsInt().Scanlines); // read all image and store it in deinterlacer
Array.Copy(deinterlacer.getImageInt()[nrow], 0, buffer, 0, unpackedMode ? ImgInfo.SamplesPerRow
: ImgInfo.SamplesPerRowPacked);
}
return buffer;
}
public byte[] ReadRowByte(byte[] buffer, int nrow)
{
if (buffer == null)
buffer = new byte[unpackedMode ? ImgInfo.SamplesPerRow : ImgInfo.SamplesPerRowPacked];
if (!interlaced)
{
if (nrow <= rowNum)
throw new PngjInputException("rows must be read in increasing order: " + nrow);
int bytesread = 0;
while (rowNum < nrow)
bytesread = ReadRowRaw(rowNum + 1); // read rows, perhaps skipping if necessary
decodeLastReadRowToByte(buffer, bytesread);
}
else
{ // interlaced
if (deinterlacer.getImageByte() == null)
deinterlacer.setImageByte(ReadRowsByte().ScanlinesB); // read all image and store it in deinterlacer
Array.Copy(deinterlacer.getImageByte()[nrow], 0, buffer, 0, unpackedMode ? ImgInfo.SamplesPerRow
: ImgInfo.SamplesPerRowPacked);
}
return buffer;
}
/// <summary>
///
/// </summary>
/// <param name="nrow"></param>
/// <returns></returns>
[Obsolete("GetRow is deprecated, use ReadRow/ReadRowInt/ReadRowByte instead.")]
public ImageLine GetRow(int nrow)
{
return ReadRow(nrow);
}
private void decodeLastReadRowToInt(int[] buffer, int bytesRead)
{ // see http://www.libpng.org/pub/png/spec/1.2/PNG-DataRep.html
if (ImgInfo.BitDepth <= 8)
{
for (int i = 0, j = 1; i < bytesRead; i++)
buffer[i] = (rowb[j++]);
}
else
{ // 16 bitspc
for (int i = 0, j = 1; j < bytesRead; i++)
buffer[i] = (rowb[j++] << 8) + rowb[j++];
}
if (ImgInfo.Packed && unpackedMode)
ImageLine.unpackInplaceInt(ImgInfo, buffer, buffer, false);
}
private void decodeLastReadRowToByte(byte[] buffer, int bytesRead)
{ // see http://www.libpng.org/pub/png/spec/1.2/PNG-DataRep.html
if (ImgInfo.BitDepth <= 8)
{
Array.Copy(rowb, 1, buffer, 0, bytesRead);
}
else
{ // 16 bitspc
for (int i = 0, j = 1; j < bytesRead; i++, j += 2)
buffer[i] = rowb[j]; // 16 bits in 1 byte: this discards the LSB!!!
}
if (ImgInfo.Packed && unpackedMode)
ImageLine.unpackInplaceByte(ImgInfo, buffer, buffer, false);
}
public ImageLines ReadRowsInt(int rowOffset, int nRows, int rowStep)
{
if (nRows < 0)
nRows = (ImgInfo.Rows - rowOffset) / rowStep;
if (rowStep < 1 || rowOffset < 0 || nRows * rowStep + rowOffset > ImgInfo.Rows)
throw new PngjInputException("bad args");
ImageLines imlines = new ImageLines(ImgInfo, ImageLine.ESampleType.INT, unpackedMode, rowOffset, nRows, rowStep);
if (!interlaced)
{
for (int j = 0; j < ImgInfo.Rows; j++)
{
int bytesread = ReadRowRaw(j); // read and perhaps discards
int mrow = imlines.ImageRowToMatrixRowStrict(j);
if (mrow >= 0)
decodeLastReadRowToInt(imlines.Scanlines[mrow], bytesread);
}
}
else
{ // and now, for something completely different (interlaced)
int[] buf = new int[unpackedMode ? ImgInfo.SamplesPerRow : ImgInfo.SamplesPerRowPacked];
for (int p = 1; p <= 7; p++)
{
deinterlacer.setPass(p);
for (int i = 0; i < deinterlacer.getRows(); i++)
{
int bytesread = ReadRowRaw(i);
int j = deinterlacer.getCurrRowReal();
int mrow = imlines.ImageRowToMatrixRowStrict(j);
if (mrow >= 0)
{
decodeLastReadRowToInt(buf, bytesread);
deinterlacer.deinterlaceInt(buf, imlines.Scanlines[mrow], !unpackedMode);
}
}
}
}
End();
return imlines;
}
public ImageLines ReadRowsInt()
{
return ReadRowsInt(0, ImgInfo.Rows, 1);
}
public ImageLines ReadRowsByte(int rowOffset, int nRows, int rowStep)
{
if (nRows < 0)
nRows = (ImgInfo.Rows - rowOffset) / rowStep;
if (rowStep < 1 || rowOffset < 0 || nRows * rowStep + rowOffset > ImgInfo.Rows)
throw new PngjInputException("bad args");
ImageLines imlines = new ImageLines(ImgInfo, ImageLine.ESampleType.BYTE, unpackedMode, rowOffset, nRows, rowStep);
if (!interlaced)
{
for (int j = 0; j < ImgInfo.Rows; j++)
{
int bytesread = ReadRowRaw(j); // read and perhaps discards
int mrow = imlines.ImageRowToMatrixRowStrict(j);
if (mrow >= 0)
decodeLastReadRowToByte(imlines.ScanlinesB[mrow], bytesread);
}
}
else
{ // and now, for something completely different (interlaced)
byte[] buf = new byte[unpackedMode ? ImgInfo.SamplesPerRow : ImgInfo.SamplesPerRowPacked];
for (int p = 1; p <= 7; p++)
{
deinterlacer.setPass(p);
for (int i = 0; i < deinterlacer.getRows(); i++)
{
int bytesread = ReadRowRaw(i);
int j = deinterlacer.getCurrRowReal();
int mrow = imlines.ImageRowToMatrixRowStrict(j);
if (mrow >= 0)
{
decodeLastReadRowToByte(buf, bytesread);
deinterlacer.deinterlaceByte(buf, imlines.ScanlinesB[mrow], !unpackedMode);
}
}
}
}
End();
return imlines;
}
public ImageLines ReadRowsByte()
{
return ReadRowsByte(0, ImgInfo.Rows, 1);
}
private int ReadRowRaw(int nrow)
{
//
if (nrow == 0 && FirstChunksNotYetRead())
ReadFirstChunks();
if (nrow == 0 && interlaced)
Array.Clear(rowb, 0, rowb.Length); // new subimage: reset filters: this is enough, see the swap that happens lines
// below
int bytesRead = ImgInfo.BytesPerRow; // NOT including the filter byte
if (interlaced)
{
if (nrow < 0 || nrow > deinterlacer.getRows() || (nrow != 0 && nrow != deinterlacer.getCurrRowSubimg() + 1))
throw new PngjInputException("invalid row in interlaced mode: " + nrow);
deinterlacer.setRow(nrow);
bytesRead = (ImgInfo.BitspPixel * deinterlacer.getPixelsToRead() + 7) / 8;
if (bytesRead < 1)
throw new PngjExceptionInternal("wtf??");
}
else
{ // check for non interlaced
if (nrow < 0 || nrow >= ImgInfo.Rows || nrow != rowNum + 1)
throw new PngjInputException("invalid row: " + nrow);
}
rowNum = nrow;
// swap buffers
byte[] tmp = rowb;
rowb = rowbprev;
rowbprev = tmp;
// loads in rowbfilter "raw" bytes, with filter
PngHelperInternal.ReadBytes(idatIstream, rowbfilter, 0, bytesRead + 1);
offset = iIdatCstream.GetOffset();
if (offset < 0)
throw new PngjExceptionInternal("bad offset ??" + offset);
if (MaxTotalBytesRead > 0 && offset >= MaxTotalBytesRead)
throw new PngjInputException("Reading IDAT: Maximum total bytes to read exceeeded: " + MaxTotalBytesRead
+ " offset:" + offset);
rowb[0] = 0;
UnfilterRow(bytesRead);
rowb[0] = rowbfilter[0];
if ((rowNum == ImgInfo.Rows - 1 && !interlaced) || (interlaced && deinterlacer.isAtLastRow()))
ReadLastAndClose();
return bytesRead;
}
public void ReadSkippingAllRows()
{
if (FirstChunksNotYetRead())
ReadFirstChunks();
// we read directly from the compressed stream, we dont decompress nor chec CRC
iIdatCstream.DisableCrcCheck();
try
{
int r;
do
{
r = iIdatCstream.Read(rowbfilter, 0, rowbfilter.Length);
} while (r >= 0);
}
catch (IOException e)
{
throw new PngjInputException("error in raw read of IDAT", e);
}
offset = iIdatCstream.GetOffset();
if (offset < 0)
throw new PngjExceptionInternal("bad offset ??" + offset);
if (MaxTotalBytesRead > 0 && offset >= MaxTotalBytesRead)
throw new PngjInputException("Reading IDAT: Maximum total bytes to read exceeeded: " + MaxTotalBytesRead
+ " offset:" + offset);
ReadLastAndClose();
}
public override String ToString()
{ // basic info
return "filename=" + filename + " " + ImgInfo.ToString();
}
/// <summary>
/// Normally this does nothing, but it can be used to force a premature closing
/// </summary>
/// <remarks></remarks>
public void End()
{
if (CurrentChunkGroup < ChunksList.CHUNK_GROUP_6_END)
Close();
}
public bool IsInterlaced()
{
return interlaced;
}
public void SetUnpackedMode(bool unPackedMode)
{
this.unpackedMode = unPackedMode;
}
/**
* @see PngReader#setUnpackedMode(boolean)
*/
public bool IsUnpackedMode()
{
return unpackedMode;
}
public void SetCrcCheckDisabled()
{
crcEnabled = false;
}
internal long GetCrctestVal()
{
return crctest.GetValue();
}
internal void InitCrctest()
{
this.crctest = new Adler32();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Collections;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Data.Core;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Styling;
using Avalonia.UnitTests;
using JetBrains.Annotations;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TreeViewTests
{
MouseTestHelper _mouse = new MouseTestHelper();
[Fact]
public void Items_Should_Be_Created()
{
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = CreateTestTreeData(),
};
var root = new TestRoot(target);
CreateNodeDataTemplate(target);
ApplyTemplates(target);
Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0));
Assert.Equal(new[] { "Child1", "Child2", "Child3" }, ExtractItemHeader(target, 1));
Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2));
}
[Fact]
public void Items_Should_Be_Created_Using_ItemTemplate_If_Present()
{
TreeView target;
var root = new TestRoot
{
Child = target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = CreateTestTreeData(),
ItemTemplate = new FuncTreeDataTemplate<Node>(
(_, __) => new Canvas(),
x => x.Children),
}
};
ApplyTemplates(target);
var items = target.ItemContainerGenerator.Index.Containers
.OfType<TreeViewItem>()
.ToList();
Assert.Equal(5, items.Count);
Assert.All(items, x => Assert.IsType<Canvas>(x.HeaderPresenter.Child));
}
[Fact]
public void Root_ItemContainerGenerator_Containers_Should_Be_Root_Containers()
{
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = CreateTestTreeData(),
};
var root = new TestRoot(target);
CreateNodeDataTemplate(target);
ApplyTemplates(target);
var container = (TreeViewItem)target.ItemContainerGenerator.Containers.Single().ContainerControl;
var header = (TextBlock)container.Header;
Assert.Equal("Root", header.Text);
}
[Fact]
public void Root_TreeContainerFromItem_Should_Return_Descendant_Item()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
// For TreeViewItem to find its parent TreeView, OnAttachedToLogicalTree needs
// to be called, which requires an IStyleRoot.
var root = new TestRoot();
root.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
var container = target.ItemContainerGenerator.Index.ContainerFromItem(
tree[0].Children[1].Children[0]);
Assert.NotNull(container);
var header = ((TreeViewItem)container).Header;
var headerContent = ((TextBlock)header).Text;
Assert.Equal("Grandchild2a", headerContent);
}
[Fact]
public void Clicking_Item_Should_Select_It()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var item = tree[0].Children[1].Children[0];
var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);
Assert.NotNull(container);
_mouse.Click(container);
Assert.Equal(item, target.SelectedItem);
Assert.True(container.IsSelected);
}
}
[Fact]
public void Clicking_WithControlModifier_Selected_Item_Should_Deselect_It()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var item = tree[0].Children[1].Children[0];
var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);
Assert.NotNull(container);
target.SelectedItem = item;
Assert.True(container.IsSelected);
_mouse.Click(container, modifiers: KeyModifiers.Control);
Assert.Null(target.SelectedItem);
Assert.False(container.IsSelected);
}
}
[Fact]
public void Clicking_WithControlModifier_Not_Selected_Item_Should_Select_It()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var item1 = tree[0].Children[1].Children[0];
var container1 = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item1);
var item2 = tree[0].Children[1];
var container2 = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item2);
Assert.NotNull(container1);
Assert.NotNull(container2);
target.SelectedItem = item1;
Assert.True(container1.IsSelected);
_mouse.Click(container2, modifiers: KeyModifiers.Control);
Assert.Equal(item2, target.SelectedItem);
Assert.False(container1.IsSelected);
Assert.True(container2.IsSelected);
}
}
[Fact]
public void Clicking_WithControlModifier_Selected_Item_Should_Deselect_And_Remove_From_SelectedItems()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var rootNode = tree[0];
var item1 = rootNode.Children[0];
var item2 = rootNode.Children.Last();
var item1Container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item1);
var item2Container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item2);
ClickContainer(item1Container, KeyModifiers.Control);
Assert.True(item1Container.IsSelected);
ClickContainer(item2Container, KeyModifiers.Control);
Assert.True(item2Container.IsSelected);
Assert.Equal(new[] { item1, item2 }, target.SelectedItems.OfType<Node>());
ClickContainer(item1Container, KeyModifiers.Control);
Assert.False(item1Container.IsSelected);
Assert.DoesNotContain(item1, target.SelectedItems.OfType<Node>());
}
}
[Fact]
public void Clicking_WithShiftModifier_DownDirection_Should_Select_Range_Of_Items()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var rootNode = tree[0];
var from = rootNode.Children[0];
var to = rootNode.Children.Last();
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(from);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
ClickContainer(fromContainer, KeyModifiers.None);
Assert.True(fromContainer.IsSelected);
ClickContainer(toContainer, KeyModifiers.Shift);
AssertChildrenSelected(target, rootNode);
}
}
[Fact]
public void Clicking_WithShiftModifier_UpDirection_Should_Select_Range_Of_Items()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var rootNode = tree[0];
var from = rootNode.Children.Last();
var to = rootNode.Children[0];
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(from);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
ClickContainer(fromContainer, KeyModifiers.None);
Assert.True(fromContainer.IsSelected);
ClickContainer(toContainer, KeyModifiers.Shift);
AssertChildrenSelected(target, rootNode);
}
}
[Fact]
public void Clicking_First_Item_Of_SelectedItems_Should_Select_Only_It()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var rootNode = tree[0];
var from = rootNode.Children.Last();
var to = rootNode.Children[0];
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(from);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
ClickContainer(fromContainer, KeyModifiers.None);
ClickContainer(toContainer, KeyModifiers.Shift);
AssertChildrenSelected(target, rootNode);
ClickContainer(fromContainer, KeyModifiers.None);
Assert.True(fromContainer.IsSelected);
foreach (var child in rootNode.Children)
{
if (child == from)
{
continue;
}
var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(child);
Assert.False(container.IsSelected);
}
}
}
[Fact]
public void Setting_SelectedItem_Should_Set_Container_Selected()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var item = tree[0].Children[1].Children[0];
var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);
Assert.NotNull(container);
target.SelectedItem = item;
Assert.True(container.IsSelected);
}
}
[Fact]
public void Setting_SelectedItem_Should_Raise_SelectedItemChanged_Event()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var item = tree[0].Children[1].Children[0];
var called = false;
target.SelectionChanged += (s, e) =>
{
Assert.Empty(e.RemovedItems);
Assert.Equal(1, e.AddedItems.Count);
Assert.Same(item, e.AddedItems[0]);
called = true;
};
target.SelectedItem = item;
Assert.True(called);
}
}
[Fact]
public void Bound_SelectedItem_Should_Not_Be_Cleared_when_Changing_Selection()
{
using (Application())
{
var dataContext = new TestDataContext();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
DataContext = dataContext
};
target.Bind(TreeView.ItemsProperty, new Binding("Items"));
target.Bind(TreeView.SelectedItemProperty, new Binding("SelectedItem"));
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
var selectedValues = new List<object>();
dataContext.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(TestDataContext.SelectedItem))
selectedValues.Add(dataContext.SelectedItem);
};
selectedValues.Add(dataContext.SelectedItem);
_mouse.Click((Interactive)target.Presenter.Panel.Children[0], MouseButton.Left);
_mouse.Click((Interactive)target.Presenter.Panel.Children[2], MouseButton.Left);
Assert.Equal(3, selectedValues.Count);
Assert.Equal(new[] { null, "Item 0", "Item 2" }, selectedValues.ToArray());
}
}
[Fact]
public void LogicalChildren_Should_Be_Set()
{
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = new[] { "Foo", "Bar", "Baz " },
};
ApplyTemplates(target);
var result = target.GetLogicalChildren()
.OfType<TreeViewItem>()
.Select(x => x.Header)
.OfType<TextBlock>()
.Select(x => x.Text)
.ToList();
Assert.Equal(new[] { "Foo", "Bar", "Baz " }, result);
}
[Fact]
public void Removing_Item_Should_Remove_Itself_And_Children_From_Index()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var root = new TestRoot();
root.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
Assert.Equal(5, target.ItemContainerGenerator.Index.Containers.Count());
tree[0].Children.RemoveAt(1);
Assert.Equal(3, target.ItemContainerGenerator.Index.Containers.Count());
}
[Fact]
public void DataContexts_Should_Be_Correctly_Set()
{
var items = new object[]
{
"Foo",
new Node { Value = "Bar" },
new TextBlock { Text = "Baz" },
new TreeViewItem { Header = "Qux" },
};
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
DataContext = "Base",
DataTemplates =
{
new FuncDataTemplate<Node>((x, _) => new Button { Content = x })
},
Items = items,
};
ApplyTemplates(target);
var dataContexts = target.Presenter.Panel.Children
.Cast<Control>()
.Select(x => x.DataContext)
.ToList();
Assert.Equal(
new object[] { items[0], items[1], "Base", "Base" },
dataContexts);
}
[Fact]
public void Control_Item_Should_Not_Be_NameScope()
{
var items = new object[]
{
new TreeViewItem(),
};
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = items,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var item = target.Presenter.Panel.LogicalChildren[0];
Assert.Null(NameScope.GetNameScope((TreeViewItem)item));
}
[Fact]
public void Should_React_To_Children_Changing()
{
var data = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = data,
};
var root = new TestRoot(target);
CreateNodeDataTemplate(target);
ApplyTemplates(target);
Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0));
Assert.Equal(new[] { "Child1", "Child2", "Child3" }, ExtractItemHeader(target, 1));
Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2));
// Make sure that the binding to Node.Children does not get collected.
GC.Collect();
data[0].Children = new AvaloniaList<Node>
{
new Node
{
Value = "NewChild1",
}
};
Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0));
Assert.Equal(new[] { "NewChild1" }, ExtractItemHeader(target, 1));
}
[Fact]
public void Keyboard_Navigation_Should_Move_To_Last_Selected_Node()
{
using (Application())
{
var focus = FocusManager.Instance;
var navigation = AvaloniaLocator.Current.GetService<IKeyboardNavigationHandler>();
var data = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = data,
};
var button = new Button();
var root = new TestRoot
{
Child = new StackPanel
{
Children = { target, button },
}
};
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var item = data[0].Children[0];
var node = target.ItemContainerGenerator.Index.ContainerFromItem(item);
Assert.NotNull(node);
target.SelectedItem = item;
node.Focus();
Assert.Same(node, focus.Current);
navigation.Move(focus.Current, NavigationDirection.Next);
Assert.Same(button, focus.Current);
navigation.Move(focus.Current, NavigationDirection.Next);
Assert.Same(node, focus.Current);
}
}
[Fact]
public void Keyboard_Navigation_Should_Not_Crash_If_Selected_Item_Is_not_In_Tree()
{
using (Application())
{
var focus = FocusManager.Instance;
var navigation = AvaloniaLocator.Current.GetService<IKeyboardNavigationHandler>();
var data = CreateTestTreeData();
var selectedNode = new Node { Value = "Out of Tree Selected Item" };
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = data,
SelectedItem = selectedNode
};
var button = new Button();
var root = new TestRoot
{
Child = new StackPanel
{
Children = { target, button },
}
};
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var item = data[0].Children[0];
var node = target.ItemContainerGenerator.Index.ContainerFromItem(item);
Assert.NotNull(node);
target.SelectedItem = selectedNode;
node.Focus();
Assert.Same(node, focus.Current);
var next = KeyboardNavigationHandler.GetNext(node, NavigationDirection.Previous);
}
}
[Fact]
public void Pressing_SelectAll_Gesture_Should_Select_All_Nodes()
{
using (UnitTestApplication.Start())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var rootNode = tree[0];
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
var selectAllGesture = keymap.SelectAll.First();
var keyEvent = new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
Key = selectAllGesture.Key,
KeyModifiers = selectAllGesture.KeyModifiers
};
target.RaiseEvent(keyEvent);
AssertChildrenSelected(target, rootNode);
}
}
[Fact]
public void Pressing_SelectAll_Gesture_With_Downward_Range_Selected_Should_Select_All_Nodes()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var rootNode = tree[0];
var from = rootNode.Children[0];
var to = rootNode.Children.Last();
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(from);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
ClickContainer(fromContainer, KeyModifiers.None);
ClickContainer(toContainer, KeyModifiers.Shift);
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
var selectAllGesture = keymap.SelectAll.First();
var keyEvent = new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
Key = selectAllGesture.Key,
KeyModifiers = selectAllGesture.KeyModifiers
};
target.RaiseEvent(keyEvent);
AssertChildrenSelected(target, rootNode);
}
}
[Fact]
public void Pressing_SelectAll_Gesture_With_Upward_Range_Selected_Should_Select_All_Nodes()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var rootNode = tree[0];
var from = rootNode.Children.Last();
var to = rootNode.Children[0];
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(from);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
ClickContainer(fromContainer, KeyModifiers.None);
ClickContainer(toContainer, KeyModifiers.Shift);
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
var selectAllGesture = keymap.SelectAll.First();
var keyEvent = new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
Key = selectAllGesture.Key,
KeyModifiers = selectAllGesture.KeyModifiers
};
target.RaiseEvent(keyEvent);
AssertChildrenSelected(target, rootNode);
}
}
[Fact]
public void Right_Click_On_SelectedItem_Should_Not_Clear_Existing_Selection()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
target.ExpandSubTree((TreeViewItem)target.Presenter.Panel.Children[0]);
target.SelectAll();
AssertChildrenSelected(target, tree[0]);
Assert.Equal(5, target.SelectedItems.Count);
_mouse.Click((Interactive)target.Presenter.Panel.Children[0], MouseButton.Right);
Assert.Equal(5, target.SelectedItems.Count);
}
[Fact]
public void Right_Click_On_UnselectedItem_Should_Clear_Existing_Selection()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
target.ExpandSubTree((TreeViewItem)target.Presenter.Panel.Children[0]);
var rootNode = tree[0];
var to = rootNode.Children[0];
var then = rootNode.Children[1];
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(rootNode);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
var thenContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(then);
ClickContainer(fromContainer, KeyModifiers.None);
ClickContainer(toContainer, KeyModifiers.Shift);
Assert.Equal(2, target.SelectedItems.Count);
_mouse.Click(thenContainer, MouseButton.Right);
Assert.Equal(1, target.SelectedItems.Count);
}
}
[Fact]
public void Shift_Right_Click_Should_Not_Select_Multiple()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
target.ExpandSubTree((TreeViewItem)target.Presenter.Panel.Children[0]);
var rootNode = tree[0];
var from = rootNode.Children[0];
var to = rootNode.Children[1];
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(from);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
_mouse.Click(fromContainer);
_mouse.Click(toContainer, MouseButton.Right, modifiers: KeyModifiers.Shift);
Assert.Equal(1, target.SelectedItems.Count);
}
}
[Fact]
public void Ctrl_Right_Click_Should_Not_Select_Multiple()
{
using (Application())
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
SelectionMode = SelectionMode.Multiple,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
target.ExpandSubTree((TreeViewItem)target.Presenter.Panel.Children[0]);
var rootNode = tree[0];
var from = rootNode.Children[0];
var to = rootNode.Children[1];
var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(from);
var toContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
_mouse.Click(fromContainer);
_mouse.Click(toContainer, MouseButton.Right, modifiers: KeyModifiers.Control);
Assert.Equal(1, target.SelectedItems.Count);
}
}
[Fact]
public void TreeViewItems_Level_Should_Be_Set()
{
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
Assert.Equal(0, GetItem(target, 0).Level);
Assert.Equal(1, GetItem(target, 0, 0).Level);
Assert.Equal(1, GetItem(target, 0, 1).Level);
Assert.Equal(1, GetItem(target, 0, 2).Level);
Assert.Equal(2, GetItem(target, 0, 1, 0).Level);
}
[Fact]
public void TreeViewItems_Level_Should_Be_Set_For_Derived_TreeView()
{
var tree = CreateTestTreeData();
var target = new DerivedTreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
Assert.Equal(0, GetItem(target, 0).Level);
Assert.Equal(1, GetItem(target, 0, 0).Level);
Assert.Equal(1, GetItem(target, 0, 1).Level);
Assert.Equal(1, GetItem(target, 0, 2).Level);
Assert.Equal(2, GetItem(target, 0, 1, 0).Level);
}
[Fact]
public void Adding_Node_To_Removed_And_ReAdded_Parent_Should_Not_Crash()
{
// Issue #2985
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var visualRoot = new TestRoot();
visualRoot.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
var parent = tree[0];
var node = parent.Children[1];
parent.Children.Remove(node);
parent.Children.Add(node);
var item = target.ItemContainerGenerator.Index.ContainerFromItem(node);
ApplyTemplates(new[] { item });
// #2985 causes ArgumentException here.
node.Children.Add(new Node());
}
[Fact]
public void Auto_Expanding_In_Style_Should_Not_Break_Range_Selection()
{
// Issue #2980.
using (Application())
{
var target = new DerivedTreeView
{
Template = CreateTreeViewTemplate(),
SelectionMode = SelectionMode.Multiple,
Items = new List<Node>
{
new Node { Value = "Root1", },
new Node { Value = "Root2", },
},
};
var visualRoot = new TestRoot
{
Styles =
{
new Style(x => x.OfType<TreeViewItem>())
{
Setters =
{
new Setter(TreeViewItem.IsExpandedProperty, true),
},
},
},
Child = target,
};
CreateNodeDataTemplate(target);
ApplyTemplates(target);
_mouse.Click(GetItem(target, 0));
_mouse.Click(GetItem(target, 1), modifiers: KeyModifiers.Shift);
}
}
[Fact]
public void Removing_TreeView_From_Root_Should_Preserve_TreeViewItems()
{
// Issue #3328
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var root = new TestRoot();
root.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
ExpandAll(target);
Assert.Equal(5, target.ItemContainerGenerator.Index.Containers.Count());
root.Child = null;
Assert.Equal(5, target.ItemContainerGenerator.Index.Containers.Count());
Assert.Equal(1, target.Presenter.Panel.Children.Count);
var rootNode = Assert.IsType<TreeViewItem>(target.Presenter.Panel.Children[0]);
Assert.Equal(3, rootNode.ItemContainerGenerator.Containers.Count());
Assert.Equal(3, rootNode.Presenter.Panel.Children.Count);
var child2Node = Assert.IsType<TreeViewItem>(rootNode.Presenter.Panel.Children[1]);
Assert.Equal(1, child2Node.ItemContainerGenerator.Containers.Count());
Assert.Equal(1, child2Node.Presenter.Panel.Children.Count);
}
[Fact]
public void Clearing_TreeView_Items_Clears_Index()
{
// Issue #3551
var tree = CreateTestTreeData();
var target = new TreeView
{
Template = CreateTreeViewTemplate(),
Items = tree,
};
var root = new TestRoot();
root.Child = target;
CreateNodeDataTemplate(target);
ApplyTemplates(target);
var rootNode = tree[0];
var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(rootNode);
Assert.NotNull(container);
root.Child = null;
tree.Clear();
Assert.Empty(target.ItemContainerGenerator.Index.Containers);
}
private void ApplyTemplates(TreeView tree)
{
tree.ApplyTemplate();
tree.Presenter.ApplyTemplate();
ApplyTemplates(tree.Presenter.Panel.Children);
}
private void ApplyTemplates(IEnumerable<IControl> controls)
{
foreach (TreeViewItem control in controls)
{
control.Template = CreateTreeViewItemTemplate();
control.ApplyTemplate();
control.Presenter.ApplyTemplate();
control.HeaderPresenter.ApplyTemplate();
ApplyTemplates(control.Presenter.Panel.Children);
}
}
private TreeViewItem GetItem(TreeView target, params int[] indexes)
{
var c = (ItemsControl)target;
foreach (var index in indexes)
{
var item = ((IList)c.Items)[index];
c = (ItemsControl)target.ItemContainerGenerator.Index.ContainerFromItem(item);
}
return (TreeViewItem)c;
}
private IList<Node> CreateTestTreeData()
{
return new AvaloniaList<Node>
{
new Node
{
Value = "Root",
Children = new AvaloniaList<Node>
{
new Node
{
Value = "Child1",
},
new Node
{
Value = "Child2",
Children = new AvaloniaList<Node>
{
new Node
{
Value = "Grandchild2a",
},
},
},
new Node
{
Value = "Child3",
}
}
}
};
}
private void CreateNodeDataTemplate(IControl control)
{
control.DataTemplates.Add(new TestTreeDataTemplate());
}
private IControlTemplate CreateTreeViewTemplate()
{
return new FuncControlTemplate<TreeView>((parent, scope) => new ItemsPresenter
{
Name = "PART_ItemsPresenter",
[~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty],
}.RegisterInNameScope(scope));
}
private IControlTemplate CreateTreeViewItemTemplate()
{
return new FuncControlTemplate<TreeViewItem>((parent, scope) => new Panel
{
Children =
{
new ContentPresenter
{
Name = "PART_HeaderPresenter",
[~ContentPresenter.ContentProperty] = parent[~TreeViewItem.HeaderProperty],
}.RegisterInNameScope(scope),
new ItemsPresenter
{
Name = "PART_ItemsPresenter",
[~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty],
}.RegisterInNameScope(scope)
}
});
}
private void ExpandAll(TreeView tree)
{
foreach (var i in tree.ItemContainerGenerator.Containers)
{
tree.ExpandSubTree((TreeViewItem)i.ContainerControl);
}
}
private List<string> ExtractItemHeader(TreeView tree, int level)
{
return ExtractItemContent(tree.Presenter.Panel, 0, level)
.Select(x => x.Header)
.OfType<TextBlock>()
.Select(x => x.Text)
.ToList();
}
private IEnumerable<TreeViewItem> ExtractItemContent(IPanel panel, int currentLevel, int level)
{
foreach (TreeViewItem container in panel.Children)
{
if (container.Template == null)
{
container.Template = CreateTreeViewItemTemplate();
container.ApplyTemplate();
}
if (currentLevel == level)
{
yield return container;
}
else
{
foreach (var child in ExtractItemContent(container.Presenter.Panel, currentLevel + 1, level))
{
yield return child;
}
}
}
}
private void ClickContainer(IControl container, KeyModifiers modifiers)
{
_mouse.Click(container, modifiers: modifiers);
}
private void AssertChildrenSelected(TreeView treeView, Node rootNode)
{
foreach (var child in rootNode.Children)
{
var container = (TreeViewItem)treeView.ItemContainerGenerator.Index.ContainerFromItem(child);
Assert.True(container.IsSelected);
}
}
private IDisposable Application()
{
return UnitTestApplication.Start(
TestServices.MockThreadingInterface.With(
focusManager: new FocusManager(),
keyboardDevice: () => new KeyboardDevice(),
keyboardNavigation: new KeyboardNavigationHandler(),
inputManager: new InputManager()));
}
private class Node : NotifyingBase
{
private IAvaloniaList<Node> _children;
public string Value { get; set; }
public IAvaloniaList<Node> Children
{
get
{
return _children;
}
set
{
_children = value;
RaisePropertyChanged(nameof(Children));
}
}
}
private class TestTreeDataTemplate : ITreeDataTemplate
{
public IControl Build(object param)
{
var node = (Node)param;
return new TextBlock { Text = node.Value };
}
public InstancedBinding ItemsSelector(object item)
{
var obs = ExpressionObserver.Create(item, o => (o as Node).Children);
return InstancedBinding.OneWay(obs);
}
public bool Match(object data)
{
return data is Node;
}
}
private class DerivedTreeView : TreeView
{
}
private class TestDataContext : INotifyPropertyChanged
{
private string _selectedItem;
public TestDataContext()
{
Items = new ObservableCollection<string>(Enumerable.Range(0, 5).Select(i => $"Item {i}"));
}
public ObservableCollection<string> Items { get; }
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItem)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
}
| |
// 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.Drawing
{
internal static class KnownColorTable
{
// All non system colors (in order of definition in the KnownColor enum).
private static readonly uint[] s_colorTable = new uint[]
{
0x00FFFFFF, // Transparent
0xFFF0F8FF, // AliceBlue
0xFFFAEBD7, // AntiqueWhite
0xFF00FFFF, // Aqua
0xFF7FFFD4, // Aquamarine
0xFFF0FFFF, // Azure
0xFFF5F5DC, // Beige
0xFFFFE4C4, // Bisque
0xFF000000, // Black
0xFFFFEBCD, // BlanchedAlmond
0xFF0000FF, // Blue
0xFF8A2BE2, // BlueViolet
0xFFA52A2A, // Brown
0xFFDEB887, // BurlyWood
0xFF5F9EA0, // CadetBlue
0xFF7FFF00, // Chartreuse
0xFFD2691E, // Chocolate
0xFFFF7F50, // Coral
0xFF6495ED, // CornflowerBlue
0xFFFFF8DC, // Cornsilk
0xFFDC143C, // Crimson
0xFF00FFFF, // Cyan
0xFF00008B, // DarkBlue
0xFF008B8B, // DarkCyan
0xFFB8860B, // DarkGoldenrod
0xFFA9A9A9, // DarkGray
0xFF006400, // DarkGreen
0xFFBDB76B, // DarkKhaki
0xFF8B008B, // DarkMagenta
0xFF556B2F, // DarkOliveGreen
0xFFFF8C00, // DarkOrange
0xFF9932CC, // DarkOrchid
0xFF8B0000, // DarkRed
0xFFE9967A, // DarkSalmon
0xFF8FBC8B, // DarkSeaGreen
0xFF483D8B, // DarkSlateBlue
0xFF2F4F4F, // DarkSlateGray
0xFF00CED1, // DarkTurquoise
0xFF9400D3, // DarkViolet
0xFFFF1493, // DeepPink
0xFF00BFFF, // DeepSkyBlue
0xFF696969, // DimGray
0xFF1E90FF, // DodgerBlue
0xFFB22222, // Firebrick
0xFFFFFAF0, // FloralWhite
0xFF228B22, // ForestGreen
0xFFFF00FF, // Fuchsia
0xFFDCDCDC, // Gainsboro
0xFFF8F8FF, // GhostWhite
0xFFFFD700, // Gold
0xFFDAA520, // Goldenrod
0xFF808080, // Gray
0xFF008000, // Green
0xFFADFF2F, // GreenYellow
0xFFF0FFF0, // Honeydew
0xFFFF69B4, // HotPink
0xFFCD5C5C, // IndianRed
0xFF4B0082, // Indigo
0xFFFFFFF0, // Ivory
0xFFF0E68C, // Khaki
0xFFE6E6FA, // Lavender
0xFFFFF0F5, // LavenderBlush
0xFF7CFC00, // LawnGreen
0xFFFFFACD, // LemonChiffon
0xFFADD8E6, // LightBlue
0xFFF08080, // LightCoral
0xFFE0FFFF, // LightCyan
0xFFFAFAD2, // LightGoldenrodYellow
0xFFD3D3D3, // LightGray
0xFF90EE90, // LightGreen
0xFFFFB6C1, // LightPink
0xFFFFA07A, // LightSalmon
0xFF20B2AA, // LightSeaGreen
0xFF87CEFA, // LightSkyBlue
0xFF778899, // LightSlateGray
0xFFB0C4DE, // LightSteelBlue
0xFFFFFFE0, // LightYellow
0xFF00FF00, // Lime
0xFF32CD32, // LimeGreen
0xFFFAF0E6, // Linen
0xFFFF00FF, // Magenta
0xFF800000, // Maroon
0xFF66CDAA, // MediumAquamarine
0xFF0000CD, // MediumBlue
0xFFBA55D3, // MediumOrchid
0xFF9370DB, // MediumPurple
0xFF3CB371, // MediumSeaGreen
0xFF7B68EE, // MediumSlateBlue
0xFF00FA9A, // MediumSpringGreen
0xFF48D1CC, // MediumTurquoise
0xFFC71585, // MediumVioletRed
0xFF191970, // MidnightBlue
0xFFF5FFFA, // MintCream
0xFFFFE4E1, // MistyRose
0xFFFFE4B5, // Moccasin
0xFFFFDEAD, // NavajoWhite
0xFF000080, // Navy
0xFFFDF5E6, // OldLace
0xFF808000, // Olive
0xFF6B8E23, // OliveDrab
0xFFFFA500, // Orange
0xFFFF4500, // OrangeRed
0xFFDA70D6, // Orchid
0xFFEEE8AA, // PaleGoldenrod
0xFF98FB98, // PaleGreen
0xFFAFEEEE, // PaleTurquoise
0xFFDB7093, // PaleVioletRed
0xFFFFEFD5, // PapayaWhip
0xFFFFDAB9, // PeachPuff
0xFFCD853F, // Peru
0xFFFFC0CB, // Pink
0xFFDDA0DD, // Plum
0xFFB0E0E6, // PowderBlue
0xFF800080, // Purple
0xFFFF0000, // Red
0xFFBC8F8F, // RosyBrown
0xFF4169E1, // RoyalBlue
0xFF8B4513, // SaddleBrown
0xFFFA8072, // Salmon
0xFFF4A460, // SandyBrown
0xFF2E8B57, // SeaGreen
0xFFFFF5EE, // SeaShell
0xFFA0522D, // Sienna
0xFFC0C0C0, // Silver
0xFF87CEEB, // SkyBlue
0xFF6A5ACD, // SlateBlue
0xFF708090, // SlateGray
0xFFFFFAFA, // Snow
0xFF00FF7F, // SpringGreen
0xFF4682B4, // SteelBlue
0xFFD2B48C, // Tan
0xFF008080, // Teal
0xFFD8BFD8, // Thistle
0xFFFF6347, // Tomato
0xFF40E0D0, // Turquoise
0xFFEE82EE, // Violet
0xFFF5DEB3, // Wheat
0xFFFFFFFF, // White
0xFFF5F5F5, // WhiteSmoke
0xFFFFFF00, // Yellow
0xFF9ACD32, // YellowGreen
};
internal static Color ArgbToKnownColor(uint argb)
{
// Should be fully opaque (and as such we can skip the first entry
// which is transparent).
Debug.Assert((argb & Color.ARGBAlphaMask) == Color.ARGBAlphaMask);
for (int index = 1; index < s_colorTable.Length; ++index)
{
if (s_colorTable[index] == argb)
{
return Color.FromKnownColor((KnownColor)(index + (int)KnownColor.Transparent));
}
}
// Not a known color
return Color.FromArgb((int)argb);
}
public static uint KnownColorToArgb(KnownColor color)
{
Debug.Assert(color > 0 && color <= KnownColor.MenuHighlight);
return Color.IsKnownColorSystem(color)
? GetSystemColorArgb(color)
: s_colorTable[(int)color - (int)KnownColor.Transparent];
}
#if FEATURE_WINDOWS_SYSTEM_COLORS
private static ReadOnlySpan<byte> SystemColorIdTable => new byte[]
{
// In order of definition in KnownColor enum
// The original group of contiguous system KnownColors
(byte)Interop.User32.Win32SystemColors.ActiveBorder,
(byte)Interop.User32.Win32SystemColors.ActiveCaption,
(byte)Interop.User32.Win32SystemColors.ActiveCaptionText,
(byte)Interop.User32.Win32SystemColors.AppWorkspace,
(byte)Interop.User32.Win32SystemColors.Control,
(byte)Interop.User32.Win32SystemColors.ControlDark,
(byte)Interop.User32.Win32SystemColors.ControlDarkDark,
(byte)Interop.User32.Win32SystemColors.ControlLight,
(byte)Interop.User32.Win32SystemColors.ControlLightLight,
(byte)Interop.User32.Win32SystemColors.ControlText,
(byte)Interop.User32.Win32SystemColors.Desktop,
(byte)Interop.User32.Win32SystemColors.GrayText,
(byte)Interop.User32.Win32SystemColors.Highlight,
(byte)Interop.User32.Win32SystemColors.HighlightText,
(byte)Interop.User32.Win32SystemColors.HotTrack,
(byte)Interop.User32.Win32SystemColors.InactiveBorder,
(byte)Interop.User32.Win32SystemColors.InactiveCaption,
(byte)Interop.User32.Win32SystemColors.InactiveCaptionText,
(byte)Interop.User32.Win32SystemColors.Info,
(byte)Interop.User32.Win32SystemColors.InfoText,
(byte)Interop.User32.Win32SystemColors.Menu,
(byte)Interop.User32.Win32SystemColors.MenuText,
(byte)Interop.User32.Win32SystemColors.ScrollBar,
(byte)Interop.User32.Win32SystemColors.Window,
(byte)Interop.User32.Win32SystemColors.WindowFrame,
(byte)Interop.User32.Win32SystemColors.WindowText,
// The appended group of SystemColors (i.e. not sequential with WindowText above)
(byte)Interop.User32.Win32SystemColors.ButtonFace,
(byte)Interop.User32.Win32SystemColors.ButtonHighlight,
(byte)Interop.User32.Win32SystemColors.ButtonShadow,
(byte)Interop.User32.Win32SystemColors.GradientActiveCaption,
(byte)Interop.User32.Win32SystemColors.GradientInactiveCaption,
(byte)Interop.User32.Win32SystemColors.MenuBar,
(byte)Interop.User32.Win32SystemColors.MenuHighlight
};
public static uint GetSystemColorArgb(KnownColor color)
=> ColorTranslator.COLORREFToARGB(Interop.User32.GetSysColor(GetSystemColorId(color)));
private static int GetSystemColorId(KnownColor color)
{
Debug.Assert(Color.IsKnownColorSystem(color));
return color < KnownColor.Transparent
? SystemColorIdTable[(int)color - (int)KnownColor.ActiveBorder]
: SystemColorIdTable[(int)color - (int)KnownColor.ButtonFace + (int)KnownColor.WindowText];
}
#else
private static readonly uint[] s_staticSystemColors = new uint[]
{
// Hard-coded constants, based on default Windows settings.
// (In order of definition in KnownColor enum.)
// First contiguous set.
0xFFD4D0C8, // ActiveBorder
0xFF0054E3, // ActiveCaption
0xFFFFFFFF, // ActiveCaptionText
0xFF808080, // AppWorkspace
0xFFECE9D8, // Control
0xFFACA899, // ControlDark
0xFF716F64, // ControlDarkDark
0xFFF1EFE2, // ControlLight
0xFFFFFFFF, // ControlLightLight
0xFF000000, // ControlText
0xFF004E98, // Desktop
0xFFACA899, // GrayText
0xFF316AC5, // Highlight
0xFFFFFFFF, // HighlightText
0xFF000080, // HotTrack
0xFFD4D0C8, // InactiveBorder
0xFF7A96DF, // InactiveCaption
0xFFD8E4F8, // InactiveCaptionText
0xFFFFFFE1, // Info
0xFF000000, // InfoText
0xFFFFFFFF, // Menu
0xFF000000, // MenuText
0xFFD4D0C8, // ScrollBar
0xFFFFFFFF, // Window
0xFF000000, // WindowFrame
0xFF000000, // WindowText
// Second contiguous set.
0xFFF0F0F0, // ButtonFace
0xFFFFFFFF, // ButtonHighlight
0xFFA0A0A0, // ButtonShadow
0xFFB9D1EA, // GradientActiveCaption
0xFFD7E4F2, // GradientInactiveCaption
0xFFF0F0F0, // MenuBar
0xFF3399FF, // MenuHighlight
};
public static uint GetSystemColorArgb(KnownColor color)
{
Debug.Assert(Color.IsKnownColorSystem(color));
return color < KnownColor.Transparent
? s_staticSystemColors[(int)color - (int)KnownColor.ActiveBorder]
: s_staticSystemColors[(int)color - (int)KnownColor.ButtonFace + (int)KnownColor.WindowText];
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace NServiceBus.Facade.Web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Octokit.Internal;
using Xunit;
namespace Octokit.Tests.Http
{
public class RedirectHandlerTests
{
[Fact]
public async Task OkStatusShouldPassThrough()
{
var handler = CreateMockHttpHandler(new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Same(httpRequestMessage, response.RequestMessage);
}
[Theory]
[InlineData(HttpStatusCode.MovedPermanently)] // 301
[InlineData(HttpStatusCode.Found)] // 302
[InlineData(HttpStatusCode.TemporaryRedirect)] // 307
public async Task ShouldRedirectSameMethod(HttpStatusCode statusCode)
{
var redirectResponse = new HttpResponseMessage(statusCode);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
}
[Fact]
public async Task Status303ShouldRedirectChangeMethod()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.SeeOther);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(HttpMethod.Get, response.RequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
}
[Fact]
public async Task RedirectWithSameHostShouldKeepAuthHeader()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.Redirect);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("fooAuth", "aparam");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.NotSame(response.RequestMessage, httpRequestMessage);
Assert.Equal("fooAuth", response.RequestMessage.Headers.Authorization.Scheme);
}
[Theory]
[InlineData(HttpStatusCode.MovedPermanently)] // 301
[InlineData(HttpStatusCode.Found)] // 302
[InlineData(HttpStatusCode.SeeOther)] // 303
[InlineData(HttpStatusCode.TemporaryRedirect)] // 307
public async Task RedirectWithDifferentHostShouldLoseAuthHeader(HttpStatusCode statusCode)
{
var redirectResponse = new HttpResponseMessage(statusCode);
redirectResponse.Headers.Location = new Uri("http://example.net/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("fooAuth", "aparam");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.NotSame(response.RequestMessage, httpRequestMessage);
Assert.Null(response.RequestMessage.Headers.Authorization);
}
[Theory]
[InlineData(HttpStatusCode.MovedPermanently)] // 301
[InlineData(HttpStatusCode.Found)] // 302
[InlineData(HttpStatusCode.TemporaryRedirect)] // 307
public async Task Status301ShouldRedirectPOSTWithBody(HttpStatusCode statusCode)
{
var redirectResponse = new HttpResponseMessage(statusCode);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
httpRequestMessage.Content = new StringContent("Hello World");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
}
// POST see other with content
[Fact]
public async Task Status303ShouldRedirectToGETWithoutBody()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.SeeOther);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
httpRequestMessage.Content = new StringContent("Hello World");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(HttpMethod.Get, response.RequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
Assert.Null(response.RequestMessage.Content);
}
[Fact]
public async Task Exceed3RedirectsShouldReturn()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.Found);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var redirectResponse2 = new HttpResponseMessage(HttpStatusCode.Found);
redirectResponse2.Headers.Location = new Uri("http://example.org/foo");
var handler = CreateMockHttpHandler(redirectResponse, redirectResponse2);
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
await Assert.ThrowsAsync<InvalidOperationException>(
() => adapter.SendAsync(httpRequestMessage, new CancellationToken()));
}
static HttpRequestMessage CreateRequest(HttpMethod method)
{
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.RequestUri = new Uri("http://example.org/foo");
httpRequestMessage.Method = method;
return httpRequestMessage;
}
static Func<HttpMessageHandler> CreateMockHttpHandler(HttpResponseMessage httpResponseMessage1, HttpResponseMessage httpResponseMessage2 = null)
{
return () => new MockRedirectHandler(httpResponseMessage1, httpResponseMessage2);
}
}
public class MockRedirectHandler : HttpMessageHandler
{
readonly HttpResponseMessage _response1;
readonly HttpResponseMessage _response2;
private bool _Response1Sent;
public MockRedirectHandler(HttpResponseMessage response1, HttpResponseMessage response2 = null)
{
_response1 = response1;
_response2 = response2;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!_Response1Sent)
{
_Response1Sent = true;
_response1.RequestMessage = request;
return _response1;
}
else
{
_response2.RequestMessage = request;
return _response2;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
namespace Orleans.Runtime
{
internal interface IGrainTypeResolver
{
bool TryGetGrainClassData(Type grainInterfaceType, out GrainClassData implementation, string grainClassNamePrefix);
bool TryGetGrainClassData(int grainInterfaceId, out GrainClassData implementation, string grainClassNamePrefix);
bool TryGetGrainClassData(string grainImplementationClassName, out GrainClassData implementation);
bool IsUnordered(int grainTypeCode);
string GetLoadedGrainAssemblies();
}
/// <summary>
/// Internal data structure that holds a grain interfaces to grain classes map.
/// </summary>
[Serializable]
internal class GrainInterfaceMap : IGrainTypeResolver
{
/// <summary>
/// Metadata for a grain interface
/// </summary>
[Serializable]
internal class GrainInterfaceData
{
[NonSerialized]
private readonly Type iface;
private readonly HashSet<GrainClassData> implementations;
internal Type Interface { get { return iface; } }
internal int InterfaceId { get; private set; }
internal ushort InterfaceVersion { get; private set; }
internal string GrainInterface { get; private set; }
internal GrainClassData[] Implementations { get { return implementations.ToArray(); } }
internal GrainClassData PrimaryImplementation { get; private set; }
internal GrainInterfaceData(int interfaceId, ushort interfaceVersion, Type iface, string grainInterface)
{
InterfaceId = interfaceId;
InterfaceVersion = interfaceVersion;
this.iface = iface;
GrainInterface = grainInterface;
implementations = new HashSet<GrainClassData>();
}
internal void AddImplementation(GrainClassData implementation, bool primaryImplemenation = false)
{
lock (this)
{
if (!implementations.Contains(implementation))
implementations.Add(implementation);
if (primaryImplemenation)
PrimaryImplementation = implementation;
}
}
public override string ToString()
{
return String.Format("{0}:{1}", GrainInterface, InterfaceId);
}
}
private readonly Dictionary<string, GrainInterfaceData> typeToInterfaceData;
private readonly Dictionary<int, GrainInterfaceData> table;
private readonly HashSet<int> unordered;
private readonly Dictionary<int, GrainClassData> implementationIndex;
[NonSerialized] // Client shouldn't need this
private readonly Dictionary<string, string> primaryImplementations;
private readonly bool localTestMode;
private readonly HashSet<string> loadedGrainAsemblies;
private readonly PlacementStrategy defaultPlacementStrategy;
internal IEnumerable<GrainClassData> SupportedGrainClassData
{
get { return implementationIndex.Values; }
}
internal IEnumerable<GrainInterfaceData> SupportedInterfaces
{
get { return table.Values; }
}
public GrainInterfaceMap(bool localTestMode, PlacementStrategy defaultPlacementStrategy)
{
table = new Dictionary<int, GrainInterfaceData>();
typeToInterfaceData = new Dictionary<string, GrainInterfaceData>();
primaryImplementations = new Dictionary<string, string>();
implementationIndex = new Dictionary<int, GrainClassData>();
unordered = new HashSet<int>();
this.localTestMode = localTestMode;
this.defaultPlacementStrategy = defaultPlacementStrategy;
if(localTestMode) // if we are running in test mode, we'll build a list of loaded grain assemblies to help with troubleshooting deployment issue
loadedGrainAsemblies = new HashSet<string>();
}
internal void AddMap(GrainInterfaceMap map)
{
foreach (var kvp in map.typeToInterfaceData)
{
if (!typeToInterfaceData.ContainsKey(kvp.Key))
{
typeToInterfaceData.Add(kvp.Key, kvp.Value);
}
}
foreach (var kvp in map.table)
{
if (!table.ContainsKey(kvp.Key))
{
table.Add(kvp.Key, kvp.Value);
}
}
foreach (var grainClassTypeCode in map.unordered)
{
unordered.Add(grainClassTypeCode);
}
foreach (var kvp in map.implementationIndex)
{
if (!implementationIndex.ContainsKey(kvp.Key))
{
implementationIndex.Add(kvp.Key, kvp.Value);
}
}
}
internal void AddEntry(Type iface, Type grain, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy, bool primaryImplementation)
{
lock (this)
{
var grainTypeInfo = grain.GetTypeInfo();
var grainName = TypeUtils.GetFullName(grainTypeInfo);
var isGenericGrainClass = grainTypeInfo.ContainsGenericParameters;
var grainTypeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grain);
var grainInterfaceData = GetOrAddGrainInterfaceData(iface, isGenericGrainClass);
var implementation = new GrainClassData(grainTypeCode, grainName, isGenericGrainClass, grainInterfaceData, placement, registrationStrategy);
if (!implementationIndex.ContainsKey(grainTypeCode))
implementationIndex.Add(grainTypeCode, implementation);
grainInterfaceData.AddImplementation(implementation, primaryImplementation);
if (primaryImplementation)
{
primaryImplementations[grainInterfaceData.GrainInterface] = grainName;
}
else
{
if (!primaryImplementations.ContainsKey(grainInterfaceData.GrainInterface))
primaryImplementations.Add(grainInterfaceData.GrainInterface, grainName);
}
if (localTestMode)
{
var assembly = grainTypeInfo.Assembly.CodeBase;
if (!loadedGrainAsemblies.Contains(assembly))
loadedGrainAsemblies.Add(assembly);
}
}
}
private GrainInterfaceData GetOrAddGrainInterfaceData(Type iface, bool isGenericGrainClass)
{
var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(iface);
var version = GrainInterfaceUtils.GetGrainInterfaceVersion(iface);
// If already exist
GrainInterfaceData grainInterfaceData;
if (table.TryGetValue(interfaceId, out grainInterfaceData))
return grainInterfaceData;
// If not create new entry
var interfaceName = TypeUtils.GetRawClassName(TypeUtils.GetFullName(iface));
grainInterfaceData = new GrainInterfaceData(interfaceId, version, iface, interfaceName);
table[interfaceId] = grainInterfaceData;
// Add entry to mapping iface string -> data
var interfaceTypeKey = GetTypeKey(iface, isGenericGrainClass);
typeToInterfaceData[interfaceTypeKey] = grainInterfaceData;
// If we are adding a concrete implementation of a generic interface
// add also the latter to the map: GrainReference and InvokeMethodRequest
// always use the id of the generic one
if (iface.IsConstructedGenericType)
GetOrAddGrainInterfaceData(iface.GetGenericTypeDefinition(), true);
return grainInterfaceData;
}
internal Dictionary<string, string> GetPrimaryImplementations()
{
lock (this)
{
return new Dictionary<string, string>(primaryImplementations);
}
}
internal bool TryGetPrimaryImplementation(string grainInterface, out string grainClass)
{
lock (this)
{
return primaryImplementations.TryGetValue(grainInterface, out grainClass);
}
}
internal bool TryGetServiceInterface(int interfaceId, out Type iface)
{
lock (this)
{
iface = null;
if (!table.ContainsKey(interfaceId))
return false;
var interfaceData = table[interfaceId];
iface = interfaceData.Interface;
return true;
}
}
internal ushort GetInterfaceVersion(int ifaceId)
{
return table[ifaceId].InterfaceVersion;
}
internal bool TryGetTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy registrationStrategy, string genericArguments = null)
{
lock (this)
{
grainClass = null;
placement = this.defaultPlacementStrategy;
registrationStrategy = null;
if (!implementationIndex.ContainsKey(typeCode))
return false;
var implementation = implementationIndex[typeCode];
grainClass = implementation.GetClassName(genericArguments);
placement = implementation.PlacementStrategy ?? this.defaultPlacementStrategy;
registrationStrategy = implementation.RegistrationStrategy;
return true;
}
}
public bool TryGetGrainClassData(Type interfaceType, out GrainClassData implementation, string grainClassNamePrefix)
{
implementation = null;
GrainInterfaceData interfaceData;
var typeInfo = interfaceType.GetTypeInfo();
// First, try to find a non-generic grain implementation:
if (this.typeToInterfaceData.TryGetValue(GetTypeKey(interfaceType, false), out interfaceData) &&
TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix))
{
return true;
}
// If a concrete implementation was not found and the interface is generic,
// try to find a generic grain implementation:
if (typeInfo.IsGenericType &&
this.typeToInterfaceData.TryGetValue(GetTypeKey(interfaceType, true), out interfaceData) &&
TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix))
{
return true;
}
return false;
}
public bool TryGetGrainClassData(int grainInterfaceId, out GrainClassData implementation, string grainClassNamePrefix = null)
{
implementation = null;
GrainInterfaceData interfaceData;
if (!table.TryGetValue(grainInterfaceId, out interfaceData))
{
return false;
}
return TryGetGrainClassData(interfaceData, out implementation, grainClassNamePrefix);
}
private string GetTypeKey(Type interfaceType, bool isGenericGrainClass)
{
var typeInfo = interfaceType.GetTypeInfo();
if (isGenericGrainClass && typeInfo.IsGenericType)
{
return typeInfo.GetGenericTypeDefinition().AssemblyQualifiedName;
}
else
{
return TypeUtils.GetTemplatedName(
TypeUtils.GetFullName(interfaceType),
interfaceType,
interfaceType.GetGenericArguments(),
t => false);
}
}
private static bool TryGetGrainClassData(GrainInterfaceData interfaceData, out GrainClassData implementation, string grainClassNamePrefix)
{
implementation = null;
var implementations = interfaceData.Implementations;
if (implementations.Length == 0)
return false;
if (String.IsNullOrEmpty(grainClassNamePrefix))
{
if (implementations.Length == 1)
{
implementation = implementations[0];
return true;
}
if (interfaceData.PrimaryImplementation != null)
{
implementation = interfaceData.PrimaryImplementation;
return true;
}
throw new OrleansException(String.Format("Cannot resolve grain interface ID={0} to a grain class because of multiple implementations of it: {1}",
interfaceData.InterfaceId, Utils.EnumerableToString(implementations, d => d.GrainClass, ",", false)));
}
if (implementations.Length == 1)
{
if (implementations[0].GrainClass.StartsWith(grainClassNamePrefix, StringComparison.Ordinal))
{
implementation = implementations[0];
return true;
}
return false;
}
var matches = implementations.Where(impl => impl.GrainClass.Equals(grainClassNamePrefix)).ToArray(); //exact match?
if (matches.Length == 0)
matches = implementations.Where(
impl => impl.GrainClass.StartsWith(grainClassNamePrefix, StringComparison.Ordinal)).ToArray(); //prefix matches
if (matches.Length == 0)
return false;
if (matches.Length == 1)
{
implementation = matches[0];
return true;
}
throw new OrleansException(String.Format("Cannot resolve grain interface ID={0}, grainClassNamePrefix={1} to a grain class because of multiple implementations of it: {2}",
interfaceData.InterfaceId,
grainClassNamePrefix,
Utils.EnumerableToString(matches, d => d.GrainClass, ",", false)));
}
public bool TryGetGrainClassData(string grainImplementationClassName, out GrainClassData implementation)
{
implementation = null;
// have to iterate since _primaryImplementations is not serialized.
foreach (var interfaceData in table.Values)
{
foreach(var implClass in interfaceData.Implementations)
if (implClass.GrainClass.Equals(grainImplementationClassName))
{
implementation = implClass;
return true;
}
}
return false;
}
public string GetLoadedGrainAssemblies()
{
return loadedGrainAsemblies != null ? loadedGrainAsemblies.ToStrings() : String.Empty;
}
public void AddToUnorderedList(Type grainClass)
{
var grainClassTypeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grainClass);
if (!unordered.Contains(grainClassTypeCode))
unordered.Add(grainClassTypeCode);
}
public bool IsUnordered(int grainTypeCode)
{
return unordered.Contains(grainTypeCode);
}
}
/// <summary>
/// Metadata for a grain class
/// </summary>
[Serializable]
internal sealed class GrainClassData
{
private readonly GrainInterfaceMap.GrainInterfaceData interfaceData;
[NonSerialized]
private readonly Dictionary<string, string> genericClassNames;
private readonly PlacementStrategy placementStrategy;
private readonly MultiClusterRegistrationStrategy registrationStrategy;
private readonly bool isGeneric;
internal int GrainTypeCode { get; private set; }
internal string GrainClass { get; private set; }
internal PlacementStrategy PlacementStrategy { get { return placementStrategy; } }
internal GrainInterfaceMap.GrainInterfaceData InterfaceData { get { return interfaceData; } }
internal bool IsGeneric { get { return isGeneric; } }
public MultiClusterRegistrationStrategy RegistrationStrategy { get { return registrationStrategy; } }
internal GrainClassData(int grainTypeCode, string grainClass, bool isGeneric, GrainInterfaceMap.GrainInterfaceData interfaceData, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy)
{
GrainTypeCode = grainTypeCode;
GrainClass = grainClass;
this.isGeneric = isGeneric;
this.interfaceData = interfaceData;
genericClassNames = new Dictionary<string, string>(); // TODO: initialize only for generic classes
placementStrategy = placement;
this.registrationStrategy = registrationStrategy;
}
internal string GetClassName(string typeArguments)
{
// Knowing whether the grain implementation is generic allows for non-generic grain classes
// to implement one or more generic grain interfaces.
// For generic grain classes, the assumption that they take the same generic arguments
// as the implemented generic interface(s) still holds.
if (!isGeneric || String.IsNullOrWhiteSpace(typeArguments))
{
return GrainClass;
}
else
{
lock (this)
{
if (genericClassNames.ContainsKey(typeArguments))
return genericClassNames[typeArguments];
var className = String.Format("{0}[{1}]", GrainClass, typeArguments);
genericClassNames.Add(typeArguments, className);
return className;
}
}
}
internal long GetTypeCode(Type interfaceType)
{
var typeInfo = interfaceType.GetTypeInfo();
if (typeInfo.IsGenericType && this.IsGeneric)
{
string args = TypeUtils.GetGenericTypeArgs(typeInfo.GetGenericArguments(), t => true);
int hash = Utils.CalculateIdHash(args);
return (((long)(hash & 0x00FFFFFF)) << 32) + GrainTypeCode;
}
else
{
return GrainTypeCode;
}
}
public override string ToString()
{
return String.Format("{0}:{1}", GrainClass, GrainTypeCode);
}
public override int GetHashCode()
{
return GrainTypeCode;
}
public override bool Equals(object obj)
{
if(!(obj is GrainClassData))
return false;
return GrainTypeCode == ((GrainClassData) obj).GrainTypeCode;
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// Linear constraint (point-to-line)
// d = p2 - p1 = x2 + r2 - x1 - r1
// C = dot(perp, d)
// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2)
// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)]
//
// Angular constraint
// C = a2 - a1 + a_initial
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
//
// K = J * invM * JT
//
// J = [-a -s1 a s2]
// [0 -1 0 1]
// a = perp
// s1 = cross(d + r1, a) = cross(p2 - x1, a)
// s2 = cross(r2, a) = cross(p2 - x2, a)
// Motor/Limit linear constraint
// C = dot(ax1, d)
// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2)
// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)]
// Block Solver
// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even
// when the mass has poor distribution (leading to large torques about the joint anchor points).
//
// The Jacobian has 3 rows:
// J = [-uT -s1 uT s2] // linear
// [0 -1 0 1] // angular
// [-vT -a1 vT a2] // limit
//
// u = perp
// v = axis
// s1 = cross(d + r1, u), s2 = cross(r2, u)
// a1 = cross(d + r1, v), a2 = cross(r2, v)
// M * (v2 - v1) = JT * df
// J * v2 = bias
//
// v2 = v1 + invM * JT * df
// J * (v1 + invM * JT * df) = bias
// K * df = bias - J * v1 = -Cdot
// K = J * invM * JT
// Cdot = J * v1 - bias
//
// Now solve for f2.
// df = f2 - f1
// K * (f2 - f1) = -Cdot
// f2 = invK * (-Cdot) + f1
//
// Clamp accumulated limit impulse.
// lower: f2(3) = max(f2(3), 0)
// upper: f2(3) = min(f2(3), 0)
//
// Solve for correct f2(1:2)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1
// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3)
// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2)
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
//
// Now compute impulse to be applied:
// df = f2 - f1
/// <summary>
/// A prismatic joint. This joint provides one degree of freedom: translation
/// along an axis fixed in bodyA. Relative rotation is prevented. You can
/// use a joint limit to restrict the range of motion and a joint motor to
/// drive the motion or to model joint friction.
/// </summary>
public class PrismaticJoint : Joint
{
#region Properties/Fields
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 LocalAnchorA;
/// <summary>
/// The local anchor point on BodyB
/// </summary>
public Vector2 LocalAnchorB;
public override Vector2 WorldAnchorA
{
get => BodyA.GetWorldPoint(LocalAnchorA);
set => LocalAnchorA = BodyA.GetLocalPoint(value);
}
public override Vector2 WorldAnchorB
{
get => BodyB.GetWorldPoint(LocalAnchorB);
set => LocalAnchorB = BodyB.GetLocalPoint(value);
}
/// <summary>
/// Get the current joint translation, usually in meters.
/// </summary>
/// <value></value>
public float JointTranslation
{
get
{
var d = BodyB.GetWorldPoint(LocalAnchorB) - BodyA.GetWorldPoint(LocalAnchorA);
var axis = BodyA.GetWorldVector(LocalXAxis);
return Vector2.Dot(d, axis);
}
}
/// <summary>
/// Get the current joint translation speed, usually in meters per second.
/// </summary>
/// <value></value>
public float JointSpeed
{
get
{
Transform xf1, xf2;
BodyA.GetTransform(out xf1);
BodyB.GetTransform(out xf2);
var r1 = MathUtils.Mul(ref xf1.Q, LocalAnchorA - BodyA.LocalCenter);
var r2 = MathUtils.Mul(ref xf2.Q, LocalAnchorB - BodyB.LocalCenter);
var p1 = BodyA._sweep.C + r1;
var p2 = BodyB._sweep.C + r2;
var d = p2 - p1;
var axis = BodyA.GetWorldVector(LocalXAxis);
var v1 = BodyA._linearVelocity;
var v2 = BodyB._linearVelocity;
float w1 = BodyA._angularVelocity;
float w2 = BodyB._angularVelocity;
float speed = Vector2.Dot(d, MathUtils.Cross(w1, axis)) + Vector2.Dot(axis,
v2 + MathUtils.Cross(w2, r2) - v1 - MathUtils.Cross(w1, r1));
return speed;
}
}
/// <summary>
/// Is the joint limit enabled?
/// </summary>
/// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value>
public bool LimitEnabled
{
get => _enableLimit;
set
{
Debug.Assert(BodyA.FixedRotation == false || BodyB.FixedRotation == false,
"Warning: limits does currently not work with fixed rotation");
if (value != _enableLimit)
{
WakeBodies();
_enableLimit = value;
_impulse.Z = 0;
}
}
}
/// <summary>
/// Get the lower joint limit, usually in meters.
/// </summary>
/// <value></value>
public float LowerLimit
{
get => _lowerTranslation;
set
{
if (value != _lowerTranslation)
{
WakeBodies();
_lowerTranslation = value;
_impulse.Z = 0.0f;
}
}
}
/// <summary>
/// Get the upper joint limit, usually in meters.
/// </summary>
/// <value></value>
public float UpperLimit
{
get => _upperTranslation;
set
{
if (value != _upperTranslation)
{
WakeBodies();
_upperTranslation = value;
_impulse.Z = 0.0f;
}
}
}
/// <summary>
/// Is the joint motor enabled?
/// </summary>
/// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value>
public bool MotorEnabled
{
get => _enableMotor;
set
{
WakeBodies();
_enableMotor = value;
}
}
/// <summary>
/// Set the motor speed, usually in meters per second.
/// </summary>
/// <value>The speed.</value>
public float MotorSpeed
{
set
{
WakeBodies();
_motorSpeed = value;
}
get => _motorSpeed;
}
/// <summary>
/// Set the maximum motor force, usually in N.
/// </summary>
/// <value>The force.</value>
public float MaxMotorForce
{
get => _maxMotorForce;
set
{
WakeBodies();
_maxMotorForce = value;
}
}
/// <summary>
/// Get the current motor impulse, usually in N.
/// </summary>
/// <value></value>
public float MotorImpulse;
/// <summary>
/// The axis at which the joint moves.
/// </summary>
public Vector2 Axis
{
get => _axis1;
set
{
_axis1 = value;
LocalXAxis = BodyA.GetLocalVector(_axis1);
Nez.Vector2Ext.Normalize(ref LocalXAxis);
_localYAxisA = MathUtils.Cross(1.0f, LocalXAxis);
}
}
/// <summary>
/// The axis in local coordinates relative to BodyA
/// </summary>
public Vector2 LocalXAxis;
/// <summary>
/// The reference angle.
/// </summary>
public float ReferenceAngle;
Vector2 _localYAxisA;
Vector3 _impulse;
float _lowerTranslation;
float _upperTranslation;
float _maxMotorForce;
float _motorSpeed;
bool _enableLimit;
bool _enableMotor;
private LimitState _limitState;
// Solver temp
int _indexA;
int _indexB;
Vector2 _localCenterA;
private Vector2 _localCenterB;
float _invMassA;
float _invMassB;
float _invIA;
float _invIB;
private Vector2 _axis, _perp;
float _s1, _s2;
float _a1, _a2;
Mat33 _K;
float _motorMass;
Vector2 _axis1;
#endregion
internal PrismaticJoint()
{
JointType = JointType.Prismatic;
}
/// <summary>
/// This requires defining a line of
/// motion using an axis and an anchor point. The definition uses local
/// anchor points and a local axis so that the initial configuration
/// can violate the constraint slightly. The joint translation is zero
/// when the local anchor points coincide in world space. Using local
/// anchors and a local axis helps when saving and loading a game.
/// </summary>
/// <param name="bodyA">The first body.</param>
/// <param name="bodyB">The second body.</param>
/// <param name="anchorA">The first body anchor.</param>
/// <param name="anchorB">The second body anchor.</param>
/// <param name="axis">The axis.</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public PrismaticJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, Vector2 axis,
bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
Initialize(anchorA, anchorB, axis, useWorldCoordinates);
}
public PrismaticJoint(Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis, bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
Initialize(anchor, anchor, axis, useWorldCoordinates);
}
void Initialize(Vector2 localAnchorA, Vector2 localAnchorB, Vector2 axis, bool useWorldCoordinates)
{
JointType = JointType.Prismatic;
if (useWorldCoordinates)
{
this.LocalAnchorA = BodyA.GetLocalPoint(localAnchorA);
this.LocalAnchorB = BodyB.GetLocalPoint(localAnchorB);
}
else
{
this.LocalAnchorA = localAnchorA;
this.LocalAnchorB = localAnchorB;
}
this.Axis = axis; //FPE only: store the orignal value for use in Serialization
ReferenceAngle = BodyB.Rotation - BodyA.Rotation;
_limitState = LimitState.Inactive;
}
/// <summary>
/// Set the joint limits, usually in meters.
/// </summary>
/// <param name="lower">The lower limit</param>
/// <param name="upper">The upper limit</param>
public void SetLimits(float lower, float upper)
{
if (upper != _upperTranslation || lower != _lowerTranslation)
{
WakeBodies();
_upperTranslation = upper;
_lowerTranslation = lower;
_impulse.Z = 0.0f;
}
}
/// <summary>
/// Gets the motor force.
/// </summary>
/// <param name="invDt">The inverse delta time</param>
public float GetMotorForce(float invDt)
{
return invDt * MotorImpulse;
}
public override Vector2 GetReactionForce(float invDt)
{
return invDt * (_impulse.X * _perp + (MotorImpulse + _impulse.Z) * _axis);
}
public override float GetReactionTorque(float invDt)
{
return invDt * _impulse.Y;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_indexB = BodyB.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_localCenterB = BodyB._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invMassB = BodyB._invMass;
_invIA = BodyA._invI;
_invIB = BodyB._invI;
Vector2 cA = data.Positions[_indexA].C;
float aA = data.Positions[_indexA].A;
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
Vector2 cB = data.Positions[_indexB].C;
float aB = data.Positions[_indexB].A;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
Rot qA = new Rot(aA), qB = new Rot(aB);
// Compute the effective masses.
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
Vector2 d = (cB - cA) + rB - rA;
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
// Compute motor Jacobian and effective mass.
{
_axis = MathUtils.Mul(qA, LocalXAxis);
_a1 = MathUtils.Cross(d + rA, _axis);
_a2 = MathUtils.Cross(rB, _axis);
_motorMass = mA + mB + iA * _a1 * _a1 + iB * _a2 * _a2;
if (_motorMass > 0.0f)
{
_motorMass = 1.0f / _motorMass;
}
}
// Prismatic constraint.
{
_perp = MathUtils.Mul(qA, _localYAxisA);
_s1 = MathUtils.Cross(d + rA, _perp);
_s2 = MathUtils.Cross(rB, _perp);
float k11 = mA + mB + iA * _s1 * _s1 + iB * _s2 * _s2;
float k12 = iA * _s1 + iB * _s2;
float k13 = iA * _s1 * _a1 + iB * _s2 * _a2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
// For bodies with fixed rotation.
k22 = 1.0f;
}
float k23 = iA * _a1 + iB * _a2;
float k33 = mA + mB + iA * _a1 * _a1 + iB * _a2 * _a2;
_K.Ex = new Vector3(k11, k12, k13);
_K.Ey = new Vector3(k12, k22, k23);
_K.Ez = new Vector3(k13, k23, k33);
}
// Compute motor and limit terms.
if (_enableLimit)
{
float jointTranslation = Vector2.Dot(_axis, d);
if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop)
{
_limitState = LimitState.Equal;
}
else if (jointTranslation <= _lowerTranslation)
{
if (_limitState != LimitState.AtLower)
{
_limitState = LimitState.AtLower;
_impulse.Z = 0.0f;
}
}
else if (jointTranslation >= _upperTranslation)
{
if (_limitState != LimitState.AtUpper)
{
_limitState = LimitState.AtUpper;
_impulse.Z = 0.0f;
}
}
else
{
_limitState = LimitState.Inactive;
_impulse.Z = 0.0f;
}
}
else
{
_limitState = LimitState.Inactive;
_impulse.Z = 0.0f;
}
if (_enableMotor == false)
{
MotorImpulse = 0.0f;
}
if (Settings.EnableWarmstarting)
{
// Account for variable time step.
_impulse *= data.Step.DtRatio;
MotorImpulse *= data.Step.DtRatio;
Vector2 P = _impulse.X * _perp + (MotorImpulse + _impulse.Z) * _axis;
float LA = _impulse.X * _s1 + _impulse.Y + (MotorImpulse + _impulse.Z) * _a1;
float LB = _impulse.X * _s2 + _impulse.Y + (MotorImpulse + _impulse.Z) * _a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
else
{
_impulse = Vector3.Zero;
MotorImpulse = 0.0f;
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
// Solve linear motor constraint.
if (_enableMotor && _limitState != LimitState.Equal)
{
float Cdot = Vector2.Dot(_axis, vB - vA) + _a2 * wB - _a1 * wA;
float impulse = _motorMass * (_motorSpeed - Cdot);
float oldImpulse = MotorImpulse;
float maxImpulse = data.Step.Dt * _maxMotorForce;
MotorImpulse = MathUtils.Clamp(MotorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = MotorImpulse - oldImpulse;
Vector2 P = impulse * _axis;
float LA = impulse * _a1;
float LB = impulse * _a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
Vector2 Cdot1 = new Vector2();
Cdot1.X = Vector2.Dot(_perp, vB - vA) + _s2 * wB - _s1 * wA;
Cdot1.Y = wB - wA;
if (_enableLimit && _limitState != LimitState.Inactive)
{
// Solve prismatic and limit constraint in block form.
float Cdot2;
Cdot2 = Vector2.Dot(_axis, vB - vA) + _a2 * wB - _a1 * wA;
Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2);
Vector3 f1 = _impulse;
Vector3 df = _K.Solve33(-Cdot);
_impulse += df;
if (_limitState == LimitState.AtLower)
{
_impulse.Z = Math.Max(_impulse.Z, 0.0f);
}
else if (_limitState == LimitState.AtUpper)
{
_impulse.Z = Math.Min(_impulse.Z, 0.0f);
}
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
Vector2 b = -Cdot1 - (_impulse.Z - f1.Z) * new Vector2(_K.Ez.X, _K.Ez.Y);
Vector2 f2r = _K.Solve22(b) + new Vector2(f1.X, f1.Y);
_impulse.X = f2r.X;
_impulse.Y = f2r.Y;
df = _impulse - f1;
Vector2 P = df.X * _perp + df.Z * _axis;
float LA = df.X * _s1 + df.Y + df.Z * _a1;
float LB = df.X * _s2 + df.Y + df.Z * _a2;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
else
{
// Limit is inactive, just solve the prismatic constraint in block form.
Vector2 df = _K.Solve22(-Cdot1);
_impulse.X += df.X;
_impulse.Y += df.Y;
Vector2 P = df.X * _perp;
float LA = df.X * _s1 + df.Y;
float LB = df.X * _s2 + df.Y;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
Vector2 cA = data.Positions[_indexA].C;
float aA = data.Positions[_indexA].A;
Vector2 cB = data.Positions[_indexB].C;
float aB = data.Positions[_indexB].A;
Rot qA = new Rot(aA), qB = new Rot(aB);
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
// Compute fresh Jacobians
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
Vector2 d = cB + rB - cA - rA;
Vector2 axis = MathUtils.Mul(qA, LocalXAxis);
float a1 = MathUtils.Cross(d + rA, axis);
float a2 = MathUtils.Cross(rB, axis);
Vector2 perp = MathUtils.Mul(qA, _localYAxisA);
float s1 = MathUtils.Cross(d + rA, perp);
float s2 = MathUtils.Cross(rB, perp);
Vector3 impulse;
Vector2 C1 = new Vector2();
C1.X = Vector2.Dot(perp, d);
C1.Y = aB - aA - ReferenceAngle;
float linearError = Math.Abs(C1.X);
float angularError = Math.Abs(C1.Y);
bool active = false;
float C2 = 0.0f;
if (_enableLimit)
{
float translation = Vector2.Dot(axis, d);
if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop)
{
// Prevent large angular corrections
C2 = MathUtils.Clamp(translation, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection);
linearError = Math.Max(linearError, Math.Abs(translation));
active = true;
}
else if (translation <= _lowerTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.Clamp(translation - _lowerTranslation + Settings.LinearSlop,
-Settings.MaxLinearCorrection, 0.0f);
linearError = Math.Max(linearError, _lowerTranslation - translation);
active = true;
}
else if (translation >= _upperTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.Clamp(translation - _upperTranslation - Settings.LinearSlop, 0.0f,
Settings.MaxLinearCorrection);
linearError = Math.Max(linearError, translation - _upperTranslation);
active = true;
}
}
if (active)
{
float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float k12 = iA * s1 + iB * s2;
float k13 = iA * s1 * a1 + iB * s2 * a2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
// For fixed rotation
k22 = 1.0f;
}
float k23 = iA * a1 + iB * a2;
float k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;
Mat33 K = new Mat33();
K.Ex = new Vector3(k11, k12, k13);
K.Ey = new Vector3(k12, k22, k23);
K.Ez = new Vector3(k13, k23, k33);
Vector3 C = new Vector3();
C.X = C1.X;
C.Y = C1.Y;
C.Z = C2;
impulse = K.Solve33(-C);
}
else
{
float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float k12 = iA * s1 + iB * s2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
k22 = 1.0f;
}
Mat22 K = new Mat22();
K.Ex = new Vector2(k11, k12);
K.Ey = new Vector2(k12, k22);
Vector2 impulse1 = K.Solve(-C1);
impulse = new Vector3();
impulse.X = impulse1.X;
impulse.Y = impulse1.Y;
impulse.Z = 0.0f;
}
Vector2 P = impulse.X * perp + impulse.Z * axis;
float LA = impulse.X * s1 + impulse.Y + impulse.Z * a1;
float LB = impulse.X * s2 + impulse.Y + impulse.Z * a2;
cA -= mA * P;
aA -= iA * LA;
cB += mB * P;
aB += iB * LB;
data.Positions[_indexA].C = cA;
data.Positions[_indexA].A = aA;
data.Positions[_indexB].C = cB;
data.Positions[_indexB].A = aB;
return linearError <= Settings.LinearSlop && angularError <= Settings.AngularSlop;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core;
using Umbraco.Core.Services;
namespace Umbraco.Core.Publishing
{
//TODO: Do we need this anymore??
/// <summary>
/// Currently acts as an interconnection between the new public api and the legacy api for publishing
/// </summary>
public class PublishingStrategy : BasePublishingStrategy
{
private readonly IEventMessagesFactory _eventMessagesFactory;
private readonly ILogger _logger;
public PublishingStrategy(IEventMessagesFactory eventMessagesFactory, ILogger logger)
{
if (eventMessagesFactory == null) throw new ArgumentNullException("eventMessagesFactory");
if (logger == null) throw new ArgumentNullException("logger");
_eventMessagesFactory = eventMessagesFactory;
_logger = logger;
}
/// <summary>
/// Publishes a single piece of Content
/// </summary>
/// <param name="content"><see cref="IContent"/> to publish</param>
/// <param name="userId">Id of the User issueing the publish operation</param>
internal Attempt<PublishStatus> PublishInternal(IContent content, int userId)
{
if (Publishing.IsRaisedEventCancelled(
_eventMessagesFactory.Get(),
messages => new PublishEventArgs<IContent>(content), this))
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' will not be published, the event was cancelled.", content.Name, content.Id));
return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedCancelledByEvent));
}
//Check if the Content is Expired to verify that it can in fact be published
if (content.Status == ContentStatus.Expired)
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' has expired and could not be published.",
content.Name, content.Id));
return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedHasExpired));
}
//Check if the Content is Awaiting Release to verify that it can in fact be published
if (content.Status == ContentStatus.AwaitingRelease)
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' is awaiting release and could not be published.",
content.Name, content.Id));
return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedAwaitingRelease));
}
//Check if the Content is Trashed to verify that it can in fact be published
if (content.Status == ContentStatus.Trashed)
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' is trashed and could not be published.",
content.Name, content.Id));
return Attempt<PublishStatus>.Fail(new PublishStatus(content, PublishStatusType.FailedIsTrashed));
}
content.ChangePublishedState(PublishedState.Published);
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' has been published.",
content.Name, content.Id));
return Attempt.Succeed(new PublishStatus(content));
}
/// <summary>
/// Publishes a single piece of Content
/// </summary>
/// <param name="content"><see cref="IContent"/> to publish</param>
/// <param name="userId">Id of the User issueing the publish operation</param>
/// <returns>True if the publish operation was successfull and not cancelled, otherwise false</returns>
public override bool Publish(IContent content, int userId)
{
return PublishInternal(content, userId).Success;
}
/// <summary>
/// Publishes a list of content items
/// </summary>
/// <param name="content"></param>
/// <param name="userId"></param>
/// <param name="includeUnpublishedDocuments">
/// By default this is set to true which means that it will publish any content item in the list that is completely unpublished and
/// not visible on the front-end. If set to false, this will only publish content that is live on the front-end but has new versions
/// that have yet to be published.
/// </param>
/// <returns></returns>
/// <remarks>
///
/// This method becomes complex once we start to be able to cancel events or stop publishing a content item in any way because if a
/// content item is not published then it's children shouldn't be published either. This rule will apply for the following conditions:
/// * If a document fails to be published, do not proceed to publish it's children if:
/// ** The document does not have a publish version
/// ** The document does have a published version but the includeUnpublishedDocuments = false
///
/// In order to do this, we will order the content by level and begin by publishing each item at that level, then proceed to the next
/// level and so on. If we detect that the above rule applies when the document publishing is cancelled we'll add it to the list of
/// parentsIdsCancelled so that it's children don't get published.
///
/// Its important to note that all 'root' documents included in the list *will* be published regardless of the rules mentioned
/// above (unless it is invalid)!! By 'root' documents we are referring to documents in the list with the minimum value for their 'level'.
/// In most cases the 'root' documents will only be one document since under normal circumstance we only publish one document and
/// its children. The reason we have to do this is because if a user is publishing a document and it's children, it is implied that
/// the user definitely wants to publish it even if it has never been published before.
///
/// </remarks>
internal IEnumerable<Attempt<PublishStatus>> PublishWithChildrenInternal(
IEnumerable<IContent> content, int userId, bool includeUnpublishedDocuments = true)
{
var statuses = new List<Attempt<PublishStatus>>();
//a list of all document ids that had their publishing cancelled during these iterations.
//this helps us apply the rule listed in the notes above by checking if a document's parent id
//matches one in this list.
var parentsIdsCancelled = new List<int>();
//group by levels and iterate over the sorted ascending level.
//TODO: This will cause all queries to execute, they will not be lazy but I'm not really sure being lazy actually made
// much difference because we iterate over them all anyways?? Morten?
// Because we're grouping I think this will execute all the queries anyways so need to fetch it all first.
var fetchedContent = content.ToArray();
//We're going to populate the statuses with all content that is already published because below we are only going to iterate over
// content that is not published. We'll set the status to "AlreadyPublished"
statuses.AddRange(fetchedContent.Where(x => x.Published)
.Select(x => Attempt.Succeed(new PublishStatus(x, PublishStatusType.SuccessAlreadyPublished))));
int? firstLevel = null;
//group by level and iterate over each level (sorted ascending)
var levelGroups = fetchedContent.GroupBy(x => x.Level);
foreach (var level in levelGroups.OrderBy(x => x.Key))
{
//set the first level flag, used to ensure that all documents at the first level will
//be published regardless of the rules mentioned in the remarks.
if (!firstLevel.HasValue)
{
firstLevel = level.Key;
}
/* Only update content thats not already been published - we want to loop through
* all unpublished content to write skipped content (expired and awaiting release) to log.
*/
foreach (var item in level.Where(x => x.Published == false))
{
//Check if this item should be excluded because it's parent's publishing has failed/cancelled
if (parentsIdsCancelled.Contains(item.ParentId))
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' will not be published because it's parent's publishing action failed or was cancelled.", item.Name, item.Id));
//if this cannot be published, ensure that it's children can definitely not either!
parentsIdsCancelled.Add(item.Id);
continue;
}
//Check if this item has never been published (and that it is not at the root level)
if (item.Level != firstLevel && !includeUnpublishedDocuments && !item.HasPublishedVersion())
{
//this item does not have a published version and the flag is set to not include them
parentsIdsCancelled.Add(item.Id);
continue;
}
//Fire Publishing event
if (Publishing.IsRaisedEventCancelled(
_eventMessagesFactory.Get(),
messages => new PublishEventArgs<IContent>(item, messages), this))
{
//the publishing has been cancelled.
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' will not be published, the event was cancelled.", item.Name, item.Id));
statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedCancelledByEvent)));
//Does this document apply to our rule to cancel it's children being published?
CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments);
continue;
}
//Check if the content is valid if the flag is set to check
if (!item.IsValid())
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' will not be published because some of it's content is not passing validation rules.",
item.Name, item.Id));
statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedContentInvalid)));
//Does this document apply to our rule to cancel it's children being published?
CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments);
continue;
}
//Check if the Content is Expired to verify that it can in fact be published
if (item.Status == ContentStatus.Expired)
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' has expired and could not be published.",
item.Name, item.Id));
statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedHasExpired)));
//Does this document apply to our rule to cancel it's children being published?
CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments);
continue;
}
//Check if the Content is Awaiting Release to verify that it can in fact be published
if (item.Status == ContentStatus.AwaitingRelease)
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' is awaiting release and could not be published.",
item.Name, item.Id));
statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedAwaitingRelease)));
//Does this document apply to our rule to cancel it's children being published?
CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments);
continue;
}
//Check if the Content is Trashed to verify that it can in fact be published
if (item.Status == ContentStatus.Trashed)
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' is trashed and could not be published.",
item.Name, item.Id));
statuses.Add(Attempt.Fail(new PublishStatus(item, PublishStatusType.FailedIsTrashed)));
//Does this document apply to our rule to cancel it's children being published?
CheckCancellingOfChildPublishing(item, parentsIdsCancelled, includeUnpublishedDocuments);
continue;
}
item.ChangePublishedState(PublishedState.Published);
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' has been published.",
item.Name, item.Id));
statuses.Add(Attempt.Succeed(new PublishStatus(item)));
}
}
return statuses;
}
/// <summary>
/// Based on the information provider we'll check if we should cancel the publishing of this document's children
/// </summary>
/// <param name="content"></param>
/// <param name="parentsIdsCancelled"></param>
/// <param name="includeUnpublishedDocuments"></param>
/// <remarks>
/// See remarks on method: PublishWithChildrenInternal
/// </remarks>
private void CheckCancellingOfChildPublishing(IContent content, List<int> parentsIdsCancelled, bool includeUnpublishedDocuments)
{
//Does this document apply to our rule to cancel it's children being published?
//TODO: We're going back to the service layer here... not sure how to avoid this? And this will add extra overhead to
// any document that fails to publish...
var hasPublishedVersion = ApplicationContext.Current.Services.ContentService.HasPublishedVersion(content.Id);
if (hasPublishedVersion && !includeUnpublishedDocuments)
{
//it has a published version but our flag tells us to not include un-published documents and therefore we should
// not be forcing decendant/child documents to be published if their parent fails.
parentsIdsCancelled.Add(content.Id);
}
else if (!hasPublishedVersion)
{
//it doesn't have a published version so we certainly cannot publish it's children.
parentsIdsCancelled.Add(content.Id);
}
}
/// <summary>
/// Publishes a list of Content
/// </summary>
/// <param name="content">An enumerable list of <see cref="IContent"/></param>
/// <param name="userId">Id of the User issueing the publish operation</param>
/// <returns>True if the publish operation was successfull and not cancelled, otherwise false</returns>
public override bool PublishWithChildren(IEnumerable<IContent> content, int userId)
{
var result = PublishWithChildrenInternal(content, userId);
//NOTE: This previously always returned true so I've left it that way. It returned true because (from Morten)...
// ... if one item couldn't be published it wouldn't be correct to return false.
// in retrospect it should have returned a list of with Ids and Publish Status
// come to think of it ... the cache would still be updated for a failed item or at least tried updated.
// It would call the Published event for the entire list, but if the Published property isn't set to True it
// wouldn't actually update the cache for that item. But not really ideal nevertheless...
return true;
}
/// <summary>
/// Unpublishes a single piece of Content
/// </summary>
/// <param name="content"><see cref="IContent"/> to unpublish</param>
/// <param name="userId">Id of the User issueing the unpublish operation</param>
/// <returns>True if the unpublish operation was successfull and not cancelled, otherwise false</returns>
public override bool UnPublish(IContent content, int userId)
{
return UnPublishInternal(content, userId).Success;
}
/// <summary>
/// Unpublishes a list of Content
/// </summary>
/// <param name="content">An enumerable list of <see cref="IContent"/></param>
/// <param name="userId">Id of the User issueing the unpublish operation</param>
/// <returns>A list of publish statuses</returns>
private IEnumerable<Attempt<PublishStatus>> UnPublishInternal(IEnumerable<IContent> content, int userId)
{
return content.Select(x => UnPublishInternal(x, userId));
}
private Attempt<PublishStatus> UnPublishInternal(IContent content, int userId)
{
// content should (is assumed to ) be the newest version, which may not be published
// don't know how to test this, so it's not verified
// NOTE
// if published != newest, then the published flags need to be reseted by whoever is calling that method
// at the moment it's done by the content service
//Fire UnPublishing event
if (UnPublishing.IsRaisedEventCancelled(
_eventMessagesFactory.Get(),
messages => new PublishEventArgs<IContent>(content, messages), this))
{
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' will not be unpublished, the event was cancelled.", content.Name, content.Id));
return Attempt.Fail(new PublishStatus(content, PublishStatusType.FailedCancelledByEvent));
}
//If Content has a release date set to before now, it should be removed so it doesn't interrupt an unpublish
//Otherwise it would remain released == published
if (content.ReleaseDate.HasValue && content.ReleaseDate.Value <= DateTime.Now)
{
content.ReleaseDate = null;
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' had its release date removed, because it was unpublished.",
content.Name, content.Id));
}
// if newest is published, unpublish
if (content.Published)
content.ChangePublishedState(PublishedState.Unpublished);
_logger.Info<PublishingStrategy>(
string.Format("Content '{0}' with Id '{1}' has been unpublished.",
content.Name, content.Id));
return Attempt.Succeed(new PublishStatus(content));
}
/// <summary>
/// Unpublishes a list of Content
/// </summary>
/// <param name="content">An enumerable list of <see cref="IContent"/></param>
/// <param name="userId">Id of the User issueing the unpublish operation</param>
/// <returns>True if the unpublish operation was successfull and not cancelled, otherwise false</returns>
public override bool UnPublish(IEnumerable<IContent> content, int userId)
{
var result = UnPublishInternal(content, userId);
//NOTE: This previously always returned true so I've left it that way. It returned true because (from Morten)...
// ... if one item couldn't be published it wouldn't be correct to return false.
// in retrospect it should have returned a list of with Ids and Publish Status
// come to think of it ... the cache would still be updated for a failed item or at least tried updated.
// It would call the Published event for the entire list, but if the Published property isn't set to True it
// wouldn't actually update the cache for that item. But not really ideal nevertheless...
return true;
}
/// <summary>
/// Call to fire event that updating the published content has finalized.
/// </summary>
/// <remarks>
/// This seperation of the OnPublished event is done to ensure that the Content
/// has been properly updated (committed unit of work) and xml saved in the db.
/// </remarks>
/// <param name="content"><see cref="IContent"/> thats being published</param>
public override void PublishingFinalized(IContent content)
{
Published.RaiseEvent(
_eventMessagesFactory.Get(),
messages => new PublishEventArgs<IContent>(content, false, false, messages), this);
}
/// <summary>
/// Call to fire event that updating the published content has finalized.
/// </summary>
/// <param name="content">An enumerable list of <see cref="IContent"/> thats being published</param>
/// <param name="isAllRepublished">Boolean indicating whether its all content that is republished</param>
public override void PublishingFinalized(IEnumerable<IContent> content, bool isAllRepublished)
{
Published.RaiseEvent(
_eventMessagesFactory.Get(),
messages => new PublishEventArgs<IContent>(content, false, isAllRepublished, messages), this);
}
/// <summary>
/// Call to fire event that updating the unpublished content has finalized.
/// </summary>
/// <param name="content"><see cref="IContent"/> thats being unpublished</param>
public override void UnPublishingFinalized(IContent content)
{
UnPublished.RaiseEvent(
_eventMessagesFactory.Get(),
messages => new PublishEventArgs<IContent>(content, false, false, messages), this);
}
/// <summary>
/// Call to fire event that updating the unpublished content has finalized.
/// </summary>
/// <param name="content">An enumerable list of <see cref="IContent"/> thats being unpublished</param>
public override void UnPublishingFinalized(IEnumerable<IContent> content)
{
UnPublished.RaiseEvent(
_eventMessagesFactory.Get(),
messages => new PublishEventArgs<IContent>(content, false, false, messages), this);
}
/// <summary>
/// Occurs before publish
/// </summary>
public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> Publishing;
/// <summary>
/// Occurs after publish
/// </summary>
public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> Published;
/// <summary>
/// Occurs before unpublish
/// </summary>
public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> UnPublishing;
/// <summary>
/// Occurs after unpublish
/// </summary>
public static event TypedEventHandler<IPublishingStrategy, PublishEventArgs<IContent>> UnPublished;
}
}
| |
using System;
#if ENABLE_CECIL
using Mono.Cecil.Cil;
#else
using System.Reflection.Emit;
#endif
namespace Mono.Debugger.Soft
{
internal class ILInterpreter
{
MethodMirror method;
public ILInterpreter (MethodMirror method) {
this.method = method;
}
public Value Evaluate (Value this_val, Value[] args) {
var body = method.GetMethodBody ();
// Implement only the IL opcodes required to evaluate mcs compiled property accessors:
// IL_0000: nop
// IL_0001: ldarg.0
// IL_0002: ldfld int32 Tests::field_i
// IL_0007: stloc.0
// IL_0008: br IL_000d
// IL_000d: ldloc.0
// IL_000e: ret
// ... or returns a simple constant:
// IL_0000: ldc.i4 1024
// IL_0005: conv.i8
// IL_0006: ret
if (args != null && args.Length != 0)
throw new NotSupportedException ();
//If method is virtual we can't optimize(execute IL) because it's maybe
//overriden... call runtime to invoke overriden version...
if (method.IsVirtual)
throw new NotSupportedException ();
if (method.IsStatic || method.DeclaringType.IsValueType || this_val == null || !(this_val is ObjectMirror))
throw new NotSupportedException ();
var instructions = body.Instructions;
if (instructions.Count < 1 || instructions.Count > 16)
throw new NotSupportedException ();
var stack = new Value [16];
var ins = instructions [0];
Value locals_0 = null;
int ins_count = 0;
int sp = 0;
while (ins != null) {
if (ins_count > 16)
throw new NotImplementedException ();
var next = ins.Next;
ins_count++;
var op = ins.OpCode;
if (op == OpCodes.Nop) {
} else if (op == OpCodes.Ldarg_0) {
if (sp != 0)
throw new NotSupportedException ();
stack [sp++] = this_val;
} else if (op == OpCodes.Ldfld) {
if (sp != 1)
throw new NotSupportedException ();
var obj = (ObjectMirror) stack [--sp];
var field = (FieldInfoMirror) ins.Operand;
try {
stack [sp++] = obj.GetValue (field);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_0) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 0);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_1) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 1);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_2) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 2);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_3) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 3);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_4) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 4);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_5) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 5);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_6) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 6);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_7) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 7);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_8) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, 8);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_M1) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, -1);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, ins.Operand);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I4_S) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, ins.Operand);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_I8) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, ins.Operand);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_R4) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, ins.Operand);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Ldc_R8) {
if (sp != 0)
throw new NotSupportedException ();
try {
stack [sp++] = new PrimitiveValue (method.VirtualMachine, ins.Operand);
} catch (ArgumentException) {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_I) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToInt32 (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_I1) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToSByte (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_U1) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToByte (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_I2) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToInt16 (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_U2) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToUInt16 (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_I4) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToInt32 (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_U4) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToUInt32 (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_I8) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToInt64 (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_U8) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToUInt64 (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_R4) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToSingle (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Conv_R8) {
if (sp != 1)
throw new NotSupportedException ();
try {
var primitive = (PrimitiveValue) stack [--sp];
stack [sp++] = new PrimitiveValue (method.VirtualMachine, Convert.ToDouble (primitive.Value));
} catch {
throw new NotSupportedException ();
}
} else if (op == OpCodes.Stloc_0) {
if (sp != 1)
throw new NotSupportedException ();
locals_0 = stack [--sp];
} else if (op == OpCodes.Br || op == OpCodes.Br_S) {
next = (ILInstruction) ins.Operand;
} else if (op == OpCodes.Ldloc_0) {
if (sp != 0)
throw new NotSupportedException ();
stack [sp++] = locals_0;
} else if (op == OpCodes.Ret) {
if (sp > 0) {
var res = stack [--sp];
var primitive = res as PrimitiveValue;
if (method.ReturnType.IsPrimitive && primitive != null) {
// cast the primitive value to the return type
try {
switch (method.ReturnType.CSharpName) {
case "double": res = new PrimitiveValue (method.VirtualMachine, Convert.ToDouble (primitive.Value)); break;
case "float": res = new PrimitiveValue (method.VirtualMachine, Convert.ToSingle (primitive.Value)); break;
case "ulong": res = new PrimitiveValue (method.VirtualMachine, Convert.ToUInt64 (primitive.Value)); break;
case "long": res = new PrimitiveValue (method.VirtualMachine, Convert.ToInt64 (primitive.Value)); break;
case "uint": res = new PrimitiveValue (method.VirtualMachine, Convert.ToUInt32 (primitive.Value)); break;
case "int": res = new PrimitiveValue (method.VirtualMachine, Convert.ToInt32 (primitive.Value)); break;
case "ushort": res = new PrimitiveValue (method.VirtualMachine, Convert.ToUInt16 (primitive.Value)); break;
case "short": res = new PrimitiveValue (method.VirtualMachine, Convert.ToInt16 (primitive.Value)); break;
case "sbyte": res = new PrimitiveValue (method.VirtualMachine, Convert.ToSByte (primitive.Value)); break;
case "byte": res = new PrimitiveValue (method.VirtualMachine, Convert.ToByte (primitive.Value)); break;
case "char": res = new PrimitiveValue (method.VirtualMachine, Convert.ToChar (primitive.Value)); break;
case "bool": res = new PrimitiveValue (method.VirtualMachine, Convert.ToBoolean (primitive.Value)); break;
}
} catch {
throw new NotSupportedException ();
}
} else if (method.ReturnType.IsEnum && primitive != null) {
try {
res = method.VirtualMachine.CreateEnumMirror (method.ReturnType, primitive);
} catch {
throw new NotSupportedException ();
}
}
return res;
}
return null;
} else {
throw new NotSupportedException ();
}
ins = next;
}
return null;
}
}
}
| |
//
// 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.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.HDInsight;
using Microsoft.Azure.Management.HDInsight.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.HDInsight
{
/// <summary>
/// The HDInsight Management Client.
/// </summary>
public partial class HDInsightManagementClient : ServiceClient<HDInsightManagementClient>, IHDInsightManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IClusterOperations _clusters;
/// <summary>
/// Contains all the cluster operations.
/// </summary>
public virtual IClusterOperations Clusters
{
get { return this._clusters; }
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
public HDInsightManagementClient()
: base()
{
this._clusters = new ClusterOperations(this);
this._apiVersion = "2015-03-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public HDInsightManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._clusters = new ClusterOperations(this);
this._apiVersion = "2015-03-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the HDInsightManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public HDInsightManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// HDInsightManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of HDInsightManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<HDInsightManagementClient> client)
{
base.Clone(client);
if (client is HDInsightManagementClient)
{
HDInsightManagementClient clonedClient = ((HDInsightManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The cluster long running operation response.
/// </returns>
public async Task<HDInsightLongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-03-01-preview");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HDInsightLongRunningOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new HDInsightLongRunningOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken errorValue = responseDoc["error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
ErrorInfo errorInstance = new ErrorInfo();
result.Error = errorInstance;
JToken codeValue = errorValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("RetryAfter"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("RetryAfter").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using Foundation;
using ObjCRuntime;
using Sparkle;
namespace Sparkle
{
// @interface SUAppcast : NSObject <NSURLDownloadDelegate>
[BaseType (typeof(NSObject))]
interface SUAppcast : INSUrlDownloadDelegate
{
// @property (copy) NSString * userAgentString;
[Export ("userAgentString")]
string UserAgent { get; set; }
// @property (copy) NSDictionary * httpHeaders;
[Export ("httpHeaders", ArgumentSemantic.Copy)]
NSDictionary HttpHeaders { get; set; }
// -(void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))err;
[Export ("fetchAppcastFromURL:completionBlock:")]
void FetchAppcast (NSUrl url, Action<NSError> err);
// @property (readonly, copy) NSArray * items;
[Export ("items", ArgumentSemantic.Copy)]
SUAppcastItem[] Items { get; }
}
// @interface SUAppcastItem : NSObject
[BaseType (typeof(NSObject))]
interface SUAppcastItem
{
// @property (readonly, copy) NSString * title;
[Export ("title")]
string Title { get; }
// @property (readonly, copy) NSDate * date;
[Export ("date", ArgumentSemantic.Copy)]
NSDate Date { get; }
// @property (readonly, copy) NSString * itemDescription;
[Export ("itemDescription")]
string ItemDescription { get; }
// @property (readonly, strong) NSURL * releaseNotesURL;
[Export ("releaseNotesURL", ArgumentSemantic.Strong)]
NSUrl ReleaseNotesUrl { get; }
// @property (readonly, copy) NSString * DSASignature;
[Export ("DSASignature")]
string DsaSignature { get; }
// @property (readonly, copy) NSString * minimumSystemVersion;
[Export ("minimumSystemVersion")]
string MinimumSystemVersion { get; }
// @property (readonly, copy) NSString * maximumSystemVersion;
[Export ("maximumSystemVersion")]
string MaximumSystemVersion { get; }
// @property (readonly, strong) NSURL * fileURL;
[Export ("fileURL", ArgumentSemantic.Strong)]
NSUrl FileUrl { get; }
// @property (readonly, copy) NSString * versionString;
[Export ("versionString")]
string Version { get; }
// @property (readonly, copy) NSString * displayVersionString;
[Export ("displayVersionString")]
string DisplayVersion { get; }
// @property (readonly, copy) NSDictionary * deltaUpdates;
[Export ("deltaUpdates", ArgumentSemantic.Copy)]
NSDictionary DeltaUpdates { get; }
// @property (readonly, strong) NSURL * infoURL;
[Export ("infoURL", ArgumentSemantic.Strong)]
NSUrl InfoUrl { get; }
// -(instancetype)initWithDictionary:(NSDictionary *)dict;
[Export ("initWithDictionary:")]
IntPtr Constructor (NSDictionary dict);
// -(instancetype)initWithDictionary:(NSDictionary *)dict failureReason:(NSString **)error;
[Export ("initWithDictionary:failureReason:")]
IntPtr Constructor (NSDictionary dict, out string error);
// @property (readonly, getter = isDeltaUpdate) BOOL deltaUpdate;
[Export ("deltaUpdate")]
bool IsDeltaUpdate { [Bind ("isDeltaUpdate")] get; }
// @property (readonly, getter = isCriticalUpdate) BOOL criticalUpdate;
[Export ("criticalUpdate")]
bool IsCriticalUpdate { [Bind ("isCriticalUpdate")] get; }
// @property (readonly, getter = isInformationOnlyUpdate) BOOL informationOnlyUpdate;
[Export ("informationOnlyUpdate")]
bool IsInformationOnlyUpdate { [Bind ("isInformationOnlyUpdate")] get; }
// @property (readonly, copy) NSDictionary * propertiesDictionary;
[Export ("propertiesDictionary", ArgumentSemantic.Copy)]
NSDictionary PropertiesDictionary { get; }
}
// @protocol SUVersionComparison
[Protocol, Model]
interface SUVersionComparison
{
// @required -(NSComparisonResult)compareVersion:(NSString *)versionA toVersion:(NSString *)versionB;
[Abstract]
[Export ("compareVersion:toVersion:")]
NSComparisonResult CompareVersion (string versionA, string versionB);
}
interface ISUVersionComparison
{
}
// @interface SUStandardVersionComparator : NSObject <SUVersionComparison>
[BaseType (typeof(NSObject))]
interface SUStandardVersionComparator : ISUVersionComparison
{
// +(SUStandardVersionComparator *)defaultComparator;
[Static]
[Export ("defaultComparator")]
SUStandardVersionComparator DefaultComparator { get; }
// -(NSComparisonResult)compareVersion:(NSString *)versionA toVersion:(NSString *)versionB;
[Export ("compareVersion:toVersion:")]
NSComparisonResult CompareVersion (string versionA, string versionB);
}
// @protocol SUVersionDisplay
[Protocol, Model]
interface SUVersionDisplay
{
// @required -(void)formatVersion:(NSString **)inOutVersionA andVersion:(NSString **)inOutVersionB;
[Abstract]
[Export ("formatVersion:andVersion:")]
void FormatVersion (ref string versionA, ref string versionB);
}
interface ISUVersionDisplay
{
}
// @interface SUUpdater : NSObject
[BaseType (typeof(NSObject))]
interface SUUpdater
{
[Wrap ("WeakDelegate")]
SUUpdaterDelegate Delegate { get; set; }
// @property (unsafe_unretained) id<SUUpdaterDelegate> delegate __attribute__((iboutlet));
[NullAllowed, Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
// +(SUUpdater *)sharedUpdater;
[Static]
[Export ("sharedUpdater")]
SUUpdater SharedUpdater { get; }
// +(SUUpdater *)updaterForBundle:(NSBundle *)bundle;
[Static]
[Export ("updaterForBundle:")]
SUUpdater GetUpdater (NSBundle bundle);
// -(instancetype)initForBundle:(NSBundle *)bundle;
[Export ("initForBundle:")]
IntPtr Constructor (NSBundle bundle);
// @property (readonly, strong) NSBundle * hostBundle;
[Export ("hostBundle", ArgumentSemantic.Strong)]
NSBundle HostBundle { get; }
// @property (readonly, strong) NSBundle * sparkleBundle;
[Export ("sparkleBundle", ArgumentSemantic.Strong)]
NSBundle SparkleBundle { get; }
// @property BOOL automaticallyChecksForUpdates;
[Export ("automaticallyChecksForUpdates")]
bool AutomaticallyChecksForUpdates { get; set; }
// @property NSTimeInterval updateCheckInterval;
[Export ("updateCheckInterval")]
double UpdateCheckInterval { get; set; }
// @property (copy) NSURL * feedURL;
[Export ("feedURL", ArgumentSemantic.Copy)]
NSUrl FeedUrl { get; set; }
// @property (copy, nonatomic) NSString * userAgentString;
[Export ("userAgentString")]
string UserAgent { get; set; }
// @property (copy) NSDictionary * httpHeaders;
[Export ("httpHeaders", ArgumentSemantic.Copy)]
NSDictionary HttpHeaders { get; set; }
// @property BOOL sendsSystemProfile;
[Export ("sendsSystemProfile")]
bool SendsSystemProfile { get; set; }
// @property BOOL automaticallyDownloadsUpdates;
[Export ("automaticallyDownloadsUpdates")]
bool AutomaticallyDownloadsUpdates { get; set; }
// -(void)checkForUpdates:(id)sender __attribute__((ibaction));
[Export ("checkForUpdates:")]
void CheckForUpdates (NSObject sender);
// -(void)checkForUpdatesInBackground;
[Export ("checkForUpdatesInBackground")]
void CheckForUpdatesInBackground ();
// -(void)installUpdatesIfAvailable;
[Export ("installUpdatesIfAvailable")]
void InstallUpdatesIfAvailable ();
// @property (readonly, copy) NSDate * lastUpdateCheckDate;
[Export ("lastUpdateCheckDate", ArgumentSemantic.Copy)]
NSDate LastUpdateCheckDate { get; }
// -(void)checkForUpdateInformation;
[Export ("checkForUpdateInformation")]
void CheckForUpdateInformation ();
// -(void)resetUpdateCycle;
[Export ("resetUpdateCycle")]
void ResetUpdateCycle ();
// @property (readonly) BOOL updateInProgress;
[Export ("updateInProgress")]
bool IsUpdateInProgress { get; }
// extern NSString *const SUUpdaterDidFinishLoadingAppCastNotification;
[Notification]
[Field ("SUUpdaterDidFinishLoadingAppCastNotification", "Sparkle")]
NSString DidFinishLoadingAppCastNotification { get; }
// extern NSString *const SUUpdaterDidFindValidUpdateNotification;
[Field ("SUUpdaterDidFindValidUpdateNotification", "Sparkle")]
[Notification]
NSString DidFindValidUpdateNotification { get; }
// extern NSString *const SUUpdaterDidNotFindUpdateNotification;
[Field ("SUUpdaterDidNotFindUpdateNotification", "Sparkle")]
[Notification]
NSString DidNotFindUpdateNotification { get; }
// extern NSString *const SUUpdaterWillRestartNotification;
[Field ("SUUpdaterWillRestartNotification", "Sparkle")]
[Notification]
NSString WillRestartNotification { get; }
// extern NSString *const SUUpdaterAppcastItemNotificationKey;
[Field ("SUUpdaterAppcastItemNotificationKey", "Sparkle")]
NSString SUUpdaterAppcastItemNotificationKey { get; }
// extern NSString *const SUUpdaterAppcastNotificationKey;
[Field ("SUUpdaterAppcastNotificationKey", "Sparkle")]
NSString SUUpdaterAppcastNotificationKey { get; }
}
// @protocol SUUpdaterDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface SUUpdaterDelegate
{
// @optional -(BOOL)updaterMayCheckForUpdates:(SUUpdater *)updater;
[Export ("updaterMayCheckForUpdates:")]
bool MayCheckForUpdates (SUUpdater updater);
// @optional -(NSArray *)feedParametersForUpdater:(SUUpdater *)updater sendingSystemProfile:(BOOL)sendingProfile;
[Export ("feedParametersForUpdater:sendingSystemProfile:")]
NSObject[] FeedParameters (SUUpdater updater, bool sendingProfile);
// @optional -(NSString *)feedURLStringForUpdater:(SUUpdater *)updater;
[Export ("feedURLStringForUpdater:")]
string FeedUrlString (SUUpdater updater);
// @optional -(BOOL)updaterShouldPromptForPermissionToCheckForUpdates:(SUUpdater *)updater;
[Export ("updaterShouldPromptForPermissionToCheckForUpdates:")]
bool ShouldPromptForPermissionToCheckForUpdates (SUUpdater updater);
// @optional -(void)updater:(SUUpdater *)updater didFinishLoadingAppcast:(SUAppcast *)appcast;
[Export ("updater:didFinishLoadingAppcast:")]
void DidFinishLoadingAppcast (SUUpdater updater, SUAppcast appcast);
// @optional -(SUAppcastItem *)bestValidUpdateInAppcast:(SUAppcast *)appcast forUpdater:(SUUpdater *)updater;
[Export ("bestValidUpdateInAppcast:forUpdater:")]
SUAppcastItem GetBestValidUpdateInAppcast (SUAppcast appcast, SUUpdater updater);
// @optional -(void)updater:(SUUpdater *)updater didFindValidUpdate:(SUAppcastItem *)item;
[Export ("updater:didFindValidUpdate:")]
void DidFindValidUpdate (SUUpdater updater, SUAppcastItem item);
// @optional -(void)updaterDidNotFindUpdate:(SUUpdater *)updater;
[Export ("updaterDidNotFindUpdate:")]
void DidNotFindUpdate (SUUpdater updater);
// @optional -(void)updater:(SUUpdater *)updater willDownloadUpdate:(SUAppcastItem *)item withRequest:(NSMutableURLRequest *)request;
[Export ("updater:willDownloadUpdate:withRequest:")]
void WillDownloadUpdate (SUUpdater updater, SUAppcastItem item, NSMutableUrlRequest request);
// @optional -(void)updater:(SUUpdater *)updater failedToDownloadUpdate:(SUAppcastItem *)item error:(NSError *)error;
[Export ("updater:failedToDownloadUpdate:error:")]
void FailedToDownloadUpdate (SUUpdater updater, SUAppcastItem item, NSError error);
// @optional -(void)userDidCancelDownload:(SUUpdater *)updater;
[Export ("userDidCancelDownload:")]
void UserDidCancelDownload (SUUpdater updater);
// @optional -(void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)item;
[Export ("updater:willInstallUpdate:")]
void WillInstallUpdate (SUUpdater updater, SUAppcastItem item);
// @optional -(BOOL)updater:(SUUpdater *)updater shouldPostponeRelaunchForUpdate:(SUAppcastItem *)item untilInvoking:(NSInvocation *)invocation;
[Export ("updater:shouldPostponeRelaunchForUpdate:untilInvoking:")]
bool ShouldPostponeRelaunchForUpdate (SUUpdater updater, SUAppcastItem item, NSInvocation invocation);
// @optional -(BOOL)updaterShouldRelaunchApplication:(SUUpdater *)updater;
[Export ("updaterShouldRelaunchApplication:")]
bool ShouldRelaunchApplication (SUUpdater updater);
// @optional -(void)updaterWillRelaunchApplication:(SUUpdater *)updater;
[Export ("updaterWillRelaunchApplication:")]
void WillRelaunchApplication (SUUpdater updater);
// @optional -(id<SUVersionComparison>)versionComparatorForUpdater:(SUUpdater *)updater;
[Export ("versionComparatorForUpdater:")]
ISUVersionComparison GetVersionComparator (SUUpdater updater);
// @optional -(id<SUVersionDisplay>)versionDisplayerForUpdater:(SUUpdater *)updater;
[Export ("versionDisplayerForUpdater:")]
ISUVersionDisplay GetVersionDisplayer (SUUpdater updater);
// @optional -(NSString *)pathToRelaunchForUpdater:(SUUpdater *)updater;
[Export ("pathToRelaunchForUpdater:")]
string GetPathToRelaunch (SUUpdater updater);
// @optional -(void)updaterWillShowModalAlert:(SUUpdater *)updater;
[Export ("updaterWillShowModalAlert:")]
void WillShowModalAlert (SUUpdater updater);
// @optional -(void)updaterDidShowModalAlert:(SUUpdater *)updater;
[Export ("updaterDidShowModalAlert:")]
void DidShowModalAlert (SUUpdater updater);
// @optional -(void)updater:(SUUpdater *)updater willInstallUpdateOnQuit:(SUAppcastItem *)item immediateInstallationInvocation:(NSInvocation *)invocation;
[Export ("updater:willInstallUpdateOnQuit:immediateInstallationInvocation:")]
void WillInstallUpdateOnQuit (SUUpdater updater, SUAppcastItem item, NSInvocation invocation);
// @optional -(void)updater:(SUUpdater *)updater didCancelInstallUpdateOnQuit:(SUAppcastItem *)item;
[Export ("updater:didCancelInstallUpdateOnQuit:")]
void DidCancelInstallUpdateOnQuit (SUUpdater updater, SUAppcastItem item);
// @optional -(void)updater:(SUUpdater *)updater didAbortWithError:(NSError *)error;
[Export ("updater:didAbortWithError:")]
void DidAbort (SUUpdater updater, NSError error);
}
[Static]
partial interface SUSparkle
{
// extern NSString *const SUSparkleErrorDomain;
[Field ("SUSparkleErrorDomain", "Sparkle")]
NSString ErrorDomain { get; }
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using SpyUO.Packets;
namespace SpyUO
{
public class Display : Form, ICounterDisplay
{
public const string Title = "SpyUO 1.10 Mod KR";
public static void Main()
{
try
{
SetupClientsConfig( "Clients.cfg" );
SetupItemsTable( "Items.cfg" );
Application.Run( new Display() );
}
catch ( Exception e )
{
MessageBox.Show( e.ToString(), "Application error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
private static void SetupClientsConfig( string file )
{
try
{
PacketPump.ClientsConfig.AddToTable( file );
}
catch ( Exception e )
{
throw new Exception( "Error reading " + file, e );
}
}
private static void SetupItemsTable( string file )
{
try
{
PacketRecorder.InitItemsTable( file );
}
catch ( Exception e )
{
throw new Exception( "Error reading " + file, e );
}
}
private System.Windows.Forms.ListView lvPackets;
private System.Windows.Forms.ColumnHeader chType;
private System.Windows.Forms.ColumnHeader chMessage;
private System.Windows.Forms.ColumnHeader chPacket;
private System.Windows.Forms.ColumnHeader chTime;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem miProcess;
private System.Windows.Forms.MenuItem miStart;
private System.Windows.Forms.MenuItem miAttach;
private System.Windows.Forms.MenuItem miDetach;
private System.Windows.Forms.MenuItem miExitSeparator;
private System.Windows.Forms.MenuItem miExit;
private System.Windows.Forms.OpenFileDialog ofdStart;
private System.Windows.Forms.MenuItem miOptions;
private System.Windows.Forms.MenuItem miFilter;
private System.Windows.Forms.MenuItem miOnTop;
private System.Windows.Forms.MenuItem miAutoScrolling;
private System.Windows.Forms.ColumnHeader chRelTime;
private System.Windows.Forms.MenuItem miLogs;
private System.Windows.Forms.MenuItem miClear;
private System.Windows.Forms.MenuItem miPause;
private System.Windows.Forms.MenuItem miSaveAs;
private System.Windows.Forms.SaveFileDialog sfdSaveAs;
private System.Windows.Forms.MenuItem miHelp;
private System.Windows.Forms.MenuItem miAbout;
private System.Windows.Forms.ColumnHeader chDifTime;
private System.Windows.Forms.ColumnHeader chASCII;
private System.Windows.Forms.MenuItem miTools;
private System.Windows.Forms.SaveFileDialog sfdExtractItems;
private System.Windows.Forms.MenuItem miExtractItems;
private System.Windows.Forms.MenuItem miExtractGump;
private System.Windows.Forms.SaveFileDialog sfdExtractGump;
private System.Windows.Forms.MenuItem miSaveHexAs;
private System.Windows.Forms.ColumnHeader chLength;
private System.Windows.Forms.MenuItem miLoad;
private System.Windows.Forms.OpenFileDialog ofdLoad;
private System.Windows.Forms.MenuItem miExtractGumpSphere;
private System.Windows.Forms.SaveFileDialog sfdExtractGumpSphere;
private System.Windows.Forms.MenuItem miSetBaseTime;
private System.Windows.Forms.MenuItem miHide;
private System.Windows.Forms.MenuItem miShowHidden;
private System.Windows.Forms.MenuItem miExtractBooks;
private System.Windows.Forms.SaveFileDialog sfdExtractBook;
private System.Windows.Forms.MenuItem miSaveBin;
private System.Windows.Forms.SaveFileDialog sfdSaveBin;
private System.Windows.Forms.MenuItem miLoadBin;
private System.Windows.Forms.OpenFileDialog ofdLoadBin;
private System.ComponentModel.Container components = null;
protected override void Dispose( bool disposing )
{
if ( disposing )
{
if ( components != null )
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Metodo necessario per il supporto della finestra di progettazione. Non modificare
/// il contenuto del metodo con l'editor di codice.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Display));
this.lvPackets = new System.Windows.Forms.ListView();
this.chType = new System.Windows.Forms.ColumnHeader();
this.chMessage = new System.Windows.Forms.ColumnHeader();
this.chTime = new System.Windows.Forms.ColumnHeader();
this.chRelTime = new System.Windows.Forms.ColumnHeader();
this.chDifTime = new System.Windows.Forms.ColumnHeader();
this.chPacket = new System.Windows.Forms.ColumnHeader();
this.chASCII = new System.Windows.Forms.ColumnHeader();
this.chLength = new System.Windows.Forms.ColumnHeader();
this.mainMenu = new System.Windows.Forms.MainMenu();
this.miProcess = new System.Windows.Forms.MenuItem();
this.miStart = new System.Windows.Forms.MenuItem();
this.miAttach = new System.Windows.Forms.MenuItem();
this.miDetach = new System.Windows.Forms.MenuItem();
this.miExitSeparator = new System.Windows.Forms.MenuItem();
this.miExit = new System.Windows.Forms.MenuItem();
this.miLogs = new System.Windows.Forms.MenuItem();
this.miLoad = new System.Windows.Forms.MenuItem();
this.miSaveAs = new System.Windows.Forms.MenuItem();
this.miSaveHexAs = new System.Windows.Forms.MenuItem();
this.miPause = new System.Windows.Forms.MenuItem();
this.miClear = new System.Windows.Forms.MenuItem();
this.miSetBaseTime = new System.Windows.Forms.MenuItem();
this.miHide = new System.Windows.Forms.MenuItem();
this.miShowHidden = new System.Windows.Forms.MenuItem();
this.miOptions = new System.Windows.Forms.MenuItem();
this.miFilter = new System.Windows.Forms.MenuItem();
this.miOnTop = new System.Windows.Forms.MenuItem();
this.miAutoScrolling = new System.Windows.Forms.MenuItem();
this.miTools = new System.Windows.Forms.MenuItem();
this.miExtractItems = new System.Windows.Forms.MenuItem();
this.miExtractBooks = new System.Windows.Forms.MenuItem();
this.miExtractGump = new System.Windows.Forms.MenuItem();
this.miExtractGumpSphere = new System.Windows.Forms.MenuItem();
this.miHelp = new System.Windows.Forms.MenuItem();
this.miAbout = new System.Windows.Forms.MenuItem();
this.ofdStart = new System.Windows.Forms.OpenFileDialog();
this.sfdSaveAs = new System.Windows.Forms.SaveFileDialog();
this.sfdExtractItems = new System.Windows.Forms.SaveFileDialog();
this.sfdExtractGump = new System.Windows.Forms.SaveFileDialog();
this.ofdLoad = new System.Windows.Forms.OpenFileDialog();
this.sfdExtractGumpSphere = new System.Windows.Forms.SaveFileDialog();
this.sfdExtractBook = new System.Windows.Forms.SaveFileDialog();
this.miSaveBin = new System.Windows.Forms.MenuItem();
this.sfdSaveBin = new System.Windows.Forms.SaveFileDialog();
this.miLoadBin = new System.Windows.Forms.MenuItem();
this.ofdLoadBin = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// lvPackets
//
this.lvPackets.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.chType,
this.chMessage,
this.chTime,
this.chRelTime,
this.chDifTime,
this.chPacket,
this.chASCII,
this.chLength});
this.lvPackets.Dock = System.Windows.Forms.DockStyle.Fill;
this.lvPackets.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lvPackets.FullRowSelect = true;
this.lvPackets.GridLines = true;
this.lvPackets.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lvPackets.Location = new System.Drawing.Point(0, 0);
this.lvPackets.MultiSelect = false;
this.lvPackets.Name = "lvPackets";
this.lvPackets.Size = new System.Drawing.Size(552, 414);
this.lvPackets.TabIndex = 0;
this.lvPackets.View = System.Windows.Forms.View.Details;
this.lvPackets.ItemActivate += new System.EventHandler(this.lvPackets_ItemActivate);
this.lvPackets.SelectedIndexChanged += new System.EventHandler(this.lvPackets_SelectedIndexChanged);
//
// chType
//
this.chType.Text = "Type";
this.chType.Width = 130;
//
// chMessage
//
this.chMessage.Text = "Message";
this.chMessage.Width = 330;
//
// chTime
//
this.chTime.Text = "Time";
this.chTime.Width = 75;
//
// chRelTime
//
this.chRelTime.Text = "Rel time";
//
// chDifTime
//
this.chDifTime.Text = "Dif time";
//
// chPacket
//
this.chPacket.Text = "Packet";
this.chPacket.Width = 250;
//
// chASCII
//
this.chASCII.Text = "ASCII";
this.chASCII.Width = 250;
//
// chLength
//
this.chLength.Text = "Length";
this.chLength.Width = 50;
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miProcess,
this.miLogs,
this.miOptions,
this.miTools,
this.miHelp});
//
// miProcess
//
this.miProcess.Index = 0;
this.miProcess.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miStart,
this.miAttach,
this.miDetach,
this.miExitSeparator,
this.miExit});
this.miProcess.Text = "&Process";
//
// miStart
//
this.miStart.Index = 0;
this.miStart.Text = "&Start...";
this.miStart.Click += new System.EventHandler(this.miStart_Click);
//
// miAttach
//
this.miAttach.Index = 1;
this.miAttach.Text = "&Attach...";
this.miAttach.Click += new System.EventHandler(this.miAttach_Click);
//
// miDetach
//
this.miDetach.Enabled = false;
this.miDetach.Index = 2;
this.miDetach.Text = "&Detach";
this.miDetach.Click += new System.EventHandler(this.miDetach_Click);
//
// miExitSeparator
//
this.miExitSeparator.Index = 3;
this.miExitSeparator.Text = "-";
//
// miExit
//
this.miExit.Index = 4;
this.miExit.Text = "&Exit";
this.miExit.Click += new System.EventHandler(this.miExit_Click);
//
// miLogs
//
this.miLogs.Index = 1;
this.miLogs.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miLoad,
this.miSaveAs,
this.miSaveHexAs,
this.miLoadBin,
this.miSaveBin,
this.miPause,
this.miClear,
this.miSetBaseTime,
this.miHide,
this.miShowHidden});
this.miLogs.Text = "&Logs";
//
// miLoad
//
this.miLoad.Index = 0;
this.miLoad.Text = "&Load...";
this.miLoad.Click += new System.EventHandler(this.miLoad_Click);
//
// miSaveAs
//
this.miSaveAs.Index = 1;
this.miSaveAs.Text = "&Save as...";
this.miSaveAs.Click += new System.EventHandler(this.miSaveAs_Click);
//
// miSaveHexAs
//
this.miSaveHexAs.Index = 2;
this.miSaveHexAs.Text = "Save &hex as...";
this.miSaveHexAs.Click += new System.EventHandler(this.miSaveHexAs_Click);
//
// miPause
//
this.miPause.Enabled = false;
this.miPause.Index = 5;
this.miPause.Text = "&Pause";
this.miPause.Click += new System.EventHandler(this.miPause_Click);
//
// miClear
//
this.miClear.Index = 6;
this.miClear.Text = "&Clear";
this.miClear.Click += new System.EventHandler(this.miClear_Click);
//
// miSetBaseTime
//
this.miSetBaseTime.Enabled = false;
this.miSetBaseTime.Index = 7;
this.miSetBaseTime.Text = "Set &base time";
this.miSetBaseTime.Click += new System.EventHandler(this.miSetBaseTime_Click);
//
// miHide
//
this.miHide.Enabled = false;
this.miHide.Index = 8;
this.miHide.Shortcut = System.Windows.Forms.Shortcut.Del;
this.miHide.Text = "&Hide";
this.miHide.Click += new System.EventHandler(this.miHide_Click);
//
// miShowHidden
//
this.miShowHidden.Enabled = false;
this.miShowHidden.Index = 9;
this.miShowHidden.Text = "Show hi&dden";
this.miShowHidden.Click += new System.EventHandler(this.miShowHidden_Click);
//
// miOptions
//
this.miOptions.Index = 2;
this.miOptions.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miFilter,
this.miOnTop,
this.miAutoScrolling});
this.miOptions.Text = "&Options";
//
// miFilter
//
this.miFilter.Index = 0;
this.miFilter.Text = "&Filter...";
this.miFilter.Click += new System.EventHandler(this.miFilter_Click);
//
// miOnTop
//
this.miOnTop.Index = 1;
this.miOnTop.Text = "Always on &top";
this.miOnTop.Click += new System.EventHandler(this.miOnTop_Click);
//
// miAutoScrolling
//
this.miAutoScrolling.Index = 2;
this.miAutoScrolling.Text = "Auto &scrolling";
this.miAutoScrolling.Click += new System.EventHandler(this.miAutoScrolling_Click);
//
// miTools
//
this.miTools.Index = 3;
this.miTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miExtractItems,
this.miExtractBooks,
this.miExtractGump,
this.miExtractGumpSphere});
this.miTools.Text = "&Tools";
//
// miExtractItems
//
this.miExtractItems.Index = 0;
this.miExtractItems.Text = "Extract &items...";
this.miExtractItems.Click += new System.EventHandler(this.miExtractItems_Click);
//
// miExtractBooks
//
this.miExtractBooks.Index = 1;
this.miExtractBooks.Text = "Extract &book...";
this.miExtractBooks.Click += new System.EventHandler(this.miExtractBooks_Click);
//
// miExtractGump
//
this.miExtractGump.Enabled = false;
this.miExtractGump.Index = 2;
this.miExtractGump.Text = "Extract &gump (RunUO)...";
this.miExtractGump.Click += new System.EventHandler(this.miExtractGump_Click);
//
// miExtractGumpSphere
//
this.miExtractGumpSphere.Enabled = false;
this.miExtractGumpSphere.Index = 3;
this.miExtractGumpSphere.Text = "Extract gump (&Sphere)...";
this.miExtractGumpSphere.Click += new System.EventHandler(this.miExtractGumpSphere_Click);
//
// miHelp
//
this.miHelp.Index = 4;
this.miHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.miAbout});
this.miHelp.Text = "&Help";
//
// miAbout
//
this.miAbout.Index = 0;
this.miAbout.Text = "&About...";
this.miAbout.Click += new System.EventHandler(this.miAbout_Click);
//
// ofdStart
//
this.ofdStart.Filter = "Exe files (*.exe)|*.exe";
//
// sfdSaveAs
//
this.sfdSaveAs.FileName = "SpyUO.log";
this.sfdSaveAs.Filter = "Log files (*.log)|*.log";
//
// sfdExtractItems
//
this.sfdExtractItems.FileName = "SpyUO.cfg";
this.sfdExtractItems.Filter = "Cfg files (*.cfg)|*.cfg";
this.sfdExtractItems.Title = "Extract to";
//
// sfdExtractGump
//
this.sfdExtractGump.FileName = "SpyUOGump.cs";
this.sfdExtractGump.Filter = "C# files (*.cs)|*.cs";
this.sfdExtractGump.Title = "Extract to";
//
// ofdLoad
//
this.ofdLoad.FileName = "SpyUO.log";
this.ofdLoad.Filter = "All files (*.*)|*.*";
//
// sfdExtractGumpSphere
//
this.sfdExtractGumpSphere.FileName = "SpyUOGump.scp";
this.sfdExtractGumpSphere.Filter = "Scp files (*.scp)|*.scp";
//
// sfdExtractBook
//
this.sfdExtractBook.FileName = "SpyUOBook.cs";
this.sfdExtractBook.Filter = "C# files (*.cs)|*.cs";
this.sfdExtractBook.Title = "Extract to";
//
// miSaveBin
//
this.miSaveBin.Index = 4;
this.miSaveBin.Text = "Save bi&n as...";
this.miSaveBin.Click += new System.EventHandler(this.miSaveBin_Click);
//
// sfdSaveBin
//
this.sfdSaveBin.FileName = "SpyUO.bin";
this.sfdSaveBin.Filter = "Bin files (*.bin)|*.bin";
//
// miLoadBin
//
this.miLoadBin.Index = 3;
this.miLoadBin.Text = "Load b&in...";
this.miLoadBin.Click += new System.EventHandler(this.miLoadBin_Click);
//
// ofdLoadBin
//
this.ofdLoadBin.FileName = "SpyUO.bin";
this.ofdLoadBin.Filter = "Bin files (*.bin)|*.bin";
//
// Display
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(552, 414);
this.Controls.Add(this.lvPackets);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu;
this.MinimumSize = new System.Drawing.Size(320, 240);
this.Name = "Display";
this.ResumeLayout(false);
}
#endregion
private PacketFilter m_PacketFilter;
private PacketRecorder m_PacketRecorder;
private PacketPump m_PacketPump;
private bool m_FilterShowAll;
private bool m_AutoScrolling;
private DateTime m_BaseTime;
private DateTime m_LastTime;
private PacketPump PacketPump
{
get
{
return m_PacketPump;
}
set
{
if ( m_PacketPump != null )
{
m_PacketPump.Dispose();
Detached();
}
m_PacketPump = value;
if ( m_PacketPump != null )
{
Attached();
m_PacketPump.OnPacketPumpTerminated += new PacketPumpTerminatedHandler( PacketPumpTerminated );
}
}
}
public Display()
{
InitializeComponent();
UpdateTitle( "" );
m_LastTime = DateTime.MinValue;
m_BaseTime = DateTime.Now;
m_FilterShowAll = false;
m_PacketFilter = new PacketFilter();
m_PacketRecorder = new PacketRecorder( this );
m_PacketRecorder.OnPacket += new OnPacket( OnPacket );
Application.ApplicationExit += new EventHandler( OnExit );
}
public void UpdateTitle( string affix )
{
Text = Title + (m_PacketPump != null ? " " + affix : "");
}
private void OnPacket( TimePacket packet )
{
if ( m_PacketFilter.Filter( packet ) )
AddPacket( packet );
}
private void AddPacket( TimePacket packet )
{
PacketListViewItem item = new PacketListViewItem( packet, m_BaseTime, m_LastTime );
lvPackets.Items.Add( item );
if ( m_AutoScrolling )
lvPackets.EnsureVisible( lvPackets.Items.Count - 1 );
m_LastTime = packet.Time;
}
private void UpdatePackets()
{
miSetBaseTime.Enabled = false;
miHide.Enabled = false;
miShowHidden.Enabled = false;
miExtractGump.Enabled = false;
miExtractGumpSphere.Enabled = false;
m_LastTime = DateTime.MinValue;
lvPackets.BeginUpdate();
lvPackets.Items.Clear();
foreach ( TimePacket packet in m_PacketRecorder.Packets )
{
if ( m_PacketFilter.Filter( packet ) )
AddPacket( packet );
}
lvPackets.EndUpdate();
}
private void Attached()
{
miStart.Enabled = false;
miAttach.Enabled = false;
miDetach.Enabled = true;
miPause.Enabled = true;
miPause.Checked = false;
}
private void Detached()
{
miStart.Enabled = true;
miAttach.Enabled = true;
miDetach.Enabled = false;
miPause.Enabled = false;
miPause.Checked = false;
}
private void PacketPumpTerminated()
{
PacketPump = null;
}
private void OnExit( object sender, System.EventArgs e )
{
if ( PacketPump != null )
PacketPump = null;
if ( m_PacketRecorder != null )
m_PacketRecorder.Dispose();
}
private void miStart_Click( object sender, System.EventArgs e )
{
if ( ofdStart.ShowDialog() == DialogResult.OK )
{
try
{
PacketPump pump = new PacketPump( this, new PacketPumpPacketHandler( m_PacketRecorder.PacketPumpDequeue ) );
pump.Start( ofdStart.FileName );
PacketPump = pump;
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Packet pump error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}
private void miAttach_Click( object sender, System.EventArgs e )
{
SelectProcess selProc = new SelectProcess();
selProc.TopMost = TopMost;
if ( selProc.ShowDialog() == DialogResult.OK )
{
Process process = selProc.GetSelectedProcess();
if ( process != null )
{
try
{
PacketPump pump = new PacketPump( this, new PacketPumpPacketHandler( m_PacketRecorder.PacketPumpDequeue ) );
pump.Start( process );
PacketPump = pump;
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Packet pump error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}
}
private void miDetach_Click( object sender, System.EventArgs e )
{
PacketPump = null;
}
private void miExit_Click( object sender, System.EventArgs e )
{
Application.Exit();
}
private void miFilter_Click( object sender, System.EventArgs e )
{
Filter filter = new Filter( m_PacketFilter, m_FilterShowAll );
filter.TopMost = TopMost;
if ( filter.ShowDialog() == DialogResult.OK )
{
m_FilterShowAll = filter.ShowAll;
UpdatePackets();
}
}
private void miOnTop_Click( object sender, System.EventArgs e )
{
TopMost = !miOnTop.Checked;
miOnTop.Checked = TopMost;
}
private void miAutoScrolling_Click( object sender, System.EventArgs e )
{
m_AutoScrolling = !m_AutoScrolling;
miAutoScrolling.Checked = m_AutoScrolling;
}
private void miSetBaseTime_Click( object sender, System.EventArgs e )
{
ListView.SelectedListViewItemCollection sel = lvPackets.SelectedItems;
if ( sel.Count > 0 )
{
PacketListViewItem item = (PacketListViewItem)sel[0];
m_BaseTime = item.TimePacket.Time;
foreach ( PacketListViewItem plvi in lvPackets.Items )
plvi.UpdateRelTime( m_BaseTime );
}
}
private void miHide_Click( object sender, System.EventArgs e )
{
if ( lvPackets.SelectedIndices.Count > 0 )
{
int index = lvPackets.SelectedIndices[0];
lvPackets.Items.RemoveAt( index );
if ( index < lvPackets.Items.Count )
{
PacketListViewItem item = (PacketListViewItem)lvPackets.Items[index];
if ( index == 0 )
item.UpdateDifTime( DateTime.MinValue );
else
item.UpdateDifTime( ((PacketListViewItem)lvPackets.Items[index - 1]).TimePacket.Time );
}
miShowHidden.Enabled = true;
}
}
private void miShowHidden_Click( object sender, System.EventArgs e )
{
UpdatePackets();
}
private void lvPackets_ItemActivate( object sender, System.EventArgs e )
{
ListView.SelectedListViewItemCollection sel = lvPackets.SelectedItems;
if ( sel.Count > 0 )
{
PacketListViewItem item = (PacketListViewItem)sel[0];
PacketDetails pDetails = new PacketDetails( item );
pDetails.Show();
}
}
private void miClear_Click( object sender, System.EventArgs e )
{
m_PacketRecorder.Clear();
UpdatePackets();
}
private void miPause_Click( object sender, System.EventArgs e )
{
if ( PacketPump != null )
PacketPump.TogglePause();
miPause.Checked = !miPause.Checked;
}
private void miLoad_Click( object sender, System.EventArgs e )
{
if ( ofdLoad.ShowDialog() == DialogResult.OK )
{
StreamReader reader = null;
try
{
reader = File.OpenText( ofdLoad.FileName );
m_PacketRecorder.Load( reader );
UpdatePackets();
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Load error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( reader != null )
reader.Close();
}
}
}
private void miSaveAs_Click( object sender, System.EventArgs e )
{
if ( sfdSaveAs.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdSaveAs.FileName );
Save( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
public void Save( StreamWriter writer )
{
writer.WriteLine( "Logs created on {0} by SpyUO", DateTime.Now );
writer.WriteLine();
writer.WriteLine();
foreach ( ListViewItem item in lvPackets.Items )
{
for ( int i = 0; i < lvPackets.Columns.Count; i++ )
writer.WriteLine( "{0} - {1}", lvPackets.Columns[i].Text, item.SubItems[i].Text );
writer.WriteLine();
}
}
private void miSaveHexAs_Click( object sender, System.EventArgs e )
{
if ( sfdSaveAs.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdSaveAs.FileName );
SaveHex( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
public void SaveHex( StreamWriter writer )
{
writer.WriteLine( "Logs created on {0} by SpyUO", DateTime.Now );
writer.WriteLine();
writer.WriteLine();
foreach ( PacketListViewItem item in lvPackets.Items )
{
TimePacket tPacket = item.TimePacket;
Packet packet = tPacket.Packet;
byte[] data = packet.Data;
writer.WriteLine( " {0} - {1} (command: 0x{2:X}, length: 0x{3:X})",
packet.Send ? "Send" : "Recv", tPacket.Time.ToString( @"H\:mm\:ss.ff" ), packet.Cmd, data.Length );
for ( int l = 0; l < data.Length; l += 0x10 )
{
writer.Write( "{0:X4}:", l );
for ( int i = l; i < l + 0x10; i++ )
writer.Write( " {0}", i < data.Length ? data[i].ToString( "X2" ) : "--" );
writer.Write( "\t" );
for ( int i = l; i < l + 0x10; i++ )
{
if ( i >= data.Length )
break;
byte b = data[i];
char c;
if ( b >= 0x20 && b < 0x80 )
c = (char)b;
else
c = '.';
writer.Write( c );
}
writer.WriteLine();
}
writer.WriteLine();
}
}
private void miSaveBin_Click( object sender, System.EventArgs e )
{
if ( sfdSaveBin.ShowDialog() == DialogResult.OK )
{
FileStream stream = null;
BinaryWriter writer = null;
try
{
stream = File.Create( sfdSaveBin.FileName );
writer = new BinaryWriter( stream );
SaveBin( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
if ( stream != null )
stream.Close();
}
}
}
public void SaveBin( BinaryWriter writer )
{
writer.Write( (int) 0 ); // version
writer.Write( (int) m_PacketRecorder.Packets.Count );
foreach ( TimePacket tPacket in m_PacketRecorder.Packets )
{
Packet packet = tPacket.Packet;
byte[] data = packet.Data;
writer.Write( (bool) packet.Send );
writer.Write( (long) tPacket.Time.Ticks );
if ( packet.Cmd == 0x80 ) // AccountLogin
data = new byte[] { 0x80 };
else if ( packet.Cmd == 0x91 ) // GameLogin
data = new byte[] { 0x91 };
writer.Write( (int) data.Length );
writer.Write( (byte[]) data );
}
}
private void miLoadBin_Click( object sender, System.EventArgs e )
{
if ( ofdLoadBin.ShowDialog() == DialogResult.OK )
{
FileStream stream = null;
BinaryReader reader = null;
try
{
stream = File.OpenRead( ofdLoadBin.FileName );
reader = new BinaryReader( stream );
m_PacketRecorder.LoadBin( reader );
UpdatePackets();
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Load error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( reader != null )
reader.Close();
if ( stream != null )
stream.Close();
}
}
}
private void miAbout_Click( object sender, System.EventArgs e )
{
About about = new About();
about.TopMost = TopMost;
about.ShowDialog();
}
private void miExtractItems_Click( object sender, System.EventArgs e )
{
if ( sfdExtractItems.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractItems.FileName );
m_PacketRecorder.ExtractItems( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
private void lvPackets_SelectedIndexChanged( object sender, System.EventArgs e )
{
if ( lvPackets.SelectedItems.Count > 0 )
{
miSetBaseTime.Enabled = true;
miHide.Enabled = true;
PacketListViewItem lvi = (PacketListViewItem)lvPackets.SelectedItems[0];
Packet packet = lvi.TimePacket.Packet;
if ( packet is BaseGump )
{
miExtractGump.Enabled = true;
miExtractGumpSphere.Enabled = true;
return;
}
}
else
{
miSetBaseTime.Enabled = false;
miHide.Enabled = false;
}
miExtractGump.Enabled = false;
miExtractGumpSphere.Enabled = false;
}
private void miExtractGump_Click( object sender, System.EventArgs e )
{
if ( sfdExtractGump.ShowDialog() == DialogResult.OK )
{
PacketListViewItem lvi = (PacketListViewItem)lvPackets.SelectedItems[0];
BaseGump gump = (BaseGump)lvi.TimePacket.Packet;
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractGump.FileName );
gump.WriteRunUOClass( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
private void miExtractGumpSphere_Click( object sender, System.EventArgs e )
{
if ( sfdExtractGumpSphere.ShowDialog() == DialogResult.OK )
{
PacketListViewItem lvi = (PacketListViewItem)lvPackets.SelectedItems[0];
BaseGump gump = (BaseGump)lvi.TimePacket.Packet;
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractGumpSphere.FileName );
gump.WriteSphereGump( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
private delegate void TitleUpdater( string affix );
public void DisplayCounter( int sentPackets, int sentPacketsSize, int recvPackets, int recvPacketsSize )
{
string title = string.Format( "(Packets/sec) s:{0} r:{1} T:{2} - (Bytes/sec) s:{3} r:{4} T:{5}",
sentPackets, recvPackets, sentPackets + recvPackets, sentPacketsSize, recvPacketsSize, sentPacketsSize + recvPacketsSize );
if ( Handle != IntPtr.Zero )
BeginInvoke( new TitleUpdater( UpdateTitle ), new object[] { title } );
}
private void miExtractBooks_Click( object sender, System.EventArgs e )
{
SelectBook selection = new SelectBook( new ArrayList( m_PacketRecorder.Books.Values ) );
if ( selection.ShowDialog() == DialogResult.OK )
{
BookInfo book = selection.GetSelectedBook();
if ( book != null && sfdExtractBook.ShowDialog() == DialogResult.OK )
{
StreamWriter writer = null;
try
{
writer = File.CreateText( sfdExtractBook.FileName );
book.WriteRunUOClass( writer );
}
catch ( Exception ex )
{
MessageBox.Show( ex.ToString(), "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
finally
{
if ( writer != null )
writer.Close();
}
}
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.EnterpriseServer;
using System.Text;
namespace WebsitePanel.Portal.UserControls
{
public partial class SpaceServiceItems : WebsitePanelControlBase
{
public string GroupName
{
get { return litGroupName.Text; }
set { litGroupName.Text = value; }
}
public string TypeName
{
get { return litTypeName.Text; }
set { litTypeName.Text = value; }
}
public string QuotaName
{
get { return (string)ViewState["QuotaName"]; }
set { ViewState["QuotaName"] = value; }
}
public string CreateControlID
{
get { return ViewState["CreateControlID"] == null ? "edit" : (string)ViewState["CreateControlID"]; }
set { ViewState["CreateControlID"] = value; }
}
public string ViewLinkText
{
get { return ViewState["ViewLinkText"] == null ? null : (string)ViewState["ViewLinkText"]; }
set { ViewState["ViewLinkText"] = value; }
}
public string CreateButtonText
{
get { return btnAddItem.Text; }
set { btnAddItem.Text = value; }
}
public bool ShowCreateButton
{
get { EnsureChildControls(); return btnAddItem.Visible; }
set { EnsureChildControls(); btnAddItem.Visible = value; }
}
public bool ShowQuota
{
get { EnsureChildControls(); return QuotasPanel.Visible; }
set { EnsureChildControls(); QuotasPanel.Visible = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptInclude("jquery", ResolveUrl("~/JavaScript/jquery-1.4.4.min.js"));
//HideServiceColumns(gvWebSites);
// set display preferences
gvItems.PageSize = UsersHelper.GetDisplayItemsPerPage();
itemsQuota.QuotaName = QuotaName;
lblQuotaName.Text = GetSharedLocalizedString("Quota." + QuotaName) + ":";
// edit button
string localizedButtonText = HostModule.GetLocalizedString(btnAddItem.Text + ".Text");
if (localizedButtonText != null)
btnAddItem.Text = localizedButtonText;
// visibility
chkRecursive.Visible = (PanelSecurity.SelectedUser.Role != UserRole.User);
gvItems.Columns[2].Visible = !String.IsNullOrEmpty(ViewLinkText);
gvItems.Columns[3].Visible = gvItems.Columns[4].Visible =
(PanelSecurity.SelectedUser.Role != UserRole.User) && chkRecursive.Checked;
gvItems.Columns[5].Visible = (PanelSecurity.SelectedUser.Role == UserRole.Administrator);
gvItems.Columns[6].Visible = (PanelSecurity.EffectiveUser.Role == UserRole.Administrator);
ShowActionList();
if (!IsPostBack)
{
// toggle controls
btnAddItem.Enabled = PackagesHelper.CheckGroupQuotaEnabled(
PanelSecurity.PackageId, GroupName, QuotaName);
searchBox.AddCriteria("ItemName", GetLocalizedString("SearchField.ItemName"));
searchBox.AddCriteria("Username", GetLocalizedString("SearchField.Username"));
searchBox.AddCriteria("FullName", GetLocalizedString("SearchField.FullName"));
searchBox.AddCriteria("Email", GetLocalizedString("SearchField.EMail"));
}
searchBox.AjaxData = this.GetSearchBoxAjaxData();
}
public string GetUrl(object param1, object param2)
{
string url = GetItemEditUrl(param1, param2) + "&Mode=View";
url = "http://localhost:8080/Portal" + url.Remove(0, 1);
string encodedUrl = System.Web.HttpUtility.UrlPathEncode(url);
return string.Format("javascript:void(window.open('{0}','{1}','{2}'))", encodedUrl, "window","width=400,height=300,scrollbars,resizable");
}
public string GetUrlNormalized(object param1, object param2)
{
string url = GetItemEditUrl(param1, param2) + "&Mode=View";
return System.Web.HttpUtility.UrlPathEncode(url);
}
public string GetItemEditUrl(object packageId, object itemId)
{
return HostModule.EditUrl("ItemID", itemId.ToString(), "edit_item",
PortalUtils.SPACE_ID_PARAM + "=" + packageId.ToString());
}
public string GetUserHomePageUrl(int userId)
{
return PortalUtils.GetUserHomePageUrl(userId);
}
public string GetSpaceHomePageUrl(int spaceId)
{
return NavigateURL(PortalUtils.SPACE_ID_PARAM, spaceId.ToString());
}
public string GetItemsPageUrl(string parameterName, string parameterValue)
{
return NavigateURL(PortalUtils.SPACE_ID_PARAM, PanelSecurity.PackageId.ToString(),
parameterName + "=" + parameterValue);
}
protected void odsItemsPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
HostModule.ProcessException(e.Exception);
e.ExceptionHandled = true;
}
}
protected void btnAddItem_Click(object sender, EventArgs e)
{
Response.Redirect(HostModule.EditUrl(PortalUtils.SPACE_ID_PARAM, PanelSecurity.PackageId.ToString(),
CreateControlID));
}
protected void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Detach")
{
// remove item from meta base
int itemId = Utils.ParseInt(e.CommandArgument.ToString(), 0);
int result = ES.Services.Packages.DetachPackageItem(itemId);
if (result < 0)
{
HostModule.ShowResultMessage(result);
return;
}
// refresh the list
gvItems.DataBind();
}
}
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
HyperLink lnkView = (HyperLink)e.Row.FindControl("lnkView");
if (lnkView == null)
return;
string localizedLinkText = HostModule.GetLocalizedString(ViewLinkText + ".Text");
lnkView.Text = localizedLinkText != null ? localizedLinkText : ViewLinkText;
}
private void ShowActionList()
{
var checkboxColumn = gvItems.Columns[0];
websiteActions.Visible = false;
mailActions.Visible = false;
checkboxColumn.Visible = false;
switch (QuotaName)
{
case "Web.Sites":
websiteActions.Visible = true;
checkboxColumn.Visible = true;
break;
case "Mail.Accounts":
ProviderInfo provider = ES.Services.Servers.GetPackageServiceProvider(PanelSecurity.PackageId, "Mail");
if (provider.EditorControl == "SmarterMail100")
{
mailActions.Visible = true;
checkboxColumn.Visible = true;
}
break;
}
}
public string GetSearchBoxAjaxData()
{
String spaceId = (String.IsNullOrEmpty(Request["SpaceID"]) ? "-1" : Request["SpaceID"]);
StringBuilder res = new StringBuilder();
res.Append("PagedStored: 'ServiceItems'");
res.Append(", RedirectUrl: '" + GetItemEditUrl(spaceId, "{0}").Substring(2) + "'");
res.Append(", PackageID: " + spaceId);
res.Append(", ItemTypeName: $('#" + litTypeName.ClientID + "').val()");
res.Append(", GroupName: $('#" + litGroupName.ClientID + "').val()");
res.Append(", ServerID: " + (String.IsNullOrEmpty(Request["ServerID"]) ? "0" : Request["ServerID"]));
res.Append(", Recursive: ($('#" + chkRecursive.ClientID + "').val() == 'on')");
return res.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private static class SslProvider
{
private static readonly Interop.Http.SslCtxCallback s_sslCtxCallback = SetSslCtxVerifyCallback;
private static readonly Interop.Ssl.AppVerifyCallback s_sslVerifyCallback = VerifyCertChain;
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
{
Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual);
// Disable SSLv2/SSLv3, allow TLSv1.*
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1);
// Create a client certificate provider if client certs may be used.
X509Certificate2Collection clientCertificates = easy._handler._clientCertificates;
ClientCertificateProvider certProvider =
clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic
clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs
null; // manual without certs
IntPtr userPointer = IntPtr.Zero;
if (certProvider != null)
{
// The client cert provider needs to be passed through to the callback, and thus
// we create a GCHandle to keep it rooted. This handle needs to be cleaned up
// when the request has completed, and a simple and pay-for-play way to do that
// is by cleaning it up in a continuation off of the request.
userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider,
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
// Register the callback with libcurl. We need to register even if there's no user-provided
// server callback and even if there are no client certificates, because we support verifying
// server certificates against more than those known to OpenSSL.
CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);
switch (answer)
{
case CURLcode.CURLE_OK:
// We successfully registered. If we'll be invoking a user-provided callback to verify the server
// certificate as part of that, disable libcurl's verification of the host name. The user's callback
// needs to be given the opportunity to examine the cert, and our logic will determine whether
// the host name matches and will inform the callback of that.
if (easy._handler.ServerCertificateValidationCallback != null)
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // don't verify the peer cert's hostname
// We don't change the SSL_VERIFYPEER setting, as setting it to 0 will cause
// SSL and libcurl to ignore the result of the server callback.
}
break;
case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior
case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later
// It's ok if we failed to register the callback if all of the defaults are in play
// with relation to handling of certificates. But if that's not the case, failing to
// register the callback will result in those options not being factored in, which is
// a significant enough error that we need to fail.
EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported: {0}", answer);
if (certProvider != null ||
easy._handler.ServerCertificateValidationCallback != null ||
easy._handler.CheckCertificateRevocationList)
{
throw new PlatformNotSupportedException(
SR.Format(SR.net_http_unix_invalid_certcallback_option, CurlVersionDescription, CurlSslVersionDescription));
}
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
private static CURLcode SetSslCtxVerifyCallback(
IntPtr curl,
IntPtr sslCtx,
IntPtr userPointer)
{
using (SafeSslContextHandle ctx = new SafeSslContextHandle(sslCtx, ownsHandle: false))
{
Interop.Ssl.SslCtxSetCertVerifyCallback(ctx, s_sslVerifyCallback, curl);
if (userPointer == IntPtr.Zero)
{
EventSourceTrace("Not using client certificate callback");
}
else
{
ClientCertificateProvider provider = null;
try
{
GCHandle handle = GCHandle.FromIntPtr(userPointer);
provider = (ClientCertificateProvider)handle.Target;
}
catch (InvalidCastException)
{
Debug.Fail("ClientCertificateProvider wasn't the GCHandle's Target");
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
catch (InvalidOperationException)
{
Debug.Fail("Invalid GCHandle in CurlSslCallback");
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
Debug.Assert(provider != null, "Expected non-null sslCallback in curlCallBack");
Interop.Ssl.SslCtxSetClientCertCallback(ctx, provider._callback);
}
}
return CURLcode.CURLE_OK;
}
private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy)
{
Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null");
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle");
if (getInfoResult == CURLcode.CURLE_OK)
{
GCHandle handle = GCHandle.FromIntPtr(gcHandlePtr);
easy = handle.Target as EasyRequest;
Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle");
return easy != null;
}
easy = null;
return false;
}
private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr)
{
EasyRequest easy;
if (!TryGetEasyRequest(curlPtr, out easy))
{
EventSourceTrace("Could not find associated easy request: {0}", curlPtr);
return 0;
}
using (var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false))
{
IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx);
if (IntPtr.Zero == leafCertPtr)
{
EventSourceTrace("Invalid certificate pointer");
return 0;
}
using (X509Certificate2 leafCert = new X509Certificate2(leafCertPtr))
{
// Set up the CBT with this certificate.
easy._requestContentStream?.SetChannelBindingToken(leafCert);
// We need to respect the user's server validation callback if there is one. If there isn't one,
// we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled,
// as OpenSSL doesn't do that.
if (easy._handler.ServerCertificateValidationCallback == null &&
!easy._handler.CheckCertificateRevocationList)
{
// Start by using the default verification provided directly by OpenSSL.
// If it succeeds in verifying the cert chain, we're done. Employing this instead of
// our custom implementation will need to be revisited if we ever decide to introduce a
// "disallowed" store that enables users to "untrust" certs the system trusts.
int sslResult = Interop.Crypto.X509VerifyCert(storeCtx);
if (sslResult == 1)
{
return 1;
}
// X509_verify_cert can return < 0 in the case of programmer error
Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult);
}
// Either OpenSSL verification failed, or there was a server validation callback.
// Either way, fall back to manual and more expensive verification that includes
// checking the user's certs (not just the system store ones as OpenSSL does).
X509Certificate2[] otherCerts;
int otherCertsCount = 0;
bool success;
using (X509Chain chain = new X509Chain())
{
chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx))
{
if (extraStack.IsInvalid)
{
otherCerts = Array.Empty<X509Certificate2>();
}
else
{
int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack);
otherCerts = new X509Certificate2[extraSize];
for (int i = 0; i < extraSize; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i);
if (certPtr != IntPtr.Zero)
{
X509Certificate2 cert = new X509Certificate2(certPtr);
otherCerts[otherCertsCount++] = cert;
chain.ChainPolicy.ExtraStore.Add(cert);
}
}
}
}
var serverCallback = easy._handler._serverCertificateValidationCallback;
if (serverCallback == null)
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: false, hostName: null); // libcurl already verifies the host name
success = errors == SslPolicyErrors.None;
}
else
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here
try
{
success = serverCallback(easy._requestMessage, leafCert, chain, errors);
}
catch (Exception exc)
{
EventSourceTrace("Server validation callback threw exception: {0}", exc);
easy.FailRequest(exc);
success = false;
}
}
}
for (int i = 0; i < otherCertsCount; i++)
{
otherCerts[i].Dispose();
}
return success ? 1 : 0;
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.